code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ /* eel-gdk-extensions.c: Graphics routines to augment what's in gdk. Copyright (C) 1999, 2000 Eazel, Inc. The Gnome Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The Gnome Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the Gnome Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Authors: Darin Adler <darin@eazel.com>, Pavel Cisler <pavel@eazel.com>, Ramiro Estrugo <ramiro@eazel.com> */ #include <config.h> #include "eel-gdk-extensions.h" #include "eel-glib-extensions.h" #include "eel-lib-self-check-functions.h" #include "eel-string.h" #include <gdk-pixbuf/gdk-pixbuf.h> #include <gdk/gdkprivate.h> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <stdlib.h> #include <pango/pango.h> #define GRADIENT_BAND_SIZE 4 /** * eel_gdk_rectangle_contains_rectangle: * @outer: Rectangle possibly containing another rectangle. * @inner: Rectangle that might be inside. * * Retun TRUE if inner rectangle is contained inside outer rectangle */ gboolean eel_gdk_rectangle_contains_rectangle (GdkRectangle outer, GdkRectangle inner) { return outer.x <= inner.x && outer.x + outer.width >= inner.x + inner.width && outer.y <= inner.y && outer.y + outer.height >= inner.y + inner.height; } /** * eel_interpolate_color: * @ratio: Place on line between colors to interpolate. * @start_color: Color for one end. * @end_color: Color for the other end * @interpolated_color: Result. * * Compute a color between @start_color and @end_color in color space. * Currently, the color space used is RGB, but a future version could * instead do the interpolation in the best color space for expressing * human perception. */ guint32 eel_interpolate_color (gdouble ratio, guint32 start_rgb, guint32 end_rgb) { guchar red, green, blue; g_return_val_if_fail (ratio >= 0.0, 0); g_return_val_if_fail (ratio <= 1.0, 0); red = ((start_rgb >> 16) & 0xFF) * (1.0 - ratio) + ((end_rgb >> 16) & 0xFF) * ratio; green = ((start_rgb >> 8) & 0xFF) * (1.0 - ratio) + ((end_rgb >> 8) & 0xFF) * ratio; blue = (start_rgb & 0xFF) * (1.0 - ratio) + (end_rgb & 0xFF) * ratio; return (((red << 8) | green) << 8) | blue; } /** * eel_gradient_new * @start_color: Color for the top or left. * @end_color: Color for the bottom or right. * @is_horizontal: Direction of the gradient. * * Create a string that combines the start and end colors along * with the direction of the gradient in a standard format. */ char * eel_gradient_new (const char *start_color, const char *end_color, gboolean is_horizontal) { /* Handle the special case where the start and end colors are identical. Handle the special case where the end color is an empty string. */ if (eel_strcmp(start_color, end_color) == 0 || end_color == NULL || end_color[0] == '\0') { return g_strdup (start_color); } /* Handle the special case where the start color is an empty string. */ if (start_color == NULL || start_color[0] == '\0') { return g_strdup (end_color); } /* Handle the general case. */ return g_strconcat (start_color, "-", end_color, is_horizontal ? ":h" : NULL, NULL); } /** * eel_gradient_is_gradient * @gradient_spec: A gradient spec. string. * * Return true if the spec. specifies a gradient instead of a solid color. */ gboolean eel_gradient_is_gradient (const char *gradient_spec) { return eel_strchr (gradient_spec, '-') != NULL; } /** * eel_gradient_is_horizontal * @gradient_spec: A gradient spec. string. * * Return true if the spec. specifies a horizontal gradient. */ gboolean eel_gradient_is_horizontal (const char *gradient_spec) { size_t length; length = eel_strlen (gradient_spec); return length >= 2 && gradient_spec[length - 2] == ':' && gradient_spec[length - 1] == 'h'; } static char * eel_gradient_strip_trailing_direction_if_any (const char *gradient_spec) { size_t length; length = eel_strlen (gradient_spec); if (length >= 2 && gradient_spec[length - 2] == ':' && (gradient_spec[length - 1] == 'v' || gradient_spec[length - 1] == 'h')) { length -= 2; } return g_strndup (gradient_spec, length); } /* For parsing n-point gradients. Successive calls should pass the next_spec value * set by the previous call as their first argument - to continue parsing where the * previous call left off. */ char * eel_gradient_parse_one_color_spec (const char *spec, int *percent, const char **next_spec) { char *result; const char *rgb_end_ptr; const char *percent_ptr; const char *separator_ptr; percent_ptr = eel_strchr (spec, '%'); separator_ptr = eel_strchr (spec, '-'); if (percent_ptr != NULL && (separator_ptr == NULL || percent_ptr < separator_ptr)) { if (percent != NULL) { *percent = (int) strtol (percent_ptr + 1, NULL, 10); } rgb_end_ptr = percent_ptr; } else { if (percent != NULL) { *percent = 100; } rgb_end_ptr = separator_ptr; } if (rgb_end_ptr != NULL) { result = g_strndup (spec, rgb_end_ptr - spec); } else { result = eel_gradient_strip_trailing_direction_if_any (spec); } /* It's important not to use spec after setting *next_spec because it's * likely that *next_spec == spec. */ if (next_spec != NULL) { *next_spec = (separator_ptr != NULL) ? separator_ptr + 1 : NULL; } return result; } /* FIXME bugzilla.eazel.com 5076: * anyone using eel_gradient_get_start_color_spec or * eel_gradient_get_end_color_spec is assuming the gradient * is 2 colors which is questionable. * * Callers should be rewritten and these fns eliminated. */ /** * eel_gradient_get_start_color_spec * @gradient_spec: A gradient spec. string. * * Return the start color. * This may be the entire gradient_spec if it's a solid color. */ char * eel_gradient_get_start_color_spec (const char *gradient_spec) { return eel_gradient_parse_one_color_spec (gradient_spec, NULL, NULL); } /** * eel_gradient_get_end_color_spec * @gradient_spec: A gradient spec. string. * * Return the end color. * This may be the entire gradient_spec if it's a solid color. */ char * eel_gradient_get_end_color_spec (const char *gradient_spec) { char* color = NULL; do { g_free (color); color = eel_gradient_parse_one_color_spec (gradient_spec, NULL, &gradient_spec); } while (gradient_spec != NULL); return color; } /* Do the work shared by all the set_color_spec functions below. */ static char * eel_gradient_set_edge_color (const char *gradient_spec, const char *edge_color, gboolean is_horizontal, gboolean change_end) { char *opposite_color; char *result; g_assert (edge_color != NULL); /* Get the color from the existing gradient spec. for the opposite edge. This will parse away all the stuff we don't want from the old gradient spec. */ opposite_color = change_end ? eel_gradient_get_start_color_spec (gradient_spec) : eel_gradient_get_end_color_spec (gradient_spec); /* Create a new gradient spec. The eel_gradient_new function handles some special cases, so we don't have to bother with them here. */ result = eel_gradient_new (change_end ? opposite_color : edge_color, change_end ? edge_color : opposite_color, is_horizontal); g_free (opposite_color); return result; } /** * eel_gradient_set_left_color_spec * @gradient_spec: A gradient spec. string. * @left_color: Color spec. to replace left color with. * * Changes the left color to what's passed in. * This creates a horizontal gradient. */ char * eel_gradient_set_left_color_spec (const char *gradient_spec, const char *left_color) { g_return_val_if_fail (gradient_spec != NULL, NULL); g_return_val_if_fail (left_color != NULL, NULL); return eel_gradient_set_edge_color (gradient_spec, left_color, TRUE, FALSE); } /** * eel_gradient_set_top_color_spec * @gradient_spec: A gradient spec. string. * @top_color: Color spec. to replace top color with. * * Changes the top color to what's passed in. * This creates a vertical gradient. */ char * eel_gradient_set_top_color_spec (const char *gradient_spec, const char *top_color) { g_return_val_if_fail (gradient_spec != NULL, NULL); g_return_val_if_fail (top_color != NULL, NULL); return eel_gradient_set_edge_color (gradient_spec, top_color, FALSE, FALSE); } /** * eel_gradient_set_right_color_spec * @gradient_spec: A gradient spec. string. * @right_color: Color spec. to replace right color with. * * Changes the right color to what's passed in. * This creates a horizontal gradient. */ char * eel_gradient_set_right_color_spec (const char *gradient_spec, const char *right_color) { g_return_val_if_fail (gradient_spec != NULL, NULL); g_return_val_if_fail (right_color != NULL, NULL); return eel_gradient_set_edge_color (gradient_spec, right_color, TRUE, TRUE); } /** * eel_gradient_set_bottom_color_spec * @gradient_spec: A gradient spec. string. * @bottom_color: Color spec. to replace bottom color with. * * Changes the bottom color to what's passed in. * This creates a vertical gradient. */ char * eel_gradient_set_bottom_color_spec (const char *gradient_spec, const char *bottom_color) { g_return_val_if_fail (gradient_spec != NULL, NULL); g_return_val_if_fail (bottom_color != NULL, NULL); return eel_gradient_set_edge_color (gradient_spec, bottom_color, FALSE, TRUE); } /** * eel_gdk_color_parse_with_white_default * @color_spec: A color spec, or NULL. * @color: Pointer to place to put resulting color. * * The same as gdk_color_parse, except sets the color to white if * the spec. can't be parsed, instead of returning a boolean flag. */ void eel_gdk_color_parse_with_white_default (const char *color_spec, GdkColor *color) { gboolean got_color; g_return_if_fail (color != NULL); got_color = FALSE; if (color_spec != NULL) { if (gdk_color_parse (color_spec, color)) { got_color = TRUE; } } if (!got_color) { color->red = 0xFFFF; color->green = 0xFFFF; color->blue = 0xFFFF; } } /** * eel_parse_rgb_with_white_default * @color_spec: A color spec, or NULL. * Returns: An rgb value. * * The same as gdk_color_parse, except sets the color to white if * the spec. can't be parsed instead of returning a boolean flag * and returns a guint32 rgb value instead of a GdkColor. */ guint32 eel_parse_rgb_with_white_default (const char *color_spec) { GdkColor color; eel_gdk_color_parse_with_white_default (color_spec, &color); return ((color.red << 8) & EEL_RGB_COLOR_RED) | (color.green & EEL_RGB_COLOR_GREEN) | ((color.blue >> 8) & EEL_RGB_COLOR_BLUE); } guint32 eel_rgb16_to_rgb (gushort r, gushort g, gushort b) { guint32 result; result = (0xff0000 | (r & 0xff00)); result <<= 8; result |= ((g & 0xff00) | (b >> 8)); return result; } guint32 eel_rgb8_to_rgb (guchar r, guchar g, guchar b) { return eel_rgb16_to_rgb (r << 8, g << 8, b << 8); } /** * eel_gdk_color_to_rgb * @color: A GdkColor style color. * Returns: An rgb value. * * Converts from a GdkColor stlye color to a gdk_rgb one. * Alpha gets set to fully opaque */ guint32 eel_gdk_color_to_rgb (const GdkColor *color) { return eel_rgb16_to_rgb (color->red, color->green, color->blue); } /** * eel_gdk_rgb_to_color * @color: a gdk_rgb style value. * * Converts from a gdk_rgb value style to a GdkColor one. * The gdk_rgb color alpha channel is ignored. * * Return value: A GdkColor structure version of the given RGB color. */ GdkColor eel_gdk_rgb_to_color (guint32 color) { GdkColor result; result.red = ((color >> 16) & 0xFF) * 0x101; result.green = ((color >> 8) & 0xFF) * 0x101; result.blue = (color & 0xff) * 0x101; result.pixel = 0; return result; } /** * eel_gdk_rgb_to_color_spec * @color: a gdk_rgb style value. * * Converts from a gdk_rgb value style to a string color spec. * The gdk_rgb color alpha channel is ignored. * * Return value: a newly allocated color spec. */ char * eel_gdk_rgb_to_color_spec (const guint32 color) { return g_strdup_printf ("#%06X", (guint) (color & 0xFFFFFF)); } static guint32 eel_shift_color_component (guchar component, float shift_by) { guint32 result; if (shift_by > 1.0) { result = component * (2 - shift_by); } else { result = 0xff - shift_by * (0xff - component); } return result & 0xff; } /** * eel_rgb_shift_color * @color: A color. * @shift_by: darken or lighten factor. * Returns: An darkened or lightened rgb value. * * Darkens (@shift_by > 1) or lightens (@shift_by < 1) * @color. */ guint32 eel_rgb_shift_color (guint32 color, float shift_by) { guint32 result; /* shift red by shift_by */ result = eel_shift_color_component((color & 0x00ff0000) >> 16, shift_by); result <<= 8; /* shift green by shift_by */ result |= eel_shift_color_component((color & 0x0000ff00) >> 8, shift_by); result <<= 8; /* shift blue by shift_by */ result |= eel_shift_color_component((color & 0x000000ff), shift_by); /* alpha doesn't change */ result |= (0xff000000 & color); return result; } /** * eel_gdk_color_is_dark: * * Return true if the given color is `dark' */ gboolean eel_gdk_color_is_dark (GdkColor *color) { int intensity; intensity = (((color->red >> 8) * 77) + ((color->green >> 8) * 150) + ((color->blue >> 8) * 28)) >> 8; return intensity < 128; } /** * eel_stipple_bitmap_for_screen: * * Get pointer to 50% stippled bitmap suitable for use * on @screen. This is a global object; do not free. */ GdkBitmap * eel_stipple_bitmap_for_screen (GdkScreen *screen) { static char stipple_bits[] = { 0x02, 0x01 }; static GPtrArray *stipples = NULL; int screen_num, n_screens, i; if (stipples == NULL) { n_screens = gdk_display_get_n_screens ( gdk_screen_get_display (screen)); stipples = g_ptr_array_sized_new (n_screens); for (i = 0; i < n_screens; i++) { g_ptr_array_index (stipples, i) = NULL; } } screen_num = gdk_screen_get_number (screen); if (g_ptr_array_index (stipples, screen_num) == NULL) { g_ptr_array_index (stipples, screen_num) = gdk_bitmap_create_from_data ( gdk_screen_get_root_window (screen), stipple_bits, 2, 2); } return g_ptr_array_index (stipples, screen_num); } /** * eel_stipple_bitmap: * * Get pointer to 50% stippled bitmap suitable for use * on the default screen. This is a global object; do * not free. * * This method is not multiscreen safe. Do not use it. */ GdkBitmap * eel_stipple_bitmap (void) { return eel_stipple_bitmap_for_screen (gdk_screen_get_default ()); } /** * eel_gdk_window_bring_to_front: * * Raise window and give it focus. */ void eel_gdk_window_bring_to_front (GdkWindow *window) { /* This takes care of un-iconifying the window and * raising it if needed. */ gdk_window_show (window); /* If the window was already showing, it would not have * the focus at this point. Do a little X trickery to * ensure it is focused. */ eel_gdk_window_focus (window, GDK_CURRENT_TIME); } void eel_gdk_window_focus (GdkWindow *window, guint32 timestamp) { gdk_error_trap_push (); XSetInputFocus (GDK_DISPLAY (), GDK_WINDOW_XWINDOW (window), RevertToParent, timestamp); gdk_flush(); gdk_error_trap_pop (); } void eel_gdk_window_set_wm_protocols (GdkWindow *window, GdkAtom *protocols, int nprotocols) { Atom *atoms; int i; atoms = g_new (Atom, nprotocols); for (i = 0; i < nprotocols; i++) { atoms[i] = gdk_x11_atom_to_xatom (protocols[i]); } XSetWMProtocols (GDK_WINDOW_XDISPLAY (window), GDK_WINDOW_XWINDOW (window), atoms, nprotocols); g_free (atoms); } /** * eel_gdk_window_set_wm_hints_input: * * Set the WM_HINTS.input flag to the passed in value */ void eel_gdk_window_set_wm_hints_input (GdkWindow *window, gboolean status) { Display *dpy; Window id; XWMHints *wm_hints; g_return_if_fail (window != NULL); dpy = GDK_WINDOW_XDISPLAY (window); id = GDK_WINDOW_XWINDOW (window); wm_hints = XGetWMHints (dpy, id); if (wm_hints == 0) { wm_hints = XAllocWMHints (); } wm_hints->flags |= InputHint; wm_hints->input = (status == FALSE) ? False : True; XSetWMHints (dpy, id, wm_hints); XFree (wm_hints); } void eel_gdk_window_set_invisible_cursor (GdkWindow *window) { GdkBitmap *empty_bitmap; GdkCursor *cursor; GdkColor useless; char invisible_cursor_bits[] = { 0x0 }; useless.red = useless.green = useless.blue = 0; useless.pixel = 0; empty_bitmap = gdk_bitmap_create_from_data (window, invisible_cursor_bits, 1, 1); cursor = gdk_cursor_new_from_pixmap (empty_bitmap, empty_bitmap, &useless, &useless, 0, 0); gdk_window_set_cursor (window, cursor); gdk_cursor_unref (cursor); g_object_unref (empty_bitmap); } EelGdkGeometryFlags eel_gdk_parse_geometry (const char *string, int *x_return, int *y_return, guint *width_return, guint *height_return) { int x11_flags; EelGdkGeometryFlags gdk_flags; g_return_val_if_fail (string != NULL, EEL_GDK_NO_VALUE); g_return_val_if_fail (x_return != NULL, EEL_GDK_NO_VALUE); g_return_val_if_fail (y_return != NULL, EEL_GDK_NO_VALUE); g_return_val_if_fail (width_return != NULL, EEL_GDK_NO_VALUE); g_return_val_if_fail (height_return != NULL, EEL_GDK_NO_VALUE); x11_flags = XParseGeometry (string, x_return, y_return, width_return, height_return); gdk_flags = EEL_GDK_NO_VALUE; if (x11_flags & XValue) { gdk_flags |= EEL_GDK_X_VALUE; } if (x11_flags & YValue) { gdk_flags |= EEL_GDK_Y_VALUE; } if (x11_flags & WidthValue) { gdk_flags |= EEL_GDK_WIDTH_VALUE; } if (x11_flags & HeightValue) { gdk_flags |= EEL_GDK_HEIGHT_VALUE; } if (x11_flags & XNegative) { gdk_flags |= EEL_GDK_X_NEGATIVE; } if (x11_flags & YNegative) { gdk_flags |= EEL_GDK_Y_NEGATIVE; } return gdk_flags; } void eel_gdk_draw_layout_with_drop_shadow (GdkDrawable *drawable, GdkGC *gc, GdkColor *text_color, GdkColor *shadow_color, int x, int y, PangoLayout *layout) { gdk_draw_layout_with_colors (drawable, gc, x+1, y+1, layout, shadow_color, NULL); gdk_draw_layout_with_colors (drawable, gc, x, y, layout, text_color, NULL); } #if ! defined (EEL_OMIT_SELF_CHECK) static char * eel_gdk_color_as_hex_string (GdkColor color) { return g_strdup_printf ("%04X%04X%04X", color.red, color.green, color.blue); } static char * eel_self_check_parse (const char *color_spec) { GdkColor color; eel_gdk_color_parse_with_white_default (color_spec, &color); return eel_gdk_color_as_hex_string (color); } static char * eel_self_check_gdk_rgb_to_color (guint32 color) { GdkColor result; result = eel_gdk_rgb_to_color (color); return eel_gdk_color_as_hex_string (result); } void eel_self_check_gdk_extensions (void) { /* eel_interpolate_color */ EEL_CHECK_INTEGER_RESULT (eel_interpolate_color (0.0, 0, 0), 0); EEL_CHECK_INTEGER_RESULT (eel_interpolate_color (0.0, 0, 0xFFFFFF), 0); EEL_CHECK_INTEGER_RESULT (eel_interpolate_color (0.5, 0, 0xFFFFFF), 0x7F7F7F); EEL_CHECK_INTEGER_RESULT (eel_interpolate_color (1.0, 0, 0xFFFFFF), 0xFFFFFF); /* eel_fill_rectangle */ /* Make a GdkImage and fill it, maybe? */ /* eel_fill_rectangle_with_color */ /* eel_fill_rectangle_with_gradient */ /* eel_gradient_new */ EEL_CHECK_STRING_RESULT (eel_gradient_new ("", "", FALSE), ""); EEL_CHECK_STRING_RESULT (eel_gradient_new ("a", "b", FALSE), "a-b"); EEL_CHECK_STRING_RESULT (eel_gradient_new ("a", "b", TRUE), "a-b:h"); EEL_CHECK_STRING_RESULT (eel_gradient_new ("a", "a", FALSE), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_new ("a", "a", TRUE), "a"); /* eel_gradient_is_gradient */ EEL_CHECK_BOOLEAN_RESULT (eel_gradient_is_gradient (""), FALSE); EEL_CHECK_BOOLEAN_RESULT (eel_gradient_is_gradient ("-"), TRUE); EEL_CHECK_BOOLEAN_RESULT (eel_gradient_is_gradient ("a"), FALSE); EEL_CHECK_BOOLEAN_RESULT (eel_gradient_is_gradient ("a-b"), TRUE); EEL_CHECK_BOOLEAN_RESULT (eel_gradient_is_gradient ("a-b:h"), TRUE); /* eel_gradient_get_start_color_spec */ EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec (""), ""); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("-"), ""); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a-b"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a-"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("-b"), ""); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a:h"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a:v"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a:c"), "a:c"); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a:-b"), "a:"); EEL_CHECK_STRING_RESULT (eel_gradient_get_start_color_spec ("a:-b:v"), "a:"); /* eel_gradient_get_end_color_spec */ EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec (""), ""); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("-"), ""); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a-b"), "b"); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a-"), ""); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("-b"), "b"); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a:h"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a:v"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a:c"), "a:c"); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a:-b"), "b"); EEL_CHECK_STRING_RESULT (eel_gradient_get_end_color_spec ("a:-b:v"), "b"); /* eel_gradient_set_left_color_spec */ EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("", ""), ""); EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("a", ""), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("a", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("a", "b"), "b-a:h"); EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("a-c:v", "b"), "b-c:h"); EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("a-c:v", "c"), "c"); EEL_CHECK_STRING_RESULT (eel_gradient_set_left_color_spec ("a:-b:v", "d"), "d-b:h"); /* eel_gradient_set_top_color_spec */ EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("", ""), ""); EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("a", ""), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("a", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("a", "b"), "b-a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("a-c:v", "b"), "b-c"); EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("a-c:v", "c"), "c"); EEL_CHECK_STRING_RESULT (eel_gradient_set_top_color_spec ("a:-b:h", "d"), "d-b"); /* eel_gradient_set_right_color_spec */ EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("", ""), ""); EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("a", ""), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("a", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("a", "b"), "a-b:h"); EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("a-c:v", "b"), "a-b:h"); EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("a-c:v", "c"), "a-c:h"); EEL_CHECK_STRING_RESULT (eel_gradient_set_right_color_spec ("a:-b:v", "d"), "a:-d:h"); /* eel_gradient_set_bottom_color_spec */ EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("", ""), ""); EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("a", ""), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("a", "a"), "a"); EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("a", "b"), "a-b"); EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("a-c:v", "b"), "a-b"); EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("a-c:v", "c"), "a-c"); EEL_CHECK_STRING_RESULT (eel_gradient_set_bottom_color_spec ("a:-b:h", "d"), "a:-d"); /* eel_gdk_color_parse_with_white_default */ EEL_CHECK_STRING_RESULT (eel_self_check_parse (""), "FFFFFFFFFFFF"); EEL_CHECK_STRING_RESULT (eel_self_check_parse ("a"), "FFFFFFFFFFFF"); EEL_CHECK_STRING_RESULT (eel_self_check_parse ("white"), "FFFFFFFFFFFF"); EEL_CHECK_STRING_RESULT (eel_self_check_parse ("black"), "000000000000"); EEL_CHECK_STRING_RESULT (eel_self_check_parse ("red"), "FFFF00000000"); EEL_CHECK_STRING_RESULT (eel_self_check_parse ("#012345"), "010123234545"); /* EEL_CHECK_STRING_RESULT (eel_self_check_parse ("rgb:0123/4567/89AB"), "#014589"); */ /* eel_gdk_rgb_to_color */ EEL_CHECK_STRING_RESULT (eel_self_check_gdk_rgb_to_color (EEL_RGB_COLOR_RED), "FFFF00000000"); EEL_CHECK_STRING_RESULT (eel_self_check_gdk_rgb_to_color (EEL_RGB_COLOR_BLACK), "000000000000"); EEL_CHECK_STRING_RESULT (eel_self_check_gdk_rgb_to_color (EEL_RGB_COLOR_WHITE), "FFFFFFFFFFFF"); EEL_CHECK_STRING_RESULT (eel_self_check_gdk_rgb_to_color (EEL_RGB_COLOR_PACK (0x01, 0x23, 0x45)), "010123234545"); /* EEL_RGBA_COLOR_PACK */ EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0xFF, 0x00, 0x00, 00), EEL_RGB_COLOR_RED); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0x00, 0xFF, 0x00, 00), EEL_RGB_COLOR_GREEN); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0x00, 0x00, 0xFF, 00), EEL_RGB_COLOR_BLUE); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0xFF, 0xFF, 0xFF, 00), EEL_RGB_COLOR_WHITE); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0x00, 0x00, 0x00, 00), EEL_RGB_COLOR_BLACK); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0xFF, 0x00, 0x00, 0xFF), EEL_RGBA_COLOR_OPAQUE_RED); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0x00, 0xFF, 0x00, 0xFF), EEL_RGBA_COLOR_OPAQUE_GREEN); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0x00, 0x00, 0xFF, 0xFF), EEL_RGBA_COLOR_OPAQUE_BLUE); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0xFF, 0xFF, 0xFF, 0xFF), EEL_RGBA_COLOR_OPAQUE_WHITE); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_PACK (0x00, 0x00, 0x00, 0xFF), EEL_RGBA_COLOR_OPAQUE_BLACK); /* EEL_RGB_COLOR_PACK */ EEL_CHECK_INTEGER_RESULT (EEL_RGB_COLOR_PACK (0xFF, 0x00, 0x00), EEL_RGBA_COLOR_OPAQUE_RED); EEL_CHECK_INTEGER_RESULT (EEL_RGB_COLOR_PACK (0x00, 0xFF, 0x00), EEL_RGBA_COLOR_OPAQUE_GREEN); EEL_CHECK_INTEGER_RESULT (EEL_RGB_COLOR_PACK (0x00, 0x00, 0xFF), EEL_RGBA_COLOR_OPAQUE_BLUE); EEL_CHECK_INTEGER_RESULT (EEL_RGB_COLOR_PACK (0xFF, 0xFF, 0xFF), EEL_RGBA_COLOR_OPAQUE_WHITE); EEL_CHECK_INTEGER_RESULT (EEL_RGB_COLOR_PACK (0x00, 0x00, 0x00), EEL_RGBA_COLOR_OPAQUE_BLACK); /* EEL_RGBA_COLOR_GET_R */ EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGBA_COLOR_OPAQUE_RED), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGBA_COLOR_OPAQUE_GREEN), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGBA_COLOR_OPAQUE_BLUE), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGBA_COLOR_OPAQUE_WHITE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGBA_COLOR_OPAQUE_BLACK), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGB_COLOR_RED), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGB_COLOR_GREEN), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGB_COLOR_BLUE), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGB_COLOR_WHITE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_R (EEL_RGB_COLOR_BLACK), 0x00); /* EEL_RGBA_COLOR_GET_G */ EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGBA_COLOR_OPAQUE_RED), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGBA_COLOR_OPAQUE_GREEN), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGBA_COLOR_OPAQUE_BLUE), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGBA_COLOR_OPAQUE_WHITE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGBA_COLOR_OPAQUE_BLACK), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGB_COLOR_RED), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGB_COLOR_GREEN), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGB_COLOR_BLUE), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGB_COLOR_WHITE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_G (EEL_RGB_COLOR_BLACK), 0x00); /* EEL_RGBA_COLOR_GET_B */ EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGBA_COLOR_OPAQUE_RED), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGBA_COLOR_OPAQUE_GREEN), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGBA_COLOR_OPAQUE_BLUE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGBA_COLOR_OPAQUE_WHITE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGBA_COLOR_OPAQUE_BLACK), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGB_COLOR_RED), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGB_COLOR_GREEN), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGB_COLOR_BLUE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGB_COLOR_WHITE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_B (EEL_RGB_COLOR_BLACK), 0x00); /* EEL_RGBA_COLOR_GET_A */ EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGBA_COLOR_OPAQUE_RED), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGBA_COLOR_OPAQUE_GREEN), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGBA_COLOR_OPAQUE_BLUE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGBA_COLOR_OPAQUE_WHITE), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGBA_COLOR_OPAQUE_BLACK), 0xFF); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGB_COLOR_RED), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGB_COLOR_GREEN), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGB_COLOR_BLUE), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGB_COLOR_WHITE), 0x00); EEL_CHECK_INTEGER_RESULT (EEL_RGBA_COLOR_GET_A (EEL_RGB_COLOR_BLACK), 0x00); } #endif /* ! EEL_OMIT_SELF_CHECK */
BadChoice/nautilus
eel/eel-gdk-extensions.c
C
gpl-2.0
31,078
--- permalink: /faq/application/documents/forms/ layout: article section: faq title: Where can I find forms that may be necessary when applying? breadcrumb: Forms category: Documents tags: [documents, required, forms] --- Forms are a type of document that agencies often request and you may need to provide supplemental forms when applying to certain jobs. You can find a list of all required documents under the **Required Documents** section of the job announcement. These will most often be documents that you have created, such as your resume or work sample, or that have been given to you by another organization, such as a license, certificate, or reference. ## Standard forms Agencies use standard forms for various employment and benefits program purposes. These forms have the abbreviation "SF" as part of the form name. Common standard forms include: - [SF-50 – Notification of Personnel Action](https://www.opm.gov/forms/standard-forms/){:target="\_blank"}(PDF, 335.25 KB) - [SF-15 – Application for 10-point Veterans Preference](https://www.opm.gov/forms/pdf_fill/SF15.pdf){:target="\_blank"}(PDF, 1.22 MB) [View all other standard forms](https://www.opm.gov/forms/standard-forms/){:target="\_blank"}. ## Optional forms Agencies use optional forms for various purposes not covered under other categories. These forms have the abbreviation "OF" as part of the form name. Common optional forms include: - [OF-306 – Declaration for Federal Employment](https://www.opm.gov/forms/pdf_fill/OF0306.pdf){:target="\_blank"}(PDF, 97.75 KB) [View all other optional forms](https://www.opm.gov/forms/Optional-forms/){:target="\_blank"}. ## Federal Aviation Administration documents The Federal Aviation Administration (FAA) uses additional documents. [View all FAA documents](http://www.faa.gov/forms/){:target="\_blank"}. For other agency-specific documents or forms, please contact the hiring agency.
USAJOBS/help-center
faq/application/documents/forms.md
Markdown
gpl-2.0
1,927
<?php /* * @version $Id: commoninjectionlib.class.php 792 2014-03-24 11:16:02Z tsmr $ LICENSE This file is part of the datainjection plugin. Datainjection plugin 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. Datainjection plugin 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 datainjection. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- @package datainjection @author the datainjection plugin team @copyright Copyright (c) 2010-2013 Datainjection plugin team @license GPLv2+ http://www.gnu.org/licenses/gpl.txt @link https://forge.indepnet.net/projects/datainjection @link http://www.glpi-project.org/ @since 2009 ---------------------------------------------------------------------- */ class PluginDatainjectionCommonInjectionLib { //Injection results private $results = array(); //Values to inject private $values = array(); //Fields mandatory for injection private $mandatory_fields = array(); //List of fields which can agregate more than one value (type multiline_text) private $severalvalues_fields = array(); private $optional_infos = array(); //Injection class to use private $injectionClass; //Primary type to inject private $primary_type; //Store checks to perform on values private $checks = array(); //Store rights private $rights = array(); //Store specific fields formats private $formats = array(); //Entity in which data will be inserted private $entity = 0; const ACTION_CHECK = 0; //Type of action to perform const IMPORT_ADD = 0; const IMPORT_UPDATE = 1; const IMPORT_DELETE = 2; //Action return constants const SUCCESS = 10; //Injection OK const FAILED = 11; //Error during injection const WARNING = 12; //Injection ok but partial //Field check return constants const TYPE_MISMATCH = 22; const MANDATORY = 23; const ITEM_NOT_FOUND = 24; //Injection Message const ERROR_CANNOT_IMPORT = 31; const ERROR_CANNOT_UPDATE = 32; const WARNING_NOTFOUND = 33; const ERROR_FIELDSIZE_EXCEEDED = 37; const ERROR_IMPORT_REFUSED = 39; //Dictionnary explicitly refuse import //Empty values const EMPTY_VALUE = ''; const DROPDOWN_EMPTY_VALUE = 0; //Format constants const FLOAT_TYPE_COMMA = 0; //xxxx,xx const FLOAT_TYPE_DOT = 1; //xxxx.xx const FLOAT_TYPE_DOT_AND_COM = 2; //xx,xxx.xx //Date management constants const DATE_TYPE_DDMMYYYY = "dd-mm-yyyy"; const DATE_TYPE_MMDDYYYY = "mm-dd-yyyy"; const DATE_TYPE_YYYYMMDD = "yyyy-mm-dd"; //Port unicity constants const UNICITY_NETPORT_LOGICAL_NUMBER = 0; const UNICITY_NETPORT_NAME = 1; const UNICITY_NETPORT_MACADDRESS = 2; const UNICITY_NETPORT_LOGICAL_NUMBER_NAME = 3; const UNICITY_NETPORT_LOGICAL_NUMBER_MAC = 4; const UNICITY_NETPORT_LOGICAL_NUMBER_NAME_MAC = 5; //Field status must evolve when ticket #2216 will be resolved const FIELD_INJECTABLE = 1; const FIELD_VIRTUAL = 2; /** * Set default values for injection parameters * * @return nothing **/ function setDefaultValues() { $this->checks = array('ip' => false, 'mac' => false, 'integer' => false, 'yes' => false, 'bool' => false, 'date' => false, 'float' => false, 'string' => false, 'right_r' => false, 'right_rw' => false, 'interface' => false, 'auth_method' => false, 'port_unicity' => false); //Rights options $this->rights = array('add_dropdown' => false, 'overwrite_notempty_fields' => false, 'can_add' => false, 'can_update' => false, 'can_delete' => false); //Field format options $this->formats = array('date_format' => self::DATE_TYPE_YYYYMMDD, 'float_format' => self::FLOAT_TYPE_COMMA); } /** * Constructor : store all needed options into the library * * @param $injectionClass class which represents the itemtype to injection * (in 0.80, will be directly the itemtype class) * @param $values array values to injection into GLPI * @param $injection_options array options that can be used during the injection * (maybe an empty array) * * @return nothinActiong **/ function __construct($injectionClass, $values=array(), $injection_options=array()) { $this->setDefaultValues(); if (isset($injection_options['checks'])) { foreach ($injection_options['checks'] as $key => $value) { $this->checks[$key] = $value; } } if (isset($injection_options['checks'])) { foreach ($injection_options['checks'] as $key => $value) { $this->checks[$key] = $value; } } if (isset($injection_options['rights'])) { foreach ($injection_options['rights'] as $key => $value) { $this->rights[$key] = $value; } } if (isset($injection_options['mandatory_fields'])) { $this->mandatory_fields = $injection_options['mandatory_fields']; } if (isset($injection_options['optional_data'])) { $this->optional_infos = $injection_options['optional_data']; } //Split $injection_options array and store data into the rights internal arrays if (isset($injection_options['formats'])) { $this->formats = $injection_options['formats']; } else { $this->formats = array('date_format' => self::DATE_TYPE_YYYYMMDD, 'float_format' => self::FLOAT_TYPE_DOT); } //Store values to inject $this->values = $values; //Store injectClass & primary_type $this->injectionClass = $injectionClass; $this->primary_type = self::getItemtypeByInjectionClass($injectionClass); //If entity is given stores it, then use root entity if (isset($injection_options['entities_id'])) { $this->entity = $injection_options['entities_id']; } else { $this->entity = 0; } } /** * Check and add fields for itemtype which depend on other itemtypes * (for example SoftwareLicense needs to be linked to a Software) * * @param $injectionClass class to use for injection **/ function areTypeMandatoryFieldsOK($injectionClass) { $itemtype = self::getItemtypeByInjectionClass($injectionClass); //Add more values needed for mandatory fields management if (method_exists($injectionClass,'getValueForAdditionalMandatoryFields')) { $this->values = $injectionClass->getValueForAdditionalMandatoryFields($this->values); } //Add new mandatory fields to check, needed by other itemtypes to inject if (method_exists($injectionClass,'addSpecificMandatoryFields')) { $fields = $injectionClass->addSpecificMandatoryFields(); foreach ($fields as $key => $value) { $this->mandatory_fields[$itemtype][$key] = $value; } } $status_check = true; if (count($this->mandatory_fields[$itemtype]) > 0) { foreach ($this->mandatory_fields[$itemtype] as $field => $value) { //Get value associated with the mandatory field $value = $this->getValueByItemtypeAndName($itemtype,$field); //Get search option associated with the mandatory field $option = self::findSearchOption($injectionClass->getOptions($itemtype),$field); //If field not defined, or if value is the dropdown's default value //If no value found or value is 0 and field is a dropdown, //then mandatory field management failed if (($value == false) || (($value == self::DROPDOWN_EMPTY_VALUE) && self::isFieldADropdown($option['displaytype']))) { $status_check = false; $this->results[self::ACTION_CHECK][] = array(self::MANDATORY,$option['name']); } } } return $status_check; } /** * Check if a field type represents a dropdown or not * * @param $field_type the type of field * * @return true if it's a dropdown type, false if not **/ static function isFieldADropdown($field_type) { if (!in_array($field_type, array('integer', 'decimal', 'tree', 'text', 'multiline_text', 'date'))) { return true; } return false; } /** * Return an the class of an item by giving his injection class * * @param $injectionClassName the injection class name * * @return an instance of the itemtype associated to the injection class name */ static function getItemtypeInstanceByInjection($injectionClassName) { $injection = self::getItemtypeByInjectionClass(new $injectionClassName); return new $injection; } /** * Get an itemtype name by giving his injection class name * * @param $injectionClassName the injection class name * * @return the itemtype associated */ static function getItemtypeByInjection($injectionClassName) { return self::getItemtypeByInjectionClass(new $injectionClassName); } /** * Get an itemtype by giving an injection class object * * @param $injectionClassName the injection class object * * @return an instance of the itemtype associated to the injection class */ static function getItemtypeByInjectionClass($injectionClass) { return Toolbox::ucfirst(getItemTypeForTable($injectionClass->getTable())); } /** * Get an injection class instance for an itemtype * * @param $itemtype the itemtype * * @return the injection class instance */ static function getInjectionClassInstance($itemtype) { if (!isPluginItemType($itemtype)) { $injectionClass = 'PluginDatainjection'.ucfirst($itemtype).'Injection'; } else { $injectionClass = ucfirst($itemtype).'Injection'; } return new $injectionClass(); } /** * Add blacklisted fields for an itemtype * * @param $itemtype the itemtype * * @return the array of all blacklisted fields */ static function getBlacklistedOptions($itemtype) { global $CFG_GLPI; //2 : id // 19 : date_mod // 80 : entity $blacklist = array(2, 19, 80); //add document fields if (in_array($itemtype, $CFG_GLPI["document_types"])) { $tabs = Document::getSearchOptionsToAdd(); $document_fields = array(); unset($tabs['document']); foreach ($tabs as $k => $v) { $document_fields[] = $k; } $blacklist = array_merge($blacklist, $document_fields); } //add infocoms fields if (in_array($itemtype, $CFG_GLPI["infocom_types"])) { $tabs = Infocom::getSearchOptionsToAdd($itemtype); $infocom_fields = array(); unset($tabs['financial']); foreach ($tabs as $k => $v) { $infocom_fields[] = $k; } $blacklist = array_merge($blacklist, $infocom_fields); } //add contract fields if (in_array($itemtype, $CFG_GLPI["contract_types"])) { $tabs = Contract::getSearchOptionsToAdd(); $contract_fields = array(); unset($tabs['contract']); foreach ($tabs as $k => $v) { $contract_fields[] = $k; } $blacklist = array_merge($blacklist, $contract_fields); } //add networkport fields if (in_array($itemtype, $CFG_GLPI["networkport_types"])) { $tabs = NetworkPort::getSearchOptionsToAdd($itemtype); $networkport_fields = array(); unset($tabs['network']); foreach ($tabs as $k => $v) { $networkport_fields[] = $k; } $blacklist = array_merge($blacklist, $networkport_fields); } //add ticket_types fields if (in_array($itemtype, $CFG_GLPI["ticket_types"])) { $ticket_fields = array(60, 140); $blacklist = array_merge($blacklist, $ticket_fields); } return $blacklist; } /** * Find and return the right search option * * @param $options the search options array * @param $lookfor the search option we're looking for * * @return the search option matching lookfor parameter or false it not found **/ static function findSearchOption($options, $lookfor) { $found = false; foreach ($options as $option) { if (isset($option['injectable']) && ($option['injectable'] == self::FIELD_INJECTABLE) && isset($option['linkfield']) && ($option['linkfield'] == $lookfor)) { $found = $option; } } return $found; } //--------------------------------------------------// //----------- Injection options getters -----------// //------------------------------------------------// /** * Get date format used for injection * * @return date format used **/ private function getDateFormat() { return $this->formats['date_format']; } /** * Get date format used for injection * * @return date format used **/ private function getFloatFormat() { return $this->formats['float_format']; } /** * Get itemtype associated to the injectionClass * * @return an itemtype **/ private function getItemtype() { $classname = get_class($this->injectionClass); return self::getItemtypeByInjection($classname); } /** * Get itemtype associated to the injectionClass * * @return an itemtype **/ private function getItemInstance() { $classname = get_class($this->injectionClass); return self::getItemtypeInstanceByInjection($classname); } /** * Return injection results * * @return an array which contains the reformat/check/injection logs **/ public function getInjectionResults() { return $this->results; } /** * Get ID associate to the value from the CSV file is needed (for example for dropdown tables) * * @return nothing **/ private function manageFieldValues() { $blacklisted_fields = array('id'); foreach ($this->values as $itemtype => $data) { $injectionClass = self::getInjectionClassInstance($itemtype); $searchOptions = $injectionClass->getOptions($this->primary_type); foreach ($data as $field => $value) { if (!in_array($field, $blacklisted_fields)) { $searchOption = self::findSearchOption($searchOptions, $field); $this->getFieldValue($injectionClass, $itemtype, $searchOption, $field, $value); } } //TODO : This is ugly, need to find why it adds an empty value to the array foreach ($this->values[$itemtype] as $field => $value) { if ($field == '') { unset($this->values[$itemtype][$field]); } } } } /** * Get the ID associated with a value from the CSV file * * @param $injectionClass * @param $itemtype itemtype of the values to inject * @param $searchOption option associated with the field to check * @param $field the field to check * @param $value the value coming from the CSV file * @param $add is insertion (true) or update (false) (true by default) * * @return nothing **/ private function getFieldValue($injectionClass, $itemtype, $searchOption, $field, $value, $add=true) { if (isset($searchOption['storevaluein'])) { $linkfield = $searchOption['storevaluein']; } else { $linkfield = $searchOption['linkfield']; } switch ($searchOption['displaytype']) { case 'tree' : $this->setValueForItemtype($itemtype, $linkfield, $value); break; case 'decimal' : case 'text' : $this->setValueForItemtype($itemtype, $linkfield, $value); break; case 'password': //To add a user password, it's mandatory is give a password and it's confirmation //Here we cannot detect if it's an add or update. We'll handle updates later in the process if ($add && $itemtype == 'User') { $this->setValueForItemtype($itemtype, $linkfield, $value); //Add field password2 is not already present //(can be present if password was an addtional information) if (!isset($this->values[$itemtype][$field])) { $this->setValueForItemtype($itemtype, $linkfield."2", $value); } } break; case 'dropdown' : case 'relation' : $tmptype = getItemTypeForTable($searchOption['table']); $item = new $tmptype(); if ($item instanceof CommonTreeDropdown) { // use findID instead of getID $input = array ('completename' => $value, 'entities_id' => $this->entity); if ($item->canCreate() && $this->rights['add_dropdown']) { $id = $item->import($input); } else { $id = $item->findID($input); } } else if ($item instanceof CommonDropdown) { if ($item->canCreate() && $this->rights['add_dropdown']) { $canadd = true; } else { $canadd = false; } $id = $item->importExternal($value, $this->entity, $this->addExternalDropdownParameters($itemtype), '', $canadd); } else { $id = self::findSingle($item, $searchOption, $this->entity, $value); } // Use EMPTY_VALUE for Mandatory field check $this->setValueForItemtype($itemtype, $linkfield, ($id>0 ? $id : self::EMPTY_VALUE)); if ($value && $id <= 0) { $this->results['status'] = self::WARNING; $this->results[self::ACTION_CHECK]['status'] = self::WARNING; $this->results[self::ACTION_CHECK][] = array(self::WARNING_NOTFOUND, $searchOption['name']."='$value'"); } break; case 'template' : $id = self::getTemplateIDByName($itemtype, $value); if ($id) { //Template id is stored into the item's id : when adding the object //glpi will understand that it needs to take fields from the template $this->setValueForItemtype($itemtype, '_oldID', $id); } break; case 'contact' : if ($value != Dropdown::EMPTY_VALUE) { $id = self::findContact($value, $this->entity); } else { $id = Dropdown::EMPTY_VALUE; } $this->setValueForItemtype($itemtype, $linkfield, $id); break; case 'user' : if ($value != Dropdown::EMPTY_VALUE) { $id = self::findUser($value, $this->entity); } else { $id = Dropdown::EMPTY_VALUE; } $this->setValueForItemtype($itemtype, $linkfield, $id); break; /* case 'multiline_text': $message = ''; if ($value != self::EMPTY_VALUE) { //If update : do not overwrite the existing field in DB, append at the end ! //if ($add == self::IMPORT_UPDATE) { $message = $this->values[$itemtype][$linkfield]."\n"; //} $message .= $value; $this->setValueForItemtype($itemtype,$linkfield,$message); } break; */ default: if (method_exists($injectionClass,'getSpecificFieldValue')) { $id = $injectionClass->getSpecificFieldValue($itemtype, $searchOption, $field, $this->values); $this->setValueForItemtype($itemtype, $linkfield, $id); } else { $this->setValueForItemtype($itemtype, $linkfield, $value); } } } /** * Add additional parameters needed for dropdown import * * @param itemtype dropdrown's itemtype * * @return an array with additional options to be added **/ private function addExternalDropdownParameters($itemtype) { global $DB; $external = array(); $values = $this->getValuesForItemtype($itemtype); $toadd = array('manufacturers_id' => 'manufacturer'); foreach ($toadd as $field => $addvalue) { if (isset($values[$field])) { switch ($addvalue) { case 'manufacturer' : if (intval($values[$field])>0) { $external[$addvalue] = $DB->escape(Dropdown::getDropdownName('glpi_manufacturers', $values[$field])); break; } default : $external[$addvalue] = $values[$field]; } } else { $external[$addvalue] = ''; } } return $external; } /** * Find a user. Look for login OR firstname + lastname OR lastname + firstname * * @param value the user to look for * @param entity the entity where the user should have right * * @return the user ID if found or '' **/ static private function findUser($value, $entity) { global $DB; $sql = "SELECT `id` FROM `glpi_users` WHERE LOWER(`name`) = '".strtolower($value)."' OR (CONCAT(LOWER(`realname`),' ',LOWER(`firstname`)) = '".strtolower($value)."' OR CONCAT(LOWER(`firstname`),' ',LOWER(`realname`)) = '".strtolower($value)."')"; $result = $DB->query($sql); if ($DB->numrows($result)>0) { //check if user has right on the current entity $ID = $DB->result($result,0,"id"); $entities = Profile_User::getUserEntities($ID,true); if (in_array($entity,$entities)) { return $ID; } return self::DROPDOWN_EMPTY_VALUE; } return self::DROPDOWN_EMPTY_VALUE; } /** * Find a user. Look for login OR firstname + lastname OR lastname + firstname * * @param value the user to look for * @param entity the entity where the user should have right * * @return the user ID if found or '' */ static private function findContact($value, $entity) { global $DB; $sql = "SELECT `id` FROM `glpi_contacts` WHERE `entities_id` = '".$entity."' AND (LOWER(`name`) = '".strtolower($value)."' OR (CONCAT(LOWER(`name`),' ',LOWER(`firstname`)) = '".strtolower($value)."' OR CONCAT(LOWER(`firstname`),' ',LOWER(`name`)) = '".strtolower($value)."'))"; $result = $DB->query($sql); if ($DB->numrows($result)>0) { //check if user has right on the current entity return $DB->result($result, 0, "id"); } return self::DROPDOWN_EMPTY_VALUE; } /** * Find id for a single type * * @param item the ComonDBTM item representing an itemtype * @param searchOption searchOption related to the item * @param entity the current entity * @param value the name of the item for which id must be returned * * @return the id of the item found **/ static private function findSingle($item, $searchOption, $entity, $value) { global $DB; $query = "SELECT `id` FROM `".$item->getTable()."` WHERE 1"; if ($item->maybeTemplate()) { $query .= " AND `is_template` = '0'"; } if ($item->isEntityAssign()) { $query .= getEntitiesRestrictRequest(" AND", $item->getTable(), 'entities_id', $entity, $item->maybeRecursive()); } $query .= " AND `".$searchOption['field']."` = '$value'"; $result = $DB->query($query); if ($DB->numrows($result)>0) { //check if user has right on the current entity return $DB->result($result, 0, "id"); } else { return self::DROPDOWN_EMPTY_VALUE; } } /** * * Get values to inject for an itemtype * * @param the itemtype * * @return an array with all values for this itemtype **/ function getValuesForItemtype($itemtype) { if (isset($this->values[$itemtype])) { return $this->values[$itemtype]; } return false; } /** * Get values to inject for an itemtype * * @param the itemtype * * @return an array with all values for this itemtype **/ private function getValueByItemtypeAndName($itemtype, $field) { $values = $this->getValuesForItemtype($itemtype); if ($values) { return (isset($values[$field])?$values[$field]:false); } return false; } /** * Unset a value to inject for an itemtype * * @param the itemtype * * @return nothing **/ private function unsetValue($itemtype, $field) { if ($this->getValueByItemtypeAndName($itemtype,$field)) { unset($this->values[$itemtype][$field]); } } /** * Set values to inject for an itemtype * * @param itemtype * @param field name * @param value of the field * @param fromdb boolean **/ private function setValueForItemtype($itemtype, $field, $value, $fromdb=false) { // TODO awfull hack, text ftom CSV set more than once, so check if "another" value if (isset($this->values[$itemtype][$field]) && $this->values[$itemtype][$field]!=$value) { // Data set twice (probably CSV + Additional info) $injectionClass = self::getInjectionClassInstance($itemtype); $option = self::findSearchOption($injectionClass->getOptions($itemtype), $field); if (isset($option['displaytype']) && $option['displaytype']=='multiline_text') { if ($fromdb) { $this->values[$itemtype][$field] = $value."\n".$this->values[$itemtype][$field]; } else { $this->values[$itemtype][$field] = $this->values[$itemtype][$field]."\n".$value; } } else if (($fromdb && $value && !$this->rights['overwrite_notempty_fields']) || !$fromdb) { // Overwrite value in DB (from CSV) if allowed in the model option. $this->values[$itemtype][$field] = $value; } } else { // First value $this->values[$itemtype][$field] = $value; } } /** * Get a template name by giving his ID * * @param itemtype the objet's type * @param id the template's id * * @return name of the template or false is no template found **/ static private function getTemplateIDByName($itemtype, $name) { global $DB; $item = new $itemtype(); $query = "SELECT `id` FROM `".getTableForItemType($itemtype)."` WHERE `is_template` = '1' AND `template_name` = '$name'"; $result = $DB->query($query); if ($DB->numrows($result) > 0) { return $DB->result($result, 0, 'id'); } return false; } //--------------------------------------------------// //----------- Reformat methods --------------------// //------------------------------------------------// //Several pass are needed to reformat data //because dictionnaries need to be process in a specific order /** * First pass of data reformat : check values like NULL or values coming from dropdown tables * * @return nothing **/ private function reformatFirstPass() { //Browse all fields & values foreach ($this->values as $itemtype => $data) { $injectionClass = self::getInjectionClassInstance($itemtype); //Get search options associated with the injectionClass $searchOptions = $injectionClass->getOptions($itemtype); foreach ($data as $field => $value) { if ($value && $value == "NULL") { if (isset($option['datatype']) && self::isFieldADropdown($option['displaytype'])) $this->values[$itemtype][$field] = self::EMPTY_VALUE; } } } } /** * Second pass of reformat : check if the itemtype needs specific reformat (like Software) * * @return nothing **/ private function reformatSecondPass() { foreach ($this->values as $itemtype => $data) { $injectionClass = self::getInjectionClassInstance($itemtype); if (method_exists($injectionClass,'reformat')) { //Specific reformat action is itemtype needs it $injectionClass->reformat($this->values); } } } /** * Third pass of reformat : datas, mac address & floats */ private function reformatThirdPass() { global $CFG_GLPI; foreach ($this->values as $itemtype => $data) { //Get injectionClass associated with the itemtype $injectionClass = self::getInjectionClassInstance($itemtype); //Get search options associated with the injectionClass $searchOptions = $injectionClass->getOptions($this->primary_type); foreach ($data as $field => $value) { //Get search option associated with the field $option = self::findSearchOption($searchOptions,$field); // Check some types switch (isset($option['checktype']) ? $option['checktype'] : 'text') { case "date" : //If the value is a date, try to reformat it if it's not the good type //(dd-mm-yyyy instead of yyyy-mm-dd) $date = self::reformatDate($value, $this->getDateFormat()); $this->setValueForItemtype($itemtype, $field, $date); break; case "mac" : $this->setValueForItemtype($itemtype, $field, self::reformatMacAddress($value)); break; case "float" : $float = self::reformatFloat($value, $this->getFloatFormat()); $this->setValueForItemtype($itemtype, $field, $float); break; default: break; } } } } /** * Perform field reformat (if needed) * Composed of 3 passes (one is optional, and depends on the itemtype to inject) * * @return nothing **/ private function reformat() { $this->reformatFirstPass(); $this->reformatSecondPass(); $this->reformatThirdPass(); } /** * Reformat float value. Input could be : * xxxx.xx * xx,xxx.xx * xxxx,xx * @param value : the float to reformat * @param the float format * * @return the float modified as expected in GLPI **/ static private function reformatFloat($value, $format) { if ($value == self::EMPTY_VALUE) { return $value; } //TODO : replace str_replace by a regex switch ($format) { case self::FLOAT_TYPE_COMMA : $value = str_replace(array(" ", ","), array("","."), $value); break; case self::FLOAT_TYPE_DOT : $value = str_replace(" ","", $value); break; case self::FLOAT_TYPE_DOT_AND_COM : $value = str_replace(",","", $value); break; } return $value; } /** * Reformat date from dd-mm-yyyy to yyyy-mm-dd * * @param original_date the original date * * @return the date reformated, if needed **/ static private function reformatDate($original_date, $date_format) { if (empty($original_date)) { return "NULL"; // required to avoid "0000-00-00" in the DB } switch ($date_format) { case self::DATE_TYPE_YYYYMMDD : $new_date = preg_replace('/(\d{4})[-\/](\d{1,2})[-\/](\d{1,2})/', '\1-\2-\3', $original_date); break; case self::DATE_TYPE_DDMMYYYY : $new_date = preg_replace('/(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})/', '\3-\2-\1', $original_date); break; case self::DATE_TYPE_MMDDYYYY : $new_date = preg_replace('/(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})/', '\3-\1-\2', $original_date); break; } if (preg_match('/[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}/',$new_date)) { return $new_date; } return $original_date; } /** * Reformat mac adress if mac doesn't contains : or - as seperator * * @param mac the original mac address * * @return the mac address modified, if needed **/ static private function reformatMacAddress($mac) { $pattern = "/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})"; $pattern .= "([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/"; preg_match($pattern, $mac, $results); if (count($results) > 0) { $mac = ""; $first = true; unset($results[0]); foreach($results as $result) { $mac .= (!$first?":":"").$result; $first = false; } } return $mac; } //--------------------------------------------------// //----------- Check methods -----------------------// //------------------------------------------------// /** * Check all data to be imported * * @return nothing **/ private function check() { $continue = true; foreach ($this->values as $itemtype => $fields) { $injectionClass = self::getInjectionClassInstance($itemtype); //Get search options associated with the injectionClass $searchOptions = $injectionClass->getOptions($itemtype); foreach ($fields as $field => $value) { $mandatory = false; if (isset($this->mandatory_fields[$itemtype][$field])) { $mandatory = $this->mandatory_fields[$itemtype][$field]; } //Get search option associated with the field $option = self::findSearchOption($searchOptions,$field); if ($value == self::EMPTY_VALUE && $mandatory) { $this->results['status'] = self::FAILED; $this->results[self::ACTION_CHECK]['status'] = self::FAILED; $this->results[self::ACTION_CHECK][] = array(self::MANDATORY, $field); $continue = false; } else { $check_result = $this->checkType($injectionClass, $option, $field, $value, $mandatory); $this->results[self::ACTION_CHECK][] = array($check_result, $field."='$value'"); if ($check_result != self::SUCCESS) { $this->results[self::ACTION_CHECK]['status'] = self::FAILED; $this->results['status'] = self::FAILED; $continue = false; } } } } } /** * Is a value a float ? * * @param val the value to check * * @return true if it's a float, false otherwise */ private function isFloat ($val) { return is_numeric($val) && ($val == floatval($val)); } /** * Is a value an integer ? * * @param val the value to check * * @return true if it's an integer, false otherwise */ private function isInteger ($val) { return is_numeric($val) && ($val == intval($val)); } /** * Check one data * * @param the type of data waited * @param data the data to import * * @return true if the data is the correct type **/ private function checkType($injectionClass, $option, $field_name, $data, $mandatory) { if (!empty($option)) { $field_type = (isset($option['checktype'])?$option['checktype']:'text'); //If no data provided AND this mapping is not mandatory if (!$mandatory && ($data == null || $data == "NULL" || $data == self::EMPTY_VALUE)) { return self::SUCCESS; } switch ($field_type) { case 'tree' : case 'text' : if (isset($option['displaytype']) && $option['displaytype']=='multiline_text') { return self::SUCCESS; } if (strlen($data) > 255) { return self::ERROR_FIELDSIZE_EXCEEDED; } return self::SUCCESS; case 'integer' : return (self::isInteger($data) ? self::SUCCESS : self::TYPE_MISMATCH); case 'decimal' : case 'float': return (self::isFloat($data) ? self::SUCCESS : self::TYPE_MISMATCH); case 'date' : // Date is already "reformat" according to getDateFormat() $pat = '/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})$/'; $res = preg_match($pat, $data, $regs); return ($res ? self::SUCCESS : self::TYPE_MISMATCH); case 'ip' : preg_match("/([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", $data, $regs); return ((count($regs) > 0)?self::SUCCESS:self::TYPE_MISMATCH); case 'mac' : preg_match("/([0-9a-fA-F]{2}([:-]|$)){6}$/", $data, $regs); return ((count($regs) > 0)?self::SUCCESS:self::TYPE_MISMATCH); case 'itemtype' : return (class_exists($data)?self::SUCCESS:self::TYPE_MISMATCH); case 'bool' : //If not numeric => type mismatch if (!is_numeric($data)) { return self::TYPE_MISMATCH; } if ($data == 0 || $data == 1) { return self::SUCCESS; } else { return self::TYPE_MISMATCH; } default : //Not a standard check ? Try checks specific to the injection class //Will return SUCCESS if it's not a specific check if (method_exists($injectionClass,'checkType')) { return $injectionClass->checkType($field_name, $data, $mandatory); } return self::SUCCESS; } } return self::SUCCESS; } //--------------------------------------------------// //------ Pre and post injection methods -----------// //------------------------------------------------// /** * Add fields needed for all type injection * * @return nothing **/ private function addNecessaryFields() { $this->setValueForItemtype($this->primary_type, 'entities_id', $this->entity); if (method_exists($this->injectionClass,'addSpecificNeededFields')) { $specific_fields = $this->injectionClass->addSpecificNeededFields($this->primary_type, $this->values); foreach ($specific_fields as $field => $value) { $this->setValueForItemtype($this->primary_type, $field, $value); } } } /** * Add fields needed to inject and itemtype * * @param injectionClass class which represents the object to inject * @param itemtype the itemtype to inject * * @return nothing **/ private function addNeededFields($injectionClass, $itemtype) { //Add itemtype $this->setValueForItemtype($itemtype, 'itemtype', $this->primary_type); //Add primary item's id $id = $this->getValueByItemtypeAndName($this->primary_type, 'id'); $this->setValueForItemtype($itemtype, 'items_id', $id); //Add entities_id if itemtype can be assigned to an entity if ($injectionClass->isEntityAssign()) { $entities_id = $this->getValueByItemtypeAndName($this->primary_type,'entities_id'); $this->setValueForItemtype($itemtype,'entities_id',$entities_id); } //Add is_recursive if itemtype can be assigned recursive if ($injectionClass->isRecursive()) { $recursive = $this->getValueByItemtypeAndName($this->primary_type, 'is_recursive'); $this->setValueForItemtype($itemtype, 'is_recursive', $recursive); } if (method_exists($injectionClass,'addSpecificNeededFields')) { $specific_fields = $injectionClass->addSpecificNeededFields($this->primary_type, $this->values); foreach ($specific_fields as $field => $value) { $this->setValueForItemtype($itemtype, $field, $value); } } } /** * Check value before processing import. Last change to stop import of data * * @return nothing **/ private function lastCheckBeforeProcess($injectionClass, $values) { //Specific reformat action is itemtype needs it if (method_exists($injectionClass,'lastCheck')) { return $injectionClass->lastCheck($this->values); } else { return true; } } //--------------------------------------------------// //-------- Add /Update/Delete methods -------------// //------------------------------------------------// /** * Process of inject data into GLPI * * @return an array which contains the injection results **/ public function processAddOrUpdate() { $process = false; $add = true; $accepted = false; // logDebug("processAddOrUpdate(), start with", $this->values); // Initial value, will be change when problem $this->results['status'] = self::SUCCESS; $this->results[self::ACTION_CHECK]['status'] = self::SUCCESS; //Manage fields belonging to relations between tables $this->manageRelations(); $accepted = $this->processDictionnariesIfNeeded(); //Get real value for fields (ie dropdown, etc) $this->manageFieldValues(); //Check if the type to inject requires additional fields //(for example to link it with another type) if (!$this->areTypeMandatoryFieldsOK($this->injectionClass)) { $process = false; $this->results['status'] = self::FAILED; $this->results[self::ACTION_CHECK]['status'] = self::FAILED; } else { //Check is data to be inject still exists in DB (update) or not (add) $this->dataAlreadyInDB($this->injectionClass, $this->primary_type); $process = true; //No item found in DB if($this->getValueByItemtypeAndName($this->primary_type, 'id') == self::ITEM_NOT_FOUND) { //Can add item ? $this->results['type'] = self::IMPORT_ADD; if (!$accepted) { $this->results['status'] = self::ERROR_IMPORT_REFUSED; $process = false; } else { if ($this->rights['can_add']) { $add = true; $this->unsetValue($this->primary_type, 'id'); } else { $process = false; $this->results['status'] = self::ERROR_CANNOT_IMPORT; } } } else { //Item found in DB $this->results['type'] = self::IMPORT_UPDATE; $this->results[$this->primary_type] = $this->getValueByItemtypeAndName($this->primary_type, 'id'); if ($this->rights['can_update']) { $add = false; } else { $process = false; $this->results['status'] = self::ERROR_CANNOT_UPDATE; } } } if ($process) { //First : reformat data $this->reformat(); //Second : check data $this->check(); if ($this->results['status'] != self::FAILED) { //Third : inject data $item = $this->getItemInstance(); $item->getEmpty(); //Add important fields for injection $this->addNecessaryFields(); //Add aditional infos $this->addOptionalInfos(); //Manage template only when adding an item if ($this->results['type'] == self::IMPORT_ADD) { //If needed, manage templates $this->addTemplateFields($this->primary_type); } $values = $this->getValuesForItemtype($this->primary_type); $newID = $this->effectiveAddOrUpdate($this->injectionClass, $add, $item, $values); if (!$newID) { $this->results['status'] = self::WARNING; } else { //Store id of the injected item $this->setValueForItemtype($this->primary_type, 'id', $newID); //If type needs it : process more data after type import $this->processAfterInsertOrUpdate($this->injectionClass, $add); //$this->results['status'] = self::SUCCESS; $this->results[get_class($item)] = $newID; //Process other types foreach ($this->values as $itemtype => $data) { //Do not process primary_type if ($itemtype != get_class($item)) { $injectionClass = self::getInjectionClassInstance($itemtype); $item = new $itemtype(); $this->addNeededFields($injectionClass, $itemtype); $this->dataAlreadyInDB($injectionClass, $itemtype); if ($this->getValueByItemtypeAndName($itemtype, 'id') == self::ITEM_NOT_FOUND) { $add = true; $this->unsetValue($itemtype, 'id'); } else { $add = false; } $values = $this->getValuesForItemtype($itemtype); if ($this->lastCheckBeforeProcess($injectionClass, $values)) { $tmpID = $this->effectiveAddOrUpdate($injectionClass, $add, $item, $values); $this->processAfterInsertOrUpdate($injectionClass, $add); } } } } } } return $this->results; } /** * Perform data injection into GLPI DB * * @param injectionClass class which represents the object to inject * @param add true to insert an object, false to update an existing object * @param item the CommonDBTM object representing the itemtype to inject * @param values the values to inject * * @return the id of the object added or updated **/ private function effectiveAddOrUpdate($injectionClass, $add=true, $item, $values) { //Insert data using the standard add() method $toinject = array(); $options = $injectionClass->getOptions(); foreach ($values as $key => $value) { $option = self::findSearchOption($options, $key); if (!isset($option['checktype']) || $option['checktype'] != self::FIELD_VIRTUAL) { //If field is a dropdown and value is '', then replace it by 0 if (self::isFieldADropdown($option['displaytype']) && $value == self::EMPTY_VALUE) { $toinject[$key] = self::DROPDOWN_EMPTY_VALUE; } else { $toinject[$key] = $value; } } } //logDebug("effectiveAddOrUpdate($add)", "Values:", $values, "ToInject:", $toinject); if (method_exists($injectionClass, 'customimport')) { $newID = call_user_func(array($injectionClass, 'customimport'), $toinject, $add, $this->rights); } elseif ($item instanceof CommonDropdown && $add) { $newID = $item->import($toinject); } else { if ($add) { if ($newID = $item->add($toinject)) { self::logAddOrUpdate($item, $add); } } else { if ($item->update($toinject)) { $newID = $toinject['id']; self::logAddOrUpdate($item, $add); } } } $this->setValueForItemtype(get_class($item), 'id', $newID); return $newID; } /** * Add optional informations filled by the user * * @return nothing **/ private function addOptionalInfos() { foreach ($this->optional_infos as $itemtype => $data) { foreach ($data as $field => $value) { //Exception for template management //We've got the template id, not let's add the template name if ($field == 'templates_id') { $item = new $itemtype(); if ($item->getFromDB($value)) { $this->setValueForItemtype($itemtype, 'template_name', $item->fields['template_name']); $this->setValueForItemtype($itemtype, '_oldID', $value); } } else { $this->setValueForItemtype($itemtype, $field, $value); } $this->addSpecificOptionalInfos($itemtype, $field, $value); } } } /** * If an optional info need more processing (for example password) * @param itemtype being injected * @param field the optional info field * @param value the optional info value * @return nothing */ protected function addSpecificOptionalInfos($itemtype, $field, $value) { } /** * Process dictionnaries if needed * @since 2.1.6 * @return nothing */ protected function processDictionnariesIfNeeded() { //If itemtype implements special process after type injection if (method_exists($this->injectionClass, 'processDictionnariesIfNeeded')) { //Invoke it return $this->injectionClass->processDictionnariesIfNeeded($this->values); } else { return true; } } /** * Manage fields tagged as relations * * @return nothing **/ private function manageRelations() { foreach ($this->values as $itemtype => $data) { $injectionClass = self::getInjectionClassInstance($itemtype); //Get search options associated with the injectionClass $searchOptions = $injectionClass->getOptions($this->primary_type); foreach ($searchOptions as $id => $option) { //If it's a relation if (isset($option['displaytype']) && $option['displaytype'] == 'relation' && isset($this->values[$itemtype][$option['linkfield']])) { //Get the relation object associated with the field //Add a new array for the relation object $value = $this->getValueByItemtypeAndName($itemtype, $option['linkfield']); $this->getFieldValue(null, $option['relationclass'], $option, $option['linkfield'], $value, true); //Remove the old option $this->unsetValue($itemtype, $option['linkfield']); } } } } /** * Function to check if the datas to inject already exists in DB * * @param class which represents type to inject * @param itemtype the itemtype to inject * * @return nothing **/ private function dataAlreadyInDB($injectionClass, $itemtype) { global $DB; $where = ""; $continue = true; $searchOptions = $injectionClass->getOptions($this->primary_type); //Add sql request checks specific to this itemtype $options['checks'] = $this->checks; $options['itemtype'] = $this->primary_type; //If injectionClass has a method to check if needed parameters are present $values = $this->getValuesForItemtype($itemtype); //If an itemtype needs special treatment (for example entity) if (method_exists($injectionClass, 'customDataAlreadyInDB')) { if ($res = $injectionClass->customDataAlreadyInDB($injectionClass, $values, $options)) { $this->setValueForItemtype($itemtype, 'id', $res); } else { $this->setValueForItemtype($itemtype, 'id', self::ITEM_NOT_FOUND); } } else { if (method_exists($injectionClass, 'checkParameters')) { $continue = $injectionClass->checkParameters($values, $options); } //Needed parameters are not present : not found if (!$continue) { $this->values[$itemtype]['id'] = self::ITEM_NOT_FOUND; } else { $sql = "SELECT * FROM `" . $injectionClass->getTable()."`"; $item = new $itemtype(); //If it's a computer device if ($item instanceof CommonDevice) { $sql.= " WHERE `designation` = '" . $this->getValueByItemtypeAndName($itemtype, 'designation') . "'"; } elseif ($item instanceof CommonDBRelation) { //Type is a relation : check it this relation still exists //Define the side of the relation to use if (method_exists($item, 'relationSide')) { $side = $injectionClass->relationSide(); } else { $side = true; } if ($side) { $source_id = $item::$items_id_2; $destination_id = $item::$items_id_1; $source_itemtype = $item::$itemtype_2; $destination_itemtype = $item::$itemtype_1; } else { $source_id = $item::$items_id_1; $destination_id = $item::$items_id_2; $source_itemtype = $item::$itemtype_1; $destination_itemtype = $item::$itemtype_2; } $where .= " AND `$source_id`='". $this->getValueByItemtypeAndName($itemtype,$source_id)."'"; if ($item->isField('itemtype')) { $where .= " AND `$source_itemtype`='". $this->getValueByItemtypeAndName($itemtype, $source_itemtype)."'"; } $where .= " AND `".$destination_id."`='". $this->getValueByItemtypeAndName($itemtype, $destination_id)."'"; $sql .= " WHERE 1 ".$where; } else { //Type is not a relation //Type can be deleted if ($injectionClass->maybeDeleted()) { $where .= " AND `is_deleted` = '0' "; } //Type can be a template if ($injectionClass->maybeTemplate()) { $where .= " AND `is_template` = '0' "; } //Type can be assigned to an entity if ($injectionClass->isEntityAssign()) { //Type can be recursive if ($injectionClass->maybeRecursive()) { $where_entity = getEntitiesRestrictRequest(" AND", $injectionClass->getTable(), "entities_id", $this->getValueByItemtypeAndName($itemtype, 'entities_id'), true); } else { //Type cannot be recursive $where_entity = " AND `entities_id` = '". $this->getValueByItemtypeAndName($itemtype, 'entities_id')."'"; } } else { //If no entity assignment for this itemtype $where_entity = ""; } //Add mandatory fields to the query only if it's the primary_type to be injected if ($itemtype == $this->primary_type) { foreach ($this->mandatory_fields[$itemtype] as $field => $is_mandatory) { if ($is_mandatory) { $option = self::findSearchOption($searchOptions, $field); $where .= " AND `" . $field . "`='". $this->getValueByItemtypeAndName($itemtype, $field) . "'"; } } } else { //Table contains an itemtype field if ($injectionClass->isField('itemtype')) { $where .= " AND `itemtype` = '".$this->getValueByItemtypeAndName($itemtype, 'itemtype')."'"; } //Table contains an items_id field if ($injectionClass->isField('items_id')) { $where .= " AND `items_id` = '".$this->getValueByItemtypeAndName($itemtype, 'items_id')."'"; } } //Add additional parameters specific to this itemtype (or function checkPresent exists) if (method_exists($injectionClass,'checkPresent')) { $where .= $injectionClass->checkPresent($this->values, $options); } $sql .= " WHERE 1 " . $where_entity . " " . $where; } $result = $DB->query($sql); if ($DB->numrows($result) > 0) { $db_fields = $DB->fetch_assoc($result); foreach ($db_fields as $key => $value) { $this->setValueForItemtype($itemtype, $key, $value, true); } $this->setValueForItemtype($itemtype, 'id', $DB->result($result, 0, 'id')); } else { $this->setValueForItemtype($itemtype, 'id', self::ITEM_NOT_FOUND); } } } } /** * Add fields coming for a template to the values to be injected * * @param itemtype the itemtype to inject * * @return nothing **/ private function addTemplateFields($itemtype) { //If data inserted is not a template if (!$this->getValueByItemtypeAndName($itemtype, 'is_template')) { $template = new $itemtype(); $template_id = $this->getValueByItemtypeAndName($itemtype, '_oldID'); if ($template->getFromDB($template_id) && $itemtype != 'Entity') { unset ($template->fields["id"]); unset ($template->fields["date_mod"]); unset ($template->fields["is_template"]); unset ($template->fields["entities_id"]); foreach ($template->fields as $key => $value) { if ($value != self::EMPTY_VALUE && (!isset ($this->values[$itemtype][$key]) || $this->values[$itemtype][$key] == self::EMPTY_VALUE || $this->values[$itemtype][$key] == self::DROPDOWN_EMPTY_VALUE)) { $value = Toolbox::addslashes_deep($value); $this->setValueForItemtype($itemtype, $key, $value); } } if (isset($this->values[$itemtype]['name'])) { $name = autoName($this->values[$itemtype]['name'], "name", true, $itemtype, $this->values[$itemtype]['entities_id']); $this->setValueForItemtype($itemtype, 'name', $name); } if (isset($this->values[$itemtype]['otherserial'])) { $otherserial = autoName($this->values[$itemtype]['otherserial'], "otherserial", true, $itemtype, $this->values[$itemtype]['entities_id']); $this->setValueForItemtype($itemtype, 'otherserial', $otherserial); } } } } /** * Log event into the history * * @param device_type the type of the item to inject * @param device_id the id of the inserted item * @param the action_type the type of action(add or update) * * @return nothing **/ static function logAddOrUpdate($item, $add=true) { if ($item->dohistory) { $changes[0] = 0; if ($add) { $changes[2] = __('Add from CSV file', 'datainjection'); } else { $changes[2] = __('Update from CSV file', 'datainjection'); } $changes[1] = ""; Log::history ($item->fields['id'], get_class($item), $changes); } } /** * Get label associated with an injection action * * @param action code as defined in the head of this file * * @return label associated with the code **/ static function getActionLabel($action) { $actions = array(self::IMPORT_ADD => __('Add'), self::IMPORT_UPDATE => __('Update'), self::IMPORT_DELETE => __('Delete')); if (isset($actions[$action])) { return $actions[$action]; } return ""; } /** * Get label associated with an injection result * * @param action code as defined in the head of this file * * @return label associated with the code **/ public static function getLogLabel($type) { $message = ""; switch ($type) { case self::ERROR_CANNOT_IMPORT : $message = __('No right to import data', 'datainjection'); break; case self::ERROR_CANNOT_UPDATE : $message = __('No right to update data', 'datainjection'); break; case self::ERROR_FIELDSIZE_EXCEEDED : $message = __('Size of the inserted value is to expansive', 'datainjection'); break; case self::ERROR_IMPORT_REFUSED : $message = __('Import not allowed', 'datainjection'); break; case self::FAILED : $message = __('Import failed', 'datainjection'); break; case self::MANDATORY : $message = __('At least one mandatory field is not present', 'datainjection'); break; case self::SUCCESS : $message = __('Datas to insert are correct', 'datainjection'); break; case self::TYPE_MISMATCH : $message = __('One data is not the good type', 'datainjection'); break; case self::WARNING : $message = __('Warning', 'datainjection'); break; case self::WARNING_NOTFOUND : $message = __('Data not found', 'datainjection'); break; default : $message = __('Undetermined', 'datainjection'); break; } return $message; } /** * Manage search options **/ static function addToSearchOptions($type_searchOptions = array(), $options = array(), $injectionClass) { self::addTemplateSearchOptions($injectionClass, $type_searchOptions); //Add linkfield for theses fields : no massive action is allowed in the core, but they can be //imported using the commonlib $add_linkfield = array('comment' => 'comment', 'notepad' => 'notepad'); foreach ($type_searchOptions as $id => $tmp) { if (!is_array($tmp) || in_array($id, $options['ignore_fields'])) { unset($type_searchOptions[$id]); } else { if (in_array($tmp['field'], $add_linkfield)) { $type_searchOptions[$id]['linkfield'] = $add_linkfield[$tmp['field']]; } if (!in_array($id, $options['ignore_fields']) && $id < 1000) { if (!isset($tmp['linkfield'])) { $type_searchOptions[$id]['injectable'] = self::FIELD_VIRTUAL; } else { $type_searchOptions[$id]['injectable'] = self::FIELD_INJECTABLE; } if (isset($tmp['linkfield']) && !isset($tmp['displaytype'])) { $type_searchOptions[$id]['displaytype'] = 'text'; } if (isset($tmp['linkfield']) && !isset($tmp['checktype'])) { $type_searchOptions[$id]['checktype'] = 'text'; } } } } foreach (array('displaytype', 'checktype') as $paramtype) { if (isset($options[$paramtype])) { foreach ($options[$paramtype] as $type => $tabsID) { foreach ($tabsID as $tabID) { $type_searchOptions[$tabID][$paramtype] = $type; } } } } return $type_searchOptions; } /** * Add necessary search options for template management * * @param injectionClass the injection class to use * @param tab the options tab, as an array (passed as a reference) * * @return nothing **/ static function addTemplateSearchOptions($injectionClass,&$tab) { $itemtype = self::getItemtypeByInjectionClass($injectionClass); $item = new $itemtype(); if ($item->maybeTemplate()) { $tab[300]['table'] = $item->getTable(); $tab[300]['field'] = 'is_template'; $tab[300]['linkfield'] = 'is_template'; $tab[300]['name'] = __('is') . " " . __('Template') . " ?"; $tab[300]['type'] = 'integer'; $tab[300]['injectable'] = 1; $tab[300]['checktype'] = 'integer'; $tab[300]['displaytype'] = 'bool'; $tab[301]['table'] = $item->getTable(); $tab[301]['field'] = 'template_name'; $tab[301]['name'] = __('Template'); $tab[301]['injectable'] = 1; $tab[301]['checktype'] = 'text'; $tab[301]['displaytype'] = 'template'; $tab[301]['linkfield'] = 'templates_id'; } } /** * If itemtype injection needs to process things after data is written in DB * @param add true if an item is created, false if it's an update * @return nothing **/ private function processAfterInsertOrUpdate($injectionClass, $add = true) { //If itemtype implements special process after type injection if (method_exists($injectionClass, 'processAfterInsertOrUpdate')) { //Invoke it $injectionClass->processAfterInsertOrUpdate($this->values, $add, $this->rights); } } } ?>
euqip/glpi-smartcities
plugins/datainjection/inc/commoninjectionlib.class.php
PHP
gpl-2.0
68,846
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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/>. */ /*Adobis * *@author SharpAceX (Alan) *@author Ronan */ importPackage(Packages.server.expeditions); importPackage(Packages.tools); importPackage(Packages.scripting.event); var status = 0; var expedition; var player; var em; var exped = MapleExpeditionType.ZAKUM; var expedName = "Zakum"; var expedBoss = "Zakum"; var expedMap = "Zakum's Altar"; var expedItem = 4001017; var list = "What would you like to do?#b\r\n\r\n#L1#View current Expedition members#l\r\n#L2#Start the fight!#l\r\n#L3#Stop the expedition.#l"; function start() { action(1, 0, 0); } function action(mode, type, selection) { player = cm.getPlayer(); expedition = cm.getExpedition(exped); em = cm.getEventManager("ZakumBattle"); if (mode == -1) { cm.dispose(); } else { if (mode == 0) { cm.dispose(); return; } if (status == 0) { if (player.getLevel() < exped.getMinLevel() && player.getLevel() > exped.getMaxLevel()) { //Don't fit requirement cm.sendOk("You do not meet the criteria to battle " + expedBoss + "!"); cm.dispose(); } else if (expedition == null) { //Start an expedition cm.sendSimple("#e#b<Expedition: " + expedName + ">\r\n#k#n" + em.getProperty("party") + "\r\n\r\nWould you like to assemble a team to take on #r" + expedBoss + "#k?\r\n#b#L1#Lets get this going!#l\r\n\#L2#No, I think I'll wait a bit...#l"); status = 1; } else if (expedition.isLeader(player)) { //If you're the leader, manage the exped cm.sendSimple(list); status = 2; } else if (expedition.isRegistering()) { //If the expedition is registering if (expedition.contains(player)) { //If you're in it but it hasn't started, be patient cm.sendOk("You have already registered for the expedition. Please wait for #r" + expedition.getLeader().getName() + "#k to begin the expedition."); cm.dispose(); } else { //If you aren't in it, you're going to get added cm.sendOk(expedition.addMember(cm.getPlayer())); cm.dispose(); } } else if (expedition.isInProgress()) { //Only if the expedition is in progress if (expedition.contains(player)) { //If you're registered, warp you in var eim = em.getInstance(expedName + player.getClient().getChannel()); if(eim.getIntProperty("canJoin") == 1) { eim.registerPlayer(player); } else { cm.sendOk("Your expedition already started the battle against " + expedBoss + ". Lets pray for those brave souls."); } cm.dispose(); } else { //If you're not in by now, tough luck cm.sendOk("Another expedition has taken the initiative to challenge " + expedBoss + ", lets pray for those brave souls."); cm.dispose(); } } } else if (status == 1) { if (selection == 1) { if (!cm.haveItem(expedItem)) { cm.sendOk("As the expedition leader, you must have on your inventory a #b#t" + expedItem + "##k to battle " + expedBoss + "!"); cm.dispose(); return; } expedition = cm.getExpedition(exped); if(expedition != null) { cm.sendOk("Someone already taken the initiative to be the leader of the expedition. Try joining them!"); cm.dispose(); return; } cm.createExpedition(exped); cm.sendOk("The #r" + expedBoss + " Expedition#k has been created.\r\n\r\nTalk to me again to view the current team, or start the fight!"); cm.dispose(); return; } else if (selection == 2) { cm.sendOk("Sure, not everyone's up to challenging " + expedBoss + "."); cm.dispose(); return; } } else if (status == 2) { if (selection == 1) { if (expedition == null) { cm.sendOk("The expedition could not be loaded."); cm.dispose(); return; } var size = expedition.getMembers().size(); if (size == 1) { cm.sendOk("You are the only member of the expedition."); cm.dispose(); return; } var text = "The following members make up your expedition (Click on them to expel them):\r\n"; text += "\r\n\t\t1." + expedition.getLeader().getName(); for (var i = 1; i < size; i++) { text += "\r\n#b#L" + (i + 1) + "#" + (i + 1) + ". " + expedition.getMembers().get(i).getName() + "#l\n"; } cm.sendSimple(text); status = 6; } else if (selection == 2) { var min = exped.getMinSize(); var size = expedition.getMembers().size(); if (size < min) { cm.sendOk("You need at least " + min + " players registered in your expedition."); cm.dispose(); return; } cm.sendOk("The expedition will begin and you will now be escorted to the #b" + expedMap + "#k."); status = 4; } else if (selection == 3) { player.getMap().broadcastMessage(MaplePacketCreator.serverNotice(6, expedition.getLeader().getName() + " has ended the expedition.")); cm.endExpedition(expedition); cm.sendOk("The expedition has now ended. Sometimes the best strategy is to run away."); cm.dispose(); return; } } else if (status == 4) { if (em == null) { cm.sendOk("The event could not be initialized, please report this on the forum."); cm.dispose(); return; } em.setProperty("leader", player.getName()); em.setProperty("channel", player.getClient().getChannel()); if(!em.startInstance(expedition)) { cm.sendOk("Another expedition has taken the initiative to challenge " + expedBoss + ", lets pray for those brave souls."); cm.dispose(); return; } cm.dispose(); return; } else if (status == 6) { if (selection > 0) { var banned = expedition.getMembers().get(selection - 1); expedition.ban(banned); cm.sendOk("You have banned " + banned.getName() + " from the expedition."); cm.dispose(); } else { cm.sendSimple(list); status = 2; } } } }
lightryuzaki/project1
scripts/npc/2030013.js
JavaScript
gpl-2.0
8,217
<?php N2Loader::import("libraries.slider.abstract", "smartslider"); class N2SmartsliderSlidersModel extends N2Model { public function __construct() { parent::__construct("nextend2_smartslider3_sliders"); } public function get($id) { return $this->db->queryRow("SELECT * FROM " . $this->db->tableName . " WHERE id = :id", array( ":id" => $id )); } public function refreshCache($sliderid) { N2Cache::clearGroup(N2SmartSliderAbstract::getCacheId($sliderid)); N2Cache::clearGroup(N2SmartSliderAbstract::getAdminCacheId($sliderid)); self::markChanged($sliderid); } /** * @return mixed */ public function getAll($orderBy = 'time', $orderByDirection = 'DESC') { return $this->db->findAll($orderBy . ' ' . $orderByDirection); } public static function renderAddForm($data = array()) { return self::editForm($data); } public static function renderEditForm($slider) { $data = json_decode($slider['params'], true); if ($data == null) $data = array(); $data['title'] = $slider['title']; $data['type'] = $slider['type']; return self::editForm($data); } private static function editForm($data = array()) { $configurationXmlFile = dirname(__FILE__) . '/forms/slider.xml'; N2Loader::import('libraries.form.form'); $form = new N2Form(N2Base::getApplication('smartslider') ->getApplicationType('backend')); $form->set('class', 'nextend-smart-slider-admin'); $form->loadArray($data); $form->loadXMLFile($configurationXmlFile); echo $form->render('slider'); N2Loader::import('libraries.form.element.url'); N2JS::addFirstCode('nextend.NextendElementUrlParams=' . N2ElementUrl::getNextendElementUrlParameters() . ';'); return $data; } public static function renderImportByUploadForm() { $configurationXmlFile = dirname(__FILE__) . '/forms/import/upload.xml'; N2Loader::import('libraries.form.form'); $form = new N2Form(N2Base::getApplication('smartslider') ->getApplicationType('backend')); $form->loadXMLFile($configurationXmlFile); echo $form->render('slider'); } public static function renderRestoreByUploadForm() { $configurationXmlFile = dirname(__FILE__) . '/forms/import/restore.xml'; N2Loader::import('libraries.form.form'); $form = new N2Form(N2Base::getApplication('smartslider') ->getApplicationType('backend')); $form->loadXMLFile($configurationXmlFile); echo $form->render('slider'); } public static function renderImportFromServerForm() { $configurationXmlFile = dirname(__FILE__) . '/forms/import/server.xml'; N2Loader::import('libraries.form.form'); $form = new N2Form(N2Base::getApplication('smartslider') ->getApplicationType('backend')); $form->loadXMLFile($configurationXmlFile); echo $form->render('slider'); } public static function renderRestoreFromServerForm(){ $configurationXmlFile = dirname(__FILE__) . '/forms/import/restorefromserver.xml'; N2Loader::import('libraries.form.form'); $form = new N2Form(N2Base::getApplication('smartslider') ->getApplicationType('backend')); $form->loadXMLFile($configurationXmlFile); echo $form->render('slider'); } function import($slider) { try { $this->db->insert(array( 'title' => $slider['title'], 'type' => $slider['type'], 'params' => $slider['params']->toJSON(), 'time' => date('Y-m-d H:i:s', N2Platform::getTime()) )); return $this->db->insertId(); } catch (Exception $e) { throw new Exception($e->getMessage()); } } function restore($slider) { if (isset($slider['id']) && $slider['id'] > 0) { $this->delete($slider['id']); try { $this->db->insert(array( 'id' => $slider['id'], 'title' => $slider['title'], 'type' => $slider['type'], 'params' => $slider['params']->toJSON(), 'time' => date('Y-m-d H:i:s', N2Platform::getTime()) )); return $this->db->insertId(); } catch (Exception $e) { throw new Exception($e->getMessage()); } } return $this->import($slider); } /** * @param $sliderId * @param $params N2Data */ function importUpdate($sliderId, $params) { $this->db->update(array( 'params' => $params->toJson() ), array( "id" => $sliderId )); } function create($slider) { if (!isset($slider['title'])) return false; if ($slider['title'] == '') $slider['title'] = n2_('New slider'); $title = $slider['title']; unset($slider['title']); $type = $slider['type']; unset($slider['type']); try { $this->db->insert(array( 'title' => $title, 'type' => $type, 'params' => json_encode($slider), 'time' => date('Y-m-d H:i:s', N2Platform::getTime()) )); return $this->db->insertId(); } catch (Exception $e) { throw new Exception($e->getMessage()); } } function save($id, $slider) { if (!isset($slider['title']) || $id <= 0) return false; if ($slider['title'] == '') $slider['title'] = n2_('New slider'); $title = $slider['title']; unset($slider['title']); $type = $slider['type']; unset($slider['type']); $this->db->update(array( 'title' => $title, 'type' => $type, 'params' => json_encode($slider) ), array( "id" => $id )); self::markChanged($id); return $id; } function delete($id) { $slidesModel = new N2SmartsliderSlidesModel(); $slidesModel->deleteBySlider($id); $this->db->deleteByPk($id); N2Cache::clearGroup(N2SmartSliderAbstract::getCacheId($id)); N2Cache::clearGroup(N2SmartSliderAbstract::getAdminCacheId($id)); self::markChanged($id); } function deleteSlides($id) { $slidesModel = new N2SmartsliderSlidesModel(); $slidesModel->deleteBySlider($id); self::markChanged($id); } function duplicate($id) { $slider = $this->get($id); unset($slider['id']); $slider['title'] .= ' - copy'; $slider['time'] = date('Y-m-d H:i:s', N2Platform::getTime()); try { $this->db->insert($slider); $newSliderId = $this->db->insertId(); } catch (Exception $e) { throw new Exception($e->getMessage()); } if (!$newSliderId) { return false; } $slidesModel = new N2SmartsliderSlidesModel(); foreach ($slidesModel->getAll($id) AS $slide) { $slidesModel->copy($slide['id'], $newSliderId); } return $newSliderId; } function redirectToCreate() { N2Request::redirect($this->appType->router->createUrl(array("sliders/create")), 302, true); } function exportSlider($id) { } function exportSliderAsHTML($id) { } public static function markChanged($sliderid) { N2SmartSliderHelper::getInstance() ->setSliderChanged($sliderid, 1); } }
ttthanhDC/ProjectTeamWP
wp-content/plugins/smart-slider-3/library/smartslider/models/Sliders.php
PHP
gpl-2.0
7,899
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="fr_FR" xml:lang="fr_FR"> <head> <title>Gestion des Templates</title> <link href="css/help.css" rel="stylesheet" type="text/css" /> <meta name="copyright" content="Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved." /> <meta name="license" content="http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL" /> </head> <body> <h1>Gestion des Templates</h1> <p>Le fichier d'aide en local n'est plus int&eacute;gr&eacute;e. Merci d'utiliser la <a href="http://help.joomla.org/index2.php?option=com_content&task=findkey&pop=1&keyref=screen.templates.15">version en ligne</a>.</p> </body> </html>
MarcAntoine-Arnaud/Joomla-for-websites
administrator/help/fr-FR/screen.templates.html
HTML
gpl-2.0
771
/* * $Id: JXFindPanel.java,v 1.11 2005/10/24 13:20:41 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Component; import java.util.regex.Pattern; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; /** * Simple FindPanel for usage in a JXDialog. * * * @author ?? * @author Jeanette Winzenburg */ public class JXFindPanel extends AbstractPatternPanel { public static final String FIND_NEXT_ACTION_COMMAND = "findNext"; public static final String FIND_PREVIOUS_ACTION_COMMAND = "findPrevious"; protected Searchable searchable; protected JCheckBox wrapCheck; protected JCheckBox backCheck; private boolean initialized; public JXFindPanel() { this(null); } public JXFindPanel(Searchable searchable) { setSearchable(searchable); initActions(); } /** * Sets the Searchable targeted of this find widget. * Triggers a search with null pattern to release the old * searchable, if any. * * @param searchable */ public void setSearchable(Searchable searchable) { if ((this.searchable != null) && this.searchable.equals(searchable)) return; Searchable old = this.searchable; if (old != null) { old.search((Pattern) null); } this.searchable = searchable; getPatternModel().setFoundIndex(-1); firePropertyChange("searchable", old, this.searchable); } public void addNotify() { init(); super.addNotify(); } protected void init() { if (initialized) return; initialized = true; initComponents(); build(); bind(); setName(getUIString(SEARCH_TITLE)); } //------------------ support synch the model <--> components protected void bind() { super.bind(); getActionContainerFactory().configureButton(wrapCheck, getAction(PatternModel.MATCH_WRAP_ACTION_COMMAND), null); getActionContainerFactory().configureButton(backCheck, getAction(PatternModel.MATCH_BACKWARDS_ACTION_COMMAND), null); } /** * called from listening to empty property of PatternModel. * * this implementation calls super and additionally synchs the * enabled state of FIND_NEXT_ACTION_COMMAND, FIND_PREVIOUS_ACTION_COMMAND * to !empty. */ @Override protected void refreshEmptyFromModel() { super.refreshEmptyFromModel(); boolean enabled = !getPatternModel().isEmpty(); getAction(FIND_NEXT_ACTION_COMMAND).setEnabled(enabled); getAction(FIND_PREVIOUS_ACTION_COMMAND).setEnabled(enabled); } //--------------------- action callbacks /** * Action callback for Find action. * Find next/previous match using current setting of direction flag. * */ public void match() { doFind(); } /** * Action callback for FindNext action. * Sets direction flag to forward and calls find. */ public void findNext() { getPatternModel().setBackwards(false); doFind(); } /** * Action callback for FindPrevious action. * Sets direction flag to previous and calls find. */ public void findPrevious() { getPatternModel().setBackwards(true); doFind(); } protected void doFind() { if (searchable == null) return; int foundIndex = doSearch(); boolean notFound = (foundIndex == -1) && !getPatternModel().isEmpty(); if (notFound) { if (getPatternModel().isWrapping()) { notFound = doSearch() == -1; } } if (notFound) { showNotFoundMessage(); } else { showFoundMessage(); } } /** * @return */ protected int doSearch() { int foundIndex = searchable.search(getPatternModel().getPattern(), getPatternModel().getFoundIndex(), getPatternModel().isBackwards()); getPatternModel().setFoundIndex(foundIndex); return getPatternModel().getFoundIndex(); } protected void showFoundMessage() { } /** * */ protected void showNotFoundMessage() { JOptionPane.showMessageDialog(this, "Value not found"); } //-------------------------- initial /** * */ protected void initExecutables() { getActionMap().put(FIND_NEXT_ACTION_COMMAND, createBoundAction(FIND_NEXT_ACTION_COMMAND, "findNext")); getActionMap().put(FIND_PREVIOUS_ACTION_COMMAND, createBoundAction(FIND_PREVIOUS_ACTION_COMMAND, "findPrevious")); super.initExecutables(); } //----------------------------- init ui /** create components. * */ protected void initComponents() { super.initComponents(); wrapCheck = new JCheckBox(); backCheck = new JCheckBox(); } protected void build() { Box lBox = new Box(BoxLayout.LINE_AXIS); lBox.add(searchLabel); lBox.add(new JLabel(":")); lBox.add(new JLabel(" ")); lBox.setAlignmentY(Component.TOP_ALIGNMENT); Box rBox = new Box(BoxLayout.PAGE_AXIS); rBox.add(searchField); rBox.add(matchCheck); rBox.add(wrapCheck); rBox.add(backCheck); rBox.setAlignmentY(Component.TOP_ALIGNMENT); setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); add(lBox); add(rBox); } }
charlycoste/TreeD
src/org/jdesktop/swingx/JXFindPanel.java
Java
gpl-2.0
6,637
<?php /* __hello.php Appelle AVANT le handler 'hello' */ // Vérification de sécurité if (!defined("WIKINI_VERSION")) { die ("acc&egrave;s direct interdit"); } echo $this->Header(); echo $this->Format("===== Je vais dire Bonjour !====="); ?> <div class="page">
YesWiki/yeswiki-external-extensions
hello/handlers/page/__hello.php
PHP
gpl-2.0
276
/* Copyright 2005-2009 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks 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. Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #ifndef _itt_shared_malloc_TypeDefinitions_H_ #define _itt_shared_malloc_TypeDefinitions_H_ // Define preprocessor symbols used to determine architecture #if _WIN32||_WIN64 # if defined(_M_AMD64) # define __ARCH_x86_64 1 # elif defined(_M_IA64) # define __ARCH_ipf 1 # elif defined(_M_IX86)||defined(__i386__) // the latter for MinGW support # define __ARCH_x86_32 1 # else # error Unknown processor architecture for Windows # endif # define USE_WINTHREAD 1 #else /* Assume generic Unix */ # if __x86_64__ # define __ARCH_x86_64 1 # elif __ia64__ # define __ARCH_ipf 1 # elif __i386__ || __i386 # define __ARCH_x86_32 1 # else # define __ARCH_other 1 # endif # define USE_PTHREAD 1 #endif // Include files containing declarations of intptr_t and uintptr_t #include <stddef.h> // size_t #if _MSC_VER typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif namespace rml { namespace internal { extern bool original_malloc_found; extern void* (*original_malloc_ptr)(size_t); extern void (*original_free_ptr)(void*); } } // namespaces //! PROVIDE YOUR OWN Customize.h IF YOU FEEL NECESSARY #include "Customize.h" /* * Functions to align an integer down or up to the given power of two, * and test for such an alignment, and for power of two. */ template<typename T> static inline T alignDown(T arg, uintptr_t alignment) { return T( (uintptr_t)arg & ~(alignment-1)); } template<typename T> static inline T alignUp (T arg, uintptr_t alignment) { return T(((uintptr_t)arg+(alignment-1)) & ~(alignment-1)); // /*is this better?*/ return (((uintptr_t)arg-1) | (alignment-1)) + 1; } template<typename T> static inline bool isAligned(T arg, uintptr_t alignment) { return 0==((uintptr_t)arg & (alignment-1)); } static inline bool isPowerOfTwo(uintptr_t arg) { return arg && (0==(arg & (arg-1))); } static inline bool isPowerOfTwoMultiple(uintptr_t arg, uintptr_t divisor) { // Divisor is assumed to be a power of two (which is valid for current uses). MALLOC_ASSERT( isPowerOfTwo(divisor), "Divisor should be a power of two" ); return arg && (0==(arg & (arg-divisor))); } #endif /* _itt_shared_malloc_TypeDefinitions_H_ */
natedahl32/portalclassic
dep/tbb/src/tbbmalloc/TypeDefinitions.h
C
gpl-2.0
3,780
#include "slconfig.h" #if(HAS_MPU9150) //////////////////////////////////////////////////////////////////////////// // // This file is part of MPU9150Lib // // Copyright (c) 2013 Pansenti, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "MPU9150Lib.h" #include "inv_mpu.h" #include "inv_mpu_dmp_motion_driver.h" #include "MPUQuaternion.h" //////////////////////////////////////////////////////////////////////////// // // The functions below are from the InvenSense SDK example code. // // Original copyright notice below: /* $License: Copyright (C) 2011-2012 InvenSense Corporation, All Rights Reserved. See included License.txt for License information. $ */ /* These next two functions converts the orientation matrix (see * gyro_orientation) to a scalar representation for use by the DMP. * NOTE: These functions are borrowed from InvenSense's MPL. */ static inline unsigned short inv_row_2_scale(const signed char *row) { unsigned short b; if (row[0] > 0) b = 0; else if (row[0] < 0) b = 4; else if (row[1] > 0) b = 1; else if (row[1] < 0) b = 5; else if (row[2] > 0) b = 2; else if (row[2] < 0) b = 6; else b = 7; // error return b; } /* The sensors can be mounted onto the board in any orientation. The mounting * matrix seen below tells the MPL how to rotate the raw data from thei * driver(s). * TODO: The following matrices refer to the configuration on an internal test * board at Invensense. If needed, please modify the matrices to match the * chip-to-body matrix for your particular set up. */ static signed char gyro_orientation[9] = { 0, -1, 0, -1, 0, 0, 0, 0, -1}; static inline unsigned short inv_orientation_matrix_to_scalar(const signed char *mtx) { unsigned short scalar; /* XYZ 010_001_000 Identity Matrix XZY 001_010_000 YXZ 010_000_001 YZX 000_010_001 ZXY 001_000_010 ZYX 000_001_010 */ scalar = inv_row_2_scale(mtx); scalar |= inv_row_2_scale(mtx + 3) << 3; scalar |= inv_row_2_scale(mtx + 6) << 6; return scalar; } // //////////////////////////////////////////////////////////////////////////// MPU9150Lib::MPU9150Lib() { // use calibration if available m_useAccelCalibration = true; m_useMagCalibration = true; m_device = 0; } void MPU9150Lib::selectDevice(int device) { m_device = device; } void MPU9150Lib::useAccelCal(boolean useCal) { m_useAccelCalibration = useCal; } void MPU9150Lib::disableAccelCal() { if (!m_useAccelCalibration) return; m_useAccelCalibration = false; m_accelOffset[0] = 0; m_accelOffset[1] = 0; m_accelOffset[2] = 0; mpu_set_accel_bias(m_accelOffset); } void MPU9150Lib::useMagCal(boolean useCal) { m_useMagCalibration = useCal; } boolean MPU9150Lib::init(int mpuRate, int magMix, int magRate, int lpf) { struct int_param_s int_param; int result; mpu_select_device(m_device); dmp_select_device(m_device); if (magRate > 100) return false; // rate must be less than or equal to 100Hz if (magRate < 1) return false; m_magInterval = (unsigned long)(1000 / magRate); // record mag interval m_lastMagSample = millis(); if (mpuRate > 1000) return false; if (mpuRate < 1) return false; m_magMix = magMix; m_lastDMPYaw = 0; m_lastYaw = 0; // get calibration data if it's there if (calLibRead(m_device, &m_calData)) { // use calibration data if it's there and wanted m_useMagCalibration &= m_calData.magValid == 1; m_useAccelCalibration &= m_calData.accelValid == 1; // Process calibration data for runtime if (m_useMagCalibration) { m_magXOffset = (short)(((long)m_calData.magMaxX + (long)m_calData.magMinX) / 2); m_magXRange = m_calData.magMaxX - m_magXOffset; m_magYOffset = (short)(((long)m_calData.magMaxY + (long)m_calData.magMinY) / 2); m_magYRange = m_calData.magMaxY - m_magYOffset; m_magZOffset = (short)(((long)m_calData.magMaxZ + (long)m_calData.magMinZ) / 2); m_magZRange = m_calData.magMaxZ - m_magZOffset; } if (m_useAccelCalibration) { m_accelOffset[0] = -((long)m_calData.accelMaxX + (long)m_calData.accelMinX) / 2; m_accelOffset[1] = -((long)m_calData.accelMaxY + (long)m_calData.accelMinY) / 2; m_accelOffset[2] = -((long)m_calData.accelMaxZ + (long)m_calData.accelMinZ) / 2; mpu_set_accel_bias(m_accelOffset); m_accelXRange = m_calData.accelMaxX + (short)m_accelOffset[0]; m_accelYRange = m_calData.accelMaxY + (short)m_accelOffset[1]; m_accelZRange = m_calData.accelMaxZ + (short)m_accelOffset[2]; } } else { m_useMagCalibration = false; m_useAccelCalibration = false; } #ifdef MPULIB_DEBUG if (m_useMagCalibration) Serial.println("log(\"Using mag cal\")"); if (m_useAccelCalibration) Serial.println("log(\"Using accel cal\")"); #endif mpu_init_structures(); // Not using interrupts so set up this structure to keep the driver happy int_param.cb = NULL; int_param.pin = 0; int_param.lp_exit = 0; int_param.active_low = 1; result = mpu_init(&int_param); if (result != 0) { #ifdef MPULIB_DEBUG Serial.print("log(\"mpu_init failed with code: "); Serial.print(result); Serial.println("\")"); #endif return false; } mpu_set_sensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS); // enable all of the sensors mpu_configure_fifo(INV_XYZ_GYRO | INV_XYZ_ACCEL); // get accel and gyro data in the FIFO also #ifdef MPULIB_DEBUG Serial.println("log(\"Loading firmware\")"); #endif if ((result = dmp_load_motion_driver_firmware()) != 0) { // try to load the DMP firmware #ifdef MPULIB_DEBUG Serial.print("log(\"Failed to load dmp firmware: "); Serial.print(result); Serial.println("\")"); #endif return false; } dmp_set_orientation(inv_orientation_matrix_to_scalar(gyro_orientation)); // set up the correct orientation dmp_enable_feature(DMP_FEATURE_6X_LP_QUAT | DMP_FEATURE_SEND_RAW_ACCEL | DMP_FEATURE_SEND_CAL_GYRO | DMP_FEATURE_GYRO_CAL); dmp_set_fifo_rate(mpuRate); if (mpu_set_dmp_state(1) != 0) { #ifdef MPULIB_DEBUG Serial.println("log(\"mpu_set_dmp_state failed\")"); #endif return false; } mpu_set_sample_rate(mpuRate); // set the update rate mpu_set_compass_sample_rate(magRate); // set the compass update rate to match if (lpf != 0) mpu_set_lpf(lpf); // set the low pass filter return true; } boolean MPU9150Lib::read() { short intStatus; int result; short sensors; unsigned char more; unsigned long timestamp; mpu_select_device(m_device); dmp_select_device(m_device); mpu_get_int_status(&intStatus); // get the current MPU state if ((intStatus & (MPU_INT_STATUS_DMP | MPU_INT_STATUS_DMP_0)) != (MPU_INT_STATUS_DMP | MPU_INT_STATUS_DMP_0)) return false; // get the data from the fifo if ((result = dmp_read_fifo(m_rawGyro, m_rawAccel, m_rawQuaternion, &timestamp, &sensors, &more)) != 0) { return false; } // got the fifo data so now get the mag data if it's time if ((millis() - m_lastMagSample) >= m_magInterval) { if ((result = mpu_get_compass_reg(m_rawMag, &timestamp)) != 0) { #ifdef MPULIB_DEBUG Serial.print("log(\"Failed to read compass: "); Serial.print(result); Serial.println("\")"); #endif return false; } // *** Note mag axes are changed here to align with gyros: Y = -X, X = Y m_lastMagSample = millis(); if (m_useMagCalibration) { m_calMag[VEC3_Y] = -(short)(((long)(m_rawMag[VEC3_X] - m_magXOffset) * (long)SENSOR_RANGE) / (long)m_magXRange); m_calMag[VEC3_X] = (short)(((long)(m_rawMag[VEC3_Y] - m_magYOffset) * (long)SENSOR_RANGE) / (long)m_magYRange); m_calMag[VEC3_Z] = (short)(((long)(m_rawMag[VEC3_Z] - m_magZOffset) * (long)SENSOR_RANGE) / (long)m_magZRange); } else { m_calMag[VEC3_Y] = -m_rawMag[VEC3_X]; m_calMag[VEC3_X] = m_rawMag[VEC3_Y]; m_calMag[VEC3_Z] = m_rawMag[VEC3_Z]; } } // got the raw data - now process m_dmpQuaternion[QUAT_W] = (float)m_rawQuaternion[QUAT_W]; // get float version of quaternion m_dmpQuaternion[QUAT_X] = (float)m_rawQuaternion[QUAT_X]; m_dmpQuaternion[QUAT_Y] = (float)m_rawQuaternion[QUAT_Y]; m_dmpQuaternion[QUAT_Z] = (float)m_rawQuaternion[QUAT_Z]; MPUQuaternionNormalize(m_dmpQuaternion); // and normalize MPUQuaternionQuaternionToEuler(m_dmpQuaternion, m_dmpEulerPose); // Scale accel data if (m_useAccelCalibration) { /* m_calAccel[VEC3_X] = -(short)((((long)m_rawAccel[VEC3_X] + m_accelOffset[0]) * (long)SENSOR_RANGE) / (long)m_accelXRange); m_calAccel[VEC3_Y] = (short)((((long)m_rawAccel[VEC3_Y] + m_accelOffset[1]) * (long)SENSOR_RANGE) / (long)m_accelYRange); m_calAccel[VEC3_Z] = (short)((((long)m_rawAccel[VEC3_Z] + m_accelOffset[2]) * (long)SENSOR_RANGE) / (long)m_accelZRange); */ if (m_rawAccel[VEC3_X] >= 0) m_calAccel[VEC3_X] = -(short)((((long)m_rawAccel[VEC3_X]) * (long)SENSOR_RANGE) / (long)m_calData.accelMaxX); else m_calAccel[VEC3_X] = -(short)((((long)m_rawAccel[VEC3_X]) * (long)SENSOR_RANGE) / -(long)m_calData.accelMinX); if (m_rawAccel[VEC3_Y] >= 0) m_calAccel[VEC3_Y] = (short)((((long)m_rawAccel[VEC3_Y]) * (long)SENSOR_RANGE) / (long)m_calData.accelMaxY); else m_calAccel[VEC3_Y] = (short)((((long)m_rawAccel[VEC3_Y]) * (long)SENSOR_RANGE) / -(long)m_calData.accelMinY); if (m_rawAccel[VEC3_Z] >= 0) m_calAccel[VEC3_Z] = (short)((((long)m_rawAccel[VEC3_Z]) * (long)SENSOR_RANGE) / (long)m_calData.accelMaxZ); else m_calAccel[VEC3_Z] = (short)((((long)m_rawAccel[VEC3_Z]) * (long)SENSOR_RANGE) / -(long)m_calData.accelMinZ); } else { m_calAccel[VEC3_X] = -m_rawAccel[VEC3_X]; m_calAccel[VEC3_Y] = m_rawAccel[VEC3_Y]; m_calAccel[VEC3_Z] = m_rawAccel[VEC3_Z]; } dataFusion(); return true; } void MPU9150Lib::dataFusion() { float qMag[4]; float deltaDMPYaw, deltaMagYaw; float newMagYaw, newYaw; float temp1[4], unFused[4]; float unFusedConjugate[4]; // *** NOTE *** pitch direction swapped here m_fusedEulerPose[VEC3_X] = m_dmpEulerPose[VEC3_X]; m_fusedEulerPose[VEC3_Y] = -m_dmpEulerPose[VEC3_Y]; m_fusedEulerPose[VEC3_Z] = 0; MPUQuaternionEulerToQuaternion(m_fusedEulerPose, unFused); // create a new quaternion deltaDMPYaw = -m_dmpEulerPose[VEC3_Z] + m_lastDMPYaw; // calculate change in yaw from dmp m_lastDMPYaw = m_dmpEulerPose[VEC3_Z]; // update that qMag[QUAT_W] = 0; qMag[QUAT_X] = m_calMag[VEC3_X]; qMag[QUAT_Y] = m_calMag[VEC3_Y]; qMag[QUAT_Z] = m_calMag[VEC3_Z]; // Tilt compensate mag with the unfused data (i.e. just roll and pitch with yaw 0) MPUQuaternionConjugate(unFused, unFusedConjugate); MPUQuaternionMultiply(qMag, unFusedConjugate, temp1); MPUQuaternionMultiply(unFused, temp1, qMag); // Now fuse this with the dmp yaw gyro information newMagYaw = -atan2(qMag[QUAT_Y], qMag[QUAT_X]); if (newMagYaw != newMagYaw) { // check for nAn #ifdef MPULIB_DEBUG // Serial.println("***nAn\n"); #endif return; // just ignore in this case } if (newMagYaw < 0) newMagYaw = 2.0f * (float)M_PI + newMagYaw; // need 0 <= newMagYaw <= 2*PI newYaw = m_lastYaw + deltaDMPYaw; // compute new yaw from change if (newYaw > (2.0f * (float)M_PI)) // need 0 <= newYaw <= 2*PI newYaw -= 2.0f * (float)M_PI; if (newYaw < 0) newYaw += 2.0f * (float)M_PI; deltaMagYaw = newMagYaw - newYaw; // compute difference if (deltaMagYaw >= (float)M_PI) deltaMagYaw = deltaMagYaw - 2.0f * (float)M_PI; if (deltaMagYaw <= -(float)M_PI) deltaMagYaw = (2.0f * (float)M_PI + deltaMagYaw); if (m_magMix > 0) { newYaw += deltaMagYaw / m_magMix; // apply some of the correction if (newYaw > (2.0f * (float)M_PI)) // need 0 <= newYaw <= 2*PI newYaw -= 2.0f * (float)M_PI; if (newYaw < 0) newYaw += 2.0f * (float)M_PI; } m_lastYaw = newYaw; if (newYaw > (float)M_PI) newYaw -= 2.0f * (float)M_PI; m_fusedEulerPose[VEC3_Z] = newYaw; // fill in output yaw value MPUQuaternionEulerToQuaternion(m_fusedEulerPose, m_fusedQuaternion); } void MPU9150Lib::printQuaternion(long *quat) { Serial.print("w: "); Serial.print(quat[QUAT_W]); Serial.print(" x: "); Serial.print(quat[QUAT_X]); Serial.print(" y: "); Serial.print(quat[QUAT_Y]); Serial.print(" z: "); Serial.print(quat[QUAT_Z]); } void MPU9150Lib::printQuaternion(float *quat) { Serial.print("w: "); Serial.print(quat[QUAT_W]); Serial.print(" x: "); Serial.print(quat[QUAT_X]); Serial.print(" y: "); Serial.print(quat[QUAT_Y]); Serial.print(" z: "); Serial.print(quat[QUAT_Z]); } void MPU9150Lib::printVector(short *vec) { Serial.print("x: "); Serial.print(vec[VEC3_X]); Serial.print(" y: "); Serial.print(vec[VEC3_Y]); Serial.print(" z: "); Serial.print(vec[VEC3_Z]); } void MPU9150Lib::printVector(float *vec) { Serial.print("x: "); Serial.print(vec[VEC3_X]); Serial.print(" y: "); Serial.print(vec[VEC3_Y]); Serial.print(" z: "); Serial.print(vec[VEC3_Z]); } void MPU9150Lib::printAngles(float *vec) { Serial.print("x: "); Serial.print(vec[VEC3_X] * RAD_TO_DEGREE); Serial.print(" y: "); Serial.print(vec[VEC3_Y] * RAD_TO_DEGREE); Serial.print(" z: "); Serial.print(vec[VEC3_Z] * RAD_TO_DEGREE); } #endif
MysteriousChanger/slrov
MPU9150Lib.cpp
C++
gpl-2.0
15,596
.saswp-course-loop{ margin-top:20px; }
MinnPost/minnpost-wordpress
wp-content/plugins/schema-and-structured-data-for-wp/modules/gutenberg/assets/css/course.css
CSS
gpl-2.0
44
# # Makefile for the Marvell Gigabit Ethernet driver # ifneq ($(MACHINE),) include $(srctree)/$(MACHINE)/config/mvRules.mk endif obj-$(CONFIG_MV_ETHERNET) += mv_netdev.o mv_ethernet.o obj-$(CONFIG_MV_ETH_PROC) += mv_eth_proc.o obj-$(CONFIG_MV_GATEWAY) += mv_gateway.o obj-$(CONFIG_MV_GTW_IGMP) += mv_gtw_igmp.o obj-$(CONFIG_MV_ETH_TOOL) += mv_eth_tool.o
sancome/linux-3.x
arch/arm/plat-armada/mv_drivers_lsp/mv_network/mv_ethernet/Makefile
Makefile
gpl-2.0
357
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for A_Asset_Info_Ins * @author Adempiere (generated) * @version Release 3.6.0LTS */ public interface I_A_Asset_Info_Ins { /** TableName=A_Asset_Info_Ins */ public static final String Table_Name = "A_Asset_Info_Ins"; /** AD_Table_ID=53135 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 7 - System - Client - Org */ BigDecimal accessLevel = BigDecimal.valueOf(7); /** Load Meta Data */ /** Column name A_Asset_ID */ public static final String COLUMNNAME_A_Asset_ID = "A_Asset_ID"; /** Set Asset. * Asset used internally or by customers */ public void setA_Asset_ID (int A_Asset_ID); /** Get Asset. * Asset used internally or by customers */ public int getA_Asset_ID(); /** Column name A_Asset_Info_Ins_ID */ public static final String COLUMNNAME_A_Asset_Info_Ins_ID = "A_Asset_Info_Ins_ID"; /** Set Asset Info Ins. */ public void setA_Asset_Info_Ins_ID (int A_Asset_Info_Ins_ID); /** Get Asset Info Ins. */ public int getA_Asset_Info_Ins_ID(); /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name A_Ins_Premium */ public static final String COLUMNNAME_A_Ins_Premium = "A_Ins_Premium"; /** Set Insurance Premium */ public void setA_Ins_Premium (BigDecimal A_Ins_Premium); /** Get Insurance Premium */ public BigDecimal getA_Ins_Premium(); /** Column name A_Insurance_Co */ public static final String COLUMNNAME_A_Insurance_Co = "A_Insurance_Co"; /** Set Insurance Company */ public void setA_Insurance_Co (String A_Insurance_Co); /** Get Insurance Company */ public String getA_Insurance_Co(); /** Column name A_Ins_Value */ public static final String COLUMNNAME_A_Ins_Value = "A_Ins_Value"; /** Set Insured Value */ public void setA_Ins_Value (BigDecimal A_Ins_Value); /** Get Insured Value */ public BigDecimal getA_Ins_Value(); /** Column name A_Policy_No */ public static final String COLUMNNAME_A_Policy_No = "A_Policy_No"; /** Set Policy Number */ public void setA_Policy_No (String A_Policy_No); /** Get Policy Number */ public String getA_Policy_No(); /** Column name A_Renewal_Date */ public static final String COLUMNNAME_A_Renewal_Date = "A_Renewal_Date"; /** Set Policy Renewal Date */ public void setA_Renewal_Date (Timestamp A_Renewal_Date); /** Get Policy Renewal Date */ public Timestamp getA_Renewal_Date(); /** Column name A_Replace_Cost */ public static final String COLUMNNAME_A_Replace_Cost = "A_Replace_Cost"; /** Set Replacement Costs */ public void setA_Replace_Cost (BigDecimal A_Replace_Cost); /** Get Replacement Costs */ public BigDecimal getA_Replace_Cost(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name Text */ public static final String COLUMNNAME_Text = "Text"; /** Set Text */ public void setText (String Text); /** Get Text */ public String getText(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); }
arthurmelo88/palmetalADP
adempiere_360/base/src/org/compiere/model/I_A_Asset_Info_Ins.java
Java
gpl-2.0
5,952
/* * Copyright (c) 2015, 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 com.sun.javafx.scene.control.behavior; import javafx.collections.ObservableList; import javafx.scene.control.Cell; import javafx.scene.control.Control; import javafx.scene.control.TableColumnBase; import javafx.scene.control.TablePositionBase; import javafx.scene.control.TableSelectionModel; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import java.util.List; public abstract class TableRowBehaviorBase<T extends Cell> extends CellBehaviorBase<T> { /*************************************************************************** * * * Constructors * * * **************************************************************************/ public TableRowBehaviorBase(T control) { super(control); } /*************************************************************************** * * * Public API * * * **************************************************************************/ @Override public void mousePressed(MouseEvent e) { // we only care about clicks to the right of the right-most column if (! isClickPositionValid(e.getX(), e.getY())) return; super.mousePressed(e); } @Override protected abstract TableSelectionModel<?> getSelectionModel(); protected abstract TablePositionBase<?> getFocusedCell(); protected abstract ObservableList getVisibleLeafColumns(); /*************************************************************************** * * * Private implementation * * * **************************************************************************/ @Override protected void doSelect(final double x, final double y, final MouseButton button, final int clickCount, final boolean shiftDown, final boolean shortcutDown) { final Control table = getCellContainer(); if (table == null) return; // if the user has clicked on the disclosure node, we do nothing other // than expand/collapse the tree item (if applicable). We do not do editing! if (handleDisclosureNode(x,y)) { return; } final TableSelectionModel<?> sm = getSelectionModel(); if (sm == null || sm.isCellSelectionEnabled()) return; final int index = getIndex(); final boolean isAlreadySelected = sm.isSelected(index); if (clickCount == 1) { // we only care about clicks to the right of the right-most column if (! isClickPositionValid(x, y)) return; // In the case of clicking to the right of the rightmost // TreeTableCell, we should still support selection, so that // is what we are doing here. if (isAlreadySelected && shortcutDown) { sm.clearSelection(index); } else { if (shortcutDown) { sm.select(getIndex()); } else if (shiftDown) { // we add all rows between the current focus and // this row (inclusive) to the current selection. TablePositionBase<?> anchor = getAnchor(table, getFocusedCell()); final int anchorRow = anchor.getRow(); selectRows(anchorRow, index); } else { simpleSelect(button, clickCount, shortcutDown); } } } else { simpleSelect(button, clickCount, shortcutDown); } } @Override protected boolean isClickPositionValid(final double x, final double y) { // get width of all visible columns (we only care about clicks to the // right of the right-most column) List<TableColumnBase<T, ?>> columns = getVisibleLeafColumns(); double width = 0.0; for (int i = 0; i < columns.size(); i++) { width += columns.get(i).getWidth(); } return x > width; } }
teamfx/openjfx-10-dev-rt
modules/javafx.controls/src/main/java/com/sun/javafx/scene/control/behavior/TableRowBehaviorBase.java
Java
gpl-2.0
5,769
<?php namespace Google\AdsApi\AdWords\v201705\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ class SharedCriterionError extends \Google\AdsApi\AdWords\v201705\cm\ApiError { /** * @var string $reason */ protected $reason = null; /** * @param string $fieldPath * @param \Google\AdsApi\AdWords\v201705\cm\FieldPathElement[] $fieldPathElements * @param string $trigger * @param string $errorString * @param string $ApiErrorType * @param string $reason */ public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $ApiErrorType = null, $reason = null) { parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString, $ApiErrorType); $this->reason = $reason; } /** * @return string */ public function getReason() { return $this->reason; } /** * @param string $reason * @return \Google\AdsApi\AdWords\v201705\cm\SharedCriterionError */ public function setReason($reason) { $this->reason = $reason; return $this; } }
renshuki/dfp-manager
vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201705/cm/SharedCriterionError.php
PHP
gpl-2.0
1,162
/* * Copyright (C) 2009-2011 Carl Hetherington <carl@carlh.net> * Copyright (C) 2009-2012 David Robillard <d@drobilla.net> * Copyright (C) 2009-2017 Paul Davis <paul@linuxaudiosystems.com> * Copyright (C) 2013-2017 Robin Gareus <robin@gareus.org> * * 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 <algorithm> #include "pbd/xml++.h" #include "ardour/amp.h" #include "ardour/audioengine.h" #include "ardour/buffer_set.h" #include "ardour/gain_control.h" #include "ardour/io.h" #include "ardour/meter.h" #include "ardour/return.h" #include "ardour/session.h" #include "pbd/i18n.h" using namespace ARDOUR; using namespace PBD; std::string Return::name_and_id_new_return (Session& s, uint32_t& bitslot) { bitslot = s.next_return_id(); return string_compose (_("return %1"), bitslot + 1); } Return::Return (Session& s, bool internal) : IOProcessor (s, (internal ? false : true), false, name_and_id_new_return (s, _bitslot), "", DataType::AUDIO, true) , _metering (false) { /* never muted */ boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation), time_domain())); _gain_control = boost::shared_ptr<GainControl> (new GainControl (_session, Evoral::Parameter (GainAutomation), gl)); add_control (_gain_control); _amp.reset (new Amp (_session, X_("Fader"), _gain_control, true)); _meter.reset (new PeakMeter (_session, name())); } Return::~Return () { _session.unmark_return_id (_bitslot); } XMLNode& Return::state() { XMLNode& node = IOProcessor::state (); node.set_property ("type", "return"); node.set_property ("bitslot", _bitslot); return node; } int Return::set_state (const XMLNode& node, int version) { XMLNodeList nlist = node.children(); XMLNodeIterator niter; const XMLNode* insert_node = &node; /* Return has regular IO automation (gain, pan) */ for (niter = nlist.begin(); niter != nlist.end(); ++niter) { if ((*niter)->name() == "IOProcessor") { insert_node = *niter; } else if ((*niter)->name() == X_("Automation")) { // _io->set_automation_state (*(*niter), Evoral::Parameter(GainAutomation)); } } IOProcessor::set_state (*insert_node, version); if (!node.property ("ignore-bitslot")) { uint32_t bitslot; if (node.get_property ("bitslot", bitslot)) { _session.unmark_return_id (_bitslot); _bitslot = bitslot; _session.mark_return_id (_bitslot); } else { _bitslot = _session.next_return_id(); } } return 0; } void Return::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample, double speed, pframes_t nframes, bool) { if (!check_active() || (_input->n_ports() == ChanCount::ZERO)) { return; } _input->collect_input (bufs, nframes, _configured_input); bufs.set_count(_configured_output); // Can't automate gain for sends or returns yet because we need different buffers // so that we don't overwrite the main automation data for the route amp // _amp->setup_gain_automation (start_sample, end_sample, nframes); _amp->run (bufs, start_sample, end_sample, speed, nframes, true); if (_metering) { if (_amp->gain_control()->get_value() == 0) { _meter->reset(); } else { _meter->run (bufs, start_sample, end_sample, speed, nframes, true); } } } bool Return::can_support_io_configuration (const ChanCount& in, ChanCount& out) { out = in + _input->n_ports(); return true; } bool Return::configure_io (ChanCount in, ChanCount out) { if (out != in + _input->n_ports()) { return false; } // Ensure there are enough buffers (since we add some) if (_session.get_scratch_buffers(in).count() < out) { Glib::Threads::Mutex::Lock em (_session.engine().process_lock()); IO::PortCountChanged(out); } Processor::configure_io(in, out); return true; }
Ardour/ardour
libs/ardour/return.cc
C++
gpl-2.0
4,409
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. 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. * * 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. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.backend.mysql.nio.handler; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.backend.BackendConnection; import io.mycat.config.ErrorCode; import io.mycat.net.mysql.ErrorPacket; import io.mycat.server.NonBlockingSession; import io.mycat.util.StringUtil; /** * @author mycat */ abstract class MultiNodeHandler implements ResponseHandler, Terminatable { private static final Logger LOGGER = LoggerFactory .getLogger(MultiNodeHandler.class); protected final ReentrantLock lock = new ReentrantLock(); protected final NonBlockingSession session; private AtomicBoolean isFailed = new AtomicBoolean(false); protected volatile String error; protected byte packetId; protected final AtomicBoolean errorRepsponsed = new AtomicBoolean(false); public MultiNodeHandler(NonBlockingSession session) { if (session == null) { throw new IllegalArgumentException("session is null!"); } this.session = session; } public void setFail(String errMsg) { isFailed.set(true); error = errMsg; } public boolean isFail() { return isFailed.get(); } private int nodeCount; private Runnable terminateCallBack; @Override public void terminate(Runnable terminateCallBack) { boolean zeroReached = false; lock.lock(); try { if (nodeCount > 0) { this.terminateCallBack = terminateCallBack; } else { zeroReached = true; } } finally { lock.unlock(); } if (zeroReached) { terminateCallBack.run(); } } protected boolean canClose(BackendConnection conn, boolean tryErrorFinish) { // realse this connection if safe session.releaseConnectionIfSafe(conn, LOGGER.isDebugEnabled(), false); boolean allFinished = false; if (tryErrorFinish) { allFinished = this.decrementCountBy(1); this.tryErrorFinished(allFinished); } return allFinished; } protected void decrementCountToZero() { Runnable callback; lock.lock(); try { nodeCount = 0; callback = this.terminateCallBack; this.terminateCallBack = null; } finally { lock.unlock(); } if (callback != null) { callback.run(); } } public void connectionError(Throwable e, BackendConnection conn) { final boolean canClose = decrementCountBy(1); // 需要把Throwable e的错误信息保存下来(setFail()), 否则会导致响应 //null信息,结果mysql命令行等客户端查询结果是"Query OK"!! // @author Uncle-pan // @since 2016-03-26 if(canClose){ setFail("backend connect: "+e); } LOGGER.warn("backend connect", e); this.tryErrorFinished(canClose); } public void errorResponse(byte[] data, BackendConnection conn) { session.releaseConnectionIfSafe(conn, LOGGER.isDebugEnabled(), false); ErrorPacket err = new ErrorPacket(); err.read(data); String errmsg = new String(err.message); this.setFail(errmsg); LOGGER.warn("error response from " + conn + " err " + errmsg + " code:" + err.errno); this.tryErrorFinished(this.decrementCountBy(1)); } public boolean clearIfSessionClosed(NonBlockingSession session) { if (session.closed()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("session closed ,clear resources " + session); } session.clearResources(true); this.clearResources(); return true; } else { return false; } } protected boolean decrementCountBy(int finished) { boolean zeroReached = false; Runnable callback = null; lock.lock(); try { if (zeroReached = --nodeCount == 0) { callback = this.terminateCallBack; this.terminateCallBack = null; } } finally { lock.unlock(); } if (zeroReached && callback != null) { callback.run(); } return zeroReached; } protected void reset(int initCount) { nodeCount = initCount; isFailed.set(false); error = null; packetId = 0; } protected ErrorPacket createErrPkg(String errmgs) { ErrorPacket err = new ErrorPacket(); lock.lock(); try { err.packetId = ++packetId; } finally { lock.unlock(); } err.errno = ErrorCode.ER_UNKNOWN_ERROR; err.message = StringUtil.encode(errmgs, session.getSource() .getCharset()); return err; } protected void tryErrorFinished(boolean allEnd) { if (allEnd && !session.closed()) { if (errorRepsponsed.compareAndSet(false, true)) { createErrPkg(this.error).write(session.getSource()); } // clear session resources,release all if (LOGGER.isDebugEnabled()) { LOGGER.debug("error all end ,clear session resource "); } if (session.getSource().isAutocommit()) { session.closeAndClearResources(error); } else { session.getSource().setTxInterrupt(this.error); // clear resouces clearResources(); } } } public void connectionClose(BackendConnection conn, String reason) { this.setFail("closed connection:" + reason + " con:" + conn); boolean finished = false; lock.lock(); try { finished = (this.nodeCount == 0); } finally { lock.unlock(); } if (finished == false) { finished = this.decrementCountBy(1); } if (error == null) { error = "back connection closed "; } tryErrorFinished(finished); } public void clearResources() { } }
ongo360/Mycat-Server
src/main/java/io/mycat/backend/mysql/nio/handler/MultiNodeHandler.java
Java
gpl-2.0
6,577
/***************************************************************************** * ft2_font.hpp ***************************************************************************** * Copyright (C) 2003 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <asmax@via.ecp.fr> * Olivier Teulière <ipkiss@via.ecp.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef FT2_FONT_HPP #define FT2_FONT_HPP #include <ft2build.h> #include FT_FREETYPE_H #include FT_GLYPH_H #include <string> #include <map> #include "generic_font.hpp" class UString; /// Freetype2 font class FT2Font: public GenericFont { public: FT2Font( intf_thread_t *pIntf, const string &rName, int size ); virtual ~FT2Font(); /// Initialize the object. Returns false if it failed virtual bool init(); /// Render a string on a bitmap. /// If maxWidth != -1, the text is truncated with '...' virtual GenericBitmap *drawString( const UString &rString, uint32_t color, int maxWidth = -1 ) const; /// Get the text height virtual int getSize() const { return m_height; } private: typedef struct { FT_Glyph m_glyph; FT_BBox m_size; int m_index; int m_advance; } Glyph_t; typedef map<uint32_t,Glyph_t> GlyphMap_t; /// File name const string m_name; /// Buffer to store the font void *m_buffer; /// Pixel size of the font int m_size; /// Handle to FT library FT_Library m_lib; /// Font face FT_Face m_face; /// Font metrics int m_height, m_ascender, m_descender; /// Glyph cache mutable GlyphMap_t m_glyphCache; /// Get the glyph corresponding to the given code Glyph_t &getGlyph( uint32_t code ) const; }; #endif
squadette/vlc
modules/gui/skins2/src/ft2_font.hpp
C++
gpl-2.0
2,646
package org.semanticweb.HermiT.reasoner; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.semanticweb.HermiT.datalog.ConjunctiveQuery; import org.semanticweb.HermiT.datalog.DatalogEngine; import org.semanticweb.HermiT.datalog.QueryResultCollector; import org.semanticweb.HermiT.model.Atom; import org.semanticweb.HermiT.model.AtomicConcept; import org.semanticweb.HermiT.model.AtomicRole; import org.semanticweb.HermiT.model.DLPredicate; import org.semanticweb.HermiT.model.Individual; import org.semanticweb.HermiT.model.Term; import org.semanticweb.HermiT.model.Variable; public class DatalogEngineTest extends AbstractReasonerTest { public DatalogEngineTest(String name) { super(name); } public void testBasic() throws Exception { loadOntologyWithAxioms( "SubClassOf( ObjectSomeValuesFrom( :R :A ) :A )"+LB+ "SubClassOf( ObjectSomeValuesFrom( :R :B ) :B )"+LB+ "SubClassOf( ObjectIntersectionOf( :A :B ) :C )"+LB+ "ClassAssertion( :A :a )"+LB+ "ObjectPropertyAssertion( :R :b :a )"+LB+ "ObjectPropertyAssertion( :R :c :b )"+LB+ "ObjectPropertyAssertion( :R :d :c )"+LB+ "ClassAssertion( :B :k )"+LB+ "ObjectPropertyAssertion( :R :l :k )"+LB+ "ObjectPropertyAssertion( :R :m :l )"+LB+ "ObjectPropertyAssertion( :R :c :m )"+LB+ "ObjectPropertyAssertion( :R :n :c )" ); createReasoner(); DatalogEngine datalogEngine=new DatalogEngine(m_reasoner.getDLOntology()); QueryChecker queryChecker=new QueryChecker(); new ConjunctiveQuery(datalogEngine, AS( A(CN("A"),V("X")) ), TS( V("X") ) ).evaluate(queryChecker); queryChecker. add(I("a")). add(I("b")). add(I("c")). add(I("d")). add(I("n")). assertEquals(); new ConjunctiveQuery(datalogEngine, AS( A(CN("B"),V("X")) ), TS( V("X") ) ).evaluate(queryChecker); queryChecker. add(I("c")). add(I("d")). add(I("k")). add(I("l")). add(I("m")). add(I("n")). assertEquals(); new ConjunctiveQuery(datalogEngine, AS( A(CN("C"),V("X")) ), TS( V("X") ) ).evaluate(queryChecker); queryChecker. add(I("c")). add(I("d")). add(I("n")). assertEquals(); } public void testEquality() throws Exception { loadOntologyWithAxioms( "FunctionalObjectProperty( :R )"+LB+ "ObjectPropertyAssertion( :R :b :a )"+LB+ "ObjectPropertyAssertion( :R :b :c )"+LB+ "ObjectPropertyAssertion( :R :d :c )"+LB+ "ObjectPropertyAssertion( :R :d :e )"+LB+ "ObjectPropertyAssertion( :R :f :e )"+LB+ "ObjectPropertyAssertion( :R :f :g )" ); createReasoner(); DatalogEngine datalogEngine=new DatalogEngine(m_reasoner.getDLOntology()); datalogEngine.materialize(); assertContainsAll( datalogEngine.getEquivalenceClass(I("a")), TS( I("a"), I("c"), I("e"), I("g") ) ); QueryChecker queryChecker=new QueryChecker(); new ConjunctiveQuery(datalogEngine, AS( A(R("R"),V("X"),V("Y")) ), TS( V("X"),V("Y") ) ).evaluate(queryChecker); queryChecker. add(I("b"),datalogEngine.getRepresentative(I("a"))). add(I("d"),datalogEngine.getRepresentative(I("a"))). add(I("f"),datalogEngine.getRepresentative(I("a"))). assertEquals(); } public void testQueryWithIndividualsAndEquality() throws Exception { loadOntologyWithAxioms( "ObjectPropertyAssertion( :R :c :b )"+LB+ "ObjectPropertyAssertion( :S :c :a )"+LB+ "SameIndividual( :a :b )"+LB+ "ObjectPropertyAssertion( :R :d :e )"+LB+ "ObjectPropertyAssertion( :S :d :f )" ); createReasoner(); DatalogEngine datalogEngine=new DatalogEngine(m_reasoner.getDLOntology()); datalogEngine.materialize(); assertContainsAll( datalogEngine.getEquivalenceClass(I("a")), TS( I("a"), I("b") ) ); QueryChecker queryChecker=new QueryChecker(); new ConjunctiveQuery(datalogEngine, AS( A(R("R"),V("X"),I("a")), A(R("S"),V("X"),I("b")) ), TS( V("X") ) ).evaluate(queryChecker); queryChecker. add(I("c")). assertEquals(); } public void testQueryWithIndividuals() throws Exception { loadOntologyWithAxioms( "DLSafeRule(Body(ClassAtom(:D0 Variable(:X))) Head(ClassAtom(:A Variable(:X))))" + LB+ "DLSafeRule(Body(ClassAtom(:D0 Variable(:X))) Head(ClassAtom(:B Variable(:X))))" + LB+ "DLSafeRule(Body(ClassAtom(:A Variable(:X))ClassAtom(:RD0 Variable(:Z))) Head(ClassAtom(:D0 Variable(:Z))))" + LB+ "DLSafeRule(Body(ClassAtom(:A Variable(:X))ClassAtom(:RD0 Variable(:Z))) Head(ObjectPropertyAtom(:R Variable(:X) Variable(:Z))))" + LB+ "ClassAssertion( owl:Thing :a )"+LB+ "ClassAssertion( :RD0 :rd0 )"+LB+ "ClassAssertion( :A :a )" ); createReasoner(); DatalogEngine datalogEngine=new DatalogEngine(m_reasoner.getDLOntology()); datalogEngine.materialize(); QueryChecker queryChecker=new QueryChecker(); new ConjunctiveQuery(datalogEngine, AS( A(R("R"),V("X"),I("a")) ), TS( V("X") ) ).evaluate(queryChecker); queryChecker.assertEquals(); } protected static class AnswerTuple { protected final Term[] m_terms; protected final int m_hashCode; public AnswerTuple(Term[] terms) { m_terms=terms; int hashCode=0; for (Term term : terms) hashCode=hashCode*7+term.hashCode(); m_hashCode=hashCode; } public int hashCode() { return m_hashCode; } public boolean equals(Object that) { if (this==that) return true; if (!(that instanceof AnswerTuple)) return false; AnswerTuple thatTuple=(AnswerTuple)that; int arity=m_terms.length; if (arity!=thatTuple.m_terms.length) return false; for (int index=0;index<arity;++index) if (!m_terms[index].equals(thatTuple.m_terms[index])) return false; return true; } public String toString() { StringBuffer buffer=new StringBuffer(); buffer.append('['); for (int index=0;index<m_terms.length;++index) { if (index!=0) buffer.append(", "); buffer.append(m_terms[index].toString()); } buffer.append(']'); return buffer.toString(); } } protected static class QueryChecker implements QueryResultCollector { protected final Set<AnswerTuple> m_answerTuples; protected final List<AnswerTuple> m_controlTuples; public QueryChecker() { m_answerTuples=new HashSet<AnswerTuple>(); m_controlTuples=new ArrayList<AnswerTuple>(); } public void processResult(ConjunctiveQuery conjunctiveQuery,Term[] result) { m_answerTuples.add(new AnswerTuple(result.clone())); } public QueryChecker add(Term... terms) { m_controlTuples.add(new AnswerTuple(terms)); return this; } public void assertEquals() { assertContainsAll(m_answerTuples,m_controlTuples.toArray(new AnswerTuple[m_controlTuples.size()])); m_answerTuples.clear(); m_controlTuples.clear(); } } protected static Variable V(String name) { return Variable.create(name); } protected static Individual I(String localName) { return Individual.create(NS+localName); } protected static AtomicConcept CN(String localName) { return AtomicConcept.create(NS+localName); } protected static AtomicRole R(String localName) { return AtomicRole.create(NS+localName); } protected static Atom A(DLPredicate dlPredicate,Term... arguments) { return Atom.create(dlPredicate,arguments); } protected static Term[] TS(Term... terms) { return terms; } protected static Atom[] AS(Atom... atoms) { return atoms; } }
hrsky/PIOT
src/Hermit/test/org/semanticweb/HermiT/reasoner/DatalogEngineTest.java
Java
gpl-2.0
9,695
# ExtractEbizzy.pm package MMTests::ExtractEbizzy; use MMTests::SummariseMultiops; use MMTests::Stat; our @ISA = qw(MMTests::SummariseMultiops); use strict; sub initialise() { my ($self, $subHeading) = @_; $self->{_ModuleName} = "ExtractEbizzy"; $self->{_DataType} = DataTypes::DATA_ACTIONS_PER_SECOND; $self->{_PlotType} = "client-errorlines"; $self->SUPER::initialise($subHeading); } sub extractReport() { my ($self, $reportDir) = @_; foreach my $instance ($self->discover_scaling_parameters($reportDir, "ebizzy-", "-1.log")) { my $iteration = 0; my @files = <$reportDir/ebizzy-$instance-*>; foreach my $file (@files) { my $records; open(INPUT, $file) || die("Failed to open $file\n"); while (<INPUT>) { my $line = $_; if ($line =~ /([0-9]*) records.*/) { $records = $1; } } close INPUT; $self->addData("Rsec-$instance", $iteration, $records); } } } 1;
gormanm/mmtests
bin/lib/MMTests/ExtractEbizzy.pm
Perl
gpl-2.0
917
eAmin
eAmin/eAmin.github.io
index.html
HTML
gpl-2.0
5
import hashlib import binascii class MerkleTools(object): def __init__(self, hash_type="sha256"): hash_type = hash_type.lower() if hash_type == 'sha256': self.hash_function = hashlib.sha256 elif hash_type == 'md5': self.hash_function = hashlib.md5 elif hash_type == 'sha224': self.hash_function = hashlib.sha224 elif hash_type == 'sha384': self.hash_function = hashlib.sha384 elif hash_type == 'sha512': self.hash_function = hashlib.sha512 elif hash_type == 'sha3_256': self.hash_function = hashlib.sha3_256 elif hash_type == 'sha3_224': self.hash_function = hashlib.sha3_224 elif hash_type == 'sha3_384': self.hash_function = hashlib.sha3_384 elif hash_type == 'sha3_512': self.hash_function = hashlib.sha3_512 else: raise Exception('`hash_type` {} nor supported'.format(hash_type)) self.reset_tree() def _to_hex(self, x): try: # python3 return x.hex() except: # python2 return binascii.hexlify(x) def reset_tree(self): self.leaves = list() self.levels = None self.is_ready = False def add_leaf(self, values, do_hash=False): self.is_ready = False # check if single leaf if isinstance(values, tuple) or isinstance(values, list): for v in values: if do_hash: v = v.encode('utf-8') v = self.hash_function(v).hexdigest() v = bytearray.fromhex(v) else: v = bytearray.fromhex(v) self.leaves.append(v) else: if do_hash: v = values.encode("utf-8") v = self.hash_function(v).hexdigest() v = bytearray.fromhex(v) else: v = bytearray.fromhex(values) self.leaves.append(v) def get_leaf(self, index): return self._to_hex(self.leaves[index]) def get_leaf_count(self): return len(self.leaves) def get_tree_ready_state(self): return self.is_ready def _calculate_next_level(self): solo_leave = None N = len(self.levels[0]) # number of leaves on the level if N % 2 == 1: # if odd number of leaves on the level solo_leave = self.levels[0][-1] N -= 1 new_level = [] for l, r in zip(self.levels[0][0:N:2], self.levels[0][1:N:2]): new_level.append(self.hash_function(l+r).digest()) if solo_leave is not None: new_level.append(solo_leave) self.levels = [new_level, ] + self.levels # prepend new level def make_tree(self): self.is_ready = False if self.get_leaf_count() > 0: self.levels = [self.leaves, ] while len(self.levels[0]) > 1: self._calculate_next_level() self.is_ready = True def get_merkle_root(self): if self.is_ready: if self.levels is not None: return self._to_hex(self.levels[0][0]) else: return None else: return None def get_proof(self, index): if self.levels is None: return None elif not self.is_ready or index > len(self.leaves)-1 or index < 0: return None else: proof = [] for x in range(len(self.levels) - 1, 0, -1): level_len = len(self.levels[x]) if (index == level_len - 1) and (level_len % 2 == 1): # skip if this is an odd end node index = int(index / 2.) continue is_right_node = index % 2 sibling_index = index - 1 if is_right_node else index + 1 sibling_pos = "left" if is_right_node else "right" sibling_value = self._to_hex(self.levels[x][sibling_index]) proof.append({sibling_pos: sibling_value}) index = int(index / 2.) return proof def validate_proof(self, proof, target_hash, merkle_root): merkle_root = bytearray.fromhex(merkle_root) target_hash = bytearray.fromhex(target_hash) if len(proof) == 0: return target_hash == merkle_root else: proof_hash = target_hash for p in proof: try: # the sibling is a left node sibling = bytearray.fromhex(p['left']) proof_hash = self.hash_function(sibling + proof_hash).digest() except: # the sibling is a right node sibling = bytearray.fromhex(p['right']) proof_hash = self.hash_function(proof_hash + sibling).digest() return proof_hash == merkle_root
OliverCole/ZeroNet
src/lib/merkletools/__init__.py
Python
gpl-2.0
4,984
/* ------------------------------------------------------------------ * Copyright (C) 2008 PacketVideo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.073 ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec Available from http://www.3gpp.org (C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Filename: /audio/gsm_amr/c/include/shl.h Date: 08/11/2000 ------------------------------------------------------------------------------ REVISION HISTORY Description: Created separate header file for shl function. Description: Changed prototype of the mult() function. Instead of using global a pointer to overflow flag is now passed into the function. Description: Updated template. Changed the parameter name from "overflow" to "pOverflow" in the function prototype declaration Description: Moved _cplusplus #ifdef after Include section. Description: ------------------------------------------------------------------------------ INCLUDE DESCRIPTION This file contains all the constant definitions and prototype definitions needed by the shl function. ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; CONTINUE ONLY IF NOT ALREADY DEFINED ----------------------------------------------------------------------------*/ #ifndef SHL_H #define SHL_H /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "basicop_malloc.h" /*--------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL VARIABLES REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; SIMPLE TYPEDEF'S ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; ENUMERATED TYPEDEF'S ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; STRUCTURES TYPEDEF'S ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; GLOBAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ Word16 shl(Word16 var1, Word16 var2, Flag *pOverflow); /*---------------------------------------------------------------------------- ; END ----------------------------------------------------------------------------*/ #ifdef __cplusplus } #endif #endif /* _SHL_H_ */
MoSync/MoSync
intlibs/gsm_amr/amr_nb/common/include/shl.h
C
gpl-2.0
4,652
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Lazaro.Mensajeria.Chat { public partial class Inicio : Lui.Forms.Form { [DllImport("user32.dll")] static extern Int32 FlashWindowEx(ref FLASHWINFO pwfi); [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { #pragma warning disable CS3003 // El tipo no es conforme a CLS public UInt32 cbSize; #pragma warning restore CS3003 // El tipo no es conforme a CLS public IntPtr hwnd; public Int32 dwFlags; #pragma warning disable CS3003 // El tipo no es conforme a CLS public UInt32 uCount; #pragma warning restore CS3003 // El tipo no es conforme a CLS public Int32 dwTimeout; } private bool Active = false; public Inicio() { InitializeComponent(); this.DisplayStyle = Lazaro.Pres.DisplayStyles.Template.Current.White; Lfx.Workspace.Master.RunTime.IpcEvent += new Lfx.RunTimeServices.IpcEventHandler(Workspace_IpcEvent); } public ChatControl IniciarChat(string nombre) { foreach (Lbl.Notificaciones.UsuarioConectado Usu in Lbl.Notificaciones.Administrador.Usuarios.Values) { if (Usu.Nombre == nombre) { return this.IniciarChat(Usu.Persona, Usu.Estacion); } } return null; } protected override void OnClosing(CancelEventArgs e) { TimerContactos.Stop(); this.Hide(); e.Cancel = true; base.OnClosing(e); } protected override void OnShown(EventArgs e) { TimerContactos.Interval = 1000; TimerContactos.Start(); base.OnShown(e); } protected override void OnActivated(EventArgs e) { this.Active = true; base.OnActivated(e); } protected override void OnDeactivate(EventArgs e) { this.Active = false; base.OnDeactivate(e); } public ChatControl IniciarChat(Lbl.Personas.Persona personaRemota, string estacionRemota) { if (this.InvokeRequired) { object Res = this.Invoke((Func<object>)(delegate { return this.IniciarChat(personaRemota, estacionRemota); })); return Res as ChatControl; } else { ChatControl NuevoCtrl = new ChatControl(); NuevoCtrl.Margin = new Padding(8); NuevoCtrl.Dock = DockStyle.Fill; NuevoCtrl.Visible = true; this.SuspendLayout(); this.Controls.Add(NuevoCtrl); this.ResumeLayout(true); NuevoCtrl.IniciarChat(personaRemota, estacionRemota); ToolStripButton Pestania = new ToolStripButton(personaRemota.ToString()); Pestania.Margin = new System.Windows.Forms.Padding(2); Pestania.Tag = NuevoCtrl; Pestania.Checked = true; this.Pestanias.Items.Add(Pestania); NuevoCtrl.Select(); Listado.Visible = false; return NuevoCtrl; } } public void MensajeRecibido(Lbl.Notificaciones.INotificacion notif) { ChatControl Ctrl = null; bool Encontrado = false; foreach (System.Windows.Forms.ToolStripItem Btn in this.Pestanias.Items) { if (Btn is System.Windows.Forms.ToolStripButton) { Ctrl = Btn.Tag as ChatControl; if (Ctrl.PersonaRemota.Id == notif.Remitente.Id) { Encontrado = true; Ctrl.MensajeRecibido(notif); } } } if (Encontrado == false) { Ctrl = this.IniciarChat(notif.Remitente, notif.EstacionOrigen); Ctrl.MensajeRecibido(notif); } if (this.InvokeRequired) { this.Invoke(new MethodInvoker(delegate { this.ShowAndFlash(); })); } else { this.ShowAndFlash(); } } public void ShowAndFlash() { if (this.Visible == false) this.Show(); if (this.Active == false && Lfx.Environment.SystemInformation.Platform == Lfx.Environment.SystemInformation.Platforms.Windows) { FLASHWINFO fw = new FLASHWINFO(); fw.cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(FLASHWINFO))); fw.hwnd = this.Handle; fw.dwFlags = 2 + 4; fw.uCount = 5; FlashWindowEx(ref fw); } } public void MostrarContactos() { if (Lbl.Notificaciones.Administrador.Principal != null) { Lbl.Notificaciones.Administrador.Principal.ActualizarUsuariosConectados(); List<ListViewItem> Eliminar = new List<ListViewItem>(); foreach (ListViewItem Itm in Listado.Items) { Eliminar.Add(Itm); } if (Lbl.Notificaciones.Administrador.Usuarios.Count > 0) { foreach (Lbl.Notificaciones.UsuarioConectado Usu in Lbl.Notificaciones.Administrador.Usuarios.Values) { string IdContacto = Usu.Id.ToString(); ListViewItem Itm; if (Listado.Items.ContainsKey(IdContacto)) Itm = Listado.Items[IdContacto]; else Itm = Listado.Items.Add(IdContacto, Usu.Nombre, 0); if (Usu.Estado == 0) { Itm.ForeColor = Color.Silver; Itm.ToolTipText = "Desconectado"; } else { Itm.ForeColor = Listado.ForeColor; Itm.ToolTipText = "Conectado en " + Usu.Estacion; } if (Eliminar.Contains(Itm)) Eliminar.Remove(Itm); Itm.Name = IdContacto; Itm.Text = Usu.Nombre; } } foreach (ListViewItem Itm in Eliminar) { Listado.Items.Remove(Itm); } // Actualizo las ventanas de chat foreach (System.Windows.Forms.ToolStripItem Btn in this.Pestanias.Items) { if (Btn is System.Windows.Forms.ToolStripButton) { ChatControl Ctrl = Btn.Tag as ChatControl; Ctrl.Offline = !Lbl.Notificaciones.Administrador.Usuarios.ContainsKey(Ctrl.PersonaRemota.Id); } } Listado.Sort(); } } public void Workspace_IpcEvent(object sender, ref Lfx.RunTimeServices.IpcEventArgs e) { if (e.Destination == "Lazaro.Mensajeria") { switch(e.EventType) { case Lfx.RunTimeServices.IpcEventArgs.EventTypes.Notification: this.MensajeRecibido(e.Arguments[0] as Lbl.Notificaciones.INotificacion); break; } } } private void Pestanias_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { this.MostrarChat(e.ClickedItem.Text); } private void Listado_DoubleClick(object sender, EventArgs e) { if (Listado.SelectedItems != null && Listado.SelectedItems.Count > 0) { string NombreClicado = Listado.SelectedItems[0].Text; if (this.MostrarChat(NombreClicado) == false) { // Inicio un nuevo chat this.IniciarChat(NombreClicado); } } } public bool MostrarChat(string nombre) { bool Encontrado = false; foreach (System.Windows.Forms.ToolStripItem Btn in this.Pestanias.Items) { if (Btn is System.Windows.Forms.ToolStripButton) { ChatControl Ctrl = Btn.Tag as ChatControl; if (Ctrl.PersonaRemota.Nombre == nombre) { Ctrl.Visible = true; Encontrado = true; Ctrl.Select(); } else { Ctrl.Visible = false; } } } Listado.Visible = Encontrado == false; return Encontrado; } private void TimerContactos_Tick(object sender, EventArgs e) { this.TimerContactos.Stop(); this.MostrarContactos(); this.TimerContactos.Interval = 10000; this.TimerContactos.Start(); } } }
lazarogestion/lazaro
Mensajeria/Chat/Inicio.cs
C#
gpl-2.0
12,076
/* Copyright (C) 2007-2019 Open Information Security Foundation * * You can copy, redistribute or modify this Program 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * \ingroup httplayer * * @{ */ /** * \file * * \author Pablo Rincon <pablo.rincon.crespo@gmail.com> * * Implements support for http_raw_header keyword. */ #include "suricata-common.h" #include "threads.h" #include "decode.h" #include "detect.h" #include "detect-parse.h" #include "detect-engine.h" #include "detect-engine-mpm.h" #include "detect-engine-prefilter.h" #include "detect-content.h" #include "flow.h" #include "flow-var.h" #include "flow-util.h" #include "util-debug.h" #include "app-layer.h" #include "app-layer-parser.h" #include "app-layer-htp.h" #include "detect-http-raw-header.h" static int DetectHttpRawHeaderSetup(DetectEngineCtx *, Signature *, const char *); static int DetectHttpRawHeaderSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str); #ifdef UNITTESTS static void DetectHttpRawHeaderRegisterTests(void); #endif static bool DetectHttpRawHeaderValidateCallback(const Signature *s, const char **sigerror); static int g_http_raw_header_buffer_id = 0; static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, const int list_id); static int PrefilterMpmHttpHeaderRawRequestRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx, const DetectBufferMpmRegistery *mpm_reg, int list_id); static int PrefilterMpmHttpHeaderRawResponseRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx, const DetectBufferMpmRegistery *mpm_reg, int list_id); /** * \brief Registers the keyword handlers for the "http_raw_header" keyword. */ void DetectHttpRawHeaderRegister(void) { /* http_raw_header content modifier */ sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].name = "http_raw_header"; sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].desc = "content modifier to match the raw HTTP header buffer"; sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].url = "/rules/http-keywords.html#http-header-and-http-raw-header"; sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].Setup = DetectHttpRawHeaderSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].RegisterTests = DetectHttpRawHeaderRegisterTests; #endif sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].alternative = DETECT_HTTP_RAW_HEADER; /* http.header.raw sticky buffer */ sigmatch_table[DETECT_HTTP_RAW_HEADER].name = "http.header.raw"; sigmatch_table[DETECT_HTTP_RAW_HEADER].desc = "sticky buffer to match the raw HTTP header buffer"; sigmatch_table[DETECT_HTTP_RAW_HEADER].url = "/rules/http-keywords.html#http-header-and-http-raw-header"; sigmatch_table[DETECT_HTTP_RAW_HEADER].Setup = DetectHttpRawHeaderSetupSticky; sigmatch_table[DETECT_HTTP_RAW_HEADER].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_raw_header", ALPROTO_HTTP, SIG_FLAG_TOSERVER, HTP_REQUEST_HEADERS+1, DetectEngineInspectBufferGeneric, GetData); DetectAppLayerInspectEngineRegister2("http_raw_header", ALPROTO_HTTP, SIG_FLAG_TOCLIENT, HTP_RESPONSE_HEADERS+1, DetectEngineInspectBufferGeneric, GetData); DetectAppLayerMpmRegister2("http_raw_header", SIG_FLAG_TOSERVER, 2, PrefilterMpmHttpHeaderRawRequestRegister, NULL, ALPROTO_HTTP, 0); /* progress handled in register */ DetectAppLayerMpmRegister2("http_raw_header", SIG_FLAG_TOCLIENT, 2, PrefilterMpmHttpHeaderRawResponseRegister, NULL, ALPROTO_HTTP, 0); /* progress handled in register */ DetectBufferTypeSetDescriptionByName("http_raw_header", "raw http headers"); DetectBufferTypeRegisterValidateCallback("http_raw_header", DetectHttpRawHeaderValidateCallback); g_http_raw_header_buffer_id = DetectBufferTypeGetByName("http_raw_header"); } /** * \brief The setup function for the http_raw_header keyword for a signature. * * \param de_ctx Pointer to the detection engine context. * \param s Pointer to signature for the current Signature being parsed * from the rules. * \param m Pointer to the head of the SigMatchs for the current rule * being parsed. * \param arg Pointer to the string holding the keyword value. * * \retval 0 On success. * \retval -1 On failure. */ int DetectHttpRawHeaderSetup(DetectEngineCtx *de_ctx, Signature *s, const char *arg) { return DetectEngineContentModifierBufferSetup(de_ctx, s, arg, DETECT_AL_HTTP_RAW_HEADER, g_http_raw_header_buffer_id, ALPROTO_HTTP); } /** * \brief this function setup the http.header.raw keyword used in the rule * * \param de_ctx Pointer to the Detection Engine Context * \param s Pointer to the Signature to which the current keyword belongs * \param str Should hold an empty string always * * \retval 0 On success */ static int DetectHttpRawHeaderSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectBufferSetActiveList(s, g_http_raw_header_buffer_id) < 0) return -1; if (DetectSignatureSetAppProto(s, ALPROTO_HTTP) < 0) return -1; return 0; } static bool DetectHttpRawHeaderValidateCallback(const Signature *s, const char **sigerror) { if ((s->flags & (SIG_FLAG_TOCLIENT|SIG_FLAG_TOSERVER)) == (SIG_FLAG_TOCLIENT|SIG_FLAG_TOSERVER)) { *sigerror = "http_raw_header signature " "without a flow direction. Use flow:to_server for " "inspecting request headers or flow:to_client for " "inspecting response headers."; SCLogError(SC_ERR_INVALID_SIGNATURE, "%s", *sigerror); SCReturnInt(FALSE); } return TRUE; } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { htp_tx_t *tx = (htp_tx_t *)txv; HtpTxUserData *tx_ud = htp_tx_get_user_data(tx); if (tx_ud == NULL) return NULL; const bool ts = ((flow_flags & STREAM_TOSERVER) != 0); const uint8_t *data = ts ? tx_ud->request_headers_raw : tx_ud->response_headers_raw; if (data == NULL) return NULL; const uint32_t data_len = ts ? tx_ud->request_headers_raw_len : tx_ud->response_headers_raw_len; InspectionBufferSetup(buffer, data, data_len); InspectionBufferApplyTransforms(buffer, transforms); } return buffer; } typedef struct PrefilterMpmHttpHeaderRawCtx { int list_id; const MpmCtx *mpm_ctx; const DetectEngineTransforms *transforms; } PrefilterMpmHttpHeaderRawCtx; /** \brief Generic Mpm prefilter callback * * \param det_ctx detection engine thread ctx * \param p packet to inspect * \param f flow to inspect * \param txv tx to inspect * \param pectx inspection context */ static void PrefilterMpmHttpHeaderRaw(DetectEngineThreadCtx *det_ctx, const void *pectx, Packet *p, Flow *f, void *txv, const uint64_t idx, const uint8_t flags) { SCEnter(); const PrefilterMpmHttpHeaderRawCtx *ctx = pectx; const MpmCtx *mpm_ctx = ctx->mpm_ctx; SCLogDebug("running on list %d", ctx->list_id); const int list_id = ctx->list_id; InspectionBuffer *buffer = GetData(det_ctx, ctx->transforms, f, flags, txv, list_id); if (buffer == NULL) return; const uint32_t data_len = buffer->inspect_len; const uint8_t *data = buffer->inspect; SCLogDebug("mpm'ing buffer:"); //PrintRawDataFp(stdout, data, data_len); if (data != NULL && data_len >= mpm_ctx->minlen) { (void)mpm_table[mpm_ctx->mpm_type].Search(mpm_ctx, &det_ctx->mtcu, &det_ctx->pmq, data, data_len); } } static void PrefilterMpmHttpTrailerRaw(DetectEngineThreadCtx *det_ctx, const void *pectx, Packet *p, Flow *f, void *txv, const uint64_t idx, const uint8_t flags) { SCEnter(); htp_tx_t *tx = txv; const HtpTxUserData *htud = (const HtpTxUserData *)htp_tx_get_user_data(tx); /* if the request wasn't flagged as having a trailer, we skip */ if (htud && ( ((flags & STREAM_TOSERVER) && !htud->request_has_trailers) || ((flags & STREAM_TOCLIENT) && !htud->response_has_trailers))) { SCReturn; } PrefilterMpmHttpHeaderRaw(det_ctx, pectx, p, f, txv, idx, flags); SCReturn; } static void PrefilterMpmHttpHeaderRawFree(void *ptr) { SCFree(ptr); } static int PrefilterMpmHttpHeaderRawRequestRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx, const DetectBufferMpmRegistery *mpm_reg, int list_id) { SCEnter(); /* header */ PrefilterMpmHttpHeaderRawCtx *pectx = SCCalloc(1, sizeof(*pectx)); if (pectx == NULL) return -1; pectx->list_id = list_id; pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeaderRaw, mpm_reg->app_v2.alproto, HTP_REQUEST_HEADERS+1, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); return r; } /* trailer */ pectx = SCCalloc(1, sizeof(*pectx)); if (pectx == NULL) return -1; pectx->list_id = list_id; pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailerRaw, mpm_reg->app_v2.alproto, HTP_REQUEST_TRAILER+1, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } return r; } static int PrefilterMpmHttpHeaderRawResponseRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx, const DetectBufferMpmRegistery *mpm_reg, int list_id) { SCEnter(); /* header */ PrefilterMpmHttpHeaderRawCtx *pectx = SCCalloc(1, sizeof(*pectx)); if (pectx == NULL) return -1; pectx->list_id = list_id; pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeaderRaw, mpm_reg->app_v2.alproto, HTP_RESPONSE_HEADERS, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); return r; } /* trailer */ pectx = SCCalloc(1, sizeof(*pectx)); if (pectx == NULL) return -1; pectx->list_id = list_id; pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailerRaw, mpm_reg->app_v2.alproto, HTP_RESPONSE_TRAILER, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } return r; } /************************************Unittests*********************************/ #ifdef UNITTESTS #include "tests/detect-http-raw-header.c" #endif /** * @} */
glongo/suricata
src/detect-http-raw-header.c
C
gpl-2.0
12,171
# encoding: utf-8 """ Miscellaneous functions, which are useful for handling bodies. """ from yade.wrapper import * import utils,math,numpy try: from minieigen import * except ImportError: from miniEigen import * #spheresPackDimensions================================================== def spheresPackDimensions(idSpheres=[],mask=-1): """The function accepts the list of spheres id's or list of bodies and calculates max and min dimensions, geometrical center. :param list idSpheres: list of spheres :param int mask: :yref:`Body.mask` for the checked bodies :return: dictionary with keys ``min`` (minimal dimension, Vector3), ``max`` (maximal dimension, Vector3), ``minId`` (minimal dimension sphere Id, Vector3), ``maxId`` (maximal dimension sphere Id, Vector3), ``center`` (central point of bounding box, Vector3), ``extends`` (sizes of bounding box, Vector3), ``volume`` (volume of spheres, Real), ``mass`` (mass of spheres, Real), ``number`` (number of spheres, int), """ idSpheresIter=[] if (len(idSpheres)<1): #check mask ifSpherMask=[] if (mask>-1): #The case, when only the mask was given, without list of ids for i in O.bodies: if ((i.mask&mask)<>0): ifSpherMask.append(i.id) if (len(ifSpherMask)<2): raise RuntimeWarning("Not enough bodies to analyze with given mask") else: idSpheresIter=ifSpherMask else: raise RuntimeWarning("Only a list of particles with length > 1 can be analyzed") else: idSpheresIter=idSpheres minVal = Vector3.Zero maxVal = Vector3.Zero minId = Vector3.Zero maxId = Vector3.Zero counter = 0 volume = 0.0 mass = 0.0 for i in idSpheresIter: if (type(i).__name__=='int'): b = O.bodies[i] #We have received a list of ID's elif (type(i).__name__=='Body'): b = i #We have recevied a list of bodies else: raise TypeError("Unknow type of data, should be list of int's or bodies's") if (b): spherePosition=b.state.pos #skip non-existent spheres try: sphereRadius=b.shape.radius #skip non-spheres except AttributeError: continue if (mask>-1) and ((mask&b.mask)==0): continue #skip bodies with wrong mask sphereRadiusVec3 = Vector3(sphereRadius,sphereRadius,sphereRadius) sphereMax = spherePosition + sphereRadiusVec3 sphereMin = spherePosition - sphereRadiusVec3 for dim in range(0,3): if ((sphereMax[dim]>maxVal[dim]) or (counter==0)): maxVal[dim]=sphereMax[dim] maxId[dim] = b.id if ((sphereMin[dim]<minVal[dim]) or (counter==0)): minVal[dim]=sphereMin[dim] minId[dim] = b.id volume += 4.0/3.0*math.pi*sphereRadius*sphereRadius*sphereRadius mass += b.state.mass counter += 1 center = (maxVal-minVal)/2.0+minVal extends = maxVal-minVal dimensions = {'max':maxVal,'min':minVal,'maxId':maxId,'minId':minId,'center':center, 'extends':extends, 'volume':volume, 'mass':mass, 'number':counter} return dimensions #facetsDimensions================================================== def facetsDimensions(idFacets=[],mask=-1): """The function accepts the list of facet id's or list of facets and calculates max and min dimensions, geometrical center. :param list idFacets: list of spheres :param int mask: :yref:`Body.mask` for the checked bodies :return: dictionary with keys ``min`` (minimal dimension, Vector3), ``max`` (maximal dimension, Vector3), ``minId`` (minimal dimension facet Id, Vector3), ``maxId`` (maximal dimension facet Id, Vector3), ``center`` (central point of bounding box, Vector3), ``extends`` (sizes of bounding box, Vector3), ``number`` (number of facets, int), """ idFacetsIter=[] if (len(idFacets)<1): #check mask ifFacetMask=[] if (mask>-1): #The case, when only the mask was given, without list of ids for i in O.bodies: if ((i.mask&mask)<>0): ifFacetMask.append(i.id) if (len(ifFacetMask)<2): raise RuntimeWarning("Not enough bodies to analyze with given mask") else: idFacetsIter=ifFacetMask else: raise RuntimeWarning("Only a list of particles with length > 1 can be analyzed") else: idFacetsIter=idFacets minVal = Vector3.Zero maxVal = Vector3.Zero minId = Vector3.Zero maxId = Vector3.Zero counter = 0 for i in idFacetsIter: if (type(i).__name__=='int'): b = O.bodies[i] #We have received a list of ID's elif (type(i).__name__=='Body'): b = i #We have recevied a list of bodies else: raise TypeError("Unknow type of data, should be list of int's or bodies's") if (b): p = b.state.pos o = b.state.ori s = b.shape pt1 = p + o*s.vertices[0] pt2 = p + o*s.vertices[1] pt3 = p + o*s.vertices[2] if (mask>-1) and ((mask&b.mask)==0): continue #skip bodies with wrong mask facetMax = Vector3(max(pt1[0], pt2[0], pt3[0]), max(pt1[1], pt2[1], pt3[1]), max(pt1[2], pt2[2], pt3[2])) facetMin = Vector3(min(pt1[0], pt2[0], pt3[0]), min(pt1[1], pt2[1], pt3[1]), min(pt1[2], pt2[2], pt3[2])) for dim in range(0,3): if ((facetMax[dim]>maxVal[dim]) or (counter==0)): maxVal[dim]=facetMax[dim] maxId[dim] = b.id if ((facetMin[dim]<minVal[dim]) or (counter==0)): minVal[dim]=facetMin[dim] minId[dim] = b.id counter += 1 center = (maxVal-minVal)/2.0+minVal extends = maxVal-minVal dimensions = {'max':maxVal,'min':minVal,'maxId':maxId,'minId':minId,'center':center, 'extends':extends, 'number':counter} return dimensions #spheresPackDimensions================================================== def spheresModify(idSpheres=[],mask=-1,shift=Vector3.Zero,scale=1.0,orientation=Quaternion((0,1,0),0.0),copy=False): """The function accepts the list of spheres id's or list of bodies and modifies them: rotating, scaling, shifting. if copy=True copies bodies and modifies them. Also the mask can be given. If idSpheres not empty, the function affects only bodies, where the mask passes. If idSpheres is empty, the function search for bodies, where the mask passes. :param Vector3 shift: Vector3(X,Y,Z) parameter moves spheres. :param float scale: factor scales given spheres. :param Quaternion orientation: orientation of spheres :param int mask: :yref:`Body.mask` for the checked bodies :returns: list of bodies if copy=True, and Boolean value if copy=False """ idSpheresIter=[] if (len(idSpheres)==0): #check mask ifSpherMask=[] if (mask>-1): #The case, when only the mask was given, without list of ids for i in O.bodies: if ((i.mask&mask)<>0): ifSpherMask.append(i.id) if (len(ifSpherMask)==0): raise RuntimeWarning("No bodies to modify with given mask") else: idSpheresIter=ifSpherMask else: raise RuntimeWarning("No bodies to modify") else: idSpheresIter=idSpheres dims = spheresPackDimensions(idSpheresIter) ret=[] for i in idSpheresIter: if (type(i).__name__=='int'): b = O.bodies[i] #We have received a list of ID's elif (type(i).__name__=='Body'): b = i #We have recevied a list of bodies else: raise TypeError("Unknown type of data, should be list of int's or bodies") try: sphereRadius=b.shape.radius #skip non-spheres except AttributeError: continue if (mask>-1) and ((mask&b.mask)==0): continue #skip bodies with wrong mask if (copy): b=sphereDuplicate(b) b.state.pos=orientation*(b.state.pos-dims['center'])+dims['center'] b.shape.radius*=scale b.state.pos=(b.state.pos-dims['center'])*scale + dims['center'] b.state.pos+=shift if (copy): ret.append(b) if (copy): return ret else: return True #spheresDublicate======================================================= def sphereDuplicate(idSphere): """The functions makes a copy of sphere""" i=idSphere if (type(i).__name__=='int'): b = O.bodies[i] #We have received a list of ID's elif (type(i).__name__=='Body'): b = i #We have recevied a list of bodies else: raise TypeError("Unknown type of data, should be list of int's or bodies") try: sphereRadius=b.shape.radius #skip non-spheres except AttributeError: return False addedBody = utils.sphere(center=b.state.pos,radius=b.shape.radius,fixed=not(b.dynamic),wire=b.shape.wire,color=b.shape.color,highlight=b.shape.highlight,material=b.material,mask=b.mask) return addedBody
ThomasSweijen/TPF
py/bodiesHandling.py
Python
gpl-2.0
8,305
/* * Off-the-Record Messaging bindings for nodejs * Copyright (C) 2012 Mokhtar Naamani, * <mokhtar.naamani@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __NODE_OTR_USERSTATE_H__ #define __NODE_OTR_USERSTATE_H__ #include "otr.hpp" extern "C" { #include <gcrypt.h> //added for libotr-v4 #include <libotr/userstate.h> } namespace otr { class UserState : public node::ObjectWrap { public: static void Init(v8::Handle<v8::Object> target); static v8::Persistent<v8::FunctionTemplate> constructor; protected: friend class MessageAppOps; friend class ConnectionCtx; friend class PrivateKey; OtrlUserState userstate_; bool reference; UserState(OtrlUserState userstate); ~UserState(); static v8::Handle<v8::Value> New(const v8::Arguments& args); static v8::Handle<v8::Value> WrapUserState(OtrlUserState userstate); static v8::Handle<v8::Value> Destroy(const v8::Arguments &args); //Async static v8::Handle<v8::Value> Generate_Key(const v8::Arguments& args); static v8::Handle<v8::Value> Read_Keys(const v8::Arguments& args); static v8::Handle<v8::Value> Read_Fingerprints(const v8::Arguments& args); static v8::Handle<v8::Value> Write_Fingerprints(const v8::Arguments& args); //Sync static v8::Handle<v8::Value> GetFingerprint(const v8::Arguments& args); static v8::Handle<v8::Value> Accounts(const v8::Arguments& args); static v8::Handle<v8::Value> Get_Key(const v8::Arguments& args); static v8::Handle<v8::Value> Import_PrivKey(const v8::Arguments& args); static v8::Handle<v8::Value> Read_Keys_Sync(const v8::Arguments& args); static v8::Handle<v8::Value> Write_Keys_Sync(const v8::Arguments& args); static v8::Handle<v8::Value> Delete_Key_On_File(const v8::Arguments& args); static v8::Handle<v8::Value> Find_Key(const v8::Arguments& args); static v8::Handle<v8::Value> Forget_All_Keys(const v8::Arguments& args); static v8::Handle<v8::Value> Read_Fingerprints_Sync(const v8::Arguments& args); static v8::Handle<v8::Value> Write_Fingerprints_Sync(const v8::Arguments& args); static v8::Handle<v8::Value> Write_Trusted_Fingerprints_Sync(const v8::Arguments& args); static v8::Handle<v8::Value> Read_Instags_Sync(const v8::Arguments& args); static v8::Handle<v8::Value> Write_Instags_Sync(const v8::Arguments& args); static v8::Handle<v8::Value> Generate_Instag(const v8::Arguments& args); static v8::Handle<v8::Value> Find_Instag(const v8::Arguments& args); static v8::Handle<v8::Value> MessagePoll_DefaultInterval(const v8::Arguments& args); static v8::Handle<v8::Value> MessagePoll(const v8::Arguments& args); static v8::Handle<v8::Value> Free(const v8::Arguments& args); static v8::Handle<v8::Value> MasterContexts(const v8::Arguments& args); //Workers static void Worker_Generate_Key (uv_work_t* req); static void Worker_Read_Keys (uv_work_t* req); static void Worker_Read_Fingerprints (uv_work_t* req); static void Worker_Write_Fingerprints (uv_work_t* req); static void Worker_After (uv_work_t* req); }; //information about the asynchronous "work request". struct Baton { uv_work_t request; bool hasCallback; v8::Persistent<v8::Function> callback; gcry_error_t error; OtrlUserState userstate; std::string arg0; std::string arg1; std::string arg2; }; } #endif
mnaamani/node-otr4
src/userstate.hpp
C++
gpl-2.0
3,941
<?php // This is global bootstrap for autoloading require_once dirname(__DIR__) . '/vendor/autoload.php';
nibra/joomla-pythagoras
tests/_bootstrap.php
PHP
gpl-2.0
107
/* Copyright (C) 2007 - 2011 YOOtheme GmbH, YOOtheme Proprietary Use License (http://www.yootheme.com/license) */ /* * item */ /* position headings */ #yoo-zoo .item h3 { margin-top: 0px; font-family: Georgia, "Times New Roman", Times, serif; font-size: 18px; font-weight: normal; color: #323232; } /* element type: textarea */ #yoo-zoo .item .element-textarea > * { margin: 0px 0px 8px 0px; } #yoo-zoo .item .element-textarea *:last-child { margin-bottom: 0px; } /* position: top */ #yoo-zoo .item div.pos-top { overflow: hidden; } #yoo-zoo .item div.pos-top .element { margin-bottom: 18px; } /* position: title */ #yoo-zoo .item h1.pos-title { margin: 0px 0px 8px 0px; font-family: Georgia, "Times New Roman", Times, serif; font-size: 40px; font-weight: normal; line-height: 42px; color: #323232; letter-spacing: -2px; } /* position: meta */ #yoo-zoo .item p.pos-meta { margin: 0px 0px 23px 0px; font-size: 11px; color: #969696; line-height: 13px; font-style: italic; } /* position: subtitle */ #yoo-zoo .item h2.pos-subtitle{ margin: 0px 0px 8px 0px; font-size: 14px; color: #787878; line-height: 16px; font-weight: normal; text-transform: uppercase; } /* position: media */ #yoo-zoo .item div.media-left { margin: 0px 15px 0px 0px; float: left; } #yoo-zoo .item div.media-right { margin: 0px 0px 0px 15px; float: right; } #yoo-zoo .item div.pos-media .element { margin-bottom: 12px; } #yoo-zoo .item div.media-bottom .element { margin: 12px 0px 0px 0px; } #yoo-zoo .item div.media-above .element { margin: 0px 0px 20px 0px; } #yoo-zoo .item div.pos-media a { display: block; } /* position: content */ #yoo-zoo .item div.pos-content {} #yoo-zoo .item div.pos-content .element { margin-bottom: 18px; } #yoo-zoo .item div.pos-content .element.last { margin-bottom: 0px; } /* element type: video */ #yoo-zoo .item div.pos-content .element-video { text-align: center; } #yoo-zoo .item div.pos-content .element-video object { outline: none; } /* position: taxonomy */ #yoo-zoo .item ul.pos-taxonomy { list-style: none; margin: 20px 0px 0px 0px; padding: 0px; } #yoo-zoo .item ul.pos-taxonomy strong { color: #323232; } /* position: bottom */ #yoo-zoo .item div.pos-bottom { overflow: hidden;} #yoo-zoo .item div.pos-bottom .element { margin-top: 15px; padding-bottom: 15px; background: url(../images/line_dotted_h.png) 0 100% repeat-x; } /* element type: socialbookmarks */ #yoo-zoo .item div.socialbookmarks { display: inline-block; cursor: pointer; } /* position: related */ #yoo-zoo .item div.pos-related { margin-top: 15px; padding-bottom: 15px; background: url(../images/line_dotted_h.png) 0 100% repeat-x; } #yoo-zoo .item div.pos-related ul { list-style: none; margin: 0px; padding: 0px; } #yoo-zoo .item div.pos-related li { padding-left: 10px; background: url(../images/arrow.png) 0px 50% no-repeat; } /* position: author */ #yoo-zoo .item div.pos-author { padding: 15px 0px 15px 0px; background: #fafafa url(../images/line_dotted_h.png) 0 100% repeat-x; overflow: hidden; } #yoo-zoo .item div.pos-author .element-relateditems > div { margin-bottom: 15px; overflow: hidden; } #yoo-zoo .item div.pos-author .element-relateditems > div:last-child { margin-bottom: 0px; } /* related item */ #yoo-zoo .item div.pos-author div.sub-pos-media { margin: 0px 15px 0px 0px; padding: 3px; border: 1px solid #E6E6E6; background: #ffffff; float: left; } #yoo-zoo .item div.pos-author div.sub-pos-media > a { display: inline-block; } #yoo-zoo .item div.pos-author h4.sub-pos-title { margin: 3px 0px 0px 0px; font-size: 16px; font-weight: normal; line-height: 18px; color: #323232; } #yoo-zoo .item div.pos-author div.sub-pos-description {} #yoo-zoo .item div.pos-author p.sub-pos-links { margin: 0px; } #yoo-zoo .item div.pos-author p.sub-pos-links span a:after { content: " »"; font-size: 14px; }
foxbei/joomla15
media/zoo/applications/blog/templates/default/assets/css/item.css
CSS
gpl-2.0
4,038
subroutine KKT(no,ni,x,y,d,a,nlam,flog) IMPLICIT NONE integer :: no integer :: ni integer :: nlam integer :: jerr double precision :: x(no,ni) double precision :: y(no) double precision :: d(no) double precision :: a(ni,nlam) double precision :: flog(ni,nlam) ! working variable integer :: i integer :: j integer :: n_s integer :: lam double precision :: fmax double precision :: t0 double precision :: f(no,nlam) double precision :: e(no,nlam) double precision :: r(ni) double precision :: xm integer :: idx(no) integer :: i_s(no) integer :: irs(no) r = 0.0 do j=1,ni xm=sum(x(:,j))/no x(:,j)=x(:,j)-xm enddo f=0.0 fmax=log(huge(f(1,1))*0.1) call riskidx(no,y,d,n_s,i_s,idx,t0,jerr) call failure(no,n_s,i_s,idx,irs) if(jerr /= 0) return f=matmul(x,a) e=exp(sign(min(abs(f),fmax),f)) do lam=1,nlam call derivative(no,ni,n_s,i_s,idx,x,e(:,lam),irs,r) flog(:,lam) = r enddo return end
emeryyi/fastcox
src-x86_64/KKT.f90
FORTRAN
gpl-2.0
1,480
/*********************************************************************** * mt4j Copyright (c) 2008 - 2009, C.Ruff, Fraunhofer-Gesellschaft All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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/>. * ***********************************************************************/ package org.mt4j.components.visibleComponents.widgets.keyboard; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.mt4j.components.MTComponent; import org.mt4j.components.StateChange; import org.mt4j.components.StateChangeEvent; import org.mt4j.components.StateChangeListener; import org.mt4j.components.visibleComponents.font.FontManager; import org.mt4j.components.visibleComponents.font.IFont; import org.mt4j.components.visibleComponents.shapes.AbstractShape; import org.mt4j.components.visibleComponents.widgets.MTTextArea; import org.mt4j.components.visibleComponents.widgets.MTTextArea.ExpandDirection; import org.mt4j.components.visibleComponents.widgets.buttons.MTSvgButton; import org.mt4j.input.gestureAction.DefaultDragAction; import org.mt4j.input.inputProcessors.MTGestureEvent; import org.mt4j.input.inputProcessors.componentProcessors.dragProcessor.DragEvent; import org.mt4j.input.inputProcessors.componentProcessors.dragProcessor.DragProcessor; import org.mt4j.input.inputProcessors.componentProcessors.lassoProcessor.LassoProcessor; import org.mt4j.input.inputProcessors.componentProcessors.rotateProcessor.RotateProcessor; import org.mt4j.input.inputProcessors.componentProcessors.scaleProcessor.ScaleProcessor; import org.mt4j.input.inputProcessors.componentProcessors.tapProcessor.TapEvent; import org.mt4j.util.MT4jSettings; import org.mt4j.util.MTColor; import org.mt4j.util.math.Matrix; import org.mt4j.util.math.Vector3D; import processing.core.PApplet; /** * A multitouch keyboard with an attached textfield that can be written to. * * @author Christopher Ruff */ public class MTTextKeyboard extends MTKeyboard { /** The font for text field. */ private IFont fontForTextField; /** The parent to add new text area to. */ private MTComponent parentToAddNewTextAreaTo; /** The clustering gesture analyzer. */ private LassoProcessor lassoProcessor; //Gesture Actions /** The default drag action. */ private DefaultDragAction defaultDragAction; // private DefaultRotateAction defaultRotateAction; // private DefaultScaleAction defaultScaleAction; /** The drag from keyb action. */ private DragTextAreaFromKeyboardAction dragFromKeybAction; /** The pa. */ private PApplet pa; private ITextInputListener textInputListener; /** * Creates a new keyboard with a default font for its textarea. * * @param pApplet the applet */ public MTTextKeyboard(PApplet pApplet) { this(pApplet, FontManager.getInstance().createFont(pApplet, "arial.ttf", 35, new MTColor(0,0,0,255), new MTColor(0,0,0,255))); // this(pApplet, FontManager.getInstance().createFont(pApplet, "Eureka90.vlw", 35, new Color(0,0,0,255), new Color(0,0,0,255))); // this(pApplet, FontManager.getInstance().createFont(pApplet, "arial", 35, new Color(0,0,0,255), new Color(0,0,0,255))); } /** * Creates a new keyboard with the specified font for its textarea. * * @param pApplet the applet * @param fontForTextField the font for text field */ public MTTextKeyboard(PApplet pApplet, IFont fontForTextField) { super(pApplet); this.pa = pApplet; this.fontForTextField = fontForTextField; lassoProcessor = null; //Set up gesture actions defaultDragAction = new DefaultDragAction(); // defaultRotateAction = new DefaultRotateAction(); // defaultScaleAction = new DefaultScaleAction(); dragFromKeybAction = new DragTextAreaFromKeyboardAction(); MTSvgButton newTextFieldSvg = new MTSvgButton(MT4jSettings.getInstance().getDefaultSVGPath() + "keybNewTextField.svg", pa); newTextFieldSvg.setBoundsPickingBehaviour(AbstractShape.BOUNDS_ONLY_CHECK); newTextFieldSvg.scale(0.8f, 0.8f, 1, new Vector3D(0,0,0)); newTextFieldSvg.translate(new Vector3D(10,5,0)); newTextFieldSvg.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() instanceof MTComponent){ MTComponent clickedComp = (MTComponent)arg0.getSource(); switch (arg0.getID()) { case TapEvent.BUTTON_CLICKED: //should always be keyboard MTComponent parent = clickedComp.getParent(); if (parent instanceof MTTextKeyboard){ MTTextKeyboard keyboard = (MTTextKeyboard)parent; //Remove old Textfield from keyboard if there is any if (textInputListener != null){ if (textInputListener instanceof MTTextArea){ MTTextArea ta = (MTTextArea)textInputListener; ta.setGestureAllowance(DragProcessor.class, true); ta.setGestureAllowance(RotateProcessor.class, true); ta.setGestureAllowance(ScaleProcessor.class, true); ta.setEnableCaret(false); //Add to clusteranylyzer for clustering the tarea if (getLassoProcessor() != null){ getLassoProcessor().addClusterable(ta); } // keyboard.setTextInputAcceptor(null); removeTextInputListener(textInputListener); textInputListener = null; ta.removeAllGestureEventListeners(DragProcessor.class); ta.addGestureListener(DragProcessor.class, defaultDragAction); // ta.unassignGestureClassAndAction(DragGestureAnalyzer.class); // ta.assignGestureClassAndAction(DragGestureAnalyzer.class, defaultDragAction); //The direction, in which the textarea will float off Vector3D v = new Vector3D(0,-100, 0); //Add the textarea to the set parent if (getParentToAddNewTextAreaTo() != null){ //Transform the textarea so it appears at the same world coords after its added to another parent Matrix m = MTComponent.getTransformToDestinationParentSpace(ta, getParentToAddNewTextAreaTo()); ta.transform(m); //Transform the direction vector for the translation animation //to preserve the direction from the old reference frame to the new parents one // v.transformNormal(m); v.transformDirectionVector(m); ta.tweenTranslate(v, 500, 0.3f, 0.7f); getParentToAddNewTextAreaTo().addChild(ta); }else{ //If that isnt set, try to add it to the keyboards parent if (getParent() != null){ ///////////////////////// // Transform the textarea so it appears at the same place after its added to another parent Matrix m = MTComponent.getTransformToDestinationParentSpace(ta, getParent()); ta.transform(m); //Transform the direction vector to preserve the global direction //from the old reference frame to the new parents one //The translation part has to be removed from the matrix because we're transforming //a translation vector not a point vector v.transformDirectionVector(m); ta.tweenTranslate(v, 500, 0.3f, 0.7f); ///////////////////// getParent().addChild(ta); }else{ //do nothing..? throw new RuntimeException("Dont know where to add text area to!"); } } }//if (text instanceof MTTextArea){ }//if (keyboard.getTextInputAcceptor() != null){ //Create a new textarea keyboard.createNewTextArea(); }//if (parent instanceof MTTextKeyboard){ break; default: break; } } } }); this.addChild(newTextFieldSvg); } // @Override // protected void keyboardButtonDown(MTKey clickedKey, boolean shiftPressed){ // ITextInputAcceptor textArea = getTextInputAcceptor(); // if (textArea != null){ // if (clickedKey.getCharacterToWrite().equals("back")){ // textArea.removeLastCharacter(); // }else if (clickedKey.getCharacterToWrite().equals("shift")){ // //no nothing // }else{ // String charToAdd = shiftPressed ? clickedKey.getCharacterToWriteShifted() : clickedKey.getCharacterToWrite(); // textArea.appendCharByUnicode(charToAdd); // } // } // } /** * Creates a new textarea at the keyboard. * Fails if there is still one attached to it. */ public void createNewTextArea(){ if (this.textInputListener == null){ final MTTextArea t = new MTTextArea(pa, fontForTextField); this.textInputListener = t; t.setExpandDirection(ExpandDirection.UP); t.setStrokeColor(new MTColor(0,0 , 0, 255)); t.setFillColor(new MTColor(205,200,177, 255)); t.setGestureAllowance(DragProcessor.class, true); t.setGestureAllowance(RotateProcessor.class, false); t.setGestureAllowance(ScaleProcessor.class, false); t.removeAllGestureEventListeners(DragProcessor.class); t.addGestureListener(DragProcessor.class, dragFromKeybAction); t.setEnableCaret(true); t.snapToKeyboard(this); this.addTextInputListener(this.textInputListener); //Remove textarea from listening if destroyed t.addStateChangeListener(StateChange.COMPONENT_DESTROYED, new StateChangeListener() { public void stateChanged(StateChangeEvent evt) { removeTextInputListener(t); } }); }else{ System.err.println("Cant create new textarea - Keyboard still has a textarea attached."); } } /** * Gets the parent to add new text area to. * * @return the parent to add new text area to */ public MTComponent getParentToAddNewTextAreaTo() { return parentToAddNewTextAreaTo; } /** * Determines to which parent the textarea of the keyboard will be added to after * decoupling it from the keyboard. * * @param parentToAddNewTextAreaTo the parent to add new text area to */ public void setParentToAddNewTextAreaTo(MTComponent parentToAddNewTextAreaTo) { this.parentToAddNewTextAreaTo = parentToAddNewTextAreaTo; } /** * Gets the clustering gesture analyzer. * * @return the clustering gesture analyzer */ public LassoProcessor getLassoProcessor() { return lassoProcessor; } /** * Sets the clustering gesture analyzer. * * @param clusteringGestureAnalyzer the new clustering gesture analyzer */ public void setLassoProcessor(LassoProcessor clusteringGestureAnalyzer) { this.lassoProcessor = clusteringGestureAnalyzer; } /** * Gesture action class to be used when a textarea is dragged away from the keyboard. * * @author C.Ruff */ private class DragTextAreaFromKeyboardAction extends DefaultDragAction { /* (non-Javadoc) * @see com.jMT.input.gestureAction.DefaultDragAction#processGesture(com.jMT.input.inputAnalyzers.GestureEvent) */ public boolean processGestureEvent(MTGestureEvent g) { super.processGestureEvent(g); if (g.getId() == MTGestureEvent.GESTURE_ENDED){ if (g instanceof DragEvent){ DragEvent dragEvent = (DragEvent)g; if (dragEvent.getTargetComponent() instanceof MTTextArea){ MTTextArea text = (MTTextArea)dragEvent.getTargetComponent(); //Add default gesture actions to textfield // text.assignGestureClassAndAction(DragGestureAnalyzer.class, defaultDragAction); // text.assignGestureClassAndAction(ScaleGestureAnalyzer.class, defaultScaleAction); // text.assignGestureClassAndAction(RotateGestureAnalyzer.class, defaultRotateAction); text.setGestureAllowance(DragProcessor.class, true); text.setGestureAllowance(RotateProcessor.class, true); text.setGestureAllowance(ScaleProcessor.class, true); //Disable caret showing text.setEnableCaret(false); //Add to clusteranylyzer for clustering the tarea if (getLassoProcessor() != null){ getLassoProcessor().addClusterable(text); } removeTextInputListener(textInputListener); textInputListener = null; text.removeAllGestureEventListeners(DragProcessor.class); text.addGestureListener(DragProcessor.class, defaultDragAction); // text.unassignGestureClassAndAction(DragGestureAnalyzer.class); // text.assignGestureClassAndAction(DragGestureAnalyzer.class, defaultDragAction); // /* //Add the textare to the set parent if (getParentToAddNewTextAreaTo() != null){ text.transform(MTComponent.getTransformToDestinationParentSpace(text, getParentToAddNewTextAreaTo())); getParentToAddNewTextAreaTo().addChild(text); }else{ //If that isnt set, try to add it to the keyboards parent if (getParent() != null){ text.transform(MTComponent.getTransformToDestinationParentSpace(text, getParent())); getParent().addChild(text); }else{ //do nothing.. // throw new RuntimeException("Dont know where to add text area to!"); System.err.println("Dont know where to add text area to!"); } } // */ } } } return false; } } }
Max90/MT4j_Breakout
src/org/mt4j/components/visibleComponents/widgets/keyboard/MTTextKeyboard.java
Java
gpl-2.0
13,725
using System; namespace JR.Stand.Core.Framework { /// <summary> /// 获取索引位置的委托 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public delegate Int32 IndexOfHandler<T>(T t); }
atnet/cms
src/JR.Stand.Core/Framework/IndexOfHandler.cs
C#
gpl-2.0
280
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * PF_INET protocol family socket handler. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Changes (see also sock.c) * * piggy, * Karl Knutson : Socket protocol table * A.N.Kuznetsov : Socket death error in accept(). * John Richardson : Fix non blocking error in connect() * so sockets that fail to connect * don't return -EINPROGRESS. * Alan Cox : Asynchronous I/O support * Alan Cox : Keep correct socket pointer on sock * structures * when accept() ed * Alan Cox : Semantics of SO_LINGER aren't state * moved to close when you look carefully. * With this fixed and the accept bug fixed * some RPC stuff seems happier. * Niibe Yutaka : 4.4BSD style write async I/O * Alan Cox, * Tony Gale : Fixed reuse semantics. * Alan Cox : bind() shouldn't abort existing but dead * sockets. Stops FTP netin:.. I hope. * Alan Cox : bind() works correctly for RAW sockets. * Note that FreeBSD at least was broken * in this respect so be careful with * compatibility tests... * Alan Cox : routing cache support * Alan Cox : memzero the socket structure for * compactness. * Matt Day : nonblock connect error handler * Alan Cox : Allow large numbers of pending sockets * (eg for big web sites), but only if * specifically application requested. * Alan Cox : New buffering throughout IP. Used * dumbly. * Alan Cox : New buffering now used smartly. * Alan Cox : BSD rather than common sense * interpretation of listen. * Germano Caronni : Assorted small races. * Alan Cox : sendmsg/recvmsg basic support. * Alan Cox : Only sendmsg/recvmsg now supported. * Alan Cox : Locked down bind (see security list). * Alan Cox : Loosened bind a little. * Mike McLagan : ADD/DEL DLCI Ioctls * Willy Konynenberg : Transparent proxying support. * David S. Miller : New socket lookup architecture. * Some other random speedups. * Cyrus Durgin : Cleaned up file for kmod hacks. * Andi Kleen : Fix inet_stream_connect TCP race. * * 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. */ #define pr_fmt(fmt) "IPv4: " fmt #include <linux/err.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/capability.h> #include <linux/fcntl.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/stat.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/netfilter_ipv4.h> #include <linux/random.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <linux/inet.h> #include <linux/igmp.h> #include <linux/inetdevice.h> #include <linux/netdevice.h> #include <net/checksum.h> #include <net/ip.h> #include <net/protocol.h> #include <net/arp.h> #include <net/route.h> #include <net/ip_fib.h> #include <net/inet_connection_sock.h> #include <net/tcp.h> #include <net/udp.h> #include <net/udplite.h> #include <net/ping.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/raw.h> #include <net/icmp.h> #include <net/ipip.h> #include <net/inet_common.h> #include <net/xfrm.h> #include <net/net_namespace.h> #ifdef CONFIG_IP_MROUTE #include <linux/mroute.h> #endif #ifdef CONFIG_ANDROID_PARANOID_NETWORK #include <linux/android_aid.h> static inline int current_has_network(void) { return in_egroup_p(AID_INET) || capable(CAP_NET_RAW); } #else static inline int current_has_network(void) { return 1; } #endif /* */ static struct list_head inetsw[SOCK_MAX]; static DEFINE_SPINLOCK(inetsw_lock); struct ipv4_config ipv4_config; EXPORT_SYMBOL(ipv4_config); /* */ void inet_sock_destruct(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); __skb_queue_purge(&sk->sk_receive_queue); __skb_queue_purge(&sk->sk_error_queue); sk_mem_reclaim(sk); if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) { pr_err("Attempt to release TCP socket in state %d %p\n", sk->sk_state, sk); return; } if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive inet socket %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); WARN_ON(sk->sk_wmem_queued); WARN_ON(sk->sk_forward_alloc); kfree(rcu_dereference_protected(inet->inet_opt, 1)); dst_release(rcu_dereference_check(sk->sk_dst_cache, 1)); sk_refcnt_debug_dec(sk); } EXPORT_SYMBOL(inet_sock_destruct); /* */ /* */ static int inet_autobind(struct sock *sk) { struct inet_sock *inet; /* */ lock_sock(sk); inet = inet_sk(sk); if (!inet->inet_num) { if (sk->sk_prot->get_port(sk, 0)) { release_sock(sk); return -EAGAIN; } inet->inet_sport = htons(inet->inet_num); } release_sock(sk); return 0; } /* */ int inet_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; unsigned char old_state; int err; lock_sock(sk); err = -EINVAL; if (sock->state != SS_UNCONNECTED || sock->type != SOCK_STREAM) goto out; old_state = sk->sk_state; if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN))) goto out; /* */ if (old_state != TCP_LISTEN) { err = inet_csk_listen_start(sk, backlog); if (err) goto out; } sk->sk_max_ack_backlog = backlog; err = 0; out: release_sock(sk); return err; } EXPORT_SYMBOL(inet_listen); u32 inet_ehash_secret __read_mostly; EXPORT_SYMBOL(inet_ehash_secret); /* */ void build_ehash_secret(void) { u32 rnd; do { get_random_bytes(&rnd, sizeof(rnd)); } while (rnd == 0); cmpxchg(&inet_ehash_secret, 0, rnd); } EXPORT_SYMBOL(build_ehash_secret); static inline int inet_netns_ok(struct net *net, int protocol) { int hash; const struct net_protocol *ipprot; if (net_eq(net, &init_net)) return 1; hash = protocol & (MAX_INET_PROTOS - 1); ipprot = rcu_dereference(inet_protos[hash]); if (ipprot == NULL) /* */ return 1; return ipprot->netns_ok; } /* */ static int inet_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct inet_protosw *answer; struct inet_sock *inet; struct proto *answer_prot; unsigned char answer_flags; char answer_no_check; int try_loading_module = 0; int err; if (!current_has_network()) return -EACCES; if (unlikely(!inet_ehash_secret)) if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM) build_ehash_secret(); sock->state = SS_UNCONNECTED; /* */ lookup_protocol: err = -ESOCKTNOSUPPORT; rcu_read_lock(); list_for_each_entry_rcu(answer, &inetsw[sock->type], list) { err = 0; /* */ if (protocol == answer->protocol) { if (protocol != IPPROTO_IP) break; } else { /* */ if (IPPROTO_IP == protocol) { protocol = answer->protocol; break; } if (IPPROTO_IP == answer->protocol) break; } err = -EPROTONOSUPPORT; } if (unlikely(err)) { if (try_loading_module < 2) { rcu_read_unlock(); /* */ if (++try_loading_module == 1) request_module("net-pf-%d-proto-%d-type-%d", PF_INET, protocol, sock->type); /* */ else request_module("net-pf-%d-proto-%d", PF_INET, protocol); goto lookup_protocol; } else goto out_rcu_unlock; } err = -EPERM; if (sock->type == SOCK_RAW && !kern && !capable(CAP_NET_RAW)) goto out_rcu_unlock; err = -EAFNOSUPPORT; if (!inet_netns_ok(net, protocol)) goto out_rcu_unlock; sock->ops = answer->ops; answer_prot = answer->prot; answer_no_check = answer->no_check; answer_flags = answer->flags; rcu_read_unlock(); WARN_ON(answer_prot->slab == NULL); err = -ENOBUFS; sk = sk_alloc(net, PF_INET, GFP_KERNEL, answer_prot); if (sk == NULL) goto out; err = 0; sk->sk_no_check = answer_no_check; if (INET_PROTOSW_REUSE & answer_flags) sk->sk_reuse = 1; inet = inet_sk(sk); inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0; inet->nodefrag = 0; if (SOCK_RAW == sock->type) { inet->inet_num = protocol; if (IPPROTO_RAW == protocol) inet->hdrincl = 1; } if (ipv4_config.no_pmtu_disc) inet->pmtudisc = IP_PMTUDISC_DONT; else inet->pmtudisc = IP_PMTUDISC_WANT; inet->inet_id = 0; sock_init_data(sock, sk); sk->sk_destruct = inet_sock_destruct; sk->sk_protocol = protocol; sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv; inet->uc_ttl = -1; inet->mc_loop = 1; inet->mc_ttl = 1; inet->mc_all = 1; inet->mc_index = 0; inet->mc_list = NULL; inet->rcv_tos = 0; sk_refcnt_debug_inc(sk); if (inet->inet_num) { /* */ inet->inet_sport = htons(inet->inet_num); /* */ sk->sk_prot->hash(sk); } if (sk->sk_prot->init) { err = sk->sk_prot->init(sk); if (err) sk_common_release(sk); } out: return err; out_rcu_unlock: rcu_read_unlock(); goto out; } /* */ int inet_release(struct socket *sock) { struct sock *sk = sock->sk; if (sk) { long timeout; sock_rps_reset_flow(sk); /* */ ip_mc_drop_socket(sk); /* */ timeout = 0; if (sock_flag(sk, SOCK_LINGER) && !(current->flags & PF_EXITING)) timeout = sk->sk_lingertime; sock->sk = NULL; sk->sk_prot->close(sk, timeout); } return 0; } EXPORT_SYMBOL(inet_release); /* */ int sysctl_ip_nonlocal_bind __read_mostly; EXPORT_SYMBOL(sysctl_ip_nonlocal_bind); int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in *addr = (struct sockaddr_in *)uaddr; struct sock *sk = sock->sk; struct inet_sock *inet = inet_sk(sk); unsigned short snum; int chk_addr_ret; int err; /* */ if (sk->sk_prot->bind) { err = sk->sk_prot->bind(sk, uaddr, addr_len); goto out; } err = -EINVAL; if (addr_len < sizeof(struct sockaddr_in)) goto out; if (addr->sin_family != AF_INET) { /* */ err = -EAFNOSUPPORT; if (addr->sin_family != AF_UNSPEC || addr->sin_addr.s_addr != htonl(INADDR_ANY)) goto out; } chk_addr_ret = inet_addr_type(sock_net(sk), addr->sin_addr.s_addr); /* */ err = -EADDRNOTAVAIL; if (!sysctl_ip_nonlocal_bind && !(inet->freebind || inet->transparent) && addr->sin_addr.s_addr != htonl(INADDR_ANY) && chk_addr_ret != RTN_LOCAL && chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST) goto out; snum = ntohs(addr->sin_port); err = -EACCES; if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE)) goto out; /* We keep a pair of addresses. rcv_saddr is the one * used by hash lookups, and saddr is used for transmit. * * In the BSD API these are the same except where it * would be illegal to use them (multicast/broadcast) in * which case the sending device address is used. */ lock_sock(sk); /* */ err = -EINVAL; if (sk->sk_state != TCP_CLOSE || inet->inet_num) goto out_release_sock; inet->inet_rcv_saddr = inet->inet_saddr = addr->sin_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST) inet->inet_saddr = 0; /* */ /* */ if (sk->sk_prot->get_port(sk, snum)) { inet->inet_saddr = inet->inet_rcv_saddr = 0; err = -EADDRINUSE; goto out_release_sock; } if (inet->inet_rcv_saddr) sk->sk_userlocks |= SOCK_BINDADDR_LOCK; if (snum) sk->sk_userlocks |= SOCK_BINDPORT_LOCK; inet->inet_sport = htons(inet->inet_num); inet->inet_daddr = 0; inet->inet_dport = 0; sk_dst_reset(sk); err = 0; out_release_sock: release_sock(sk); out: return err; } EXPORT_SYMBOL(inet_bind); int inet_dgram_connect(struct socket *sock, struct sockaddr * uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; if (addr_len < sizeof(uaddr->sa_family)) return -EINVAL; if (uaddr->sa_family == AF_UNSPEC) return sk->sk_prot->disconnect(sk, flags); if (!inet_sk(sk)->inet_num && inet_autobind(sk)) return -EAGAIN; return sk->sk_prot->connect(sk, (struct sockaddr *)uaddr, addr_len); } EXPORT_SYMBOL(inet_dgram_connect); static long inet_wait_for_connect(struct sock *sk, long timeo) { DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); /* */ while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) { release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); if (signal_pending(current) || !timeo) break; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* */ int inet_stream_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; int err; long timeo; if (addr_len < sizeof(uaddr->sa_family)) return -EINVAL; lock_sock(sk); if (uaddr->sa_family == AF_UNSPEC) { err = sk->sk_prot->disconnect(sk, flags); sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED; goto out; } switch (sock->state) { default: err = -EINVAL; goto out; case SS_CONNECTED: err = -EISCONN; goto out; case SS_CONNECTING: err = -EALREADY; /* */ break; case SS_UNCONNECTED: err = -EISCONN; if (sk->sk_state != TCP_CLOSE) goto out; err = sk->sk_prot->connect(sk, uaddr, addr_len); if (err < 0) goto out; sock->state = SS_CONNECTING; /* */ err = -EINPROGRESS; break; } timeo = sock_sndtimeo(sk, flags & O_NONBLOCK); if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) { /* */ if (!timeo || !inet_wait_for_connect(sk, timeo)) goto out; err = sock_intr_errno(timeo); if (signal_pending(current)) goto out; } /* */ if (sk->sk_state == TCP_CLOSE) goto sock_error; /* */ sock->state = SS_CONNECTED; err = 0; out: release_sock(sk); return err; sock_error: err = sock_error(sk) ? : -ECONNABORTED; sock->state = SS_UNCONNECTED; if (sk->sk_prot->disconnect(sk, flags)) sock->state = SS_DISCONNECTING; goto out; } EXPORT_SYMBOL(inet_stream_connect); /* * Accept a pending connection. The TCP layer now gives BSD semantics. */ int inet_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk1 = sock->sk; int err = -EINVAL; struct sock *sk2 = sk1->sk_prot->accept(sk1, flags, &err); if (!sk2) goto do_err; lock_sock(sk2); sock_rps_record_flow(sk2); WARN_ON(!((1 << sk2->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_CLOSE))); sock_graft(sk2, newsock); newsock->state = SS_CONNECTED; err = 0; release_sock(sk2); do_err: return err; } EXPORT_SYMBOL(inet_accept); /* */ int inet_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sock *sk = sock->sk; struct inet_sock *inet = inet_sk(sk); DECLARE_SOCKADDR(struct sockaddr_in *, sin, uaddr); sin->sin_family = AF_INET; if (peer) { if (!inet->inet_dport || (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) && peer == 1)) return -ENOTCONN; sin->sin_port = inet->inet_dport; sin->sin_addr.s_addr = inet->inet_daddr; } else { __be32 addr = inet->inet_rcv_saddr; if (!addr) addr = inet->inet_saddr; sin->sin_port = inet->inet_sport; sin->sin_addr.s_addr = addr; } memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *uaddr_len = sizeof(*sin); return 0; } EXPORT_SYMBOL(inet_getname); int inet_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { struct sock *sk = sock->sk; sock_rps_record_flow(sk); /* */ if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind && inet_autobind(sk)) return -EAGAIN; return sk->sk_prot->sendmsg(iocb, sk, msg, size); } EXPORT_SYMBOL(inet_sendmsg); ssize_t inet_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { struct sock *sk = sock->sk; sock_rps_record_flow(sk); /* */ if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind && inet_autobind(sk)) return -EAGAIN; if (sk->sk_prot->sendpage) return sk->sk_prot->sendpage(sk, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } EXPORT_SYMBOL(inet_sendpage); int inet_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int addr_len = 0; int err; sock_rps_record_flow(sk); err = sk->sk_prot->recvmsg(iocb, sk, msg, size, flags & MSG_DONTWAIT, flags & ~MSG_DONTWAIT, &addr_len); if (err >= 0) msg->msg_namelen = addr_len; return err; } EXPORT_SYMBOL(inet_recvmsg); int inet_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; /* */ how++; /* */ if ((how & ~SHUTDOWN_MASK) || !how) /* */ return -EINVAL; lock_sock(sk); if (sock->state == SS_CONNECTING) { if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE)) sock->state = SS_DISCONNECTING; else sock->state = SS_CONNECTED; } switch (sk->sk_state) { case TCP_CLOSE: err = -ENOTCONN; /* */ default: sk->sk_shutdown |= how; if (sk->sk_prot->shutdown) sk->sk_prot->shutdown(sk, how); break; /* */ case TCP_LISTEN: if (!(how & RCV_SHUTDOWN)) break; /* */ case TCP_SYN_SENT: err = sk->sk_prot->disconnect(sk, O_NONBLOCK); sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED; break; } /* */ sk->sk_state_change(sk); release_sock(sk); return err; } EXPORT_SYMBOL(inet_shutdown); /* */ int inet_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; int err = 0; struct net *net = sock_net(sk); switch (cmd) { case SIOCGSTAMP: err = sock_get_timestamp(sk, (struct timeval __user *)arg); break; case SIOCGSTAMPNS: err = sock_get_timestampns(sk, (struct timespec __user *)arg); break; case SIOCADDRT: case SIOCDELRT: case SIOCRTMSG: err = ip_rt_ioctl(net, cmd, (void __user *)arg); break; case SIOCDARP: case SIOCGARP: case SIOCSARP: err = arp_ioctl(net, cmd, (void __user *)arg); break; case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCSIFFLAGS: case SIOCKILLADDR: err = devinet_ioctl(net, cmd, (void __user *)arg); break; default: if (sk->sk_prot->ioctl) err = sk->sk_prot->ioctl(sk, cmd, arg); else err = -ENOIOCTLCMD; break; } return err; } EXPORT_SYMBOL(inet_ioctl); #ifdef CONFIG_COMPAT static int inet_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; int err = -ENOIOCTLCMD; if (sk->sk_prot->compat_ioctl) err = sk->sk_prot->compat_ioctl(sk, cmd, arg); return err; } #endif const struct proto_ops inet_stream_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_stream_connect, .socketpair = sock_no_socketpair, .accept = inet_accept, .getname = inet_getname, .poll = tcp_poll, .ioctl = inet_ioctl, .listen = inet_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = inet_recvmsg, .mmap = sock_no_mmap, .sendpage = inet_sendpage, .splice_read = tcp_splice_read, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, .compat_ioctl = inet_compat_ioctl, #endif }; EXPORT_SYMBOL(inet_stream_ops); const struct proto_ops inet_dgram_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = inet_getname, .poll = udp_poll, .ioctl = inet_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = inet_recvmsg, .mmap = sock_no_mmap, .sendpage = inet_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, .compat_ioctl = inet_compat_ioctl, #endif }; EXPORT_SYMBOL(inet_dgram_ops); /* */ static const struct proto_ops inet_sockraw_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = inet_getname, .poll = datagram_poll, .ioctl = inet_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = inet_recvmsg, .mmap = sock_no_mmap, .sendpage = inet_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, .compat_ioctl = inet_compat_ioctl, #endif }; static const struct net_proto_family inet_family_ops = { .family = PF_INET, .create = inet_create, .owner = THIS_MODULE, }; /* */ static struct inet_protosw inetsw_array[] = { { .type = SOCK_STREAM, .protocol = IPPROTO_TCP, .prot = &tcp_prot, .ops = &inet_stream_ops, .no_check = 0, .flags = INET_PROTOSW_PERMANENT | INET_PROTOSW_ICSK, }, { .type = SOCK_DGRAM, .protocol = IPPROTO_UDP, .prot = &udp_prot, .ops = &inet_dgram_ops, .no_check = UDP_CSUM_DEFAULT, .flags = INET_PROTOSW_PERMANENT, }, { .type = SOCK_DGRAM, .protocol = IPPROTO_ICMP, .prot = &ping_prot, .ops = &inet_dgram_ops, .no_check = UDP_CSUM_DEFAULT, .flags = INET_PROTOSW_REUSE, }, { .type = SOCK_RAW, .protocol = IPPROTO_IP, /* */ .prot = &raw_prot, .ops = &inet_sockraw_ops, .no_check = UDP_CSUM_DEFAULT, .flags = INET_PROTOSW_REUSE, } }; #define INETSW_ARRAY_LEN ARRAY_SIZE(inetsw_array) void inet_register_protosw(struct inet_protosw *p) { struct list_head *lh; struct inet_protosw *answer; int protocol = p->protocol; struct list_head *last_perm; spin_lock_bh(&inetsw_lock); if (p->type >= SOCK_MAX) goto out_illegal; /* */ answer = NULL; last_perm = &inetsw[p->type]; list_for_each(lh, &inetsw[p->type]) { answer = list_entry(lh, struct inet_protosw, list); /* */ if (INET_PROTOSW_PERMANENT & answer->flags) { if (protocol == answer->protocol) break; last_perm = lh; } answer = NULL; } if (answer) goto out_permanent; /* */ list_add_rcu(&p->list, last_perm); out: spin_unlock_bh(&inetsw_lock); return; out_permanent: pr_err("Attempt to override permanent protocol %d\n", protocol); goto out; out_illegal: pr_err("Ignoring attempt to register invalid socket type %d\n", p->type); goto out; } EXPORT_SYMBOL(inet_register_protosw); void inet_unregister_protosw(struct inet_protosw *p) { if (INET_PROTOSW_PERMANENT & p->flags) { pr_err("Attempt to unregister permanent protocol %d\n", p->protocol); } else { spin_lock_bh(&inetsw_lock); list_del_rcu(&p->list); spin_unlock_bh(&inetsw_lock); synchronize_net(); } } EXPORT_SYMBOL(inet_unregister_protosw); /* */ int sysctl_ip_dynaddr __read_mostly; static int inet_sk_reselect_saddr(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); __be32 old_saddr = inet->inet_saddr; __be32 daddr = inet->inet_daddr; struct flowi4 *fl4; struct rtable *rt; __be32 new_saddr; struct ip_options_rcu *inet_opt; inet_opt = rcu_dereference_protected(inet->inet_opt, sock_owned_by_user(sk)); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; /* */ fl4 = &inet->cork.fl.u.ip4; rt = ip_route_connect(fl4, daddr, 0, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, sk->sk_protocol, inet->inet_sport, inet->inet_dport, sk, false); if (IS_ERR(rt)) return PTR_ERR(rt); sk_setup_caps(sk, &rt->dst); new_saddr = fl4->saddr; if (new_saddr == old_saddr) return 0; if (sysctl_ip_dynaddr > 1) { pr_info("%s(): shifting inet->saddr from %pI4 to %pI4\n", __func__, &old_saddr, &new_saddr); } inet->inet_saddr = inet->inet_rcv_saddr = new_saddr; /* */ __sk_prot_rehash(sk); return 0; } int inet_sk_rebuild_header(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0); __be32 daddr; struct ip_options_rcu *inet_opt; struct flowi4 *fl4; int err; /* */ if (rt) return 0; /* */ rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); daddr = inet->inet_daddr; if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; rcu_read_unlock(); fl4 = &inet->cork.fl.u.ip4; rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (!IS_ERR(rt)) { err = 0; sk_setup_caps(sk, &rt->dst); } else { err = PTR_ERR(rt); /* */ sk->sk_route_caps = 0; /* */ if (!sysctl_ip_dynaddr || sk->sk_state != TCP_SYN_SENT || (sk->sk_userlocks & SOCK_BINDADDR_LOCK) || (err = inet_sk_reselect_saddr(sk)) != 0) sk->sk_err_soft = -err; } return err; } EXPORT_SYMBOL(inet_sk_rebuild_header); static int inet_gso_send_check(struct sk_buff *skb) { const struct iphdr *iph; const struct net_protocol *ops; int proto; int ihl; int err = -EINVAL; if (unlikely(!pskb_may_pull(skb, sizeof(*iph)))) goto out; iph = ip_hdr(skb); ihl = iph->ihl * 4; if (ihl < sizeof(*iph)) goto out; if (unlikely(!pskb_may_pull(skb, ihl))) goto out; __skb_pull(skb, ihl); skb_reset_transport_header(skb); iph = ip_hdr(skb); proto = iph->protocol & (MAX_INET_PROTOS - 1); err = -EPROTONOSUPPORT; rcu_read_lock(); ops = rcu_dereference(inet_protos[proto]); if (likely(ops && ops->gso_send_check)) err = ops->gso_send_check(skb); rcu_read_unlock(); out: return err; } static struct sk_buff *inet_gso_segment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); struct iphdr *iph; const struct net_protocol *ops; int proto; int ihl; int id; unsigned int offset = 0; if (!(features & NETIF_F_V4_CSUM)) features &= ~NETIF_F_SG; if (unlikely(skb_shinfo(skb)->gso_type & ~(SKB_GSO_TCPV4 | SKB_GSO_UDP | SKB_GSO_DODGY | SKB_GSO_TCP_ECN | 0))) goto out; if (unlikely(!pskb_may_pull(skb, sizeof(*iph)))) goto out; iph = ip_hdr(skb); ihl = iph->ihl * 4; if (ihl < sizeof(*iph)) goto out; if (unlikely(!pskb_may_pull(skb, ihl))) goto out; __skb_pull(skb, ihl); skb_reset_transport_header(skb); iph = ip_hdr(skb); id = ntohs(iph->id); proto = iph->protocol & (MAX_INET_PROTOS - 1); segs = ERR_PTR(-EPROTONOSUPPORT); rcu_read_lock(); ops = rcu_dereference(inet_protos[proto]); if (likely(ops && ops->gso_segment)) segs = ops->gso_segment(skb, features); rcu_read_unlock(); if (!segs || IS_ERR(segs)) goto out; skb = segs; do { iph = ip_hdr(skb); if (proto == IPPROTO_UDP) { iph->id = htons(id); iph->frag_off = htons(offset >> 3); if (skb->next != NULL) iph->frag_off |= htons(IP_MF); offset += (skb->len - skb->mac_len - iph->ihl * 4); } else iph->id = htons(id++); iph->tot_len = htons(skb->len - skb->mac_len); iph->check = 0; iph->check = ip_fast_csum(skb_network_header(skb), iph->ihl); } while ((skb = skb->next)); out: return segs; } static struct sk_buff **inet_gro_receive(struct sk_buff **head, struct sk_buff *skb) { const struct net_protocol *ops; struct sk_buff **pp = NULL; struct sk_buff *p; const struct iphdr *iph; unsigned int hlen; unsigned int off; unsigned int id; int flush = 1; int proto; off = skb_gro_offset(skb); hlen = off + sizeof(*iph); iph = skb_gro_header_fast(skb, off); if (skb_gro_header_hard(skb, hlen)) { iph = skb_gro_header_slow(skb, hlen, off); if (unlikely(!iph)) goto out; } proto = iph->protocol & (MAX_INET_PROTOS - 1); rcu_read_lock(); ops = rcu_dereference(inet_protos[proto]); if (!ops || !ops->gro_receive) goto out_unlock; if (*(u8 *)iph != 0x45) goto out_unlock; if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl))) goto out_unlock; id = ntohl(*(__be32 *)&iph->id); flush = (u16)((ntohl(*(__be32 *)iph) ^ skb_gro_len(skb)) | (id ^ IP_DF)); id >>= 16; for (p = *head; p; p = p->next) { struct iphdr *iph2; if (!NAPI_GRO_CB(p)->same_flow) continue; iph2 = ip_hdr(p); if ((iph->protocol ^ iph2->protocol) | (iph->tos ^ iph2->tos) | ((__force u32)iph->saddr ^ (__force u32)iph2->saddr) | ((__force u32)iph->daddr ^ (__force u32)iph2->daddr)) { NAPI_GRO_CB(p)->same_flow = 0; continue; } /* */ NAPI_GRO_CB(p)->flush |= (iph->ttl ^ iph2->ttl) | ((u16)(ntohs(iph2->id) + NAPI_GRO_CB(p)->count) ^ id); NAPI_GRO_CB(p)->flush |= flush; } NAPI_GRO_CB(skb)->flush |= flush; skb_gro_pull(skb, sizeof(*iph)); skb_set_transport_header(skb, skb_gro_offset(skb)); pp = ops->gro_receive(head, skb); out_unlock: rcu_read_unlock(); out: NAPI_GRO_CB(skb)->flush |= flush; return pp; } static int inet_gro_complete(struct sk_buff *skb) { const struct net_protocol *ops; struct iphdr *iph = ip_hdr(skb); int proto = iph->protocol & (MAX_INET_PROTOS - 1); int err = -ENOSYS; __be16 newlen = htons(skb->len - skb_network_offset(skb)); csum_replace2(&iph->check, iph->tot_len, newlen); iph->tot_len = newlen; rcu_read_lock(); ops = rcu_dereference(inet_protos[proto]); if (WARN_ON(!ops || !ops->gro_complete)) goto out_unlock; err = ops->gro_complete(skb); out_unlock: rcu_read_unlock(); return err; } int inet_ctl_sock_create(struct sock **sk, unsigned short family, unsigned short type, unsigned char protocol, struct net *net) { struct socket *sock; int rc = sock_create_kern(family, type, protocol, &sock); if (rc == 0) { *sk = sock->sk; (*sk)->sk_allocation = GFP_ATOMIC; /* */ (*sk)->sk_prot->unhash(*sk); sk_change_net(*sk, net); } return rc; } EXPORT_SYMBOL_GPL(inet_ctl_sock_create); unsigned long snmp_fold_field(void __percpu *mib[], int offt) { unsigned long res = 0; int i, j; for_each_possible_cpu(i) { for (j = 0; j < SNMP_ARRAY_SZ; j++) res += *(((unsigned long *) per_cpu_ptr(mib[j], i)) + offt); } return res; } EXPORT_SYMBOL_GPL(snmp_fold_field); #if BITS_PER_LONG==32 u64 snmp_fold_field64(void __percpu *mib[], int offt, size_t syncp_offset) { u64 res = 0; int cpu; for_each_possible_cpu(cpu) { void *bhptr; struct u64_stats_sync *syncp; u64 v; unsigned int start; bhptr = per_cpu_ptr(mib[0], cpu); syncp = (struct u64_stats_sync *)(bhptr + syncp_offset); do { start = u64_stats_fetch_begin_bh(syncp); v = *(((u64 *) bhptr) + offt); } while (u64_stats_fetch_retry_bh(syncp, start)); res += v; } return res; } EXPORT_SYMBOL_GPL(snmp_fold_field64); #endif int snmp_mib_init(void __percpu *ptr[2], size_t mibsize, size_t align) { BUG_ON(ptr == NULL); ptr[0] = __alloc_percpu(mibsize, align); if (!ptr[0]) return -ENOMEM; #if SNMP_ARRAY_SZ == 2 ptr[1] = __alloc_percpu(mibsize, align); if (!ptr[1]) { free_percpu(ptr[0]); ptr[0] = NULL; return -ENOMEM; } #endif return 0; } EXPORT_SYMBOL_GPL(snmp_mib_init); void snmp_mib_free(void __percpu *ptr[SNMP_ARRAY_SZ]) { int i; BUG_ON(ptr == NULL); for (i = 0; i < SNMP_ARRAY_SZ; i++) { free_percpu(ptr[i]); ptr[i] = NULL; } } EXPORT_SYMBOL_GPL(snmp_mib_free); #ifdef CONFIG_IP_MULTICAST static const struct net_protocol igmp_protocol = { .handler = igmp_rcv, .netns_ok = 1, }; #endif static const struct net_protocol tcp_protocol = { .handler = tcp_v4_rcv, .err_handler = tcp_v4_err, .gso_send_check = tcp_v4_gso_send_check, .gso_segment = tcp_tso_segment, .gro_receive = tcp4_gro_receive, .gro_complete = tcp4_gro_complete, .no_policy = 1, .netns_ok = 1, }; static const struct net_protocol udp_protocol = { .handler = udp_rcv, .err_handler = udp_err, .gso_send_check = udp4_ufo_send_check, .gso_segment = udp4_ufo_fragment, .no_policy = 1, .netns_ok = 1, }; static const struct net_protocol icmp_protocol = { .handler = icmp_rcv, .err_handler = ping_v4_err, .no_policy = 1, .netns_ok = 1, }; static __net_init int ipv4_mib_init_net(struct net *net) { if (snmp_mib_init((void __percpu **)net->mib.tcp_statistics, sizeof(struct tcp_mib), __alignof__(struct tcp_mib)) < 0) goto err_tcp_mib; if (snmp_mib_init((void __percpu **)net->mib.ip_statistics, sizeof(struct ipstats_mib), __alignof__(struct ipstats_mib)) < 0) goto err_ip_mib; if (snmp_mib_init((void __percpu **)net->mib.net_statistics, sizeof(struct linux_mib), __alignof__(struct linux_mib)) < 0) goto err_net_mib; if (snmp_mib_init((void __percpu **)net->mib.udp_statistics, sizeof(struct udp_mib), __alignof__(struct udp_mib)) < 0) goto err_udp_mib; if (snmp_mib_init((void __percpu **)net->mib.udplite_statistics, sizeof(struct udp_mib), __alignof__(struct udp_mib)) < 0) goto err_udplite_mib; if (snmp_mib_init((void __percpu **)net->mib.icmp_statistics, sizeof(struct icmp_mib), __alignof__(struct icmp_mib)) < 0) goto err_icmp_mib; net->mib.icmpmsg_statistics = kzalloc(sizeof(struct icmpmsg_mib), GFP_KERNEL); if (!net->mib.icmpmsg_statistics) goto err_icmpmsg_mib; tcp_mib_init(net); return 0; err_icmpmsg_mib: snmp_mib_free((void __percpu **)net->mib.icmp_statistics); err_icmp_mib: snmp_mib_free((void __percpu **)net->mib.udplite_statistics); err_udplite_mib: snmp_mib_free((void __percpu **)net->mib.udp_statistics); err_udp_mib: snmp_mib_free((void __percpu **)net->mib.net_statistics); err_net_mib: snmp_mib_free((void __percpu **)net->mib.ip_statistics); err_ip_mib: snmp_mib_free((void __percpu **)net->mib.tcp_statistics); err_tcp_mib: return -ENOMEM; } static __net_exit void ipv4_mib_exit_net(struct net *net) { kfree(net->mib.icmpmsg_statistics); snmp_mib_free((void __percpu **)net->mib.icmp_statistics); snmp_mib_free((void __percpu **)net->mib.udplite_statistics); snmp_mib_free((void __percpu **)net->mib.udp_statistics); snmp_mib_free((void __percpu **)net->mib.net_statistics); snmp_mib_free((void __percpu **)net->mib.ip_statistics); snmp_mib_free((void __percpu **)net->mib.tcp_statistics); } static __net_initdata struct pernet_operations ipv4_mib_ops = { .init = ipv4_mib_init_net, .exit = ipv4_mib_exit_net, }; static int __init init_ipv4_mibs(void) { return register_pernet_subsys(&ipv4_mib_ops); } static int ipv4_proc_init(void); /* */ static struct packet_type ip_packet_type __read_mostly = { .type = cpu_to_be16(ETH_P_IP), .func = ip_rcv, .gso_send_check = inet_gso_send_check, .gso_segment = inet_gso_segment, .gro_receive = inet_gro_receive, .gro_complete = inet_gro_complete, }; static int __init inet_init(void) { struct sk_buff *dummy_skb; struct inet_protosw *q; struct list_head *r; int rc = -EINVAL; BUILD_BUG_ON(sizeof(struct inet_skb_parm) > sizeof(dummy_skb->cb)); sysctl_local_reserved_ports = kzalloc(65536 / 8, GFP_KERNEL); if (!sysctl_local_reserved_ports) goto out; rc = proto_register(&tcp_prot, 1); if (rc) goto out_free_reserved_ports; rc = proto_register(&udp_prot, 1); if (rc) goto out_unregister_tcp_proto; rc = proto_register(&raw_prot, 1); if (rc) goto out_unregister_udp_proto; rc = proto_register(&ping_prot, 1); if (rc) goto out_unregister_raw_proto; /* */ (void)sock_register(&inet_family_ops); #ifdef CONFIG_SYSCTL ip_static_sysctl_init(); #endif tcp_prot.sysctl_mem = init_net.ipv4.sysctl_tcp_mem; /* */ if (inet_add_protocol(&icmp_protocol, IPPROTO_ICMP) < 0) pr_crit("%s: Cannot add ICMP protocol\n", __func__); if (inet_add_protocol(&udp_protocol, IPPROTO_UDP) < 0) pr_crit("%s: Cannot add UDP protocol\n", __func__); if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0) pr_crit("%s: Cannot add TCP protocol\n", __func__); #ifdef CONFIG_IP_MULTICAST if (inet_add_protocol(&igmp_protocol, IPPROTO_IGMP) < 0) pr_crit("%s: Cannot add IGMP protocol\n", __func__); #endif /* */ for (r = &inetsw[0]; r < &inetsw[SOCK_MAX]; ++r) INIT_LIST_HEAD(r); for (q = inetsw_array; q < &inetsw_array[INETSW_ARRAY_LEN]; ++q) inet_register_protosw(q); /* */ arp_init(); /* */ ip_init(); tcp_v4_init(); /* */ tcp_init(); /* */ udp_init(); /* */ udplite4_register(); ping_init(); /* */ if (icmp_init() < 0) panic("Failed to create the ICMP control socket.\n"); /* */ #if defined(CONFIG_IP_MROUTE) if (ip_mr_init()) pr_crit("%s: Cannot init ipv4 mroute\n", __func__); #endif /* */ if (init_ipv4_mibs()) pr_crit("%s: Cannot init ipv4 mibs\n", __func__); ipv4_proc_init(); ipfrag_init(); dev_add_pack(&ip_packet_type); rc = 0; out: return rc; out_unregister_raw_proto: proto_unregister(&raw_prot); out_unregister_udp_proto: proto_unregister(&udp_prot); out_unregister_tcp_proto: proto_unregister(&tcp_prot); out_free_reserved_ports: kfree(sysctl_local_reserved_ports); goto out; } fs_initcall(inet_init); /* */ #ifdef CONFIG_PROC_FS static int __init ipv4_proc_init(void) { int rc = 0; if (raw_proc_init()) goto out_raw; if (tcp4_proc_init()) goto out_tcp; if (udp4_proc_init()) goto out_udp; if (ping_proc_init()) goto out_ping; if (ip_misc_proc_init()) goto out_misc; out: return rc; out_misc: ping_proc_exit(); out_ping: udp4_proc_exit(); out_udp: tcp4_proc_exit(); out_tcp: raw_proc_exit(); out_raw: rc = -ENOMEM; goto out; } #else /* */ static int __init ipv4_proc_init(void) { return 0; } #endif /* */ MODULE_ALIAS_NETPROTO(PF_INET);
aicjofs/android_kernel_lge_v500
net/ipv4/af_inet.c
C
gpl-2.0
43,980
/* * Copyright (c) 2012, The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _QC_SAP_IOCTL_H_ #define _QC_SAP_IOCTL_H_ /* */ /* */ #define QCSAP_MAX_OPT_IE 256 #define QCSAP_MAX_WSC_IE 256 typedef struct sSSID { u_int8_t length; u_int8_t ssId[32]; } tSSID; typedef struct sSSIDInfo { tSSID ssid; u_int8_t ssidHidden; }tSSIDInfo; typedef enum { eQC_DOT11_MODE_ALL = 0, eQC_DOT11_MODE_ABG = 0x0001, // eQC_DOT11_MODE_11A = 0x0002, eQC_DOT11_MODE_11B = 0x0004, eQC_DOT11_MODE_11G = 0x0008, eQC_DOT11_MODE_11N = 0x0010, eQC_DOT11_MODE_11G_ONLY = 0x0020, eQC_DOT11_MODE_11N_ONLY = 0x0040, eQC_DOT11_MODE_11B_ONLY = 0x0080, eQC_DOT11_MODE_11A_ONLY = 0x0100, // // eQC_DOT11_MODE_AUTO = 0x0200, } tQcPhyMode; #define QCSAP_ADDR_LEN 6 typedef u_int8_t qcmacaddr[QCSAP_ADDR_LEN]; struct qc_mac_acl_entry { qcmacaddr addr; int vlan_id; }; typedef enum { eQC_AUTH_TYPE_OPEN_SYSTEM, eQC_AUTH_TYPE_SHARED_KEY, eQC_AUTH_TYPE_AUTO_SWITCH } eQcAuthType; typedef enum { eQC_WPS_BEACON_IE, eQC_WPS_PROBE_RSP_IE, eQC_WPS_ASSOC_RSP_IE } eQCWPSType; typedef struct s_CommitConfig { tSSIDInfo SSIDinfo; u_int32_t beacon_int; /* */ tQcPhyMode hw_mode; /* */ u_int32_t channel; /* */ u_int32_t max_num_sta; /* */ u_int32_t dtim_period; /* */ u_int32_t max_listen_interval; enum { QC_ACCEPT_UNLESS_DENIED = 0, QC_DENY_UNLESS_ACCEPTED = 1, } qc_macaddr_acl; struct qc_mac_acl_entry *accept_mac; /* */ u_int32_t num_accept_mac; struct qc_mac_acl_entry *deny_mac; /* */ u_int32_t num_deny_mac; u_int32_t ap_table_max_size; u_int32_t ap_table_expiration_time; int qcsap80211d; u_int32_t countryCode[3]; // u_int32_t ht_op_mode_fixed; /* */ u_int16_t ht_capab; u_int32_t qcsap80211n; eQcAuthType authType; u_int8_t privacy; u_int8_t set_ieee8021x; u_int8_t RSNWPAReqIE[QCSAP_MAX_OPT_IE]; // u_int16_t RSNWPAReqIELength; // u_int8_t wps_state; // } s_CommitConfig_t; /* */ struct sQcSapreq_mlme { u_int8_t im_op; /* */ #define QCSAP_MLME_ASSOC 1 /* */ #define QCSAP_MLME_DISASSOC 2 /* */ #define QCSAP_MLME_DEAUTH 3 /* */ #define QCSAP_MLME_AUTHORIZE 4 /* */ #define QCSAP_MLME_UNAUTHORIZE 5 /* */ #define QCSAP_MLME_MICFAILURE 6 /* */ u_int16_t im_reason; /* */ u_int8_t im_macaddr[QCSAP_ADDR_LEN]; }; /* */ struct sQcSapreq_wpaie { u_int8_t wpa_ie[QCSAP_MAX_OPT_IE]; u_int8_t wpa_macaddr[QCSAP_ADDR_LEN]; }; /* */ struct sQcSapreq_wscie { u_int8_t wsc_macaddr[QCSAP_ADDR_LEN]; u_int8_t wsc_ie[QCSAP_MAX_WSC_IE]; }; /* */ typedef struct sQcSapreq_WPSPBCProbeReqIES { u_int8_t macaddr[QCSAP_ADDR_LEN]; u_int16_t probeReqIELen; u_int8_t probeReqIE[512]; } sQcSapreq_WPSPBCProbeReqIES_t ; /* */ typedef struct { v_U8_t num_channels; v_U8_t channels[WNI_CFG_VALID_CHANNEL_LIST_LEN]; }tChannelListInfo, *tpChannelListInfo; #ifdef __linux__ /* */ #define QCSAP_IOCTL_SETPARAM (SIOCIWFIRSTPRIV+0) #define QCSAP_IOCTL_GETPARAM (SIOCIWFIRSTPRIV+1) #define QCSAP_IOCTL_COMMIT (SIOCIWFIRSTPRIV+2) #define QCSAP_IOCTL_SETMLME (SIOCIWFIRSTPRIV+3) #define QCSAP_IOCTL_GET_STAWPAIE (SIOCIWFIRSTPRIV+4) #define QCSAP_IOCTL_SETWPAIE (SIOCIWFIRSTPRIV+5) #define QCSAP_IOCTL_STOPBSS (SIOCIWFIRSTPRIV+6) #define QCSAP_IOCTL_VERSION (SIOCIWFIRSTPRIV+7) #define QCSAP_IOCTL_GET_WPS_PBC_PROBE_REQ_IES (SIOCIWFIRSTPRIV+8) #define QCSAP_IOCTL_GET_CHANNEL (SIOCIWFIRSTPRIV+9) #define QCSAP_IOCTL_ASSOC_STA_MACADDR (SIOCIWFIRSTPRIV+10) #define QCSAP_IOCTL_DISASSOC_STA (SIOCIWFIRSTPRIV+11) #define QCSAP_IOCTL_AP_STATS (SIOCIWFIRSTPRIV+12) #define QCSAP_IOCTL_GET_STATS (SIOCIWFIRSTPRIV+13) #define QCSAP_IOCTL_CLR_STATS (SIOCIWFIRSTPRIV+14) #define QCSAP_IOCTL_PRIV_SET_THREE_INT_GET_NONE (SIOCIWFIRSTPRIV+15) #define WE_SET_WLAN_DBG 1 #define QCSAP_IOCTL_PRIV_SET_VAR_INT_GET_NONE (SIOCIWFIRSTPRIV+16) #define WE_LOG_DUMP_CMD 1 #define QCSAP_IOCTL_SET_CHANNEL_RANGE (SIOCIWFIRSTPRIV+17) #ifdef WLAN_FEATURE_P2P #define WE_P2P_NOA_CMD 2 #endif #define QCSAP_IOCTL_MODIFY_ACL (SIOCIWFIRSTPRIV+18) #define QCSAP_IOCTL_GET_CHANNEL_LIST (SIOCIWFIRSTPRIV+19) #define QCSAP_IOCTL_SET_TX_POWER (SIOCIWFIRSTPRIV+20) #define MAX_VAR_ARGS 7 #define QCSAP_IOCTL_PRIV_GET_SOFTAP_LINK_SPEED (SIOCIWFIRSTPRIV + 31) enum { QCSAP_PARAM_MAX_ASSOC = 1, QCSAP_PARAM_GET_WLAN_DBG = 4, QCSAP_PARAM_MODULE_DOWN_IND = 5, QCSAP_PARAM_CLR_ACL = 6, QCSAP_PARAM_ACL_MODE = 7, QCSAP_PARAM_HIDE_SSID = 8, QCSAP_PARAM_AUTO_CHANNEL = 9, }; int iw_softap_get_channel_list(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra); #endif /* */ #endif /* */
aicjofs/android_kernel_lge_v500
drivers/staging/prima/CORE/HDD/inc/qc_sap_ioctl.h
C
gpl-2.0
7,691
#ifndef MADNESS_CHEM_XCFUNCTIONAL_H__INCLUDED #define MADNESS_CHEM_XCFUNCTIONAL_H__INCLUDED #include <madness/madness_config.h> /// \file moldft/xcfunctional.h /// \brief Defines interface for DFT XC functionals /// \ingroup chemistry #include <madness/tensor/tensor.h> #include <vector> #include <algorithm> #include <utility> #include <madness/mra/key.h> #include <madness/world/MADworld.h> #include <madness/mra/function_common_data.h> #ifdef MADNESS_HAS_LIBXC #include <xc.h> #endif namespace madness { /// Compute the spin-restricted LDA potential using unaryop (only for the initial guess) struct xc_lda_potential { xc_lda_potential() {} void operator()(const Key<3> & key, Tensor<double>& t) const { int x_rks_s__(const double *r__, double *f, double * dfdra); int c_rks_vwn5__(const double *r__, double *f, double * dfdra); double* rho = t.ptr(); for (int i=0; i<t.size(); i++) { double r = std::max(rho[i],1e-12); double q, dq1, dq2; x_rks_s__(&r, &q, &dq1); c_rks_vwn5__(&r, &q, &dq2); rho[i] = dq1 + dq2; } } }; /// Simplified interface to XC functionals class XCfunctional { public: /// The ordering of the intermediates is fixed, but the code can handle /// non-initialized functions, so if e.g. no GGA is requested, all the /// corresponding vector components may be left empty. /// /// Note the additional quantities \f$ \zeta \f$ and \f$ \chi \f$, which are defined as /// \f$ /// \rho = exp(\zeta) /// \f$ /// and thus the derivative of rho is given by /// \f$ /// \nabla_x\rho = exp(\zeta)\nabla_x\zeta = \rho \nabla_x\zeta /// \f$ /// The reduced gradients \sigma may then be expressed as /// \f$ /// \sigma = |\nabla\rho|^2 = |\rho|^2 |\nabla\zeta|^2 = |\rho|^2 \chi /// \f$ enum xc_arg { enum_rhoa=0, ///< alpha density \f$ \rho_\alpha \f$ enum_rhob=1, ///< beta density \f$ \rho_\beta \f$ enum_rho_pt=2, ///< perturbed density (CPHF, TDKS) \f$ \rho_{pt} \f$ enum_saa=10, ///< \f$ \sigma_{aa} = \nabla \rho_{\alpha}.\nabla \rho_{\alpha} \f$ enum_sab=11, ///< \f$ \sigma_{ab} = \nabla \rho_{\alpha}.\nabla \rho_{\beta} \f$ enum_sbb=12, ///< \f$ \sigma_{bb} = \nabla \rho_{\beta}.\nabla \rho_{\beta} \f$ enum_sigtot=13, ///< \f$ \sigma = \nabla \rho.\nabla \rho \f$ enum_sigma_pta_div_rho=14, ///< \f$ \zeta_{\alpha}.\nabla\rho_{pt} \f$ enum_sigma_ptb_div_rho=15, ///< \f$ \zeta_{\beta}.\nabla\rho_{pt} \f$ enum_zetaa_x=16, ///< \f$ \zeta_{a,x}=\partial/{\partial x} \ln(\rho_a) \f$ enum_zetaa_y=17, ///< \f$ \zeta_{a,y}=\partial/{\partial y} \ln(\rho_a) \f$ enum_zetaa_z=18, ///< \f$ \zeta_{a,z}=\partial/{\partial z} \ln(\rho_a) \f$ enum_zetab_x=19, ///< \f$ \zeta_{b,x} = \partial/{\partial x} \ln(\rho_b) \f$ enum_zetab_y=20, ///< \f$ \zeta_{b,y} = \partial/{\partial y} \ln(\rho_b) \f$ enum_zetab_z=21, ///< \f$ \zeta_{b,z} = \partial/{\partial z} \ln(\rho_b) \f$ enum_chi_aa=22, ///< \f$ \chi_{aa} = \nabla \zeta_{\alpha}.\nabla \zeta_{\alpha} \f$ enum_chi_ab=23, ///< \f$ \chi_{ab} = \nabla \zeta_{\alpha}.\nabla \zeta_{\beta} \f$ enum_chi_bb=24, ///< \f$ \chi_{bb} = \nabla \zeta_{\beta}.\nabla \zeta_{\beta} \f$ enum_ddens_ptx=25, ///< \f$ \nabla\rho_{pt}\f$ enum_ddens_pty=26, ///< \f$ \nabla\rho_{pt}\f$ enum_ddens_ptz=27 ///< \f$ \nabla\rho_{pt}\f$ }; const static int number_xc_args=28; ///< max number of intermediates /// return the munging threshold for the density double get_rhotol() const {return rhotol;} /// return the binary munging threshold for the final result in the GGA potential/kernel /// the GGA potential will be munged based on the smallness of the original /// density, which we call binary munging double get_ggatol() const {return ggatol;} protected: bool spin_polarized; ///< True if the functional is spin polarized double hf_coeff; ///< Factor multiplying HF exchange (+1.0 gives HF) double rhomin, rhotol; ///< See initialize and munge* double ggatol; ///< See initialize and munge* #ifdef MADNESS_HAS_LIBXC std::vector< std::pair<xc_func_type*,double> > funcs; #endif /// convert the raw density (gradient) data to be used by the xc operators /// Involves mainly munging of the densities and multiplying with 2 /// if the calculation is spin-restricted. /// Response densities and density gradients are munged based on the /// value of the ground state density, since they may become negative /// and may also be much more diffuse. /// dimensions of the output tensors are for spin-restricted and unrestricted /// (with np the number of grid points in the box): /// rho(np) or rho(2*np) /// sigma(np) sigma(3*np) /// rho_pt(np) /// sigma_pt(2*np) /// @param[in] t input density (gradients) /// @param[out] rho ground state (spin) density, properly munged /// @param[out] sigma ground state (spin) density gradients, properly munged /// @param[out] rho_pt response density, properly munged (no spin) /// @param[out] sigma_pt response (spin) density gradients, properly munged /// @param[out] drho density derivative, constructed from rho and zeta /// @param[out] drho_pt response density derivative directly from xc_args /// @param[in] need_response flag if rho_pt and sigma_pt need to be calculated void make_libxc_args(const std::vector< madness::Tensor<double> >& t, madness::Tensor<double>& rho, madness::Tensor<double>& sigma, madness::Tensor<double>& rho_pt, madness::Tensor<double>& sigma_pt, std::vector<madness::Tensor<double> >& drho, std::vector<madness::Tensor<double> >& drho_pt, const bool need_response) const; /// the number of xc kernel derivatives (lda: 0, gga: 1, etc) int nderiv; /// Smoothly switches between constant (x<xmin) and linear function (x>xmax) /// \f[ /// f(x,x_{\mathrm{min}},x_{\mathrm{max}}) = \left\{ /// \begin{array}{ll} /// x_{\mathrm{min}} & x < x_{\mathrm{min}} \\ /// p(x,x_{\mathrm{min}},x_{\mathrm{max}}) & x_{\mathrm{min}} \leq x_{\mathrm{max}} \\ /// x & x_{\mathrm{max}} < x /// \end{array} /// \right. /// \f] /// where \f$p(x)\f$ is the unique quintic polynomial that /// satisfies \f$p(x_{min})=x_{min}\f$, \f$p(x_{max})=x_{max}\f$, /// \f$dp(x_{max})/dx=1\f$, and /// \f$dp(x_{min})/dx=d^2p(x_{min})/dx^2=d^2p(x_{max})/dx^2=0\f$. static void polyn(const double x, double& p, double& dpdx) { // All of the static const stuff is evaluated at compile time static const double xmin = 1.e-6; // <<<< MINIMUM VALUE OF DENSITY static const double xmax = 5.e-5; // <<<< DENSITY SMOOTHLY MODIFIED BELOW THIS VALUE static const double xmax2 = xmax*xmax; static const double xmax3 = xmax2*xmax; static const double xmin2 = xmin*xmin; static const double xmin3 = xmin2*xmin; static const double r = 1.0/((xmax-xmin)*(-xmin3+(3.0*xmin2+(-3.0*xmin+xmax)*xmax)*xmax)); static const double a0 = xmax3*xmin*(xmax-4.0*xmin)*r; static const double a = xmin2*(xmin2+(-4.0*xmin+18.0*xmax)*xmax)*r; static const double b = -6.0*xmin*xmax*(3.0*xmax+2.0*xmin)*r; static const double c = (4.0*xmin2+(20.0*xmin+6.0*xmax)*xmax)*r; static const double d = -(8.0*xmax+7.0*xmin)*r; static const double e = 3.0*r; if (x > xmax) { p = x; dpdx = 1.0; } else if (x < xmin) { p = xmin; dpdx = 0.0; } else { p = a0+(a+(b+(c+(d+e*x)*x)*x)*x)*x; dpdx = a+(2.0*b+(3.0*c+(4.0*d+5.0*e*x)*x)*x)*x; } } public: static double munge_old(double rho) { double p, dpdx; polyn(rho, p, dpdx); return p; } private: /// simple munging for the density only (LDA) double munge(double rho) const { if (rho <= rhotol) rho=rhomin; return rho; } /// munge rho if refrho is small /// special case for perturbed densities, which might be negative and diffuse. /// Munge rho (e.g. the perturbed density) if the reference density refrho /// e.g. the ground state density is small. Only where the reference density /// is large enough DFT is numerically well-defined. /// @param[in] rho number to be munged /// @param[in] refrho reference value for munging /// @param[in] thresh threshold for munging double binary_munge(double rho, double refrho, const double thresh) const { if (refrho<thresh) rho=rhomin; return rho; } public: /// Default constructor is required XCfunctional(); /// Initialize the object from the user input data /// @param[in] input_line User input line (without beginning XC keyword) /// @param[in] polarized Boolean flag indicating if the calculation is spin-polarized void initialize(const std::string& input_line, bool polarized, World& world, const bool verbose=false); /// Destructor ~XCfunctional(); /// Returns true if the potential is lda bool is_lda() const; /// Returns true if the potential is gga (needs first derivatives) bool is_gga() const; /// Returns true if the potential is meta gga (needs second derivatives ... not yet supported) bool is_meta() const; /// Returns true if there is a DFT functional (false probably means Hatree-Fock exchange only) bool is_dft() const; /// Returns true if the functional is spin_polarized bool is_spin_polarized() const { return spin_polarized; } /// Returns true if the second derivative of the functional is available (not yet supported) bool has_fxc() const; /// Returns true if the third derivative of the functional is available (not yet supported) bool has_kxc() const; /// Returns the value of the hf exact exchange coefficient double hf_exchange_coefficient() const { return hf_coeff; } /// Computes the energy functional at given points /// This uses the convention that the total energy is /// \f$ E[\rho] = \int \epsilon[\rho(x)] dx\f$ /// Any HF exchange contribution must be separately computed. Items in the /// vector argument \c t are interpreted similarly to the xc_arg enum. /// @param[in] t The input densities and derivatives as required by the functional /// @return The exchange-correlation energy functional madness::Tensor<double> exc(const std::vector< madness::Tensor<double> >& t) const; /// Computes components of the potential (derivative of the energy functional) at np points /// Any HF exchange contribution must be separately computed. Items in the /// vector argument \c t are interpreted similarly to the xc_arg enum. /// /// We define \f$ \sigma_{\mu \nu} = \nabla \rho_{\mu} . \nabla \rho_{\nu} \f$ /// with \f$ \mu, \nu = \alpha\f$ or \f$ \beta \f$. /// /// For unpolarized GGA, matrix elements of the potential are /// \f[ /// < \phi | \hat V | \psi > = \int \left( \frac{\partial \epsilon}{\partial \rho} \phi \psi /// + \left( 2 \frac{\partial \epsilon}{\partial \sigma} \right) /// \nabla \rho \cdot \nabla \left( \phi \psi \right) \right) dx /// \f] /// /// For polarized GGA, matrix elements of the potential are /// \f[ /// < \phi_{\alpha} | \hat V | \psi_{\alpha} > = \int \left( \frac{\partial \epsilon}{\partial \rho_{\alpha}} \phi \psi /// + \left( 2 \frac{\partial \epsilon}{\partial \sigma_{\alpha \alpha}} \nabla \rho_{\alpha} /// + \frac{\partial \epsilon}{\partial \sigma_{\alpha \beta}} \nabla \rho_{\beta} \right) . \nabla \left( \phi \psi \right) \right) dx /// \f] /// /// Integrating the above by parts and assuming free-space or periodic boundary conditions /// we obtain that the local multiplicative form of the GGA potential is /// \f[ /// V_{\alpha} = \frac{\partial \epsilon}{\partial \rho_{\alpha}} /// - \left(\nabla . \left(2 \frac{\partial \epsilon}{\partial \sigma_{\alpha \alpha}} \nabla \rho_{\alpha} /// + \frac{\partial \epsilon}{\partial \sigma_{\alpha \beta}} \nabla \rho_{\beta} \right) \right) /// \f] /// /// Return the following quantities for RHF: (see Yanai2005, Eq. (12)) /// \f{eqnarray*}{ /// \mbox{result[0]} &:& \qquad \frac{\partial \epsilon}{\partial \rho} \\ /// \mbox{result[1-3]} &:& \qquad 2 \rho \frac{\partial \epsilon}{\partial \sigma} \nabla\rho /// \f} /// and for UHF same-spin and other-spin quantities /// \f{eqnarray*}{ /// \mbox{result[0]} &:& \qquad \frac{\partial \epsilon}{\partial \rho_{\alpha}} \\ /// \mbox{result[1-3]} &:& \qquad \rho_\alpha \frac{\partial \epsilon}{\partial \sigma_{\alpha \alpha}} \nabla\rho_\alpha\\ /// \mbox{result[4-6]} &:& \qquad \rho_\alpha \frac{\partial \epsilon}{\partial \sigma_{\alpha \beta}} \nabla\rho_\beta /// \f} /// @param[in] t The input densities and derivatives as required by the functional /// @param[in] ispin Specifies which component of the potential is to be computed as described above /// @return the requested quantity, based on ispin (0: same spin, 1: other spin) std::vector<madness::Tensor<double> > vxc(const std::vector< madness::Tensor<double> >& t, const int ispin) const; /// compute the second derivative of the XC energy wrt the density and apply /// Return the following quantities (RHF only) (see Yanai2005, Eq. (13)) /// \f{eqnarray*}{ /// \mbox{result[0]} &:& \qquad \frac{\partial^2 \epsilon}{\partial \rho^2} \rho_\mathrm{pt} /// + 2.0 * \frac{\partial^2 \epsilon}{\partial \rho\partial\sigma}\sigma_\mathrm{pt}\\ /// \mbox{result[1-3]} &:& \qquad 2.0 * \frac{\partial\epsilon}{\partial\sigma}\nabla\rho_\mathrm{pt} /// + 2.0 * \frac{\partial^2\epsilon}{\partial\rho\partial\sigma} \rho_\mathrm{pt}\nabla\rho /// + 4.0 * \frac{\partial^2\epsilon}{\partial^2\sigma} \sigma_\mathrm{pt}\nabla\rho /// \f} /// @param[in] t The input densities and derivatives as required by the functional, /// as in the xc_arg enum /// @param[in] ispin not referenced since only RHF is implemented, always 0 /// @return a vector of Functions containing the contributions to the kernel apply std::vector<madness::Tensor<double> > fxc_apply( const std::vector< madness::Tensor<double> >& t, const int ispin) const; /// Crude function to plot the energy and potential functionals void plot() const { long npt = 1001; double lo=1e-6, hi=1e+1, s=std::pow(hi/lo, 1.0/(npt-1)); madness::Tensor<double> rho(npt); for (int i=0; i<npt; i++) { rho[i] = lo; lo *= s; } std::vector< madness::Tensor<double> > t(13); t[enum_rhoa]=(rho); if (is_spin_polarized()) t[enum_rhob]=(rho); // if (is_gga()) t[enum_saa]=madness::Tensor<double>(npt); // sigma_aa=0 if (is_gga()) t[enum_saa]=0.5*rho; // sigma_aa=0 madness::Tensor<double> f = exc(t); //pending UGHHHHH std::vector<madness::Tensor<double> > va = vxc(t,0); for (long i=0; i<npt; i++) { printf("%.3e %.3e %.3e\n", rho[i], f[i], va[0][i]); } } }; /// Class to compute the energy functional struct xc_functional { const XCfunctional* xc; xc_functional(const XCfunctional& xc) : xc(&xc) {} madness::Tensor<double> operator()(const madness::Key<3> & key, const std::vector< madness::Tensor<double> >& t) const { MADNESS_ASSERT(xc); return xc->exc(t); } }; /// Class to compute terms of the potential struct xc_potential { const XCfunctional* xc; const int ispin; xc_potential(const XCfunctional& xc, int ispin) : xc(&xc), ispin(ispin) {} std::size_t get_result_size() const { // local terms, same spin if (xc->is_lda()) return 1; // local terms, 3x semilocal terms (x,y,z) if (xc->is_gga() and (not xc->is_spin_polarized())) return 4; // local terms, 3x semilocal terms (x,y,z) for same spin and opposite spin if (xc->is_gga() and (xc->is_spin_polarized())) return 7; MADNESS_EXCEPTION("only lda and gga in xc_potential_multi",1); return 0; } std::vector<madness::Tensor<double> > operator()(const madness::Key<3> & key, const std::vector< madness::Tensor<double> >& t) const { MADNESS_ASSERT(xc); std::vector<madness::Tensor<double> > r = xc->vxc(t, ispin); return r; } }; /// Class to compute terms of the kernel struct xc_kernel_apply { const XCfunctional* xc; const int ispin; const FunctionCommonData<double,3>& cdata; xc_kernel_apply(const XCfunctional& xc, int ispin) : xc(&xc), ispin(ispin), cdata(FunctionCommonData<double,3>::get(FunctionDefaults<3>::get_k())) { MADNESS_ASSERT(ispin==0); // closed shell only! } std::size_t get_result_size() const { // all spin-restricted if (xc->is_gga()) return 4; // local terms, 3x semilocal terms (x,y,z) return 1; // local terms only } std::vector<madness::Tensor<double> > operator()(const madness::Key<3> & key, const std::vector< madness::Tensor<double> >& t) const { MADNESS_ASSERT(xc); std::vector<madness::Tensor<double> > r = xc->fxc_apply(t, ispin); return r; } }; } #endif
fishjojo/madoep
src/apps/chem/xcfunctional.h
C
gpl-2.0
18,439
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2017 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EDITABLE_TREE_VIEW_H_ #define _U2_EDITABLE_TREE_VIEW_H_ #include <U2Core/global.h> #include <QTreeView> namespace U2 { class U2GUI_EXPORT EditableTreeView : public QTreeView { public: EditableTreeView(QWidget* p); bool isEditingActive(); }; } // namespace #endif // _U2_EDITABLE_TREE_VIEW_H_
mfursov/ugene
src/corelibs/U2Gui/src/util/project/EditableTreeView.h
C
gpl-2.0
1,167
#include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/malloc.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <asm/setup.h> #include <asm/segment.h> #include <asm/system.h> /*#include <asm/irq.h>*/ #include <asm/q40_master.h> #include <linux/fb.h> #include <linux/module.h> #include <asm/pgtable.h> #include <video/fbcon-cfb16.h> #define Q40_PHYS_SCREEN_ADDR 0xFE800000 static unsigned long q40_screen_addr; static u16 fbcon_cmap_cfb16[16]; /* frame buffer operations */ static int q40fb_open(struct fb_info *info, int user); static int q40fb_release(struct fb_info *info, int user); static int q40fb_get_fix(struct fb_fix_screeninfo *fix, int con, struct fb_info *info); static int q40fb_get_var(struct fb_var_screeninfo *var, int con, struct fb_info *info); static int q40fb_set_var(struct fb_var_screeninfo *var, int con, struct fb_info *info); static int q40fb_get_cmap(struct fb_cmap *cmap,int kspc,int con, struct fb_info *info); static int q40fb_set_cmap(struct fb_cmap *cmap,int kspc,int con, struct fb_info *info); static int q40fb_pan_display(struct fb_var_screeninfo *var, int con, struct fb_info *info); static int q40fb_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg, int con, struct fb_info *info); static int q40con_switch(int con, struct fb_info *info); static int q40con_updatevar(int con, struct fb_info *info); static void q40con_blank(int blank, struct fb_info *info); static void q40fb_set_disp(int con, struct fb_info *info); static struct display disp[MAX_NR_CONSOLES]; static struct fb_info fb_info; static struct fb_ops q40fb_ops = { q40fb_open,q40fb_release, q40fb_get_fix, q40fb_get_var, q40fb_set_var, q40fb_get_cmap, q40fb_set_cmap, q40fb_pan_display, q40fb_ioctl }; static int currcon=0; static char q40fb_name[]="Q40"; static int q40fb_open(struct fb_info *info, int user) { /* * Nothing, only a usage count for the moment */ MOD_INC_USE_COUNT; return(0); } static int q40fb_release(struct fb_info *info, int user) { MOD_DEC_USE_COUNT; return(0); } static int q40fb_get_fix(struct fb_fix_screeninfo *fix, int con, struct fb_info *info) { memset(fix, 0, sizeof(struct fb_fix_screeninfo)); strcpy(fix->id,"Q40"); fix->smem_start=(char*)q40_screen_addr; fix->smem_len=1024*1024; fix->type=FB_TYPE_PACKED_PIXELS; fix->type_aux=0; fix->visual=FB_VISUAL_TRUECOLOR; /* good approximation so far ..*/; fix->xpanstep=0; fix->ypanstep=0; fix->ywrapstep=0; fix->line_length=1024*2; /* no mmio,accel ...*/ return 0; } static int q40fb_get_var(struct fb_var_screeninfo *var, int con, struct fb_info *info) { memset(var, 0, sizeof(struct fb_var_screeninfo)); var->xres=1024; var->yres=512; var->xres_virtual=1024; var->yres_virtual=512; var->xoffset=0; var->yoffset=0; var->bits_per_pixel=16; var->grayscale=0; var->nonstd=0; var->activate=FB_ACTIVATE_NOW; var->height=230; /* approx for my 17" monitor, more important */ var->width=300; /* than the absolute values is the unusual aspect ratio*/ var->red.offset=6; /*6*/ var->red.length=5; var->green.offset=11; /*11*/ var->green.length=5; var->blue.offset=0; var->blue.length=6; var->transp.length=0; var->pixclock=0; var->left_margin=0; var->right_margin=0; var->hsync_len=0; var->vsync_len=0; var->sync=0; var->vmode=FB_VMODE_NONINTERLACED; return 0; } static int q40fb_set_var(struct fb_var_screeninfo *var, int con, struct fb_info *info) { if(var->xres!=1024) return -EINVAL; if(var->yres!=512) return -EINVAL; if(var->xres_virtual!=1024) return -EINVAL; if(var->yres_virtual!=512) return -EINVAL; if(var->xoffset!=0) return -EINVAL; if(var->yoffset!=0) return -EINVAL; if(var->bits_per_pixel!=16) return -EINVAL; if(var->grayscale!=0) return -EINVAL; if(var->nonstd!=0) return -EINVAL; if(var->activate!=FB_ACTIVATE_NOW) return -EINVAL; if(var->pixclock!=0) return -EINVAL; if(var->left_margin!=0) return -EINVAL; if(var->right_margin!=0) return -EINVAL; if(var->hsync_len!=0) return -EINVAL; if(var->vsync_len!=0) return -EINVAL; if(var->sync!=0) return -EINVAL; if(var->vmode!=FB_VMODE_NONINTERLACED) return -EINVAL; return 0; } static int q40_getcolreg(unsigned regno, unsigned *red, unsigned *green, unsigned *blue, unsigned *transp, struct fb_info *info) { /* * Read a single color register and split it into colors/transparent. * The return values must have a 16 bit magnitude. * Return != 0 for invalid regno. */ if (regno>=16) return 1; *transp=0; *green = ((fbcon_cmap_cfb16[regno]>>11) & 31)<<11; *red = ((fbcon_cmap_cfb16[regno]>>6) & 31)<<11; *blue = ((fbcon_cmap_cfb16[regno]) & 63)<<10; return 0; } static int q40_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, const struct fb_info *info) { /* * Set a single color register. The values supplied have a 16 bit * magnitude. * Return != 0 for invalid regno. */ red>>=11; green>>=11; blue>>=10; if (regno < 16) { fbcon_cmap_cfb16[regno] = ((red & 31) <<5) | ((green & 31) << 11) | (blue & 63); } return 0; } static int q40fb_get_cmap(struct fb_cmap *cmap, int kspc, int con, struct fb_info *info) { #if 1 if (con == currcon) /* current console? */ return fb_get_cmap(cmap, kspc, q40_getcolreg, info); else if (fb_display[con].cmap.len) /* non default colormap? */ fb_copy_cmap(&fb_display[con].cmap, cmap, kspc ? 0 : 2); else fb_copy_cmap(fb_default_cmap(1<<fb_display[con].var.bits_per_pixel), cmap, kspc ? 0 : 2); return 0; #else printk("get cmap not supported\n"); return -EINVAL; #endif } static int q40fb_set_cmap(struct fb_cmap *cmap, int kspc, int con, struct fb_info *info) { #if 1 int err; if (!fb_display[con].cmap.len) { /* no colormap allocated? */ if ((err = fb_alloc_cmap(&fb_display[con].cmap, 1<<fb_display[con].var.bits_per_pixel, 0))) return err; } if (con == currcon) /* current console? */ return fb_set_cmap(cmap, kspc, q40_setcolreg, info); else fb_copy_cmap(cmap, &fb_display[con].cmap, kspc ? 0 : 1); return 0; #else printk("set cmap not supported\n"); return -EINVAL; #endif } static int q40fb_pan_display(struct fb_var_screeninfo *var, int con, struct fb_info *info) { printk("panning not supported\n"); return -EINVAL; } static int q40fb_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg, int con, struct fb_info *info) { return -EINVAL; } static void q40fb_set_disp(int con, struct fb_info *info) { struct fb_fix_screeninfo fix; struct display *display; q40fb_get_fix(&fix, con, info); if (con>=0) display = &fb_display[con]; else display = &disp[0]; if (con<0) con=0; display->screen_base = fix.smem_start; display->visual = fix.visual; display->type = fix.type; display->type_aux = fix.type_aux; display->ypanstep = fix.ypanstep; display->ywrapstep = fix.ywrapstep; display->can_soft_blank = 0; display->inverse = 0; display->line_length = fix.line_length; #ifdef FBCON_HAS_CFB16 display->dispsw = &fbcon_cfb16; disp->dispsw_data = fbcon_cmap_cfb16; #else display->dispsw = &fbcon_dummy; #endif } void q40fb_init(void) { #if 0 q40_screen_addr = kernel_map(Q40_PHYS_SCREEN_ADDR, 1024*1024, KERNELMAP_NO_COPYBACK, NULL); #else q40_screen_addr = Q40_PHYS_SCREEN_ADDR; /* mapped in q40/config.c */ #endif fb_info.changevar=NULL; strcpy(&fb_info.modename[0],q40fb_name); fb_info.fontname[0]=0; fb_info.disp=disp; fb_info.switch_con=&q40con_switch; fb_info.updatevar=&q40con_updatevar; fb_info.blank=&q40con_blank; fb_info.node = -1; fb_info.fbops = &q40fb_ops; fb_info.flags = FBINFO_FLAG_DEFAULT; /* not as module for now */ master_outb(3,DISPLAY_CONTROL_REG); q40fb_get_var(&disp[0].var, 0, &fb_info); q40fb_set_disp(-1, &fb_info); if (register_framebuffer(&fb_info) < 0) panic("unable to register Q40 frame buffer\n"); printk("fb%d: Q40 frame buffer alive and kicking !\n", GET_FB_IDX(fb_info.node)); } static int q40con_switch(int con, struct fb_info *info) { currcon=con; return 0; } static int q40con_updatevar(int con, struct fb_info *info) { return 0; } static void q40con_blank(int blank, struct fb_info *info) { }
empeg/empeg-hijack
drivers/video/q40fb.c
C
gpl-2.0
8,669
/* * Asus Mypal 600/620 GPIO definitions. * * Author: Nicolas Pouillon <nipo@ssji.net> * * 2006-02-08 by Vincent Benony : adding GPO bit definitions, and small updates * */ #ifndef _ASUS_620_GPIO_ #define _ASUS_620_GPIO_ #define GET_A620_GPIO(gpio) \ (GPLR(GPIO_NR_A620_ ## gpio) & GPIO_bit(GPIO_NR_A620_ ## gpio)) #define SET_A620_GPIO(gpio, setp) \ do { \ if (setp) \ GPSR(GPIO_NR_A620_ ## gpio) = GPIO_bit(GPIO_NR_A620_ ## gpio); \ else \ GPCR(GPIO_NR_A620_ ## gpio) = GPIO_bit(GPIO_NR_A620_ ## gpio); \ } while (0) #define SET_A620_GPIO_N(gpio, setp) \ do { \ if (setp) \ GPCR(GPIO_NR_A620_ ## gpio ## _N) = GPIO_bit(GPIO_NR_A620_ ## gpio ## _N); \ else \ GPSR(GPIO_NR_A620_ ## gpio ## _N) = GPIO_bit(GPIO_NR_A620_ ## gpio ## _N); \ } while (0) #define A620_IRQ(gpio) \ IRQ_GPIO(GPIO_NR_A620_ ## gpio) #define GPIO_NR_A620_POWER_BUTTON_N (0) /* 1 is reboot non maskable */ #define GPIO_NR_A620_HOME_BUTTON_N (2) #define GPIO_NR_A620_CALENDAR_BUTTON_N (3) #define GPIO_NR_A620_CONTACTS_BUTTON_N (4) #define GPIO_NR_A620_TASKS_BUTTON_N (5) /* 6 missing */ /* hand probed */ #define GPIO_NR_A620_CF_IRQ (7) /* hand probed */ #define GPIO_NR_A620_CF_BVD1 (8) /* Not sure, just a guess */ #define GPIO_NR_A620_CF_READY_N (9) #define GPIO_NR_A620_USB_DETECT (10) #define GPIO_NR_A620_RECORD_BUTTON_N (11) #define GPIO_NR_A620_HEARPHONE_N (12) /* 13 missing (output) */ #define GPIO_NR_A620_CF_RESET (13) /* hand probed */ #define GPIO_NR_A620_CF_POWER (14) #define GPIO_NR_A620_COM_DETECT_N (15) #define GPIO_NR_A620_BACKLIGHT (16) /* Not sure, guessed */ #define GPIO_NR_A620_CF_ENABLE (17) /* * 18 Power detect, see below * 19 missing (output) * * 18,20 * going 0/1 with Power * input * 18: Interrupt on none * 20: Interrupt on RE/FE * * Putting GPIO_NR_A620_AC_IN on 20 is arbitrary */ #define GPIO_NR_A620_AC_IN (20) /* hand probed */ #define GPIO_NR_A620_CF_VS1_N (21) #define GPIO_NR_A620_CF_DETECT_N (21) #define GPIO_NR_A620_CF_VS2_N (22) /* 23-26 is SSP to AD7873 */ #define GPIO_NR_A620_STYLUS_IRQ (27) /* * 28-32 IIS to UDA1380 * * 33 USB pull-up * Must be input when disconnected (floating) * Must be output set to 1 when connected */ #define GPIO_NR_A620_USBP_PULLUP (33) /* * Serial connector has no handshaking * 34,39 Serial port * * 38 missing * * Joystick directions and button * Center is 35 * Directions triggers one or two of 36,67,40,41 * * 36 36,37 37 * * 36,41 35 37,40 * * 41 40,41 40 */ #define GPIO_NR_A620_JOY_PUSH_N (35) #define GPIO_NR_A620_JOY_NW_N (36) #define GPIO_NR_A620_JOY_NE_N (37) #define GPIO_NR_A620_JOY_SE_N (40) #define GPIO_NR_A620_JOY_SW_N (41) #define GPIO_A620_JOY_DIR (((GPLR1&0x300)>>6)|((GPLR1&0x30)>>4)) /* * 42-45 Bluetooth * 46-47 IrDA * * 48-57 Card ? * 54 is led control */ #define GPIO_NR_A620_LED_ENABLE (54) /* * * 58 through 77 is LCD signals * 74,75 seems related to TCON chip * -74 is TCON presence probing * -75 is set to GAFR2 when TCON is here */ #define GPIO_NR_A620_TCON_HERE_N (74) #define GPIO_NR_A620_TCON_EN (75) /* * Power management (scaling to 200, 300, 400MHz) * Chart is: * 78 79 * 200 1 0 * 300 0 1 * 400 1 1 */ #define GPIO_NR_A620_PWRMGMT0 (78) #define GPIO_NR_A620_PWRMGMT1 (79) /* * 81-84 missing */ /* * Other infos */ #define ASUS_IDE_BASE 0x00000000 #define ASUS_IDE_SIZE 0x04000000 #define ASUS_IDE_VIRTUAL 0xF8000000 #define GPO_A620_USB (1 << 0) // 0x00000001 #define GPO_A620_LCD_POWER1 (1 << 1) // 0x00000002 #define GPO_A620_LCD_POWER2 (1 << 2) // 0x00000004 #define GPO_A620_LCD_POWER3 (1 << 3) // 0x00000008 #define GPO_A620_BACKLIGHT (1 << 4) // 0x00000010 #define GPO_A620_BLUETOOTH (1 << 5) // 0x00000020 #define GPO_A620_MICROPHONE (1 << 6) // 0x00000040 #define GPO_A620_SOUND (1 << 7) // 0x00000080 #define GPO_A620_UNK_1 (1 << 8) // 0x00000100 #define GPO_A620_BLUE_LED (1 << 9) // 0x00000200 #define GPO_A620_UNK_2 (1 << 10) // 0x00000400 #define GPO_A620_RED_LED (1 << 11) // 0x00000800 #define GPO_A620_UNK_3 (1 << 12) // 0x00001000 #define GPO_A620_CF_RESET (1 << 13) // 0x00002000 #define GPO_A620_IRDA_FIR_MODE (1 << 14) // 0x00004000 #define GPO_A620_IRDA_POWER_N (1 << 15) // 0x00008000 #define GPIO_I2C_EARPHONES_DETECTED (1 << 2) // 0x00000004 void asus620_gpo_set(unsigned long bits); void asus620_gpo_clear(unsigned long bits); #endif /* _ASUS_620_GPIO_ */
janrinze/loox7xxport.loox2-6-22
include/asm-arm/arch-pxa/asus620-gpio.h
C
gpl-2.0
4,495
/* * Copyright 2014 Freescale Semiconductor, Inc. * * SPDX-License-Identifier: GPL-2.0+ */ /* * T1024/T1023 RDB board configuration file */ #ifndef __T1024RDB_H #define __T1024RDB_H /* High Level Configuration Options */ #define CONFIG_SYS_GENERIC_BOARD #define CONFIG_DISPLAY_BOARDINFO #define CONFIG_BOOKE #define CONFIG_E500 /* BOOKE e500 family */ #define CONFIG_E500MC /* BOOKE e500mc family */ #define CONFIG_SYS_BOOK3E_HV /* Category E.HV supported */ #define CONFIG_MP /* support multiple processors */ #define CONFIG_PHYS_64BIT #define CONFIG_ENABLE_36BIT_PHYS #ifdef CONFIG_PHYS_64BIT #define CONFIG_ADDR_MAP 1 #define CONFIG_SYS_NUM_ADDR_MAP 64 /* number of TLB1 entries */ #endif #define CONFIG_SYS_FSL_CPC /* Corenet Platform Cache */ #define CONFIG_SYS_NUM_CPC CONFIG_NUM_DDR_CONTROLLERS #define CONFIG_FSL_IFC /* Enable IFC Support */ #define CONFIG_FSL_LAW /* Use common FSL init code */ #define CONFIG_ENV_OVERWRITE /* support deep sleep */ #ifdef CONFIG_PPC_T1024 #define CONFIG_DEEP_SLEEP #endif #if defined(CONFIG_DEEP_SLEEP) #define CONFIG_SILENT_CONSOLE #define CONFIG_BOARD_EARLY_INIT_F #endif #ifdef CONFIG_RAMBOOT_PBL #define CONFIG_SYS_FSL_PBL_PBI board/freescale/t102xrdb/t1024_pbi.cfg #if defined(CONFIG_T1024RDB) #define CONFIG_SYS_FSL_PBL_RCW board/freescale/t102xrdb/t1024_rcw.cfg #elif defined(CONFIG_T1023RDB) #define CONFIG_SYS_FSL_PBL_RCW board/freescale/t102xrdb/t1023_rcw.cfg #endif #define CONFIG_SPL_MPC8XXX_INIT_DDR_SUPPORT #define CONFIG_SPL_ENV_SUPPORT #define CONFIG_SPL_SERIAL_SUPPORT #define CONFIG_SPL_FLUSH_IMAGE #define CONFIG_SPL_TARGET "u-boot-with-spl.bin" #define CONFIG_SPL_LIBGENERIC_SUPPORT #define CONFIG_SPL_LIBCOMMON_SUPPORT #define CONFIG_SPL_I2C_SUPPORT #define CONFIG_SPL_DRIVERS_MISC_SUPPORT #define CONFIG_FSL_LAW /* Use common FSL init code */ #define CONFIG_SYS_TEXT_BASE 0x30001000 #define CONFIG_SPL_TEXT_BASE 0xFFFD8000 #define CONFIG_SPL_PAD_TO 0x40000 #define CONFIG_SPL_MAX_SIZE 0x28000 #define RESET_VECTOR_OFFSET 0x27FFC #define BOOT_PAGE_OFFSET 0x27000 #ifdef CONFIG_SPL_BUILD #define CONFIG_SPL_SKIP_RELOCATE #define CONFIG_SPL_COMMON_INIT_DDR #define CONFIG_SYS_CCSR_DO_NOT_RELOCATE #define CONFIG_SYS_NO_FLASH #endif #ifdef CONFIG_NAND #define CONFIG_SPL_NAND_SUPPORT #define CONFIG_SYS_NAND_U_BOOT_SIZE (768 << 10) #define CONFIG_SYS_NAND_U_BOOT_DST 0x30000000 #define CONFIG_SYS_NAND_U_BOOT_START 0x30000000 #define CONFIG_SYS_NAND_U_BOOT_OFFS (256 << 10) #define CONFIG_SYS_LDSCRIPT "arch/powerpc/cpu/mpc85xx/u-boot-nand.lds" #define CONFIG_SPL_NAND_BOOT #endif #ifdef CONFIG_SPIFLASH #define CONFIG_RESET_VECTOR_ADDRESS 0x30000FFC #define CONFIG_SPL_SPI_SUPPORT #define CONFIG_SPL_SPI_FLASH_SUPPORT #define CONFIG_SPL_SPI_FLASH_MINIMAL #define CONFIG_SYS_SPI_FLASH_U_BOOT_SIZE (768 << 10) #define CONFIG_SYS_SPI_FLASH_U_BOOT_DST (0x30000000) #define CONFIG_SYS_SPI_FLASH_U_BOOT_START (0x30000000) #define CONFIG_SYS_SPI_FLASH_U_BOOT_OFFS (256 << 10) #define CONFIG_SYS_LDSCRIPT "arch/powerpc/cpu/mpc85xx/u-boot.lds" #ifndef CONFIG_SPL_BUILD #define CONFIG_SYS_MPC85XX_NO_RESETVEC #endif #define CONFIG_SPL_SPI_BOOT #endif #ifdef CONFIG_SDCARD #define CONFIG_RESET_VECTOR_ADDRESS 0x30000FFC #define CONFIG_SPL_MMC_SUPPORT #define CONFIG_SPL_MMC_MINIMAL #define CONFIG_SYS_MMC_U_BOOT_SIZE (768 << 10) #define CONFIG_SYS_MMC_U_BOOT_DST (0x30000000) #define CONFIG_SYS_MMC_U_BOOT_START (0x30000000) #define CONFIG_SYS_MMC_U_BOOT_OFFS (260 << 10) #define CONFIG_SYS_LDSCRIPT "arch/powerpc/cpu/mpc85xx/u-boot.lds" #ifndef CONFIG_SPL_BUILD #define CONFIG_SYS_MPC85XX_NO_RESETVEC #endif #define CONFIG_SPL_MMC_BOOT #endif #endif /* CONFIG_RAMBOOT_PBL */ #ifndef CONFIG_SYS_TEXT_BASE #define CONFIG_SYS_TEXT_BASE 0xeff40000 #endif #ifndef CONFIG_RESET_VECTOR_ADDRESS #define CONFIG_RESET_VECTOR_ADDRESS 0xeffffffc #endif #ifndef CONFIG_SYS_NO_FLASH #define CONFIG_FLASH_CFI_DRIVER #define CONFIG_SYS_FLASH_CFI #define CONFIG_SYS_FLASH_USE_BUFFER_WRITE #endif /* PCIe Boot - Master */ #define CONFIG_SRIO_PCIE_BOOT_MASTER /* * for slave u-boot IMAGE instored in master memory space, * PHYS must be aligned based on the SIZE */ #define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_BUS1 0xfff00000ull #define CONFIG_SRIO_PCIE_BOOT_IMAGE_SIZE 0x100000 /* 1M */ #ifdef CONFIG_PHYS_64BIT #define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_PHYS 0xfef200000ull #define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_BUS2 0x3fff00000ull #else #define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_PHYS 0xef200000 #define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_BUS2 0xfff00000 #endif /* * for slave UCODE and ENV instored in master memory space, * PHYS must be aligned based on the SIZE */ #ifdef CONFIG_PHYS_64BIT #define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_MEM_PHYS 0xfef100000ull #define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_MEM_BUS 0x3ffe00000ull #else #define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_MEM_PHYS 0xef100000 #define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_MEM_BUS 0xffe00000 #endif #define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_SIZE 0x40000 /* 256K */ /* slave core release by master*/ #define CONFIG_SRIO_PCIE_BOOT_BRR_OFFSET 0xe00e4 #define CONFIG_SRIO_PCIE_BOOT_RELEASE_MASK 0x00000001 /* release core 0 */ /* PCIe Boot - Slave */ #ifdef CONFIG_SRIO_PCIE_BOOT_SLAVE #define CONFIG_SYS_SRIO_PCIE_BOOT_UCODE_ENV_ADDR 0xFFE00000 #define CONFIG_SYS_SRIO_PCIE_BOOT_UCODE_ENV_ADDR_PHYS \ (0x300000000ull | CONFIG_SYS_SRIO_PCIE_BOOT_UCODE_ENV_ADDR) /* Set 1M boot space for PCIe boot */ #define CONFIG_SYS_SRIO_PCIE_BOOT_SLAVE_ADDR (CONFIG_SYS_TEXT_BASE & 0xfff00000) #define CONFIG_SYS_SRIO_PCIE_BOOT_SLAVE_ADDR_PHYS \ (0x300000000ull | CONFIG_SYS_SRIO_PCIE_BOOT_SLAVE_ADDR) #define CONFIG_RESET_VECTOR_ADDRESS 0xfffffffc #define CONFIG_SYS_NO_FLASH #endif #if defined(CONFIG_SPIFLASH) #define CONFIG_SYS_EXTRA_ENV_RELOC #define CONFIG_ENV_IS_IN_SPI_FLASH #define CONFIG_ENV_SPI_BUS 0 #define CONFIG_ENV_SPI_CS 0 #define CONFIG_ENV_SPI_MAX_HZ 10000000 #define CONFIG_ENV_SPI_MODE 0 #define CONFIG_ENV_SIZE 0x2000 /* 8KB */ #define CONFIG_ENV_OFFSET 0x100000 /* 1MB */ #if defined(CONFIG_T1024RDB) #define CONFIG_ENV_SECT_SIZE 0x10000 #elif defined(CONFIG_T1023RDB) #define CONFIG_ENV_SECT_SIZE 0x40000 #endif #elif defined(CONFIG_SDCARD) #define CONFIG_SYS_EXTRA_ENV_RELOC #define CONFIG_ENV_IS_IN_MMC #define CONFIG_SYS_MMC_ENV_DEV 0 #define CONFIG_ENV_SIZE 0x2000 #define CONFIG_ENV_OFFSET (512 * 0x800) #elif defined(CONFIG_NAND) #define CONFIG_SYS_EXTRA_ENV_RELOC #define CONFIG_ENV_IS_IN_NAND #define CONFIG_ENV_SIZE 0x2000 #if defined(CONFIG_T1024RDB) #define CONFIG_ENV_OFFSET (2 * CONFIG_SYS_NAND_BLOCK_SIZE) #elif defined(CONFIG_T1023RDB) #define CONFIG_ENV_OFFSET (10 * CONFIG_SYS_NAND_BLOCK_SIZE) #endif #elif defined(CONFIG_SRIO_PCIE_BOOT_SLAVE) #define CONFIG_ENV_IS_IN_REMOTE #define CONFIG_ENV_ADDR 0xffe20000 #define CONFIG_ENV_SIZE 0x2000 #elif defined(CONFIG_ENV_IS_NOWHERE) #define CONFIG_ENV_SIZE 0x2000 #else #define CONFIG_ENV_IS_IN_FLASH #define CONFIG_ENV_ADDR (CONFIG_SYS_MONITOR_BASE - CONFIG_ENV_SECT_SIZE) #define CONFIG_ENV_SIZE 0x2000 #define CONFIG_ENV_SECT_SIZE 0x20000 /* 128K (one sector) */ #endif #ifndef __ASSEMBLY__ unsigned long get_board_sys_clk(void); unsigned long get_board_ddr_clk(void); #endif #define CONFIG_SYS_CLK_FREQ 100000000 #define CONFIG_DDR_CLK_FREQ 100000000 /* * These can be toggled for performance analysis, otherwise use default. */ #define CONFIG_SYS_CACHE_STASHING #define CONFIG_BACKSIDE_L2_CACHE #define CONFIG_SYS_INIT_L2CSR0 L2CSR0_L2E #define CONFIG_BTB /* toggle branch predition */ #define CONFIG_DDR_ECC #ifdef CONFIG_DDR_ECC #define CONFIG_ECC_INIT_VIA_DDRCONTROLLER #define CONFIG_MEM_INIT_VALUE 0xdeadbeef #endif #define CONFIG_CMD_MEMTEST #define CONFIG_SYS_MEMTEST_START 0x00200000 /* memtest works on */ #define CONFIG_SYS_MEMTEST_END 0x00400000 #define CONFIG_SYS_ALT_MEMTEST #define CONFIG_PANIC_HANG /* do not reset board on panic */ /* * Config the L3 Cache as L3 SRAM */ #define CONFIG_SYS_INIT_L3_ADDR 0xFFFC0000 #define CONFIG_SYS_L3_SIZE (256 << 10) #define CONFIG_SPL_GD_ADDR (CONFIG_SYS_INIT_L3_ADDR + 32 * 1024) #ifdef CONFIG_RAMBOOT_PBL #define CONFIG_ENV_ADDR (CONFIG_SPL_GD_ADDR + 4 * 1024) #endif #define CONFIG_SPL_RELOC_MALLOC_ADDR (CONFIG_SPL_GD_ADDR + 12 * 1024) #define CONFIG_SPL_RELOC_MALLOC_SIZE (30 << 10) #define CONFIG_SPL_RELOC_STACK (CONFIG_SPL_GD_ADDR + 64 * 1024) #define CONFIG_SPL_RELOC_STACK_SIZE (22 << 10) #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_DCSRBAR 0xf0000000 #define CONFIG_SYS_DCSRBAR_PHYS 0xf00000000ull #endif /* EEPROM */ #define CONFIG_ID_EEPROM #define CONFIG_SYS_I2C_EEPROM_NXID #define CONFIG_SYS_EEPROM_BUS_NUM 0 #define CONFIG_SYS_I2C_EEPROM_ADDR 0x50 #define CONFIG_SYS_I2C_EEPROM_ADDR_LEN 2 #define CONFIG_SYS_EEPROM_PAGE_WRITE_BITS 3 #define CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS 5 /* * DDR Setup */ #define CONFIG_VERY_BIG_RAM #define CONFIG_SYS_DDR_SDRAM_BASE 0x00000000 #define CONFIG_SYS_SDRAM_BASE CONFIG_SYS_DDR_SDRAM_BASE #define CONFIG_DIMM_SLOTS_PER_CTLR 1 #define CONFIG_CHIP_SELECTS_PER_CTRL (4 * CONFIG_DIMM_SLOTS_PER_CTLR) #define CONFIG_FSL_DDR_INTERACTIVE #if defined(CONFIG_T1024RDB) #define CONFIG_DDR_SPD #define CONFIG_SYS_FSL_DDR3 #define CONFIG_SYS_SPD_BUS_NUM 0 #define SPD_EEPROM_ADDRESS 0x51 #define CONFIG_SYS_SDRAM_SIZE 4096 /* for fixed parameter use */ #elif defined(CONFIG_T1023RDB) #define CONFIG_SYS_FSL_DDR4 #define CONFIG_SYS_DDR_RAW_TIMING #define CONFIG_SYS_SDRAM_SIZE 2048 #endif /* * IFC Definitions */ #define CONFIG_SYS_FLASH_BASE 0xe8000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_FLASH_BASE_PHYS (0xf00000000ull | CONFIG_SYS_FLASH_BASE) #else #define CONFIG_SYS_FLASH_BASE_PHYS CONFIG_SYS_FLASH_BASE #endif #define CONFIG_SYS_NOR0_CSPR_EXT (0xf) #define CONFIG_SYS_NOR0_CSPR (CSPR_PHYS_ADDR(CONFIG_SYS_FLASH_BASE_PHYS) | \ CSPR_PORT_SIZE_16 | \ CSPR_MSEL_NOR | \ CSPR_V) #define CONFIG_SYS_NOR_AMASK IFC_AMASK(128*1024*1024) /* NOR Flash Timing Params */ #if defined(CONFIG_T1024RDB) #define CONFIG_SYS_NOR_CSOR CSOR_NAND_TRHZ_80 #elif defined(CONFIG_T1023RDB) #define CONFIG_SYS_NOR_CSOR (CSOR_NOR_ADM_SHIFT(0) | \ CSOR_NAND_TRHZ_80 | CSOR_NOR_ADM_SHFT_MODE_EN) #endif #define CONFIG_SYS_NOR_FTIM0 (FTIM0_NOR_TACSE(0x4) | \ FTIM0_NOR_TEADC(0x5) | \ FTIM0_NOR_TEAHC(0x5)) #define CONFIG_SYS_NOR_FTIM1 (FTIM1_NOR_TACO(0x35) | \ FTIM1_NOR_TRAD_NOR(0x1A) |\ FTIM1_NOR_TSEQRAD_NOR(0x13)) #define CONFIG_SYS_NOR_FTIM2 (FTIM2_NOR_TCS(0x4) | \ FTIM2_NOR_TCH(0x4) | \ FTIM2_NOR_TWPH(0x0E) | \ FTIM2_NOR_TWP(0x1c)) #define CONFIG_SYS_NOR_FTIM3 0x0 #define CONFIG_SYS_FLASH_QUIET_TEST #define CONFIG_FLASH_SHOW_PROGRESS 45 /* count down from 45/5: 9..1 */ #define CONFIG_SYS_MAX_FLASH_BANKS 1 /* number of banks */ #define CONFIG_SYS_MAX_FLASH_SECT 1024 /* sectors per device */ #define CONFIG_SYS_FLASH_ERASE_TOUT 60000 /* Flash Erase Timeout (ms) */ #define CONFIG_SYS_FLASH_WRITE_TOUT 500 /* Flash Write Timeout (ms) */ #define CONFIG_SYS_FLASH_EMPTY_INFO #define CONFIG_SYS_FLASH_BANKS_LIST {CONFIG_SYS_FLASH_BASE_PHYS} #ifdef CONFIG_T1024RDB /* CPLD on IFC */ #define CONFIG_SYS_CPLD_BASE 0xffdf0000 #define CONFIG_SYS_CPLD_BASE_PHYS (0xf00000000ull | CONFIG_SYS_CPLD_BASE) #define CONFIG_SYS_CSPR2_EXT (0xf) #define CONFIG_SYS_CSPR2 (CSPR_PHYS_ADDR(CONFIG_SYS_CPLD_BASE) \ | CSPR_PORT_SIZE_8 \ | CSPR_MSEL_GPCM \ | CSPR_V) #define CONFIG_SYS_AMASK2 IFC_AMASK(64*1024) #define CONFIG_SYS_CSOR2 0x0 /* CPLD Timing parameters for IFC CS2 */ #define CONFIG_SYS_CS2_FTIM0 (FTIM0_GPCM_TACSE(0x0e) | \ FTIM0_GPCM_TEADC(0x0e) | \ FTIM0_GPCM_TEAHC(0x0e)) #define CONFIG_SYS_CS2_FTIM1 (FTIM1_GPCM_TACO(0x0e) | \ FTIM1_GPCM_TRAD(0x1f)) #define CONFIG_SYS_CS2_FTIM2 (FTIM2_GPCM_TCS(0x0e) | \ FTIM2_GPCM_TCH(0x8) | \ FTIM2_GPCM_TWP(0x1f)) #define CONFIG_SYS_CS2_FTIM3 0x0 #endif /* NAND Flash on IFC */ #define CONFIG_NAND_FSL_IFC #define CONFIG_SYS_NAND_BASE 0xff800000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_NAND_BASE_PHYS (0xf00000000ull | CONFIG_SYS_NAND_BASE) #else #define CONFIG_SYS_NAND_BASE_PHYS CONFIG_SYS_NAND_BASE #endif #define CONFIG_SYS_NAND_CSPR_EXT (0xf) #define CONFIG_SYS_NAND_CSPR (CSPR_PHYS_ADDR(CONFIG_SYS_NAND_BASE_PHYS) \ | CSPR_PORT_SIZE_8 /* Port Size = 8 bit */ \ | CSPR_MSEL_NAND /* MSEL = NAND */ \ | CSPR_V) #define CONFIG_SYS_NAND_AMASK IFC_AMASK(64*1024) #if defined(CONFIG_T1024RDB) #define CONFIG_SYS_NAND_CSOR (CSOR_NAND_ECC_ENC_EN /* ECC on encode */ \ | CSOR_NAND_ECC_DEC_EN /* ECC on decode */ \ | CSOR_NAND_ECC_MODE_4 /* 4-bit ECC */ \ | CSOR_NAND_RAL_3 /* RAL = 3Byes */ \ | CSOR_NAND_PGS_4K /* Page Size = 4K */ \ | CSOR_NAND_SPRZ_224 /* Spare size = 224 */ \ | CSOR_NAND_PB(64)) /*Pages Per Block = 64*/ #define CONFIG_SYS_NAND_BLOCK_SIZE (512 * 1024) #elif defined(CONFIG_T1023RDB) #define CONFIG_SYS_NAND_CSOR (CSOR_NAND_ECC_ENC_EN /* ECC on encode */ \ | CSOR_NAND_ECC_DEC_EN /* ECC on decode */ \ | CSOR_NAND_ECC_MODE_4 /* 4-bit ECC */ \ | CSOR_NAND_RAL_3 /* RAL 3Bytes */ \ | CSOR_NAND_PGS_2K /* Page Size = 2K */ \ | CSOR_NAND_SPRZ_128 /* Spare size = 128 */ \ | CSOR_NAND_PB(64)) /*Pages Per Block = 64*/ #define CONFIG_SYS_NAND_BLOCK_SIZE (128 * 1024) #endif #define CONFIG_SYS_NAND_ONFI_DETECTION /* ONFI NAND Flash mode0 Timing Params */ #define CONFIG_SYS_NAND_FTIM0 (FTIM0_NAND_TCCST(0x07) | \ FTIM0_NAND_TWP(0x18) | \ FTIM0_NAND_TWCHT(0x07) | \ FTIM0_NAND_TWH(0x0a)) #define CONFIG_SYS_NAND_FTIM1 (FTIM1_NAND_TADLE(0x32) | \ FTIM1_NAND_TWBE(0x39) | \ FTIM1_NAND_TRR(0x0e) | \ FTIM1_NAND_TRP(0x18)) #define CONFIG_SYS_NAND_FTIM2 (FTIM2_NAND_TRAD(0x0f) | \ FTIM2_NAND_TREH(0x0a) | \ FTIM2_NAND_TWHRE(0x1e)) #define CONFIG_SYS_NAND_FTIM3 0x0 #define CONFIG_SYS_NAND_DDR_LAW 11 #define CONFIG_SYS_NAND_BASE_LIST { CONFIG_SYS_NAND_BASE } #define CONFIG_SYS_MAX_NAND_DEVICE 1 #define CONFIG_CMD_NAND #if defined(CONFIG_NAND) #define CONFIG_SYS_CSPR0_EXT CONFIG_SYS_NAND_CSPR_EXT #define CONFIG_SYS_CSPR0 CONFIG_SYS_NAND_CSPR #define CONFIG_SYS_AMASK0 CONFIG_SYS_NAND_AMASK #define CONFIG_SYS_CSOR0 CONFIG_SYS_NAND_CSOR #define CONFIG_SYS_CS0_FTIM0 CONFIG_SYS_NAND_FTIM0 #define CONFIG_SYS_CS0_FTIM1 CONFIG_SYS_NAND_FTIM1 #define CONFIG_SYS_CS0_FTIM2 CONFIG_SYS_NAND_FTIM2 #define CONFIG_SYS_CS0_FTIM3 CONFIG_SYS_NAND_FTIM3 #define CONFIG_SYS_CSPR1_EXT CONFIG_SYS_NOR0_CSPR_EXT #define CONFIG_SYS_CSPR1 CONFIG_SYS_NOR0_CSPR #define CONFIG_SYS_AMASK1 CONFIG_SYS_NOR_AMASK #define CONFIG_SYS_CSOR1 CONFIG_SYS_NOR_CSOR #define CONFIG_SYS_CS1_FTIM0 CONFIG_SYS_NOR_FTIM0 #define CONFIG_SYS_CS1_FTIM1 CONFIG_SYS_NOR_FTIM1 #define CONFIG_SYS_CS1_FTIM2 CONFIG_SYS_NOR_FTIM2 #define CONFIG_SYS_CS1_FTIM3 CONFIG_SYS_NOR_FTIM3 #else #define CONFIG_SYS_CSPR0_EXT CONFIG_SYS_NOR0_CSPR_EXT #define CONFIG_SYS_CSPR0 CONFIG_SYS_NOR0_CSPR #define CONFIG_SYS_AMASK0 CONFIG_SYS_NOR_AMASK #define CONFIG_SYS_CSOR0 CONFIG_SYS_NOR_CSOR #define CONFIG_SYS_CS0_FTIM0 CONFIG_SYS_NOR_FTIM0 #define CONFIG_SYS_CS0_FTIM1 CONFIG_SYS_NOR_FTIM1 #define CONFIG_SYS_CS0_FTIM2 CONFIG_SYS_NOR_FTIM2 #define CONFIG_SYS_CS0_FTIM3 CONFIG_SYS_NOR_FTIM3 #define CONFIG_SYS_CSPR1_EXT CONFIG_SYS_NAND_CSPR_EXT #define CONFIG_SYS_CSPR1 CONFIG_SYS_NAND_CSPR #define CONFIG_SYS_AMASK1 CONFIG_SYS_NAND_AMASK #define CONFIG_SYS_CSOR1 CONFIG_SYS_NAND_CSOR #define CONFIG_SYS_CS1_FTIM0 CONFIG_SYS_NAND_FTIM0 #define CONFIG_SYS_CS1_FTIM1 CONFIG_SYS_NAND_FTIM1 #define CONFIG_SYS_CS1_FTIM2 CONFIG_SYS_NAND_FTIM2 #define CONFIG_SYS_CS1_FTIM3 CONFIG_SYS_NAND_FTIM3 #endif #ifdef CONFIG_SPL_BUILD #define CONFIG_SYS_MONITOR_BASE CONFIG_SPL_TEXT_BASE #else #define CONFIG_SYS_MONITOR_BASE CONFIG_SYS_TEXT_BASE #endif #if defined(CONFIG_RAMBOOT_PBL) #define CONFIG_SYS_RAMBOOT #endif #define CONFIG_BOARD_EARLY_INIT_R #define CONFIG_MISC_INIT_R #define CONFIG_HWCONFIG /* define to use L1 as initial stack */ #define CONFIG_L1_INIT_RAM #define CONFIG_SYS_INIT_RAM_LOCK #define CONFIG_SYS_INIT_RAM_ADDR 0xfdd00000 /* Initial L1 address */ #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_INIT_RAM_ADDR_PHYS_HIGH 0xf #define CONFIG_SYS_INIT_RAM_ADDR_PHYS_LOW 0xfe03c000 /* The assembler doesn't like typecast */ #define CONFIG_SYS_INIT_RAM_ADDR_PHYS \ ((CONFIG_SYS_INIT_RAM_ADDR_PHYS_HIGH * 1ull << 32) | \ CONFIG_SYS_INIT_RAM_ADDR_PHYS_LOW) #else #define CONFIG_SYS_INIT_RAM_ADDR_PHYS 0xfe03c000 /* Initial L1 address */ #define CONFIG_SYS_INIT_RAM_ADDR_PHYS_HIGH 0 #define CONFIG_SYS_INIT_RAM_ADDR_PHYS_LOW CONFIG_SYS_INIT_RAM_ADDR_PHYS #endif #define CONFIG_SYS_INIT_RAM_SIZE 0x00004000 #define CONFIG_SYS_GBL_DATA_OFFSET (CONFIG_SYS_INIT_RAM_SIZE - \ GENERATED_GBL_DATA_SIZE) #define CONFIG_SYS_INIT_SP_OFFSET CONFIG_SYS_GBL_DATA_OFFSET #define CONFIG_SYS_MONITOR_LEN (768 * 1024) #define CONFIG_SYS_MALLOC_LEN (10 * 1024 * 1024) /* Serial Port */ #define CONFIG_CONS_INDEX 1 #define CONFIG_SYS_NS16550 #define CONFIG_SYS_NS16550_SERIAL #define CONFIG_SYS_NS16550_REG_SIZE 1 #define CONFIG_SYS_NS16550_CLK (get_bus_freq(0)/2) #define CONFIG_SYS_BAUDRATE_TABLE \ {300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200} #define CONFIG_SYS_NS16550_COM1 (CONFIG_SYS_CCSRBAR+0x11C500) #define CONFIG_SYS_NS16550_COM2 (CONFIG_SYS_CCSRBAR+0x11C600) #define CONFIG_SYS_NS16550_COM3 (CONFIG_SYS_CCSRBAR+0x11D500) #define CONFIG_SYS_NS16550_COM4 (CONFIG_SYS_CCSRBAR+0x11D600) #define CONFIG_SYS_CONSOLE_IS_IN_ENV /* determine from environment */ /* Use the HUSH parser */ #define CONFIG_SYS_HUSH_PARSER #define CONFIG_SYS_PROMPT_HUSH_PS2 "> " /* Video */ #undef CONFIG_FSL_DIU_FB /* RDB doesn't support DIU */ #ifdef CONFIG_FSL_DIU_FB #define CONFIG_SYS_DIU_ADDR (CONFIG_SYS_CCSRBAR + 0x180000) #define CONFIG_VIDEO #define CONFIG_CMD_BMP #define CONFIG_CFB_CONSOLE #define CONFIG_VIDEO_SW_CURSOR #define CONFIG_VGA_AS_SINGLE_DEVICE #define CONFIG_VIDEO_LOGO #define CONFIG_VIDEO_BMP_LOGO #define CONFIG_CFI_FLASH_USE_WEAK_ACCESSORS /* * With CONFIG_CFI_FLASH_USE_WEAK_ACCESSORS, flash I/O is really slow, so * disable empty flash sector detection, which is I/O-intensive. */ #undef CONFIG_SYS_FLASH_EMPTY_INFO #endif /* pass open firmware flat tree */ #define CONFIG_OF_LIBFDT #define CONFIG_OF_BOARD_SETUP #define CONFIG_OF_STDOUT_VIA_ALIAS /* new uImage format support */ #define CONFIG_FIT #define CONFIG_FIT_VERBOSE /* enable fit_format_{error,warning}() */ /* I2C */ #define CONFIG_SYS_I2C #define CONFIG_SYS_I2C_FSL /* Use FSL common I2C driver */ #define CONFIG_SYS_FSL_I2C_SPEED 50000 /* I2C speed in Hz */ #define CONFIG_SYS_FSL_I2C_SLAVE 0x7F #define CONFIG_SYS_FSL_I2C2_SPEED 50000 /* I2C speed in Hz */ #define CONFIG_SYS_FSL_I2C2_SLAVE 0x7F #define CONFIG_SYS_FSL_I2C_OFFSET 0x118000 #define CONFIG_SYS_FSL_I2C2_OFFSET 0x118100 #define I2C_PCA6408_BUS_NUM 1 #define I2C_PCA6408_ADDR 0x20 /* I2C bus multiplexer */ #define I2C_MUX_CH_DEFAULT 0x8 /* * RTC configuration */ #define RTC #define CONFIG_RTC_DS1337 1 #define CONFIG_SYS_I2C_RTC_ADDR 0x68 /* * eSPI - Enhanced SPI */ #define CONFIG_FSL_ESPI #if defined(CONFIG_T1024RDB) #define CONFIG_SPI_FLASH_STMICRO #elif defined(CONFIG_T1023RDB) #define CONFIG_SPI_FLASH_SPANSION #endif #define CONFIG_CMD_SF #define CONFIG_SPI_FLASH_BAR #define CONFIG_SF_DEFAULT_SPEED 10000000 #define CONFIG_SF_DEFAULT_MODE 0 /* * General PCIe * Memory space is mapped 1-1, but I/O space must start from 0. */ #define CONFIG_PCI /* Enable PCI/PCIE */ #define CONFIG_PCIE1 /* PCIE controler 1 */ #define CONFIG_PCIE2 /* PCIE controler 2 */ #define CONFIG_PCIE3 /* PCIE controler 3 */ #ifdef CONFIG_PPC_T1040 #define CONFIG_PCIE4 /* PCIE controler 4 */ #endif #define CONFIG_FSL_PCI_INIT /* Use common FSL init code */ #define CONFIG_SYS_PCI_64BIT /* enable 64-bit PCI resources */ #define CONFIG_PCI_INDIRECT_BRIDGE #ifdef CONFIG_PCI /* controller 1, direct to uli, tgtid 3, Base address 20000 */ #ifdef CONFIG_PCIE1 #define CONFIG_SYS_PCIE1_MEM_VIRT 0x80000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE1_MEM_BUS 0xe0000000 #define CONFIG_SYS_PCIE1_MEM_PHYS 0xc00000000ull #else #define CONFIG_SYS_PCIE1_MEM_BUS 0x80000000 #define CONFIG_SYS_PCIE1_MEM_PHYS 0x80000000 #endif #define CONFIG_SYS_PCIE1_MEM_SIZE 0x10000000 /* 256M */ #define CONFIG_SYS_PCIE1_IO_VIRT 0xf8000000 #define CONFIG_SYS_PCIE1_IO_BUS 0x00000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE1_IO_PHYS 0xff8000000ull #else #define CONFIG_SYS_PCIE1_IO_PHYS 0xf8000000 #endif #define CONFIG_SYS_PCIE1_IO_SIZE 0x00010000 /* 64k */ #endif /* controller 2, Slot 2, tgtid 2, Base address 201000 */ #ifdef CONFIG_PCIE2 #define CONFIG_SYS_PCIE2_MEM_VIRT 0x90000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE2_MEM_BUS 0xe0000000 #define CONFIG_SYS_PCIE2_MEM_PHYS 0xc10000000ull #else #define CONFIG_SYS_PCIE2_MEM_BUS 0x90000000 #define CONFIG_SYS_PCIE2_MEM_PHYS 0x90000000 #endif #define CONFIG_SYS_PCIE2_MEM_SIZE 0x10000000 /* 256M */ #define CONFIG_SYS_PCIE2_IO_VIRT 0xf8010000 #define CONFIG_SYS_PCIE2_IO_BUS 0x00000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE2_IO_PHYS 0xff8010000ull #else #define CONFIG_SYS_PCIE2_IO_PHYS 0xf8010000 #endif #define CONFIG_SYS_PCIE2_IO_SIZE 0x00010000 /* 64k */ #endif /* controller 3, Slot 1, tgtid 1, Base address 202000 */ #ifdef CONFIG_PCIE3 #define CONFIG_SYS_PCIE3_MEM_VIRT 0xa0000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE3_MEM_BUS 0xe0000000 #define CONFIG_SYS_PCIE3_MEM_PHYS 0xc20000000ull #else #define CONFIG_SYS_PCIE3_MEM_BUS 0xa0000000 #define CONFIG_SYS_PCIE3_MEM_PHYS 0xa0000000 #endif #define CONFIG_SYS_PCIE3_MEM_SIZE 0x10000000 /* 256M */ #define CONFIG_SYS_PCIE3_IO_VIRT 0xf8020000 #define CONFIG_SYS_PCIE3_IO_BUS 0x00000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE3_IO_PHYS 0xff8020000ull #else #define CONFIG_SYS_PCIE3_IO_PHYS 0xf8020000 #endif #define CONFIG_SYS_PCIE3_IO_SIZE 0x00010000 /* 64k */ #endif /* controller 4, Base address 203000, to be removed */ #ifdef CONFIG_PCIE4 #define CONFIG_SYS_PCIE4_MEM_VIRT 0xb0000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE4_MEM_BUS 0xe0000000 #define CONFIG_SYS_PCIE4_MEM_PHYS 0xc30000000ull #else #define CONFIG_SYS_PCIE4_MEM_BUS 0xb0000000 #define CONFIG_SYS_PCIE4_MEM_PHYS 0xb0000000 #endif #define CONFIG_SYS_PCIE4_MEM_SIZE 0x10000000 /* 256M */ #define CONFIG_SYS_PCIE4_IO_VIRT 0xf8030000 #define CONFIG_SYS_PCIE4_IO_BUS 0x00000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_PCIE4_IO_PHYS 0xff8030000ull #else #define CONFIG_SYS_PCIE4_IO_PHYS 0xf8030000 #endif #define CONFIG_SYS_PCIE4_IO_SIZE 0x00010000 /* 64k */ #endif #define CONFIG_PCI_PNP /* do pci plug-and-play */ #define CONFIG_PCI_SCAN_SHOW /* show pci devices on startup */ #define CONFIG_DOS_PARTITION #endif /* CONFIG_PCI */ /* * USB */ #define CONFIG_HAS_FSL_DR_USB #ifdef CONFIG_HAS_FSL_DR_USB #define CONFIG_USB_EHCI #define CONFIG_CMD_USB #define CONFIG_USB_STORAGE #define CONFIG_USB_EHCI_FSL #define CONFIG_EHCI_HCD_INIT_AFTER_RESET #define CONFIG_CMD_EXT2 #endif /* * SDHC */ #define CONFIG_MMC #ifdef CONFIG_MMC #define CONFIG_FSL_ESDHC #define CONFIG_SYS_FSL_ESDHC_ADDR CONFIG_SYS_MPC85xx_ESDHC_ADDR #define CONFIG_CMD_MMC #define CONFIG_GENERIC_MMC #define CONFIG_CMD_EXT2 #define CONFIG_CMD_FAT #define CONFIG_DOS_PARTITION #endif /* Qman/Bman */ #ifndef CONFIG_NOBQFMAN #define CONFIG_SYS_DPAA_QBMAN /* Support Q/Bman */ #define CONFIG_SYS_BMAN_NUM_PORTALS 10 #define CONFIG_SYS_BMAN_MEM_BASE 0xf4000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_BMAN_MEM_PHYS 0xff4000000ull #else #define CONFIG_SYS_BMAN_MEM_PHYS CONFIG_SYS_BMAN_MEM_BASE #endif #define CONFIG_SYS_BMAN_MEM_SIZE 0x02000000 #define CONFIG_SYS_BMAN_SP_CENA_SIZE 0x4000 #define CONFIG_SYS_BMAN_SP_CINH_SIZE 0x1000 #define CONFIG_SYS_BMAN_CENA_BASE CONFIG_SYS_BMAN_MEM_BASE #define CONFIG_SYS_BMAN_CENA_SIZE (CONFIG_SYS_BMAN_MEM_SIZE >> 1) #define CONFIG_SYS_BMAN_CINH_BASE (CONFIG_SYS_BMAN_MEM_BASE + \ CONFIG_SYS_BMAN_CENA_SIZE) #define CONFIG_SYS_BMAN_CINH_SIZE (CONFIG_SYS_BMAN_MEM_SIZE >> 1) #define CONFIG_SYS_BMAN_SWP_ISDR_REG 0xE08 #define CONFIG_SYS_QMAN_NUM_PORTALS 10 #define CONFIG_SYS_QMAN_MEM_BASE 0xf6000000 #ifdef CONFIG_PHYS_64BIT #define CONFIG_SYS_QMAN_MEM_PHYS 0xff6000000ull #else #define CONFIG_SYS_QMAN_MEM_PHYS CONFIG_SYS_QMAN_MEM_BASE #endif #define CONFIG_SYS_QMAN_MEM_SIZE 0x02000000 #define CONFIG_SYS_QMAN_SP_CENA_SIZE 0x4000 #define CONFIG_SYS_QMAN_SP_CINH_SIZE 0x1000 #define CONFIG_SYS_QMAN_CENA_BASE CONFIG_SYS_QMAN_MEM_BASE #define CONFIG_SYS_QMAN_CENA_SIZE (CONFIG_SYS_QMAN_MEM_SIZE >> 1) #define CONFIG_SYS_QMAN_CINH_BASE (CONFIG_SYS_QMAN_MEM_BASE + \ CONFIG_SYS_QMAN_CENA_SIZE) #define CONFIG_SYS_QMAN_CINH_SIZE (CONFIG_SYS_QMAN_MEM_SIZE >> 1) #define CONFIG_SYS_QMAN_SWP_ISDR_REG 0xE08 #define CONFIG_SYS_DPAA_FMAN #ifdef CONFIG_T1024RDB #define CONFIG_QE #define CONFIG_U_QE #endif /* Default address of microcode for the Linux FMan driver */ #if defined(CONFIG_SPIFLASH) /* * env is stored at 0x100000, sector size is 0x10000, ucode is stored after * env, so we got 0x110000. */ #define CONFIG_SYS_QE_FW_IN_SPIFLASH #define CONFIG_SYS_FMAN_FW_ADDR 0x110000 #define CONFIG_SYS_QE_FW_ADDR 0x130000 #elif defined(CONFIG_SDCARD) /* * PBL SD boot image should stored at 0x1000(8 blocks), the size of the image is * about 1MB (2048 blocks), Env is stored after the image, and the env size is * 0x2000 (16 blocks), 8 + 2048 + 16 = 2072, enlarge it to 2080(0x820). */ #define CONFIG_SYS_QE_FMAN_FW_IN_MMC #define CONFIG_SYS_FMAN_FW_ADDR (512 * 0x820) #define CONFIG_SYS_QE_FW_ADDR (512 * 0x920) #elif defined(CONFIG_NAND) #define CONFIG_SYS_QE_FMAN_FW_IN_NAND #if defined(CONFIG_T1024RDB) #define CONFIG_SYS_FMAN_FW_ADDR (3 * CONFIG_SYS_NAND_BLOCK_SIZE) #define CONFIG_SYS_QE_FW_ADDR (4 * CONFIG_SYS_NAND_BLOCK_SIZE) #elif defined(CONFIG_T1023RDB) #define CONFIG_SYS_FMAN_FW_ADDR (11 * CONFIG_SYS_NAND_BLOCK_SIZE) #define CONFIG_SYS_QE_FW_ADDR (12 * CONFIG_SYS_NAND_BLOCK_SIZE) #endif #elif defined(CONFIG_SRIO_PCIE_BOOT_SLAVE) /* * Slave has no ucode locally, it can fetch this from remote. When implementing * in two corenet boards, slave's ucode could be stored in master's memory * space, the address can be mapped from slave TLB->slave LAW-> * slave SRIO or PCIE outbound window->master inbound window-> * master LAW->the ucode address in master's memory space. */ #define CONFIG_SYS_QE_FMAN_FW_IN_REMOTE #define CONFIG_SYS_FMAN_FW_ADDR 0xFFE00000 #else #define CONFIG_SYS_QE_FMAN_FW_IN_NOR #define CONFIG_SYS_FMAN_FW_ADDR 0xEFF00000 #define CONFIG_SYS_QE_FW_ADDR 0xEFE00000 #endif #define CONFIG_SYS_QE_FMAN_FW_LENGTH 0x10000 #define CONFIG_SYS_FDT_PAD (0x3000 + CONFIG_SYS_QE_FMAN_FW_LENGTH) #endif /* CONFIG_NOBQFMAN */ #ifdef CONFIG_SYS_DPAA_FMAN #define CONFIG_FMAN_ENET #define CONFIG_PHYLIB_10G #define CONFIG_PHY_REALTEK #define CONFIG_PHY_AQUANTIA #if defined(CONFIG_T1024RDB) #define RGMII_PHY1_ADDR 0x2 #define RGMII_PHY2_ADDR 0x6 #define SGMII_AQR_PHY_ADDR 0x2 #define FM1_10GEC1_PHY_ADDR 0x1 #elif defined(CONFIG_T1023RDB) #define RGMII_PHY1_ADDR 0x1 #define SGMII_RTK_PHY_ADDR 0x3 #define SGMII_AQR_PHY_ADDR 0x2 #endif #endif #ifdef CONFIG_FMAN_ENET #define CONFIG_MII /* MII PHY management */ #define CONFIG_ETHPRIME "FM1@DTSEC4" #define CONFIG_PHY_GIGE /* Include GbE speed/duplex detection */ #endif /* * Dynamic MTD Partition support with mtdparts */ #ifndef CONFIG_SYS_NO_FLASH #define CONFIG_MTD_DEVICE #define CONFIG_MTD_PARTITIONS #define CONFIG_CMD_MTDPARTS #define CONFIG_FLASH_CFI_MTD #define MTDIDS_DEFAULT "nor0=fe8000000.nor,nand0=fff800000.flash," \ "spi0=spife110000.1" #define MTDPARTS_DEFAULT "mtdparts=fe8000000.nor:1m(uboot),5m(kernel)," \ "128k(dtb),96m(fs),-(user);fff800000.flash:1m(uboot)," \ "5m(kernel),128k(dtb),96m(fs),-(user);spife110000.0:" \ "1m(uboot),5m(kernel),128k(dtb),-(user)" #endif /* * Environment */ #define CONFIG_LOADS_ECHO /* echo on for serial download */ #define CONFIG_SYS_LOADS_BAUD_CHANGE /* allow baudrate change */ /* * Command line configuration. */ #define CONFIG_CMD_DATE #define CONFIG_CMD_DHCP #define CONFIG_CMD_EEPROM #define CONFIG_CMD_ELF #define CONFIG_CMD_ERRATA #define CONFIG_CMD_GREPENV #define CONFIG_CMD_IRQ #define CONFIG_CMD_I2C #define CONFIG_CMD_MII #define CONFIG_CMD_PING #define CONFIG_CMD_REGINFO #ifdef CONFIG_PCI #define CONFIG_CMD_PCI #endif /* * Miscellaneous configurable options */ #define CONFIG_SYS_LONGHELP /* undef to save memory */ #define CONFIG_CMDLINE_EDITING /* Command-line editing */ #define CONFIG_AUTO_COMPLETE /* add autocompletion support */ #define CONFIG_SYS_LOAD_ADDR 0x2000000 /* default load address */ #ifdef CONFIG_CMD_KGDB #define CONFIG_SYS_CBSIZE 1024 /* Console I/O Buffer Size */ #else #define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */ #endif #define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE+sizeof(CONFIG_SYS_PROMPT)+16) #define CONFIG_SYS_MAXARGS 16 /* max number of command args */ #define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* Boot Argument Buffer Size */ /* * For booting Linux, the board info and command line data * have to be in the first 64 MB of memory, since this is * the maximum mapped by the Linux kernel during initialization. */ #define CONFIG_SYS_BOOTMAPSZ (64 << 20) /* Initial map for Linux*/ #define CONFIG_SYS_BOOTM_LEN (64 << 20) /* Increase max gunzip size */ #ifdef CONFIG_CMD_KGDB #define CONFIG_KGDB_BAUDRATE 230400 /* speed to run kgdb serial port */ #endif /* * Environment Configuration */ #define CONFIG_ROOTPATH "/opt/nfsroot" #define CONFIG_BOOTFILE "uImage" #define CONFIG_UBOOTPATH u-boot.bin /* U-Boot image on TFTP server */ #define CONFIG_LOADADDR 1000000 /* default location for tftp, bootm */ #define CONFIG_BOOTDELAY 10 /* -1 disables auto-boot */ #define CONFIG_BAUDRATE 115200 #define __USB_PHY_TYPE utmi #ifdef CONFIG_PPC_T1024 #define CONFIG_BOARDNAME t1024rdb #define BANK_INTLV cs0_cs1 #else #define CONFIG_BOARDNAME t1023rdb #define BANK_INTLV null #endif #define CONFIG_EXTRA_ENV_SETTINGS \ "hwconfig=fsl_ddr:ctlr_intlv=cacheline," \ "bank_intlv=" __stringify(BANK_INTLV) "\0" \ "usb1:dr_mode=host,phy_type=" __stringify(__USB_PHY_TYPE) "\0" \ "ramdiskfile=" __stringify(CONFIG_BOARDNAME) "/ramdisk.uboot\0" \ "fdtfile=" __stringify(CONFIG_BOARDNAME) "/" \ __stringify(CONFIG_BOARDNAME) ".dtb\0" \ "uboot=" __stringify(CONFIG_UBOOTPATH) "\0" \ "ubootaddr=" __stringify(CONFIG_SYS_TEXT_BASE) "\0" \ "bootargs=root=/dev/ram rw console=ttyS0,115200\0" \ "netdev=eth0\0" \ "tftpflash=tftpboot $loadaddr $uboot && " \ "protect off $ubootaddr +$filesize && " \ "erase $ubootaddr +$filesize && " \ "cp.b $loadaddr $ubootaddr $filesize && " \ "protect on $ubootaddr +$filesize && " \ "cmp.b $loadaddr $ubootaddr $filesize\0" \ "consoledev=ttyS0\0" \ "ramdiskaddr=2000000\0" \ "fdtaddr=c00000\0" \ "bdev=sda3\0" #define CONFIG_LINUX \ "setenv bootargs root=/dev/ram rw " \ "console=$consoledev,$baudrate $othbootargs;" \ "setenv ramdiskaddr 0x02000000;" \ "setenv fdtaddr 0x00c00000;" \ "setenv loadaddr 0x1000000;" \ "bootm $loadaddr $ramdiskaddr $fdtaddr" #define CONFIG_NFSBOOTCOMMAND \ "setenv bootargs root=/dev/nfs rw " \ "nfsroot=$serverip:$rootpath " \ "ip=$ipaddr:$serverip:$gatewayip:$netmask:$hostname:$netdev:off " \ "console=$consoledev,$baudrate $othbootargs;" \ "tftp $loadaddr $bootfile;" \ "tftp $fdtaddr $fdtfile;" \ "bootm $loadaddr - $fdtaddr" #define CONFIG_BOOTCOMMAND CONFIG_LINUX #ifdef CONFIG_SECURE_BOOT #include <asm/fsl_secure_boot.h> #endif #endif /* __T1024RDB_H */
mdxy2010/forlinux-ok6410
u-boot15/include/configs/T102xRDB.h
C
gpl-2.0
31,691
#import <Foundation/Foundation.h> #import "MediaServiceRemote.h" #import "ServiceRemoteWordPressXMLRPC.h" @interface MediaServiceRemoteXMLRPC : ServiceRemoteWordPressXMLRPC <MediaServiceRemote> @end
atl009/WordPress-iOS
WordPressKit/WordPressKit/MediaServiceRemoteXMLRPC.h
C
gpl-2.0
200
<?php /** * Functions controlling the counter/tracker * * @package Top_Ten */ /** * Function to update the post views for the current post. Filters `the_content`. * * @since 1.0 * * @param string $content Post content * @return string Filtered content */ function tptn_add_viewed_count( $content ) { global $post, $wpdb, $single, $tptn_url, $tptn_path, $tptn_settings; $table_name = $wpdb->base_prefix . 'top_ten'; $home_url = home_url( '/' ); /** * Filter the script URL of the counter. * * Create a filter function to overwrite the script URL to use the external top-10-counter.js.php * You can use $tptn_url . '/top-10-addcount.js.php' as a source * $tptn_url is a global variable * * @since 2.0 */ $home_url = apply_filters( 'tptn_add_counter_script_url', $home_url ); if ( is_singular() ) { $current_user = wp_get_current_user(); // Let's get the current user $post_author = ( $current_user->ID == $post->post_author ) ? true : false; // Is the current user the post author? $current_user_admin = ( current_user_can( 'manage_options' ) ) ? true : false; // Is the current user an admin? $current_user_editor = ( ( current_user_can( 'edit_others_posts' ) ) && ( ! current_user_can( 'manage_options' ) ) ) ? true : false; // Is the current user an editor? $include_code = true; if ( ( $post_author ) && ( ! $tptn_settings['track_authors'] ) ) { $include_code = false; } if ( ( $current_user_admin ) && ( ! $tptn_settings['track_admins'] ) ) { $include_code = false; } if ( ( $current_user_editor ) && ( ! $tptn_settings['track_editors'] ) ) { $include_code = false; } if ( $include_code ) { $output = ''; $id = intval( $post->ID ); $blog_id = get_current_blog_id(); $activate_counter = $tptn_settings['activate_overall'] ? 1 : 0; // It's 1 if we're updating the overall count $activate_counter = $activate_counter + ( $tptn_settings['activate_daily'] ? 10 : 0 ); // It's 10 if we're updating the daily count if ( $activate_counter > 0 ) { if ( $tptn_settings['cache_fix'] ) { $output = '<script type="text/javascript">jQuery.ajax({url: "' . $home_url . '", data: {top_ten_id: ' . $id . ', top_ten_blog_id: ' . $blog_id . ', activate_counter: ' . $activate_counter . ', top10_rnd: (new Date()).getTime() + "-" + Math.floor(Math.random()*100000)}});</script>'; } else { $output = '<script type="text/javascript" async src="' . $home_url . '?top_ten_id=' . $id . '&amp;top_ten_blog_id=' . $blog_id . '&amp;activate_counter=' . $activate_counter . '"></script>'; } } /** * Filter the counter script * * @since 1.9.8.5 * * @param string $output Counter script code */ $output = apply_filters( 'tptn_viewed_count', $output ); return $content.$output; } else { return $content; } } else { return $content; } } add_filter( 'the_content', 'tptn_add_viewed_count' ); /** * Enqueue Scripts. * * @since 1.9.7 */ function tptn_enqueue_scripts() { global $tptn_settings; if ( $tptn_settings['cache_fix'] ) { wp_enqueue_script( 'jquery' ); } } add_action( 'wp_enqueue_scripts', 'tptn_enqueue_scripts' ); // wp_enqueue_scripts action hook to link only on the front-end /** * Function to add additional queries to query_vars. * * @since 2.0.0 * * @param array $vars Query variables array * @return array $Query variables array with Top 10 parameters appended */ function tptn_query_vars( $vars ) { // add these to the list of queryvars that WP gathers $vars[] = 'top_ten_id'; $vars[] = 'top_ten_blog_id'; $vars[] = 'activate_counter'; $vars[] = 'view_counter'; return $vars; } add_filter( 'query_vars', 'tptn_query_vars' ); /** * Function to update the . * * @since 2.0.0 * * @param object $wp WordPress object */ function tptn_parse_request( $wp ) { global $wpdb, $tptn_settings; if ( empty( $wp ) ) { global $wp; } if ( ! isset( $wp->query_vars ) || ! is_array( $wp->query_vars ) ) { return; } $table_name = $wpdb->base_prefix . 'top_ten'; $top_ten_daily = $wpdb->base_prefix . 'top_ten_daily'; $str = ''; if ( array_key_exists( 'top_ten_id', $wp->query_vars ) && array_key_exists( 'activate_counter', $wp->query_vars ) && $wp->query_vars['top_ten_id'] != '' ) { $id = intval( $wp->query_vars['top_ten_id'] ); $blog_id = intval( $wp->query_vars['top_ten_blog_id'] ); $activate_counter = intval( $wp->query_vars['activate_counter'] ); if ( $id > 0 ) { if ( ( 1 == $activate_counter ) || ( 11 == $activate_counter ) ) { $tt = $wpdb->query( $wpdb->prepare( "INSERT INTO {$table_name} (postnumber, cntaccess, blog_id) VALUES('%d', '1', '%d') ON DUPLICATE KEY UPDATE cntaccess= cntaccess+1 ", $id, $blog_id ) ); $str .= ( false === $tt ) ? 'tte' : 'tt' . $tt; } if ( ( 10 == $activate_counter ) || ( 11 == $activate_counter ) ) { $current_date = gmdate( 'Y-m-d H', current_time( 'timestamp', 0 ) ); $ttd = $wpdb->query( $wpdb->prepare( "INSERT INTO {$top_ten_daily} (postnumber, cntaccess, dp_date, blog_id) VALUES('%d', '1', '%s', '%d' ) ON DUPLICATE KEY UPDATE cntaccess= cntaccess+1 ", $id, $current_date, $blog_id ) ); $str .= ( false === $ttd ) ? ' ttde' : ' ttd' . $ttd; } } Header( 'content-type: application/x-javascript' ); echo '<!-- ' . $str . ' -->'; // stop anything else from loading as it is not needed. exit; } elseif ( array_key_exists( 'top_ten_id', $wp->query_vars ) && array_key_exists( 'view_counter', $wp->query_vars ) && $wp->query_vars['top_ten_id'] != '' ) { $id = intval( $wp->query_vars['top_ten_id'] ); if ( $id > 0 ) { $output = get_tptn_post_count( $id ); Header( 'content-type: application/x-javascript' ); echo 'document.write("' . $output . '")'; // stop anything else from loading as it is not needed. exit; } } else { return; } } add_action( 'parse_request', 'tptn_parse_request' ); /** * Function to add the viewed count to the post content. Filters `the_content`. * * @since 1.0 * @param string $content Post content * @return string Filtered post content */ function tptn_pc_content( $content ) { global $single, $post, $tptn_settings; $exclude_on_post_ids = explode( ',', $tptn_settings['exclude_on_post_ids'] ); if ( in_array( $post->ID, $exclude_on_post_ids ) ) { return $content; // Exit without adding related posts } if ( ( is_single() ) && ( $tptn_settings['add_to_content'] ) ) { return $content . echo_tptn_post_count( 0 ); } elseif ( ( is_page() ) && ( $tptn_settings['count_on_pages'] ) ) { return $content . echo_tptn_post_count( 0 ); } elseif ( ( is_home() ) && ( $tptn_settings['add_to_home'] ) ) { return $content . echo_tptn_post_count( 0 ); } elseif ( ( is_category() ) && ( $tptn_settings['add_to_category_archives'] ) ) { return $content . echo_tptn_post_count( 0 ); } elseif ( ( is_tag() ) && ( $tptn_settings['add_to_tag_archives'] ) ) { return $content . echo_tptn_post_count( 0 ); } elseif ( ( ( is_tax() ) || ( is_author() ) || ( is_date() ) ) && ( $tptn_settings['add_to_archives'] ) ) { return $content . echo_tptn_post_count( 0 ); } else { return $content; } } add_filter( 'the_content', 'tptn_pc_content' ); /** * Filter to add related posts to feeds. * * @since 1.9.8 * * @param string $content Post content * @return string Filtered post content */ function tptn_rss_filter( $content ) { global $post, $tptn_settings; $id = intval( $post->ID ); if ( $tptn_settings['add_to_feed'] ) { return $content . '<div class="tptn_counter" id="tptn_counter_' . $id . '">' . get_tptn_post_count( $id ) . '</div>'; } else { return $content; } } add_filter( 'the_excerpt_rss', 'tptn_rss_filter' ); add_filter( 'the_content_feed', 'tptn_rss_filter' ); /** * Function to manually display count. * * @since 1.0 * @param int|boolean $echo Flag to echo the output? * @return string Formatted string if $echo is set to 0|false */ function echo_tptn_post_count( $echo = 1 ) { global $post, $tptn_url, $tptn_path, $tptn_settings; $home_url = home_url( '/' ); /** * Filter the script URL of the counter. * * Create a filter function to overwrite the script URL to use the external top-10-counter.js.php * You can use $tptn_url . '/top-10-counter.js.php' as a source * $tptn_url is a global variable * * @since 2.0 */ $home_url = apply_filters( 'tptn_view_counter_script_url', $home_url ); $id = intval( $post->ID ); $nonce_action = 'tptn-nonce-' . $id ; $nonce = wp_create_nonce( $nonce_action ); if ( $tptn_settings['dynamic_post_count'] ) { $output = '<div class="tptn_counter" id="tptn_counter_' . $id . '"><script type="text/javascript" data-cfasync="false" src="' . $home_url . '?top_ten_id='.$id.'&amp;view_counter=1&amp;_wpnonce=' . $nonce . '"></script></div>'; } else { $output = '<div class="tptn_counter" id="tptn_counter_' . $id . '">' . get_tptn_post_count( $id ) . '</div>'; } /** * Filter the viewed count script * * @since 2.0.0 * * @param string $output Counter viewed count code */ $output = apply_filters( 'tptn_view_post_count', $output ); if ( $echo ) { echo $output; } else { return $output; } } /** * Return the formatted post count for the supplied ID. * * @since 1.9.2 * @param int|string $id Post ID * @param int|string $blog_id Blog ID * @return int|string Formatted post count */ function get_tptn_post_count( $id = false, $blog_id = false ) { global $wpdb, $tptn_settings; $table_name = $wpdb->base_prefix . 'top_ten'; $table_name_daily = $wpdb->base_prefix . 'top_ten_daily'; $count_disp_form = stripslashes( $tptn_settings['count_disp_form'] ); $count_disp_form_zero = stripslashes( $tptn_settings['count_disp_form_zero'] ); $totalcntaccess = get_tptn_post_count_only( $id, 'total', $blog_id ); if ( $id > 0 ) { // Total count per post if ( ( false !== strpos( $count_disp_form, '%totalcount%' ) ) || ( false !== strpos( $count_disp_form_zero, '%totalcount%' ) ) ) { if ( ( 0 == $totalcntaccess ) && ( ! is_singular() ) ) { $count_disp_form_zero = str_replace( '%totalcount%', $totalcntaccess, $count_disp_form_zero ); } else { $count_disp_form = str_replace( '%totalcount%', ( 0 == $totalcntaccess ? $totalcntaccess + 1 : $totalcntaccess ), $count_disp_form ); } } // Now process daily count if ( ( false !== strpos( $count_disp_form, '%dailycount%' ) ) || ( false !== strpos( $count_disp_form_zero, '%dailycount%' ) ) ) { $cntaccess = get_tptn_post_count_only( $id, 'daily' ); if ( ( 0 == $totalcntaccess ) && ( ! is_singular() ) ) { $count_disp_form_zero = str_replace( '%dailycount%', $cntaccess, $count_disp_form_zero ); } else { $count_disp_form = str_replace( '%dailycount%', ( 0 == $cntaccess ? $cntaccess + 1 : $cntaccess ), $count_disp_form ); } } // Now process overall count if ( ( false !== strpos( $count_disp_form, '%overallcount%' ) ) || ( false !== strpos( $count_disp_form_zero, '%overallcount%' ) ) ) { $cntaccess = get_tptn_post_count_only( $id, 'overall' ); if ( ( 0 == $cntaccess ) && ( ! is_singular() ) ) { $count_disp_form_zero = str_replace( '%overallcount%', $cntaccess, $count_disp_form_zero ); } else { $count_disp_form = str_replace( '%overallcount%', ( 0 == $cntaccess ? $cntaccess + 1 : $cntaccess ), $count_disp_form ); } } if ( ( 0 == $totalcntaccess ) && ( ! is_singular() ) ) { return apply_filters( 'tptn_post_count', $count_disp_form_zero ); } else { return apply_filters( 'tptn_post_count', $count_disp_form ); } } else { return 0; } } /** * Returns the post count. * * @since 1.9.8.5 * * @param mixed $id Post ID * @param string $count Which count to return? total, daily or overall * @return int Post count */ function get_tptn_post_count_only( $id = false, $count = 'total', $blog_id = false ) { global $wpdb, $tptn_settings; $table_name = $wpdb->base_prefix . 'top_ten'; $table_name_daily = $wpdb->base_prefix . 'top_ten_daily'; if ( empty( $blog_id ) ) { $blog_id = get_current_blog_id(); } if ( $id > 0 ) { switch ( $count ) { case 'total': $resultscount = $wpdb->get_row( $wpdb->prepare( "SELECT postnumber, cntaccess FROM {$table_name} WHERE postnumber = %d AND blog_id = %d " , $id, $blog_id ) ); $cntaccess = number_format_i18n( ( ( $resultscount ) ? $resultscount->cntaccess : 0 ) ); break; case 'daily': $daily_range = $tptn_settings['daily_range']; $hour_range = $tptn_settings['hour_range']; if ( $tptn_settings['daily_midnight'] ) { $current_time = current_time( 'timestamp', 0 ); $from_date = $current_time - ( max( 0, ( $daily_range - 1 ) ) * DAY_IN_SECONDS ); $from_date = gmdate( 'Y-m-d 0' , $from_date ); } else { $current_time = current_time( 'timestamp', 0 ); $from_date = $current_time - ( $daily_range * DAY_IN_SECONDS + $hour_range * HOUR_IN_SECONDS ); $from_date = gmdate( 'Y-m-d H' , $from_date ); } $resultscount = $wpdb->get_row( $wpdb->prepare( "SELECT postnumber, SUM(cntaccess) as sumCount FROM {$table_name_daily} WHERE postnumber = %d AND blog_id = %d AND dp_date >= '%s' GROUP BY postnumber ", array( $id, $blog_id, $from_date ) ) ); $cntaccess = number_format_i18n( ( ( $resultscount ) ? $resultscount->sumCount : 0 ) ); break; case 'overall': $resultscount = $wpdb->get_row( 'SELECT SUM(cntaccess) as sumCount FROM ' . $table_name ); $cntaccess = number_format_i18n( ( ( $resultscount ) ? $resultscount->sumCount : 0 ) ); break; } return apply_filters( 'tptn_post_count_only', $cntaccess ); } else { return 0; } }
robinskumar73/blog
wp-content/plugins/top-10/includes/counter.php
PHP
gpl-2.0
13,656
<?php die("Access Denied"); ?>#x#a:2:{s:6:"output";s:0:"";s:6:"result";s:7:"1168806";}
jolay/pesatec
cache/mod_vvisit_counter/860aea6b5aac75573e8d7d8ebc839c97-cache-mod_vvisit_counter-12df222378ce93925aa4729912440590.php
PHP
gpl-2.0
86
/* Copyright (c) 2004, 2013, Oracle and/or its affiliates. Copyright (c) 2011, 2016, MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #define MYSQL_LEX 1 #include <my_global.h> /* NO_EMBEDDED_ACCESS_CHECKS */ #include "sql_priv.h" #include "unireg.h" #include "sql_view.h" #include "sql_base.h" // find_table_in_global_list, lock_table_names #include "sql_parse.h" // sql_parse #include "sql_cache.h" // query_cache_* #include "lock.h" // MYSQL_OPEN_SKIP_TEMPORARY #include "sql_show.h" // append_identifier #include "sql_table.h" // build_table_filename #include "sql_db.h" // mysql_opt_change_db, mysql_change_db #include "sql_acl.h" // *_ACL, check_grant #include "sql_select.h" #include "parse_file.h" #include "sp_head.h" #include "sp.h" #include "sp_cache.h" #include "datadict.h" // dd_frm_is_view() #include "sql_derived.h" #include "sql_cte.h" // check_dependencies_in_with_clauses() #define MD5_BUFF_LENGTH 33 const LEX_STRING view_type= { C_STRING_WITH_LEN("VIEW") }; static int mysql_register_view(THD *, TABLE_LIST *, enum_view_create_mode); /* Make a unique name for an anonymous view column SYNOPSIS target reference to the item for which a new name has to be made item_list list of items within which we should check uniqueness of the created name last_element the last element of the list above NOTE Unique names are generated by adding 'My_exp_' to the old name of the column. In case the name that was created this way already exists, we add a numeric postfix to its end (i.e. "1") and increase the number until the name becomes unique. If the generated name is longer than NAME_LEN, it is truncated. */ static void make_unique_view_field_name(THD *thd, Item *target, List<Item> &item_list, Item *last_element) { char *name= (target->orig_name ? target->orig_name : target->name); size_t name_len; uint attempt; char buff[NAME_LEN+1]; List_iterator_fast<Item> itc(item_list); for (attempt= 0;; attempt++) { Item *check; bool ok= TRUE; if (attempt) name_len= my_snprintf(buff, NAME_LEN, "My_exp_%d_%s", attempt, name); else name_len= my_snprintf(buff, NAME_LEN, "My_exp_%s", name); do { check= itc++; if (check != target && my_strcasecmp(system_charset_info, buff, check->name) == 0) { ok= FALSE; break; } } while (check != last_element); if (ok) break; itc.rewind(); } target->orig_name= target->name; target->set_name(thd, buff, name_len, system_charset_info); } /* Check if items with same names are present in list and possibly generate unique names for them. SYNOPSIS item_list list of Items which should be checked for duplicates gen_unique_view_name flag: generate unique name or return with error when duplicate names are found. DESCRIPTION This function is used on view creation and preparation of derived tables. It checks item_list for items with duplicate names. If it founds two items with same name and conversion to unique names isn't allowed, or names for both items are set by user - function fails. Otherwise it generates unique name for one item with autogenerated name using make_unique_view_field_name() RETURN VALUE FALSE no duplicate names found, or they are converted to unique ones TRUE duplicate names are found and they can't be converted or conversion isn't allowed */ bool check_duplicate_names(THD *thd, List<Item> &item_list, bool gen_unique_view_name) { Item *item; List_iterator_fast<Item> it(item_list); List_iterator_fast<Item> itc(item_list); DBUG_ENTER("check_duplicate_names"); while ((item= it++)) { Item *check; /* treat underlying fields like set by user names */ if (item->real_item()->type() == Item::FIELD_ITEM) item->is_autogenerated_name= FALSE; itc.rewind(); while ((check= itc++) && check != item) { if (my_strcasecmp(system_charset_info, item->name, check->name) == 0) { if (!gen_unique_view_name) goto err; if (item->is_autogenerated_name) make_unique_view_field_name(thd, item, item_list, item); else if (check->is_autogenerated_name) make_unique_view_field_name(thd, check, item_list, item); else goto err; } } } DBUG_RETURN(FALSE); err: my_error(ER_DUP_FIELDNAME, MYF(0), item->name); DBUG_RETURN(TRUE); } /** Check if auto generated column names are conforming and possibly generate a conforming name for them if not. @param item_list List of Items which should be checked */ void make_valid_column_names(THD *thd, List<Item> &item_list) { Item *item; uint name_len; List_iterator_fast<Item> it(item_list); char buff[NAME_LEN]; DBUG_ENTER("make_valid_column_names"); for (uint column_no= 1; (item= it++); column_no++) { if (!item->is_autogenerated_name || !check_column_name(item->name)) continue; name_len= my_snprintf(buff, NAME_LEN, "Name_exp_%u", column_no); item->orig_name= item->name; item->set_name(thd, buff, name_len, system_charset_info); } DBUG_VOID_RETURN; } /* Fill defined view parts SYNOPSIS fill_defined_view_parts() thd current thread. view view to operate on DESCRIPTION This function will initialize the parts of the view definition that are not specified in ALTER VIEW to their values from CREATE VIEW. The view must be opened to get its definition. We use a copy of the view when opening because we want to preserve the original view instance. RETURN VALUE TRUE can't open table FALSE success */ static bool fill_defined_view_parts (THD *thd, TABLE_LIST *view) { LEX *lex= thd->lex; TABLE_LIST decoy; memcpy (&decoy, view, sizeof (TABLE_LIST)); if (tdc_open_view(thd, &decoy, OPEN_VIEW_NO_PARSE)) return TRUE; if (!lex->definer) { view->definer.host= decoy.definer.host; view->definer.user= decoy.definer.user; lex->definer= &view->definer; } if (lex->create_view_algorithm == VIEW_ALGORITHM_INHERIT) lex->create_view_algorithm= (uint8) decoy.algorithm; if (lex->create_view_suid == VIEW_SUID_DEFAULT) lex->create_view_suid= decoy.view_suid ? VIEW_SUID_DEFINER : VIEW_SUID_INVOKER; return FALSE; } #ifndef NO_EMBEDDED_ACCESS_CHECKS /** @brief CREATE VIEW privileges pre-check. @param thd thread handler @param tables tables used in the view @param views views to create @param mode VIEW_CREATE_NEW, VIEW_ALTER, VIEW_CREATE_OR_REPLACE @retval FALSE Operation was a success. @retval TRUE An error occurred. */ bool create_view_precheck(THD *thd, TABLE_LIST *tables, TABLE_LIST *view, enum_view_create_mode mode) { LEX *lex= thd->lex; /* first table in list is target VIEW name => cut off it */ TABLE_LIST *tbl; SELECT_LEX *select_lex= &lex->select_lex; SELECT_LEX *sl; bool res= TRUE; DBUG_ENTER("create_view_precheck"); /* Privilege check for view creation: - user has CREATE VIEW privilege on view table - user has DROP privilege in case of ALTER VIEW or CREATE OR REPLACE VIEW - user has some (SELECT/UPDATE/INSERT/DELETE) privileges on columns of underlying tables used on top of SELECT list (because it can be (theoretically) updated, so it is enough to have UPDATE privilege on them, for example) - user has SELECT privilege on columns used in expressions of VIEW select - for columns of underly tables used on top of SELECT list also will be checked that we have not more privileges on correspondent column of view table (i.e. user will not get some privileges by view creation) */ if ((check_access(thd, CREATE_VIEW_ACL, view->db, &view->grant.privilege, &view->grant.m_internal, 0, 0) || check_grant(thd, CREATE_VIEW_ACL, view, FALSE, 1, FALSE)) || (mode != VIEW_CREATE_NEW && (check_access(thd, DROP_ACL, view->db, &view->grant.privilege, &view->grant.m_internal, 0, 0) || check_grant(thd, DROP_ACL, view, FALSE, 1, FALSE)))) goto err; for (sl= select_lex; sl; sl= sl->next_select()) { for (tbl= sl->get_table_list(); tbl; tbl= tbl->next_local) { /* Ensure that we have some privileges on this table, more strict check will be done on column level after preparation, */ if (check_some_access(thd, VIEW_ANY_ACL, tbl)) { my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), "ANY", thd->security_ctx->priv_user, thd->security_ctx->priv_host, tbl->table_name); goto err; } /* Mark this table as a table which will be checked after the prepare phase */ tbl->table_in_first_from_clause= 1; /* We need to check only SELECT_ACL for all normal fields, fields for which we need "any" (SELECT/UPDATE/INSERT/DELETE) privilege will be checked later */ tbl->grant.want_privilege= SELECT_ACL; /* Make sure that all rights are loaded to the TABLE::grant field. tbl->table_name will be correct name of table because VIEWs are not opened yet. */ fill_effective_table_privileges(thd, &tbl->grant, tbl->db, tbl->table_name); } } if (&lex->select_lex != lex->all_selects_list) { /* check tables of subqueries */ for (tbl= tables; tbl; tbl= tbl->next_global) { if (!tbl->table_in_first_from_clause) { if (check_access(thd, SELECT_ACL, tbl->db, &tbl->grant.privilege, &tbl->grant.m_internal, 0, 0) || check_grant(thd, SELECT_ACL, tbl, FALSE, 1, FALSE)) goto err; } } } /* Mark fields for special privilege check ("any" privilege) */ for (sl= select_lex; sl; sl= sl->next_select()) { List_iterator_fast<Item> it(sl->item_list); Item *item; while ((item= it++)) { Item_field *field; if ((field= item->field_for_view_update())) { /* any_privileges may be reset later by the Item_field::set_field method in case of a system temporary table. */ field->any_privileges= 1; } } } res= FALSE; err: DBUG_RETURN(res || thd->is_error()); } #else bool create_view_precheck(THD *thd, TABLE_LIST *tables, TABLE_LIST *view, enum_view_create_mode mode) { return FALSE; } #endif /** @brief Creating/altering VIEW procedure @param thd thread handler @param views views to create @param mode VIEW_CREATE_NEW, VIEW_ALTER, VIEW_CREATE_OR_REPLACE @note This function handles both create and alter view commands. @retval FALSE Operation was a success. @retval TRUE An error occurred. */ bool mysql_create_view(THD *thd, TABLE_LIST *views, enum_view_create_mode mode) { LEX *lex= thd->lex; bool link_to_local; /* first table in list is target VIEW name => cut off it */ TABLE_LIST *view= lex->unlink_first_table(&link_to_local); TABLE_LIST *tables= lex->query_tables; TABLE_LIST *tbl; SELECT_LEX *select_lex= &lex->select_lex; SELECT_LEX *sl; SELECT_LEX_UNIT *unit= &lex->unit; bool res= FALSE; DBUG_ENTER("mysql_create_view"); /* This is ensured in the parser. */ DBUG_ASSERT(!lex->proc_list.first && !lex->result && !lex->param_list.elements); /* We can't allow taking exclusive meta-data locks of unlocked view under LOCK TABLES since this might lead to deadlock. Since at the moment we can't really lock view with LOCK TABLES we simply prohibit creation/ alteration of views under LOCK TABLES. */ if (thd->locked_tables_mode) { my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0)); res= TRUE; goto err; } if ((res= create_view_precheck(thd, tables, view, mode))) goto err; lex->link_first_table_back(view, link_to_local); view->open_type= OT_BASE_ONLY; if (check_dependencies_in_with_clauses(lex->with_clauses_list)) { res= TRUE; goto err; } /* ignore lock specs for CREATE statement */ if (lex->current_select->lock_type != TL_READ_DEFAULT) { lex->current_select->set_lock_for_tables(TL_READ_DEFAULT); view->mdl_request.set_type(MDL_EXCLUSIVE); } if (thd->open_temporary_tables(lex->query_tables) || open_and_lock_tables(thd, lex->query_tables, TRUE, 0)) { view= lex->unlink_first_table(&link_to_local); res= TRUE; goto err; } view= lex->unlink_first_table(&link_to_local); if (check_db_dir_existence(view->db)) { my_error(ER_BAD_DB_ERROR, MYF(0), view->db); res= TRUE; goto err; } if (mode == VIEW_ALTER && fill_defined_view_parts(thd, view)) { res= TRUE; goto err; } if (lex->limit_rows_examined) { /* LIMIT ROWS EXAMINED is not supported inside views to avoid complicated side-effects and semantics of the clause. */ my_error(ER_NOT_SUPPORTED_YET, MYF(0), "LIMIT ROWS EXAMINED inside views"); res= TRUE; goto err; } sp_cache_invalidate(); if (sp_process_definer(thd)) goto err; /* check that tables are not temporary and this VIEW do not used in query (it is possible with ALTERing VIEW). open_and_lock_tables can change the value of tables, e.g. it may happen if before the function call tables was equal to 0. */ for (tbl= lex->query_tables; tbl; tbl= tbl->next_global) { /* is this table view and the same view which we creates now? */ if (tbl->view && strcmp(tbl->view_db.str, view->db) == 0 && strcmp(tbl->view_name.str, view->table_name) == 0) { my_error(ER_NO_SUCH_TABLE, MYF(0), tbl->view_db.str, tbl->view_name.str); res= TRUE; goto err; } /* tbl->table can be NULL when tbl is a placeholder for a view that is indirectly referenced via a stored function from the view being created. We don't check these indirectly referenced views in CREATE VIEW so they don't have table object. */ if (tbl->table) { /* is this table temporary and is not view? */ if (tbl->table->s->tmp_table != NO_TMP_TABLE && !tbl->view && !tbl->schema_table) { my_error(ER_VIEW_SELECT_TMPTABLE, MYF(0), tbl->alias); res= TRUE; goto err; } /* Copy the privileges of the underlying VIEWs which were filled by fill_effective_table_privileges (they were not copied at derived tables processing) */ tbl->table->grant.privilege= tbl->grant.privilege; } } /* prepare select to resolve all fields */ lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW; if (unit->prepare(thd, 0, 0)) { /* some errors from prepare are reported to user, if is not then it will be checked after err: label */ res= TRUE; goto err; } /* view list (list of view fields names) */ if (lex->view_list.elements) { List_iterator_fast<Item> it(select_lex->item_list); List_iterator_fast<LEX_STRING> nm(lex->view_list); Item *item; LEX_STRING *name; if (lex->view_list.elements != select_lex->item_list.elements) { my_message(ER_VIEW_WRONG_LIST, ER_THD(thd, ER_VIEW_WRONG_LIST), MYF(0)); res= TRUE; goto err; } while ((item= it++, name= nm++)) { item->set_name(thd, name->str, (uint) name->length, system_charset_info); item->is_autogenerated_name= FALSE; } } /* Check if the auto generated column names are conforming. */ for (sl= select_lex; sl; sl= sl->next_select()) make_valid_column_names(thd, sl->item_list); if (check_duplicate_names(thd, select_lex->item_list, 1)) { res= TRUE; goto err; } #ifndef NO_EMBEDDED_ACCESS_CHECKS /* Compare/check grants on view with grants of underlying tables */ fill_effective_table_privileges(thd, &view->grant, view->db, view->table_name); /* Make sure that the current user does not have more column-level privileges on the newly created view than he/she does on the underlying tables. E.g. it must not be so that the user has UPDATE privileges on a view column of he/she doesn't have it on the underlying table's corresponding column. In that case, return an error for CREATE VIEW. */ { Item *report_item= NULL; /* This will hold the intersection of the priviliges on all columns in the view. */ uint final_priv= VIEW_ANY_ACL; for (sl= select_lex; sl; sl= sl->next_select()) { DBUG_ASSERT(view->db); /* Must be set in the parser */ List_iterator_fast<Item> it(sl->item_list); Item *item; while ((item= it++)) { Item_field *fld= item->field_for_view_update(); uint priv= (get_column_grant(thd, &view->grant, view->db, view->table_name, item->name) & VIEW_ANY_ACL); if (fld && !fld->field->table->s->tmp_table) { final_priv&= fld->have_privileges; if (~fld->have_privileges & priv) report_item= item; } } } if (!final_priv && report_item) { my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0), "create view", thd->security_ctx->priv_user, thd->security_ctx->priv_host, report_item->name, view->table_name); res= TRUE; goto err; } } #endif res= mysql_register_view(thd, view, mode); /* View TABLE_SHARE must be removed from the table definition cache in order to make ALTER VIEW work properly. Otherwise, we would not be able to detect meta-data changes after ALTER VIEW. */ if (!res) tdc_remove_table(thd, TDC_RT_REMOVE_ALL, view->db, view->table_name, false); if (!res && mysql_bin_log.is_open()) { String buff; const LEX_STRING command[3]= {{ C_STRING_WITH_LEN("CREATE ") }, { C_STRING_WITH_LEN("ALTER ") }, { C_STRING_WITH_LEN("CREATE OR REPLACE ") }}; buff.append(command[thd->lex->create_view_mode].str, command[thd->lex->create_view_mode].length); view_store_options(thd, views, &buff); buff.append(STRING_WITH_LEN("VIEW ")); /* Appending IF NOT EXISTS if present in the query */ if (lex->create_info.if_not_exists()) buff.append(STRING_WITH_LEN("IF NOT EXISTS ")); /* Test if user supplied a db (ie: we did not use thd->db) */ if (views->db && views->db[0] && (thd->db == NULL || strcmp(views->db, thd->db))) { append_identifier(thd, &buff, views->db, views->db_length); buff.append('.'); } append_identifier(thd, &buff, views->table_name, views->table_name_length); if (lex->view_list.elements) { List_iterator_fast<LEX_STRING> names(lex->view_list); LEX_STRING *name; int i; for (i= 0; (name= names++); i++) { buff.append(i ? ", " : "("); append_identifier(thd, &buff, name->str, name->length); } buff.append(')'); } buff.append(STRING_WITH_LEN(" AS ")); buff.append(views->source.str, views->source.length); int errcode= query_error_code(thd, TRUE); if (thd->binlog_query(THD::STMT_QUERY_TYPE, buff.ptr(), buff.length(), FALSE, FALSE, FALSE, errcode)) res= TRUE; } if (mode != VIEW_CREATE_NEW) query_cache_invalidate3(thd, view, 0); if (res) goto err; my_ok(thd); lex->link_first_table_back(view, link_to_local); DBUG_RETURN(0); err: THD_STAGE_INFO(thd, stage_end); lex->link_first_table_back(view, link_to_local); unit->cleanup(); DBUG_RETURN(res || thd->is_error()); } static void make_view_filename(LEX_STRING *dir, char *dir_buff, size_t dir_buff_len, LEX_STRING *path, char *path_buff, size_t path_buff_len, LEX_STRING *file, TABLE_LIST *view) { /* print file name */ dir->length= build_table_filename(dir_buff, dir_buff_len - 1, view->db, "", "", 0); dir->str= dir_buff; path->length= build_table_filename(path_buff, path_buff_len - 1, view->db, view->table_name, reg_ext, 0); path->str= path_buff; file->str= path->str + dir->length; file->length= path->length - dir->length; } /* number of required parameters for making view */ static const int required_view_parameters= 15; /* table of VIEW .frm field descriptors Note that one should NOT change the order for this, as it's used by parse() */ static File_option view_parameters[]= {{{ C_STRING_WITH_LEN("query")}, my_offsetof(TABLE_LIST, select_stmt), FILE_OPTIONS_ESTRING}, {{ C_STRING_WITH_LEN("md5")}, my_offsetof(TABLE_LIST, md5), FILE_OPTIONS_STRING}, {{ C_STRING_WITH_LEN("updatable")}, my_offsetof(TABLE_LIST, updatable_view), FILE_OPTIONS_ULONGLONG}, {{ C_STRING_WITH_LEN("algorithm")}, my_offsetof(TABLE_LIST, algorithm), FILE_OPTIONS_VIEW_ALGO}, {{ C_STRING_WITH_LEN("definer_user")}, my_offsetof(TABLE_LIST, definer.user), FILE_OPTIONS_STRING}, {{ C_STRING_WITH_LEN("definer_host")}, my_offsetof(TABLE_LIST, definer.host), FILE_OPTIONS_STRING}, {{ C_STRING_WITH_LEN("suid")}, my_offsetof(TABLE_LIST, view_suid), FILE_OPTIONS_ULONGLONG}, {{ C_STRING_WITH_LEN("with_check_option")}, my_offsetof(TABLE_LIST, with_check), FILE_OPTIONS_ULONGLONG}, {{ C_STRING_WITH_LEN("timestamp")}, my_offsetof(TABLE_LIST, timestamp), FILE_OPTIONS_TIMESTAMP}, {{ C_STRING_WITH_LEN("create-version")}, my_offsetof(TABLE_LIST, file_version), FILE_OPTIONS_ULONGLONG}, {{ C_STRING_WITH_LEN("source")}, my_offsetof(TABLE_LIST, source), FILE_OPTIONS_ESTRING}, {{(char*) STRING_WITH_LEN("client_cs_name")}, my_offsetof(TABLE_LIST, view_client_cs_name), FILE_OPTIONS_STRING}, {{(char*) STRING_WITH_LEN("connection_cl_name")}, my_offsetof(TABLE_LIST, view_connection_cl_name), FILE_OPTIONS_STRING}, {{(char*) STRING_WITH_LEN("view_body_utf8")}, my_offsetof(TABLE_LIST, view_body_utf8), FILE_OPTIONS_ESTRING}, {{ C_STRING_WITH_LEN("mariadb-version")}, my_offsetof(TABLE_LIST, mariadb_version), FILE_OPTIONS_ULONGLONG}, {{NullS, 0}, 0, FILE_OPTIONS_STRING} }; static LEX_STRING view_file_type[]= {{(char*) STRING_WITH_LEN("VIEW") }}; int mariadb_fix_view(THD *thd, TABLE_LIST *view, bool wrong_checksum, bool swap_alg) { char dir_buff[FN_REFLEN + 1], path_buff[FN_REFLEN + 1]; LEX_STRING dir, file, path; DBUG_ENTER("mariadb_fix_view"); if (!wrong_checksum && view->mariadb_version) DBUG_RETURN(HA_ADMIN_OK); make_view_filename(&dir, dir_buff, sizeof(dir_buff), &path, path_buff, sizeof(path_buff), &file, view); /* init timestamp */ if (!view->timestamp.str) view->timestamp.str= view->timestamp_buffer; if (swap_alg && view->algorithm != VIEW_ALGORITHM_UNDEFINED) { DBUG_ASSERT(view->algorithm == VIEW_ALGORITHM_MERGE || view->algorithm == VIEW_ALGORITHM_TMPTABLE); if (view->algorithm == VIEW_ALGORITHM_MERGE) view->algorithm= VIEW_ALGORITHM_TMPTABLE; else view->algorithm= VIEW_ALGORITHM_MERGE; } else swap_alg= 0; if (wrong_checksum) { if (view->md5.length != 32) { if ((view->md5.str= (char *)thd->alloc(32 + 1)) == NULL) DBUG_RETURN(HA_ADMIN_FAILED); } view->calc_md5(view->md5.str); view->md5.length= 32; } view->mariadb_version= MYSQL_VERSION_ID; if (sql_create_definition_file(&dir, &file, view_file_type, (uchar*)view, view_parameters)) { sql_print_error("View '%-.192s'.'%-.192s': algorithm swap error.", view->db, view->table_name); DBUG_RETURN(HA_ADMIN_INTERNAL_ERROR); } sql_print_information("View %`s.%`s: the version is set to %llu%s%s", view->db, view->table_name, view->mariadb_version, (wrong_checksum ? ", checksum corrected" : ""), (swap_alg ? ((view->algorithm == VIEW_ALGORITHM_MERGE) ? ", algorithm restored to be MERGE" : ", algorithm restored to be TEMPTABLE") : "")); DBUG_RETURN(HA_ADMIN_OK); } /* Register VIEW (write .frm & process .frm's history backups) SYNOPSIS mysql_register_view() thd - thread handler view - view description mode - VIEW_CREATE_NEW, VIEW_ALTER, VIEW_CREATE_OR_REPLACE RETURN 0 OK -1 Error 1 Error and error message given */ static int mysql_register_view(THD *thd, TABLE_LIST *view, enum_view_create_mode mode) { LEX *lex= thd->lex; /* View definition query -- a SELECT statement that fully defines view. It is generated from the Item-tree built from the original (specified by the user) query. The idea is that generated query should eliminates all ambiguities and fix view structure at CREATE-time (once for all). Item::print() virtual operation is used to generate view definition query. INFORMATION_SCHEMA query (IS query) -- a SQL statement describing a view that is shown in INFORMATION_SCHEMA. Basically, it is 'view definition query' with text literals converted to UTF8 and without character set introducers. For example: Let's suppose we have: CREATE TABLE t1(a INT, b INT); User specified query: CREATE VIEW v1(x, y) AS SELECT * FROM t1; Generated query: SELECT a AS x, b AS y FROM t1; IS query: SELECT a AS x, b AS y FROM t1; View definition query is stored in the client character set. */ char view_query_buff[4096]; String view_query(view_query_buff, sizeof (view_query_buff), thd->charset()); char is_query_buff[4096]; String is_query(is_query_buff, sizeof (is_query_buff), system_charset_info); char md5[MD5_BUFF_LENGTH]; bool can_be_merged; char dir_buff[FN_REFLEN + 1], path_buff[FN_REFLEN + 1]; LEX_STRING dir, file, path; int error= 0; DBUG_ENTER("mysql_register_view"); /* Generate view definition and IS queries. */ view_query.length(0); is_query.length(0); { sql_mode_t sql_mode= thd->variables.sql_mode & MODE_ANSI_QUOTES; thd->variables.sql_mode&= ~MODE_ANSI_QUOTES; lex->unit.print(&view_query, enum_query_type(QT_VIEW_INTERNAL | QT_ITEM_ORIGINAL_FUNC_NULLIF)); lex->unit.print(&is_query, enum_query_type(QT_TO_SYSTEM_CHARSET | QT_WITHOUT_INTRODUCERS | QT_ITEM_ORIGINAL_FUNC_NULLIF)); thd->variables.sql_mode|= sql_mode; } DBUG_PRINT("info", ("View: %.*s", view_query.length(), view_query.ptr())); /* fill structure */ view->source= thd->lex->create_view_select; if (!thd->make_lex_string(&view->select_stmt, view_query.ptr(), view_query.length())) { my_error(ER_OUT_OF_RESOURCES, MYF(0)); error= -1; goto err; } /* version 1 - before 10.0.5 version 2 - empty definer_host means a role */ view->file_version= 2; view->mariadb_version= MYSQL_VERSION_ID; view->calc_md5(md5); if (!(view->md5.str= (char*) thd->memdup(md5, 32))) { my_error(ER_OUT_OF_RESOURCES, MYF(0)); error= -1; goto err; } view->md5.length= 32; can_be_merged= lex->can_be_merged(); if (lex->create_view_algorithm == VIEW_ALGORITHM_MERGE && !lex->can_be_merged()) { push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_WARN_VIEW_MERGE, ER_THD(thd, ER_WARN_VIEW_MERGE)); lex->create_view_algorithm= DTYPE_ALGORITHM_UNDEFINED; } view->algorithm= lex->create_view_algorithm; view->definer.user= lex->definer->user; view->definer.host= lex->definer->host; view->view_suid= lex->create_view_suid; view->with_check= lex->create_view_check; DBUG_EXECUTE_IF("simulate_register_view_failure", { my_error(ER_OUT_OF_RESOURCES, MYF(0)); error= -1; goto err; }); if ((view->updatable_view= (can_be_merged && view->algorithm != VIEW_ALGORITHM_TMPTABLE))) { /* TODO: change here when we will support UNIONs */ for (TABLE_LIST *tbl= lex->select_lex.table_list.first; tbl; tbl= tbl->next_local) { if ((tbl->view && !tbl->updatable_view) || tbl->schema_table) { view->updatable_view= 0; break; } for (TABLE_LIST *up= tbl; up; up= up->embedding) { if (up->outer_join) { view->updatable_view= 0; goto loop_out; } } } } loop_out: /* print file name */ make_view_filename(&dir, dir_buff, sizeof(dir_buff), &path, path_buff, sizeof(path_buff), &file, view); /* init timestamp */ if (!view->timestamp.str) view->timestamp.str= view->timestamp_buffer; /* check old .frm */ { char path_buff[FN_REFLEN]; LEX_STRING path; File_parser *parser; path.str= path_buff; fn_format(path_buff, file.str, dir.str, "", MY_UNPACK_FILENAME); path.length= strlen(path_buff); if (ha_table_exists(thd, view->db, view->table_name, NULL)) { if (lex->create_info.if_not_exists()) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_TABLE_EXISTS_ERROR, ER_THD(thd, ER_TABLE_EXISTS_ERROR), view->table_name); DBUG_RETURN(0); } else if (mode == VIEW_CREATE_NEW) { my_error(ER_TABLE_EXISTS_ERROR, MYF(0), view->alias); error= -1; goto err; } if (!(parser= sql_parse_prepare(&path, thd->mem_root, 0))) { error= 1; goto err; } if (!parser->ok() || !is_equal(&view_type, parser->type())) { my_error(ER_WRONG_OBJECT, MYF(0), view->db, view->table_name, "VIEW"); error= -1; goto err; } /* TODO: read dependence list, too, to process cascade/restrict TODO: special cascade/restrict procedure for alter? */ } else { if (mode == VIEW_ALTER) { my_error(ER_NO_SUCH_TABLE, MYF(0), view->db, view->alias); error= -1; goto err; } } } /* Initialize view creation context from the environment. */ view->view_creation_ctx= View_creation_ctx::create(thd); /* Set LEX_STRING attributes in view-structure for parser to create frm-file. */ lex_string_set(&view->view_client_cs_name, view->view_creation_ctx->get_client_cs()->csname); lex_string_set(&view->view_connection_cl_name, view->view_creation_ctx->get_connection_cl()->name); if (!thd->make_lex_string(&view->view_body_utf8, is_query.ptr(), is_query.length())) { my_error(ER_OUT_OF_RESOURCES, MYF(0)); error= -1; goto err; } /* Check that table of main select do not used in subqueries. This test can catch only very simple cases of such non-updateable views, all other will be detected before updating commands execution. (it is more optimisation then real check) NOTE: this skip cases of using table via VIEWs, joined VIEWs, VIEWs with UNION */ if (view->updatable_view && !lex->select_lex.master_unit()->is_union() && !(lex->select_lex.table_list.first)->next_local && find_table_in_global_list(lex->query_tables->next_global, lex->query_tables->db, lex->query_tables->table_name)) { view->updatable_view= 0; } if (view->with_check != VIEW_CHECK_NONE && !view->updatable_view) { my_error(ER_VIEW_NONUPD_CHECK, MYF(0), view->db, view->table_name); error= -1; goto err; } if (sql_create_definition_file(&dir, &file, view_file_type, (uchar*)view, view_parameters)) { error= thd->is_error() ? -1 : 1; goto err; } DBUG_RETURN(0); err: view->select_stmt.str= NULL; view->select_stmt.length= 0; view->md5.str= NULL; view->md5.length= 0; DBUG_RETURN(error); } /** read VIEW .frm and create structures @param[in] thd Thread handler @param[in] share Share object of view @param[in] table TABLE_LIST structure for filling @param[in] open_view_no_parse Flag to indicate open view but do not parse. @return false-in case of success, true-in case of error. */ bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table, bool open_view_no_parse) { SELECT_LEX *end, *UNINIT_VAR(view_select); LEX *old_lex, *lex; Query_arena *arena, backup; TABLE_LIST *top_view= table->top_table(); bool UNINIT_VAR(parse_status); bool result, view_is_mergeable; TABLE_LIST *UNINIT_VAR(view_main_select_tables); DBUG_ENTER("mysql_make_view"); DBUG_PRINT("info", ("table: 0x%lx (%s)", (ulong) table, table->table_name)); if (table->required_type == FRMTYPE_TABLE) { my_error(ER_WRONG_OBJECT, MYF(0), share->db.str, share->table_name.str, "BASE TABLE"); DBUG_RETURN(true); } if (table->view) { /* It's an execution of a PS/SP and the view has already been unfolded into a list of used tables. Now we only need to update the information about granted privileges in the view tables with the actual data stored in MySQL privilege system. We don't need to restore the required privileges (by calling register_want_access) because they has not changed since PREPARE or the previous execution: the only case when this information is changed is execution of UPDATE on a view, but the original want_access is restored in its end. */ if (!table->prelocking_placeholder && table->prepare_security(thd)) { DBUG_RETURN(1); } DBUG_PRINT("info", ("VIEW %s.%s is already processed on previous PS/SP execution", table->view_db.str, table->view_name.str)); /* Clear old variables in the TABLE_LIST that could be left from an old view This is only needed if there was an error at last usage of view, in which case the reinit call wasn't done. See MDEV-6668 for details. */ mysql_derived_reinit(thd, NULL, table); thd->select_number+= table->view->number_of_selects; DEBUG_SYNC(thd, "after_cached_view_opened"); DBUG_RETURN(0); } if (table->index_hints && table->index_hints->elements) { my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), table->index_hints->head()->key_name.str, table->table_name); DBUG_RETURN(TRUE); } /* check loop via view definition */ for (TABLE_LIST *precedent= table->referencing_view; precedent; precedent= precedent->referencing_view) { if (precedent->view_name.length == table->table_name_length && precedent->view_db.length == table->db_length && my_strcasecmp(system_charset_info, precedent->view_name.str, table->table_name) == 0 && my_strcasecmp(system_charset_info, precedent->view_db.str, table->db) == 0) { my_error(ER_VIEW_RECURSIVE, MYF(0), top_view->view_db.str, top_view->view_name.str); DBUG_RETURN(TRUE); } } /* For now we assume that tables will not be changed during PS life (it will be TRUE as far as we make new table cache). */ old_lex= thd->lex; arena= thd->activate_stmt_arena_if_needed(&backup); /* init timestamp */ if (!table->timestamp.str) table->timestamp.str= table->timestamp_buffer; /* prepare default values for old format */ table->view_suid= TRUE; table->definer.user.str= table->definer.host.str= 0; table->definer.user.length= table->definer.host.length= 0; /* TODO: when VIEWs will be stored in cache (not only parser), table mem_root should be used here */ DBUG_ASSERT(share->view_def != NULL); if ((result= share->view_def->parse((uchar*)table, thd->mem_root, view_parameters, required_view_parameters, &file_parser_dummy_hook))) goto end; /* check old format view .frm */ if (!table->definer.user.str) { DBUG_ASSERT(!table->definer.host.str && !table->definer.user.length && !table->definer.host.length); push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_VIEW_FRM_NO_USER, ER_THD(thd, ER_VIEW_FRM_NO_USER), table->db, table->table_name); get_default_definer(thd, &table->definer, false); } /* since 10.0.5 definer.host can never be "" for a User, but it's always "" for a Role. Before 10.0.5 it could be "" for a User, but roles didn't exist. file_version helps. */ if (!table->definer.host.str[0] && table->file_version < 2) table->definer.host= host_not_specified; // User, not Role /* Initialize view definition context by character set names loaded from the view definition file. Use UTF8 character set if view definition file is of old version and does not contain the character set names. */ table->view_creation_ctx= View_creation_ctx::create(thd, table); if (open_view_no_parse) { if (arena) thd->restore_active_arena(arena, &backup); DBUG_RETURN(FALSE); } /* Save VIEW parameters, which will be wiped out by derived table processing */ table->view_db.str= table->db; table->view_db.length= table->db_length; table->view_name.str= table->table_name; table->view_name.length= table->table_name_length; /* We don't invalidate a prepared statement when a view changes, or when someone creates a temporary table. Instead, the view is inlined into the body of the statement upon the first execution. Below, make sure that on re-execution of a prepared statement we don't prefer a temporary table to the view, if the view name was shadowed with a temporary table with the same name. This assignment ensures that on re-execution open_table() will not try to call find_temporary_table() for this TABLE_LIST, but will invoke open_table_from_share(), which will eventually call this function. */ table->open_type= OT_BASE_ONLY; /* Clear old variables in the TABLE_LIST that could be left from an old view */ table->merged_for_insert= FALSE; /*TODO: md5 test here and warning if it is differ */ /* TODO: TABLE mem root should be used here when VIEW will be stored in TABLE cache now Lex placed in statement memory */ table->view= lex= thd->lex= (LEX*) new(thd->mem_root) st_lex_local; if (!table->view) { result= true; goto end; } { char old_db_buf[SAFE_NAME_LEN+1]; LEX_STRING old_db= { old_db_buf, sizeof(old_db_buf) }; bool dbchanged; Parser_state parser_state; if (parser_state.init(thd, table->select_stmt.str, table->select_stmt.length)) goto err; /* Use view db name as thread default database, in order to ensure that the view is parsed and prepared correctly. */ if ((result= mysql_opt_change_db(thd, &table->view_db, &old_db, 1, &dbchanged))) goto end; lex_start(thd); view_select= &lex->select_lex; view_select->select_number= ++thd->select_number; sql_mode_t saved_mode= thd->variables.sql_mode; /* switch off modes which can prevent normal parsing of VIEW - MODE_REAL_AS_FLOAT affect only CREATE TABLE parsing + MODE_PIPES_AS_CONCAT affect expression parsing + MODE_ANSI_QUOTES affect expression parsing + MODE_IGNORE_SPACE affect expression parsing - MODE_IGNORE_BAD_TABLE_OPTIONS affect only CREATE/ALTER TABLE parsing * MODE_ONLY_FULL_GROUP_BY affect execution * MODE_NO_UNSIGNED_SUBTRACTION affect execution - MODE_NO_DIR_IN_CREATE affect table creation only - MODE_POSTGRESQL compounded from other modes - MODE_ORACLE compounded from other modes - MODE_MSSQL compounded from other modes - MODE_DB2 compounded from other modes - MODE_MAXDB affect only CREATE TABLE parsing - MODE_NO_KEY_OPTIONS affect only SHOW - MODE_NO_TABLE_OPTIONS affect only SHOW - MODE_NO_FIELD_OPTIONS affect only SHOW - MODE_MYSQL323 affect only SHOW - MODE_MYSQL40 affect only SHOW - MODE_ANSI compounded from other modes (+ transaction mode) ? MODE_NO_AUTO_VALUE_ON_ZERO affect UPDATEs + MODE_NO_BACKSLASH_ESCAPES affect expression parsing */ thd->variables.sql_mode&= ~(MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | MODE_IGNORE_SPACE | MODE_NO_BACKSLASH_ESCAPES); /* Parse the query. */ parse_status= parse_sql(thd, & parser_state, table->view_creation_ctx); lex->number_of_selects= (thd->select_number - view_select->select_number) + 1; /* Restore environment. */ if ((old_lex->sql_command == SQLCOM_SHOW_FIELDS) || (old_lex->sql_command == SQLCOM_SHOW_CREATE)) lex->sql_command= old_lex->sql_command; thd->variables.sql_mode= saved_mode; if (dbchanged && mysql_change_db(thd, &old_db, TRUE)) goto err; } if (!parse_status) { TABLE_LIST *view_tables= lex->query_tables; TABLE_LIST *view_tables_tail= 0; TABLE_LIST *tbl; Security_context *security_ctx= 0; if (check_dependencies_in_with_clauses(thd->lex->with_clauses_list)) goto err; /* Check rights to run commands (ANALYZE SELECT, EXPLAIN SELECT & SHOW CREATE) which show underlying tables. Skip this step if we are opening view for prelocking only. */ if (!table->prelocking_placeholder && (old_lex->describe || old_lex->analyze_stmt)) { /* The user we run EXPLAIN as (either the connected user who issued the EXPLAIN statement, or the definer of a SUID stored routine which contains the EXPLAIN) should have both SHOW_VIEW_ACL and SELECT_ACL on the view being opened as well as on all underlying views since EXPLAIN will disclose their structure. This user also should have SELECT_ACL on all underlying tables of the view since this EXPLAIN will disclose information about the number of rows in it. To perform this privilege check we create auxiliary TABLE_LIST object for the view in order a) to avoid trashing "table->grant" member for original table list element, which contents can be important at later stage for column-level privilege checking b) get TABLE_LIST object with "security_ctx" member set to 0, i.e. forcing check_table_access() to use active user's security context. There is no need for creating similar copies of TABLE_LIST elements for underlying tables since they just have been constructed and thus have TABLE_LIST::security_ctx == 0 and fresh TABLE_LIST::grant member. Finally at this point making sure we have SHOW_VIEW_ACL on the views will suffice as we implicitly require SELECT_ACL anyway. */ TABLE_LIST view_no_suid; bzero(static_cast<void *>(&view_no_suid), sizeof(TABLE_LIST)); view_no_suid.db= table->db; view_no_suid.table_name= table->table_name; DBUG_ASSERT(view_tables == NULL || view_tables->security_ctx == NULL); if (check_table_access(thd, SELECT_ACL, view_tables, FALSE, UINT_MAX, TRUE) || check_table_access(thd, SHOW_VIEW_ACL, &view_no_suid, FALSE, UINT_MAX, TRUE)) { my_message(ER_VIEW_NO_EXPLAIN, ER_THD(thd, ER_VIEW_NO_EXPLAIN), MYF(0)); goto err; } } else if (!table->prelocking_placeholder && (old_lex->sql_command == SQLCOM_SHOW_CREATE) && !table->belong_to_view) { if (check_table_access(thd, SHOW_VIEW_ACL, table, FALSE, UINT_MAX, FALSE)) goto err; } if (!(table->view_tables= (List<TABLE_LIST>*) new(thd->mem_root) List<TABLE_LIST>)) goto err; /* mark to avoid temporary table using and put view reference and find last view table */ for (tbl= view_tables; tbl; tbl= (view_tables_tail= tbl)->next_global) { tbl->open_type= OT_BASE_ONLY; tbl->belong_to_view= top_view; tbl->referencing_view= table; tbl->prelocking_placeholder= table->prelocking_placeholder; /* First we fill want_privilege with SELECT_ACL (this is needed for the tables which belongs to view subqueries and temporary table views, then for the merged view underlying tables we will set wanted privileges of top_view */ tbl->grant.want_privilege= SELECT_ACL; /* After unfolding the view we lose the list of tables referenced in it (we will have only a list of underlying tables in case of MERGE algorithm, which does not include the tables referenced from subqueries used in view definition). Let's build a list of all tables referenced in the view. */ table->view_tables->push_back(tbl); } /* Put tables of VIEW after VIEW TABLE_LIST NOTE: It is important for UPDATE/INSERT/DELETE checks to have this tables just after VIEW instead of tail of list, to be able check that table is unique. Also we store old next table for the same purpose. */ if (view_tables) { if (table->next_global) { view_tables_tail->next_global= table->next_global; table->next_global->prev_global= &view_tables_tail->next_global; } else { old_lex->query_tables_last= &view_tables_tail->next_global; } view_tables->prev_global= &table->next_global; table->next_global= view_tables; } /* If the view's body needs row-based binlogging (e.g. the VIEW is created from SELECT UUID()), the top statement also needs it. */ old_lex->set_stmt_unsafe_flags(lex->get_stmt_unsafe_flags()); view_is_mergeable= (table->algorithm != VIEW_ALGORITHM_TMPTABLE && lex->can_be_merged()); if (view_is_mergeable) { /* Currently 'view_main_select_tables' differs from 'view_tables' only then view has CONVERT_TZ() function in its select list. This may change in future, for example if we enable merging of views with subqueries in select list. */ view_main_select_tables= lex->select_lex.table_list.first; /* Let us set proper lock type for tables of the view's main select since we may want to perform update or insert on view. This won't work for view containing union. But this is ok since we don't allow insert and update on such views anyway. */ for (tbl= view_main_select_tables; tbl; tbl= tbl->next_local) { tbl->lock_type= table->lock_type; tbl->mdl_request.set_type((tbl->lock_type >= TL_WRITE_ALLOW_WRITE) ? MDL_SHARED_WRITE : MDL_SHARED_READ); } /* If the view is mergeable, we might want to INSERT/UPDATE/DELETE into tables of this view. Preserve the original sql command and 'duplicates' of the outer lex. This is used later in set_trg_event_type_for_command. */ lex->sql_command= old_lex->sql_command; lex->duplicates= old_lex->duplicates; /* Fields in this view can be used in upper select in case of merge. */ if (table->select_lex) table->select_lex->add_where_field(&lex->select_lex); } /* This method has a dependency on the proper lock type being set, so in case of views should be called here. */ lex->set_trg_event_type_for_tables(); /* If we are opening this view as part of implicit LOCK TABLES, then this view serves as simple placeholder and we should not continue further processing. */ if (table->prelocking_placeholder) goto ok2; old_lex->derived_tables|= (DERIVED_VIEW | lex->derived_tables); /* move SQL_NO_CACHE & Co to whole query */ old_lex->safe_to_cache_query= (old_lex->safe_to_cache_query && lex->safe_to_cache_query); /* move SQL_CACHE to whole query */ if (view_select->options & OPTION_TO_QUERY_CACHE) old_lex->select_lex.options|= OPTION_TO_QUERY_CACHE; #ifndef NO_EMBEDDED_ACCESS_CHECKS if (table->view_suid) { /* For suid views prepare a security context for checking underlying objects of the view. */ if (!(table->view_sctx= (Security_context *) thd->stmt_arena->calloc(sizeof(Security_context)))) goto err; security_ctx= table->view_sctx; } else { /* For non-suid views inherit security context from view's table list. This allows properly handle situation when non-suid view is used from within suid view. */ security_ctx= table->security_ctx; } #endif /* Assign the context to the tables referenced in the view */ if (view_tables) { DBUG_ASSERT(view_tables_tail); for (tbl= view_tables; tbl != view_tables_tail->next_global; tbl= tbl->next_global) tbl->security_ctx= security_ctx; } /* assign security context to SELECT name resolution contexts of view */ for(SELECT_LEX *sl= lex->all_selects_list; sl; sl= sl->next_select_in_list()) sl->context.security_ctx= security_ctx; /* Setup an error processor to hide error messages issued by stored routines referenced in the view */ for (SELECT_LEX *sl= lex->all_selects_list; sl; sl= sl->next_select_in_list()) { sl->context.error_processor= &view_error_processor; sl->context.error_processor_data= (void *)table; } view_select->master_unit()->is_view= true; /* check MERGE algorithm ability - algorithm is not explicit TEMPORARY TABLE - VIEW SELECT allow merging - VIEW used in subquery or command support MERGE algorithm */ if (view_is_mergeable && (table->select_lex->master_unit() != &old_lex->unit || old_lex->can_use_merged()) && !old_lex->can_not_use_merged()) { /* lex should contain at least one table */ DBUG_ASSERT(view_main_select_tables != 0); List_iterator_fast<TABLE_LIST> ti(view_select->top_join_list); table->derived_type= VIEW_ALGORITHM_MERGE; DBUG_PRINT("info", ("algorithm: MERGE")); table->updatable= (table->updatable_view != 0); table->effective_with_check= old_lex->get_effective_with_check(table); table->merge_underlying_list= view_main_select_tables; /* Fill correct wanted privileges. */ for (tbl= view_main_select_tables; tbl; tbl= tbl->next_local) tbl->grant.want_privilege= top_view->grant.orig_want_privilege; /* prepare view context */ lex->select_lex.context.resolve_in_table_list_only(view_main_select_tables); lex->select_lex.context.outer_context= 0; lex->select_lex.select_n_having_items+= table->select_lex->select_n_having_items; table->where= view_select->where; /* We can safely ignore the VIEW's ORDER BY if we merge into union branch, as order is not important there. */ if (!table->select_lex->master_unit()->is_union() && table->select_lex->order_list.elements == 0) table->select_lex->order_list.push_back(&lex->select_lex.order_list); else { if (old_lex->sql_command == SQLCOM_SELECT && (old_lex->describe & DESCRIBE_EXTENDED) && lex->select_lex.order_list.elements && !table->select_lex->master_unit()->is_union()) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_VIEW_ORDERBY_IGNORED, ER_THD(thd, ER_VIEW_ORDERBY_IGNORED), table->db, table->table_name); } } /* This SELECT_LEX will be linked in global SELECT_LEX list to make it processed by mysql_handle_derived(), but it will not be included to SELECT_LEX tree, because it will not be executed */ goto ok; } table->derived_type= VIEW_ALGORITHM_TMPTABLE; DBUG_PRINT("info", ("algorithm: TEMPORARY TABLE")); view_select->linkage= DERIVED_TABLE_TYPE; table->updatable= 0; table->effective_with_check= VIEW_CHECK_NONE; old_lex->subqueries= TRUE; table->derived= &lex->unit; } else goto err; ok: /* SELECT tree link */ lex->unit.include_down(table->select_lex); lex->unit.slave= view_select; // fix include_down initialisation /* global SELECT list linking */ end= view_select; // primary SELECT_LEX is always last end->link_next= old_lex->all_selects_list; old_lex->all_selects_list->link_prev= &end->link_next; old_lex->all_selects_list= lex->all_selects_list; lex->all_selects_list->link_prev= (st_select_lex_node**)&old_lex->all_selects_list; ok2: DBUG_ASSERT(lex == thd->lex); thd->lex= old_lex; // Needed for prepare_security result= !table->prelocking_placeholder && table->prepare_security(thd); lex_end(lex); end: if (arena) thd->restore_active_arena(arena, &backup); thd->lex= old_lex; status_var_increment(thd->status_var.opened_views); DBUG_RETURN(result); err: DBUG_ASSERT(thd->lex == table->view); lex_end(thd->lex); delete table->view; table->view= 0; // now it is not VIEW placeholder result= 1; goto end; } /* drop view SYNOPSIS mysql_drop_view() thd - thread handle views - views to delete drop_mode - cascade/check RETURN VALUE FALSE OK TRUE Error */ bool mysql_drop_view(THD *thd, TABLE_LIST *views, enum_drop_mode drop_mode) { char path[FN_REFLEN + 1]; TABLE_LIST *view; String non_existant_views; char *wrong_object_db= NULL, *wrong_object_name= NULL; bool error= FALSE; bool some_views_deleted= FALSE; bool something_wrong= FALSE; DBUG_ENTER("mysql_drop_view"); /* We can't allow dropping of unlocked view under LOCK TABLES since this might lead to deadlock. But since we can't really lock view with LOCK TABLES we have to simply prohibit dropping of views. */ if (thd->locked_tables_mode) { my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0)); DBUG_RETURN(TRUE); } if (lock_table_names(thd, views, 0, thd->variables.lock_wait_timeout, 0)) DBUG_RETURN(TRUE); for (view= views; view; view= view->next_local) { bool not_exist; build_table_filename(path, sizeof(path) - 1, view->db, view->table_name, reg_ext, 0); if ((not_exist= my_access(path, F_OK)) || !dd_frm_is_view(thd, path)) { char name[FN_REFLEN]; my_snprintf(name, sizeof(name), "%s.%s", view->db, view->table_name); if (thd->lex->if_exists()) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_BAD_TABLE_ERROR, ER_THD(thd, ER_BAD_TABLE_ERROR), name); continue; } if (not_exist) { if (non_existant_views.length()) non_existant_views.append(','); non_existant_views.append(name); } else { if (!wrong_object_name) { wrong_object_db= view->db; wrong_object_name= view->table_name; } } continue; } if (mysql_file_delete(key_file_frm, path, MYF(MY_WME))) error= TRUE; some_views_deleted= TRUE; /* For a view, there is a TABLE_SHARE object. Remove it from the table definition cache, in case the view was cached. */ tdc_remove_table(thd, TDC_RT_REMOVE_ALL, view->db, view->table_name, FALSE); query_cache_invalidate3(thd, view, 0); sp_cache_invalidate(); } if (wrong_object_name) { my_error(ER_WRONG_OBJECT, MYF(0), wrong_object_db, wrong_object_name, "VIEW"); } if (non_existant_views.length()) { my_error(ER_BAD_TABLE_ERROR, MYF(0), non_existant_views.c_ptr_safe()); } something_wrong= error || wrong_object_name || non_existant_views.length(); if (some_views_deleted || !something_wrong) { /* if something goes wrong, bin-log with possible error code, otherwise bin-log with error code cleared. */ if (write_bin_log(thd, !something_wrong, thd->query(), thd->query_length())) something_wrong= 1; } if (something_wrong) { DBUG_RETURN(TRUE); } my_ok(thd); DBUG_RETURN(FALSE); } /* check of key (primary or unique) presence in updatable view SYNOPSIS check_key_in_view() thd thread handle view view for check with opened table DESCRIPTION If it is VIEW and query have LIMIT clause then check that underlying table of view contain one of following: 1) primary key of underlying table 2) unique key underlying table with fields for which NULL value is impossible 3) all fields of underlying table RETURN FALSE OK TRUE view do not contain key or all fields */ bool check_key_in_view(THD *thd, TABLE_LIST *view) { TABLE *table; Field_translator *trans, *end_of_trans; KEY *key_info, *key_info_end; DBUG_ENTER("check_key_in_view"); /* we do not support updatable UNIONs in VIEW, so we can check just limit of LEX::select_lex */ if ((!view->view && !view->belong_to_view) || thd->lex->sql_command == SQLCOM_INSERT || thd->lex->select_lex.select_limit == 0) DBUG_RETURN(FALSE); /* it is normal table or query without LIMIT */ table= view->table; view= view->top_table(); trans= view->field_translation; key_info_end= (key_info= table->key_info)+ table->s->keys; end_of_trans= view->field_translation_end; DBUG_ASSERT(table != 0 && view->field_translation != 0); { /* We should be sure that all fields are ready to get keys from them, but this operation should not have influence on Field::query_id, to avoid marking as used fields which are not used */ enum_mark_columns save_mark_used_columns= thd->mark_used_columns; thd->mark_used_columns= MARK_COLUMNS_NONE; DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); for (Field_translator *fld= trans; fld < end_of_trans; fld++) { if (!fld->item->fixed && fld->item->fix_fields(thd, &fld->item)) { thd->mark_used_columns= save_mark_used_columns; DBUG_RETURN(TRUE); } } thd->mark_used_columns= save_mark_used_columns; DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); } /* Loop over all keys to see if a unique-not-null key is used */ for (;key_info != key_info_end ; key_info++) { if ((key_info->flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME) { KEY_PART_INFO *key_part= key_info->key_part; KEY_PART_INFO *key_part_end= key_part + key_info->user_defined_key_parts; /* check that all key parts are used */ for (;;) { Field_translator *k; for (k= trans; k < end_of_trans; k++) { Item_field *field; if ((field= k->item->field_for_view_update()) && field->field == key_part->field) break; } if (k == end_of_trans) break; // Key is not possible if (++key_part == key_part_end) DBUG_RETURN(FALSE); // Found usable key } } } DBUG_PRINT("info", ("checking if all fields of table are used")); /* check all fields presence */ { Field **field_ptr; Field_translator *fld; for (field_ptr= table->field; *field_ptr; field_ptr++) { for (fld= trans; fld < end_of_trans; fld++) { Item_field *field; if ((field= fld->item->field_for_view_update()) && field->field == *field_ptr) break; } if (fld == end_of_trans) // If field didn't exists { /* Keys or all fields of underlying tables are not found => we have to check variable updatable_views_with_limit to decide should we issue an error or just a warning */ if (thd->variables.updatable_views_with_limit) { /* update allowed, but issue warning */ push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_WARN_VIEW_WITHOUT_KEY, ER_THD(thd, ER_WARN_VIEW_WITHOUT_KEY)); DBUG_RETURN(FALSE); } /* prohibit update */ DBUG_RETURN(TRUE); } } } DBUG_RETURN(FALSE); } /* insert fields from VIEW (MERGE algorithm) into given list SYNOPSIS insert_view_fields() thd thread handler list list for insertion view view for processing RETURN FALSE OK TRUE error (is not sent to cliet) */ bool insert_view_fields(THD *thd, List<Item> *list, TABLE_LIST *view) { Field_translator *trans_end; Field_translator *trans; DBUG_ENTER("insert_view_fields"); if (!(trans= view->field_translation)) DBUG_RETURN(FALSE); trans_end= view->field_translation_end; for (Field_translator *entry= trans; entry < trans_end; entry++) { Item_field *fld; if ((fld= entry->item->field_for_view_update())) list->push_back(fld, thd->mem_root); else { my_error(ER_NON_INSERTABLE_TABLE, MYF(0), view->alias, "INSERT"); DBUG_RETURN(TRUE); } } DBUG_RETURN(FALSE); } /* checking view md5 check suum SINOPSYS view_checksum() thd threar handler view view for check RETUIRN HA_ADMIN_OK OK HA_ADMIN_NOT_IMPLEMENTED it is not VIEW HA_ADMIN_WRONG_CHECKSUM check sum is wrong */ int view_checksum(THD *thd, TABLE_LIST *view) { char md5[MD5_BUFF_LENGTH]; if (!view->view || view->md5.length != 32) return HA_ADMIN_NOT_IMPLEMENTED; view->calc_md5(md5); return (strncmp(md5, view->md5.str, 32) ? HA_ADMIN_WRONG_CHECKSUM : HA_ADMIN_OK); } /** Check view @param thd thread handle @param view view for check @param check_opt check options @retval HA_ADMIN_OK OK @retval HA_ADMIN_NOT_IMPLEMENTED it is not VIEW @retval HA_ADMIN_WRONG_CHECKSUM check sum is wrong */ int view_check(THD *thd, TABLE_LIST *view, HA_CHECK_OPT *check_opt) { DBUG_ENTER("view_check"); int res= view_checksum(thd, view); if (res != HA_ADMIN_OK) DBUG_RETURN(res); if (((check_opt->sql_flags & TT_FOR_UPGRADE) && !view->mariadb_version)) DBUG_RETURN(HA_ADMIN_NEEDS_UPGRADE); DBUG_RETURN(HA_ADMIN_OK); } /** Repair view @param thd thread handle @param view view for check @param check_opt check options @retval HA_ADMIN_OK OK @retval HA_ADMIN_NOT_IMPLEMENTED it is not VIEW @retval HA_ADMIN_WRONG_CHECKSUM check sum is wrong */ int view_repair(THD *thd, TABLE_LIST *view, HA_CHECK_OPT *check_opt) { DBUG_ENTER("view_repair"); bool swap_alg= (check_opt->sql_flags & TT_FROM_MYSQL); bool wrong_checksum= view_checksum(thd, view) != HA_ADMIN_OK; int ret; if (wrong_checksum || swap_alg || (!view->mariadb_version)) { ret= mariadb_fix_view(thd, view, wrong_checksum, swap_alg); DBUG_RETURN(ret); } DBUG_RETURN(HA_ADMIN_OK); } /* rename view Synopsis: renames a view Parameters: thd thread handler new_db new name of database new_name new name of view view view Return values: FALSE Ok TRUE Error */ bool mysql_rename_view(THD *thd, const char *new_db, const char *new_name, TABLE_LIST *view) { LEX_STRING pathstr; File_parser *parser; char path_buff[FN_REFLEN + 1]; bool error= TRUE; DBUG_ENTER("mysql_rename_view"); pathstr.str= (char *) path_buff; pathstr.length= build_table_filename(path_buff, sizeof(path_buff) - 1, view->db, view->table_name, reg_ext, 0); if ((parser= sql_parse_prepare(&pathstr, thd->mem_root, 1)) && is_equal(&view_type, parser->type())) { TABLE_LIST view_def; char dir_buff[FN_REFLEN + 1]; LEX_STRING dir, file; /* To be PS-friendly we should either to restore state of TABLE_LIST object pointed by 'view' after using it for view definition parsing or use temporary 'view_def' object for it. */ bzero(&view_def, sizeof(view_def)); view_def.timestamp.str= view_def.timestamp_buffer; view_def.view_suid= TRUE; /* get view definition and source */ if (parser->parse((uchar*)&view_def, thd->mem_root, view_parameters, array_elements(view_parameters)-1, &file_parser_dummy_hook)) goto err; /* rename view and it's backups */ if (rename_in_schema_file(thd, view->db, view->table_name, new_db, new_name)) goto err; dir.str= dir_buff; dir.length= build_table_filename(dir_buff, sizeof(dir_buff) - 1, new_db, "", "", 0); pathstr.str= path_buff; pathstr.length= build_table_filename(path_buff, sizeof(path_buff) - 1, new_db, new_name, reg_ext, 0); file.str= pathstr.str + dir.length; file.length= pathstr.length - dir.length; if (sql_create_definition_file(&dir, &file, view_file_type, (uchar*)&view_def, view_parameters)) { /* restore renamed view in case of error */ rename_in_schema_file(thd, new_db, new_name, view->db, view->table_name); goto err; } } else DBUG_RETURN(1); /* remove cache entries */ query_cache_invalidate3(thd, view, 0); sp_cache_invalidate(); error= FALSE; err: DBUG_RETURN(error); }
chidelmun/server
sql/sql_view.cc
C++
gpl-2.0
68,497
/*===================================================================== container.h -------------- Copyright (C) Vladimir Panteleev 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. http://www.gnu.org/copyleft/gpl.html.. =====================================================================*/ #pragma once #include <unordered_map> /// Find an entry with the specified key and return its value, /// or, failing that, return a default value. template<typename MAP> static typename MAP::value_type::second_type map_get(const MAP &map, const typename MAP::key_type &key, const typename MAP::value_type::second_type defaultValue = MAP::value_type::second_type()) { MAP::const_iterator i = map.find(key); if (i == map.end()) return defaultValue; return i->second; } /// Add or find an entry to the map with the specified key. /// Copies true to *pinserted if a new entry was added, false if an existing one was found. /// Returns a reference to the new/existing value. template<class MAP> static typename MAP::value_type::second_type& map_emplace(MAP &map, const typename MAP::key_type &key, bool *pinserted=NULL) { auto pair = map.emplace(std::make_pair(key, MAP::value_type::second_type())); if (pinserted) *pinserted = pair.second; return pair.first->second; } /// Add or find an entry in a string[id] vector / id[string] map pair, and return its ID. template<typename ID> static ID map_string(std::vector<std::wstring> &list, std::unordered_map<std::wstring, ID>&map, std::wstring key) { bool inserted; ID &id = map_emplace(map, key, &inserted); if (inserted) // new entry { list.push_back(key); return id = list.size() - 1; } else // existing entry return id; } #include <unordered_set> /// Nicer wrapper around set::count. template<class SET> static bool set_get(const SET &set, const typename SET::key_type &key) { return set.count(key) != 0; } /// Make sure the specified item is / isn't in the set, according to a boolean. template<class SET> static void set_set(SET &set, const typename SET::key_type &key, bool value) { if (value) set.insert(key); else { SET::const_iterator i = set.find(key); if (i != set.end()) set.erase(i); } }
firememory/verysleepy
src/utils/container.h
C
gpl-2.0
2,894
/* system.h * * This include file contains information that is included in every * function in the test set. * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. * * $Id$ */ /* functions */ #include <pmacros.h> #include <unistd.h> #include <errno.h> #include <sched.h> void *POSIX_Init ( void *arg ); /* configuration information */ #define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER #define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER #define CONFIGURE_POSIX_INIT_THREAD_TABLE #define CONFIGURE_MAXIMUM_POSIX_THREADS 1 #define CONFIGURE_MAXIMUM_POSIX_TIMERS 1 #include <rtems/confdefs.h> /* end of include file */
daniel-hellstrom/leon-rtems
testsuites/psxtests/psxtimer02/system.h
C
gpl-2.0
768
<?php /** * * @author FABteam * @version 1.0 * @license https://opensource.org/licenses/GPL-3.0 * */ ?> <script type="text/javascript"> var temperaturesGraph; var mode = 'e'; var showExtruderLines = true; var isRunning = <?php echo $runningTask ? 'true' : 'false' ?>; window.manageMonitor = function(data){ handleTaskStatus(data.task.status); handleValues(data.pid_tune); }; $(document).ready(function() { initGraph(); if(isRunning) initRunningTaskPage(); else fabApp.checkSafety('print', 'any', '#main-widget-nozzle-pidtune'); disableButton('#save'); $("#autotune").on('click', handleAutotuneAction); $("#save").on('click', savePIDValues); }); /** init temperatures graph */ function initGraph() { temperaturesGraph = $.plot("#temperatures-chart", getPlotTemperatures(), { series : { lines : { show : true, lineWidth : 1, fill : true, fillColor : { colors : [{ opacity : 0.1 }, { opacity : 0.15 }] } } }, xaxis: { mode: "time", show: true, tickFormatter: function (val, axis) { var d = new Date(val); return d.getHours() + ":" + d.getMinutes(); }, timeformat: "%Y/%m/%d", zoomRange: [1,100] }, yaxis: { min: 0, max: <?php echo ($installed_head['max_temp'] + 10) ?>, tickFormatter: function (v, axis) { return v + "&deg;C"; }, }, tooltip : true, tooltipOpts : { content : "%s: %y &deg;C", defaultTheme : false }, legend: { show : true }, grid: { hoverable : true, clickable : true, borderWidth : 0, borderColor : "#efefef", tickColor : "#efefef" }, zoom:{ interactive: false } }); setInterval(updateGraph, 1000); } /** * get plots for temperatures graph */ function getPlotTemperatures() { var seriesExtTemp = []; var seriesExtTarget = []; var data = new Array(); $.each( temperaturesPlot.extruder.temp, function( key, plot ) { seriesExtTemp.push([plot.time, plot.value]); }); $.each( temperaturesPlot.extruder.target, function( key, plot ) { seriesExtTarget.push([plot.time, plot.value]); }); //extruder actual line if(showExtruderLines){ data.push({ data: seriesExtTemp, lines: { show: true, fill: true, lineWidth:0.5}, label: "<?php echo _("Nozzle Temperature");?>", color: "#FF0000", points: {"show" : false} }); //extruder target line data.push({ data: seriesExtTarget, lines: { show: true, fill: false, lineWidth:1 }, label: "<?php echo _("Nozzle Target");?>", color: "#33ccff", points: {"show" : false} }); } return data; } /** * update graph */ function updateGraph() { var data = getPlotTemperatures(); if(typeof temperaturesGraph !== 'undefined' ){ temperaturesGraph.setData(data); temperaturesGraph.draw(); temperaturesGraph.setupGrid(); } var temperature = temperaturesPlot.extruder.temp[temperaturesPlot.extruder.temp.length - 1]; $(".spd-temperature").html(parseInt(temperature.value)); } /** * **/ function handleAutotuneAction() { var action = $(this).attr('data-action'); if(action == 'start'){ startPidTune(); }else if(action == 'abort'){ doAbort(); } } /** * **/ function startPidTune() { disableButton('#autotune'); var data = { temperature : $("#temperature_target").val(), cycle : $("#cycle").val(), } $.ajax({ type: "POST", url: "<?php echo site_url("nozzle/startPidTune") ?>", data: data, dataType: "json" }).done(function( data ) { fabApp.resetTemperaturesPlot(1); initRunningTaskPage(); }); } /** * **/ function initRunningTaskPage() { fabApp.freezeMenu('pid_tune'); fabApp.disableTopBarControls(); disableInputs(); getTaskMonitor(); $("#autotune").html("<i class='fa fa-stop'></i> <?php echo _("Abort"); ?>"); $("#autotune").attr("data-action", "abort"); enableButton('#autotune'); } /** * **/ function handleTaskStatus(status) { switch(status) { case 'running': $("#autotune").html("<i class='fa fa-stop'></i> <?php echo _("Abort"); ?>"); $("#autotune").attr("data-action", "abort"); disableButton('#save'); break; case 'completed': completedTask(); break; } } /** * **/ function getTaskMonitor() { $.get('/temp/task_monitor.json'+ '?' + jQuery.now(), function(data, status){ manageMonitor(data); }); } /** * **/ function handleValues(object) { if(typeof object != "undefined"){ $("#kp").val(object.P); $("#ki").val(object.I); $("#kd").val(object.D); $("#temperature_target").val(object.target); } } /** * **/ function completedTask() { number_tasks = number_tasks - 1; fabApp.updateNotificationBadge(); $("#autotune").html("<i class='fa fa-play'></i> <?php echo _("Start"); ?>"); $("#autotune").attr("data-action", "start"); enableButton('#save'); fabApp.enableTopBarControls(); enableInputs(); fabApp.unFreezeMenu(); fabApp.showInfoAlert("<?php echo _("Pid tune completed") ?>"); } /** * **/ function savePIDValues() { openWait('<i class="fa fa-spinner fa-spin "></i> <?php echo _("Saving and applying new values"); ?>', "<?php echo _("Please wait"); ?>..", false ); var data = { i: $("#ki").val(), p: $("#kp").val(), d: $("#kd").val(), } $.ajax({ type: "POST", url: "<?php echo site_url("nozzle/savePIDValues") ?>", data: data, dataType: "json" }).done(function( data ) { closeWait(); $(".current-pid").html(data.pid.replace("M301", "")); }); } /** * **/ function doAbort() { openWait('<i class="fa fa-spinner fa-spin "></i> '+_("Aborting PID tune"), _("Please wait")+"...", false); if (typeof ga !== 'undefined') { ga('send', 'event', 'pidtune', 'abort', 'pidtune aborted'); } $.ajax({ type: "POST", url: "<?php echo site_url("control/taskAction/abort") ?>", dataType: "json" }).done(function( data ) { location.reload(); }).fail(function(jqXHR, textStatus){ location.reload(); }); } /** * **/ function disableInputs() { $("#temperature_target").attr('readonly', 'readonly'); $("#cycle").attr('readonly', 'readonly'); } /** * **/ function enableInputs() { $("#temperature_target").removeAttr('readonly'); $("#cycle").removeAttr('readonly'); } </script>
FABtotum/fabui-colibri
fabui/application/views/nozzle/pidtune/js.php
PHP
gpl-2.0
6,554
/* * Interface for hwdep device * * Copyright (C) 2004 Takashi Iwai <tiwai@suse.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <sound/core.h> #include <sound/hwdep.h> #include <asm/uaccess.h> #include "emux_voice.h" #define TMP_CLIENT_ID 0x1001 /* * load patch */ static int snd_emux_hwdep_load_patch(struct snd_emux *emu, void __user *arg) { int err; struct soundfont_patch_info patch; if (copy_from_user(&patch, arg, sizeof(patch))) return -EFAULT; if (patch.type >= SNDRV_SFNT_LOAD_INFO && patch.type <= SNDRV_SFNT_PROBE_DATA) { err = snd_soundfont_load(emu->sflist, arg, patch.len + sizeof(patch), TMP_CLIENT_ID); if (err < 0) return err; } else { if (emu->ops.load_fx) return emu->ops.load_fx(emu, patch.type, patch.optarg, arg, patch.len + sizeof(patch)); else return -EINVAL; } return 0; } /* * set misc mode */ static int snd_emux_hwdep_misc_mode(struct snd_emux *emu, void __user *arg) { struct snd_emux_misc_mode info; int i; if (copy_from_user(&info, arg, sizeof(info))) return -EFAULT; if (info.mode < 0 || info.mode >= EMUX_MD_END) return -EINVAL; if (info.port < 0) { for (i = 0; i < emu->num_ports; i++) emu->portptrs[i]->ctrls[info.mode] = info.value; } else { if (info.port < emu->num_ports) emu->portptrs[info.port]->ctrls[info.mode] = info.value; } return 0; } /* * ioctl */ static int snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file, unsigned int cmd, unsigned long arg) { struct snd_emux *emu = hw->private_data; switch (cmd) { case SNDRV_EMUX_IOCTL_VERSION: return put_user(SNDRV_EMUX_VERSION, (unsigned int __user *)arg); case SNDRV_EMUX_IOCTL_LOAD_PATCH: return snd_emux_hwdep_load_patch(emu, (void __user *)arg); case SNDRV_EMUX_IOCTL_RESET_SAMPLES: snd_soundfont_remove_samples(emu->sflist); break; case SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES: snd_soundfont_remove_unlocked(emu->sflist); break; case SNDRV_EMUX_IOCTL_MEM_AVAIL: if (emu->memhdr) { int size = snd_util_mem_avail(emu->memhdr); return put_user(size, (unsigned int __user *)arg); } break; case SNDRV_EMUX_IOCTL_MISC_MODE: return snd_emux_hwdep_misc_mode(emu, (void __user *)arg); } return 0; } /* * register hwdep device */ int snd_emux_init_hwdep(struct snd_emux *emu) { struct snd_hwdep *hw; int err; if ((err = snd_hwdep_new(emu->card, SNDRV_EMUX_HWDEP_NAME, emu->hwdep_idx, &hw)) < 0) return err; emu->hwdep = hw; strcpy(hw->name, SNDRV_EMUX_HWDEP_NAME); hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE; hw->ops.ioctl = snd_emux_hwdep_ioctl; /* The ioctl parameter types are compatible between 32- and * 64-bit architectures, so use the same function. */ hw->ops.ioctl_compat = snd_emux_hwdep_ioctl; hw->exclusive = 1; hw->private_data = emu; if ((err = snd_card_register(emu->card)) < 0) return err; return 0; } /* * unregister */ void snd_emux_delete_hwdep(struct snd_emux *emu) { if (emu->hwdep) { snd_device_free(emu->card, emu->hwdep); emu->hwdep = NULL; } }
andi34/kernel_samsung_espresso-cm
sound/synth/emux/emux_hwdep.c
C
gpl-2.0
3,727
/** * \file output_xhtml.cpp * This file is part of LyX, the document processor. * Licence details can be found in the file COPYING. * * \author Richard Heck * * This code is based upon output_docbook.cpp * * Full author contact details are available in file CREDITS. */ #include <config.h> #include "output_xhtml.h" #include "Buffer.h" #include "buffer_funcs.h" #include "BufferParams.h" #include "Counters.h" #include "Font.h" #include "Layout.h" #include "OutputParams.h" #include "Paragraph.h" #include "ParagraphList.h" #include "ParagraphParameters.h" #include "sgml.h" #include "Text.h" #include "TextClass.h" #include "support/convert.h" #include "support/debug.h" #include "support/lassert.h" #include "support/lstrings.h" #include "support/textutils.h" #include <vector> // Uncomment to activate debugging code. // #define XHTML_DEBUG using namespace std; using namespace lyx::support; namespace lyx { namespace html { docstring escapeChar(char_type c, XHTMLStream::EscapeSettings e) { docstring str; switch (e) { case XHTMLStream::ESCAPE_NONE: str += c; break; case XHTMLStream::ESCAPE_ALL: if (c == '<') { str += "&lt;"; break; } else if (c == '>') { str += "&gt;"; break; } // fall through case XHTMLStream::ESCAPE_AND: if (c == '&') str += "&amp;"; else str +=c ; break; } return str; } // escape what needs escaping docstring htmlize(docstring const & str, XHTMLStream::EscapeSettings e) { odocstringstream d; docstring::const_iterator it = str.begin(); docstring::const_iterator en = str.end(); for (; it != en; ++it) d << escapeChar(*it, e); return d.str(); } string escapeChar(char c, XHTMLStream::EscapeSettings e) { string str; switch (e) { case XHTMLStream::ESCAPE_NONE: str += c; break; case XHTMLStream::ESCAPE_ALL: if (c == '<') { str += "&lt;"; break; } else if (c == '>') { str += "&gt;"; break; } // fall through case XHTMLStream::ESCAPE_AND: if (c == '&') str += "&amp;"; else str +=c ; break; } return str; } // escape what needs escaping string htmlize(string const & str, XHTMLStream::EscapeSettings e) { ostringstream d; string::const_iterator it = str.begin(); string::const_iterator en = str.end(); for (; it != en; ++it) d << escapeChar(*it, e); return d.str(); } string cleanAttr(string const & str) { string newname; string::const_iterator it = str.begin(); string::const_iterator en = str.end(); for (; it != en; ++it) newname += isAlnumASCII(*it) ? *it : '_'; return newname; } docstring cleanAttr(docstring const & str) { docstring newname; docstring::const_iterator it = str.begin(); docstring::const_iterator en = str.end(); for (; it != en; ++it) { char_type const c = *it; newname += isAlnumASCII(c) ? c : char_type('_'); } return newname; } docstring StartTag::writeTag() const { string output = "<" + tag_; if (!attr_.empty()) output += " " + html::htmlize(attr_, XHTMLStream::ESCAPE_NONE); output += ">"; return from_utf8(output); } docstring StartTag::writeEndTag() const { string output = "</" + tag_ + ">"; return from_utf8(output); } bool StartTag::operator==(FontTag const & rhs) const { return rhs == *this; } docstring EndTag::writeEndTag() const { string output = "</" + tag_ + ">"; return from_utf8(output); } docstring ParTag::writeTag() const { docstring output = StartTag::writeTag(); if (parid_.empty()) return output; string const pattr = "id='" + parid_ + "'"; output += html::CompTag("a", pattr).writeTag(); return output; } docstring CompTag::writeTag() const { string output = "<" + tag_; if (!attr_.empty()) output += " " + html::htmlize(attr_, XHTMLStream::ESCAPE_NONE); output += " />"; return from_utf8(output); } namespace { string fontToTag(html::FontTypes type) { switch(type) { case FT_EMPH: return "em"; case FT_BOLD: return "b"; case FT_NOUN: return "dfn"; case FT_UBAR: case FT_WAVE: case FT_DBAR: return "u"; case FT_SOUT: return "del"; case FT_ITALIC: return "i"; case FT_UPRIGHT: case FT_SLANTED: case FT_SMALLCAPS: case FT_ROMAN: case FT_SANS: case FT_TYPE: case FT_SIZE_TINY: case FT_SIZE_SCRIPT: case FT_SIZE_FOOTNOTE: case FT_SIZE_SMALL: case FT_SIZE_NORMAL: case FT_SIZE_LARGE: case FT_SIZE_LARGER: case FT_SIZE_LARGEST: case FT_SIZE_HUGE: case FT_SIZE_HUGER: case FT_SIZE_INCREASE: case FT_SIZE_DECREASE: return "span"; } // kill warning return ""; } StartTag fontToStartTag(html::FontTypes type) { string tag = fontToTag(type); switch(type) { case FT_EMPH: return html::StartTag(tag); case FT_BOLD: return html::StartTag(tag); case FT_NOUN: return html::StartTag(tag, "class='lyxnoun'"); case FT_UBAR: return html::StartTag(tag); case FT_DBAR: return html::StartTag(tag, "class='dline'"); case FT_SOUT: return html::StartTag(tag, "class='strikeout'"); case FT_WAVE: return html::StartTag(tag, "class='wline'"); case FT_ITALIC: return html::StartTag(tag); case FT_UPRIGHT: return html::StartTag(tag, "style='font-style:normal;'"); case FT_SLANTED: return html::StartTag(tag, "style='font-style:oblique;'"); case FT_SMALLCAPS: return html::StartTag(tag, "style='font-variant:small-caps;'"); case FT_ROMAN: return html::StartTag(tag, "style='font-family:serif;'"); case FT_SANS: return html::StartTag(tag, "style='font-family:sans-serif;'"); case FT_TYPE: return html::StartTag(tag, "style='font-family:monospace;'"); case FT_SIZE_TINY: case FT_SIZE_SCRIPT: case FT_SIZE_FOOTNOTE: return html::StartTag(tag, "style='font-size:x-small;'"); case FT_SIZE_SMALL: return html::StartTag(tag, "style='font-size:small;'"); case FT_SIZE_NORMAL: return html::StartTag(tag, "style='font-size:normal;'"); case FT_SIZE_LARGE: return html::StartTag(tag, "style='font-size:large;'"); case FT_SIZE_LARGER: case FT_SIZE_LARGEST: return html::StartTag(tag, "style='font-size:x-large;'"); case FT_SIZE_HUGE: case FT_SIZE_HUGER: return html::StartTag(tag, "style='font-size:xx-large;'"); case FT_SIZE_INCREASE: return html::StartTag(tag, "style='font-size:larger;'"); case FT_SIZE_DECREASE: return html::StartTag(tag, "style='font-size:smaller;'"); } // kill warning return StartTag(""); } } // end anonymous namespace FontTag::FontTag(FontTypes type) : StartTag(fontToStartTag(type)), font_type_(type) {} bool FontTag::operator==(StartTag const & tag) const { FontTag const * const ftag = tag.asFontTag(); if (!ftag) return false; return (font_type_ == ftag->font_type_); } EndFontTag::EndFontTag(FontTypes type) : EndTag(fontToTag(type)), font_type_(type) {} } // namespace html //////////////////////////////////////////////////////////////// /// /// XHTMLStream /// //////////////////////////////////////////////////////////////// XHTMLStream::XHTMLStream(odocstream & os) : os_(os), escape_(ESCAPE_ALL) {} #ifdef XHTML_DEBUG void XHTMLStream::dumpTagStack(string const & msg) const { writeError(msg + ": Tag Stack"); TagStack::const_reverse_iterator it = tag_stack_.rbegin(); TagStack::const_reverse_iterator en = tag_stack_.rend(); for (; it != en; ++it) { writeError(it->tag_); } writeError("Pending Tags"); it = pending_tags_.rbegin(); en = pending_tags_.rend(); for (; it != en; ++it) { writeError(it->tag_); } writeError("End Tag Stack"); } #endif void XHTMLStream::writeError(std::string const & s) const { LYXERR0(s); os_ << from_utf8("<!-- Output Error: " + s + " -->\n"); } namespace { // an illegal tag for internal use static html::StartTag const parsep_tag("&LyX_parsep_tag&"); } bool XHTMLStream::closeFontTags() { if (isTagPending(parsep_tag)) // we haven't had any content return true; // this may be a useless check, since we ought at least to have // the parsep_tag. but it can't hurt too much to be careful. if (tag_stack_.empty()) return true; // first, we close any open font tags we can close TagPtr curtag = tag_stack_.back(); while (curtag->asFontTag()) { os_ << curtag->writeEndTag(); tag_stack_.pop_back(); // this shouldn't happen, since then the font tags // weren't in any other tag. LBUFERR(!tag_stack_.empty()); curtag = tag_stack_.back(); } if (*curtag == parsep_tag) return true; // so we've hit a non-font tag. writeError("Tags still open in closeFontTags(). Probably not a problem,\n" "but you might want to check these tags:"); TagDeque::const_reverse_iterator it = tag_stack_.rbegin(); TagDeque::const_reverse_iterator const en = tag_stack_.rend(); for (; it != en; ++it) { if (**it == parsep_tag) break; writeError((*it)->tag_); } return false; } void XHTMLStream::startParagraph(bool keep_empty) { pending_tags_.push_back(makeTagPtr(html::StartTag(parsep_tag))); if (keep_empty) clearTagDeque(); } void XHTMLStream::endParagraph() { if (isTagPending(parsep_tag)) { // this case is normal. it just means we didn't have content, // so the parsep_tag never got moved onto the tag stack. while (!pending_tags_.empty()) { // clear all pending tags up to and including the parsep tag. // note that we work from the back, because we want to get rid // of everything that hasn't been used. TagPtr const cur_tag = pending_tags_.back(); pending_tags_.pop_back(); if (*cur_tag == parsep_tag) break; } return; } if (!isTagOpen(parsep_tag)) { writeError("No paragraph separation tag found in endParagraph()."); return; } // this case is also normal, if the parsep tag is the last one // on the stack. otherwise, it's an error. while (!tag_stack_.empty()) { TagPtr const cur_tag = tag_stack_.back(); tag_stack_.pop_back(); if (*cur_tag == parsep_tag) break; writeError("Tag `" + cur_tag->tag_ + "' still open at end of paragraph. Closing."); os_ << cur_tag->writeEndTag(); } } void XHTMLStream::clearTagDeque() { while (!pending_tags_.empty()) { TagPtr const tag = pending_tags_.front(); if (*tag != parsep_tag) // tabs? os_ << tag->writeTag(); tag_stack_.push_back(tag); pending_tags_.pop_front(); } } XHTMLStream & XHTMLStream::operator<<(docstring const & d) { clearTagDeque(); os_ << html::htmlize(d, escape_); escape_ = ESCAPE_ALL; return *this; } XHTMLStream & XHTMLStream::operator<<(const char * s) { clearTagDeque(); docstring const d = from_ascii(s); os_ << html::htmlize(d, escape_); escape_ = ESCAPE_ALL; return *this; } XHTMLStream & XHTMLStream::operator<<(char_type c) { clearTagDeque(); os_ << html::escapeChar(c, escape_); escape_ = ESCAPE_ALL; return *this; } XHTMLStream & XHTMLStream::operator<<(char c) { clearTagDeque(); string const d = html::escapeChar(c, escape_); escape_ = ESCAPE_ALL; return *this; } XHTMLStream & XHTMLStream::operator<<(int i) { clearTagDeque(); os_ << i; escape_ = ESCAPE_ALL; return *this; } XHTMLStream & XHTMLStream::operator<<(EscapeSettings e) { escape_ = e; return *this; } XHTMLStream & XHTMLStream::operator<<(html::StartTag const & tag) { if (tag.tag_.empty()) return *this; pending_tags_.push_back(makeTagPtr(tag)); if (tag.keepempty_) clearTagDeque(); return *this; } XHTMLStream & XHTMLStream::operator<<(html::ParTag const & tag) { if (tag.tag_.empty()) return *this; pending_tags_.push_back(makeTagPtr(tag)); return *this; } XHTMLStream & XHTMLStream::operator<<(html::CompTag const & tag) { if (tag.tag_.empty()) return *this; clearTagDeque(); os_ << tag.writeTag(); *this << html::CR(); return *this; } XHTMLStream & XHTMLStream::operator<<(html::FontTag const & tag) { if (tag.tag_.empty()) return *this; pending_tags_.push_back(makeTagPtr(tag)); return *this; } XHTMLStream & XHTMLStream::operator<<(html::CR const &) { // tabs? os_ << from_ascii("\n"); return *this; } bool XHTMLStream::isTagOpen(html::StartTag const & stag) const { TagDeque::const_iterator sit = tag_stack_.begin(); TagDeque::const_iterator const sen = tag_stack_.end(); for (; sit != sen; ++sit) if (**sit == stag) return true; return false; } bool XHTMLStream::isTagOpen(html::EndTag const & etag) const { TagDeque::const_iterator sit = tag_stack_.begin(); TagDeque::const_iterator const sen = tag_stack_.end(); for (; sit != sen; ++sit) if (etag == **sit) return true; return false; } bool XHTMLStream::isTagPending(html::StartTag const & stag) const { TagDeque::const_iterator sit = pending_tags_.begin(); TagDeque::const_iterator const sen = pending_tags_.end(); for (; sit != sen; ++sit) if (**sit == stag) return true; return false; } // this is complicated, because we want to make sure that // everything is properly nested. the code ought to make // sure of that, but we won't assert (yet) if we run into // a problem. we'll just output error messages and try our // best to make things work. XHTMLStream & XHTMLStream::operator<<(html::EndTag const & etag) { if (etag.tag_.empty()) return *this; // if this tag is pending, we can simply discard it. if (!pending_tags_.empty()) { if (etag == *pending_tags_.back()) { // we have <tag></tag>, so we discard it and remove it // from the pending_tags_. pending_tags_.pop_back(); return *this; } // there is a pending tag that isn't the one we are trying // to close. // is this tag itself pending? // non-const iterators because we may call erase(). TagDeque::iterator dit = pending_tags_.begin(); TagDeque::iterator const den = pending_tags_.end(); for (; dit != den; ++dit) { if (etag == **dit) { // it was pending, so we just erase it writeError("Tried to close pending tag `" + etag.tag_ + "' when other tags were pending. Last pending tag is `" + to_utf8(pending_tags_.back()->writeTag()) + "'. Tag discarded."); pending_tags_.erase(dit); return *this; } } // so etag isn't itself pending. is it even open? if (!isTagOpen(etag)) { writeError("Tried to close `" + etag.tag_ + "' when tag was not open. Tag discarded."); return *this; } // ok, so etag is open. // our strategy will be as below: we will do what we need to // do to close this tag. string estr = "Closing tag `" + etag.tag_ + "' when other tags are pending. Discarded pending tags:\n"; for (dit = pending_tags_.begin(); dit != den; ++dit) estr += to_utf8(html::htmlize((*dit)->writeTag(), XHTMLStream::ESCAPE_ALL)) + "\n"; writeError(estr); // clear the pending tags... pending_tags_.clear(); // ...and then just fall through. } // make sure there are tags to be closed if (tag_stack_.empty()) { writeError("Tried to close `" + etag.tag_ + "' when no tags were open!"); return *this; } // is the tag we are closing the last one we opened? if (etag == *tag_stack_.back()) { // output it... os_ << etag.writeEndTag(); // ...and forget about it tag_stack_.pop_back(); return *this; } // we are trying to close a tag other than the one last opened. // let's first see if this particular tag is still open somehow. if (!isTagOpen(etag)) { writeError("Tried to close `" + etag.tag_ + "' when tag was not open. Tag discarded."); return *this; } // so the tag was opened, but other tags have been opened since // and not yet closed. // if it's a font tag, though... if (etag.asFontTag()) { // it won't be a problem if the other tags open since this one // are also font tags. TagDeque::const_reverse_iterator rit = tag_stack_.rbegin(); TagDeque::const_reverse_iterator ren = tag_stack_.rend(); for (; rit != ren; ++rit) { if (etag == **rit) break; if (!(*rit)->asFontTag()) { // we'll just leave it and, presumably, have to close it later. writeError("Unable to close font tag `" + etag.tag_ + "' due to open non-font tag `" + (*rit)->tag_ + "'."); return *this; } } // so we have e.g.: // <em>this is <strong>bold // and are being asked to closed em. we want: // <em>this is <strong>bold</strong></em><strong> // first, we close the intervening tags... TagPtr curtag = tag_stack_.back(); // ...remembering them in a stack. TagDeque fontstack; while (etag != *curtag) { os_ << curtag->writeEndTag(); fontstack.push_back(curtag); tag_stack_.pop_back(); curtag = tag_stack_.back(); } os_ << etag.writeEndTag(); tag_stack_.pop_back(); // ...and restore the other tags. rit = fontstack.rbegin(); ren = fontstack.rend(); for (; rit != ren; ++rit) pending_tags_.push_back(*rit); return *this; } // it wasn't a font tag. // so other tags were opened before this one and not properly closed. // so we'll close them, too. that may cause other issues later, but it // at least guarantees proper nesting. writeError("Closing tag `" + etag.tag_ + "' when other tags are open, namely:"); TagPtr curtag = tag_stack_.back(); while (etag != *curtag) { writeError(curtag->tag_); if (*curtag != parsep_tag) os_ << curtag->writeEndTag(); tag_stack_.pop_back(); curtag = tag_stack_.back(); } // curtag is now the one we actually want. os_ << curtag->writeEndTag(); tag_stack_.pop_back(); return *this; } // End code for XHTMLStream namespace { // convenience functions inline void openTag(XHTMLStream & xs, Layout const & lay) { xs << html::StartTag(lay.htmltag(), lay.htmlattr()); } void openTag(XHTMLStream & xs, Layout const & lay, ParagraphParameters const & params) { // FIXME Are there other things we should handle here? string const align = alignmentToCSS(params.align()); if (align.empty()) { openTag(xs, lay); return; } string attrs = lay.htmlattr() + " style='text-align: " + align + ";'"; xs << html::StartTag(lay.htmltag(), attrs); } inline void openParTag(XHTMLStream & xs, Layout const & lay, std::string parlabel) { xs << html::ParTag(lay.htmltag(), lay.htmlattr(), parlabel); } void openParTag(XHTMLStream & xs, Layout const & lay, ParagraphParameters const & params, std::string parlabel) { // FIXME Are there other things we should handle here? string const align = alignmentToCSS(params.align()); if (align.empty()) { openParTag(xs, lay, parlabel); return; } string attrs = lay.htmlattr() + " style='text-align: " + align + ";'"; xs << html::ParTag(lay.htmltag(), attrs, parlabel); } inline void closeTag(XHTMLStream & xs, Layout const & lay) { xs << html::EndTag(lay.htmltag()); } inline void openLabelTag(XHTMLStream & xs, Layout const & lay) { xs << html::StartTag(lay.htmllabeltag(), lay.htmllabelattr()); } inline void closeLabelTag(XHTMLStream & xs, Layout const & lay) { xs << html::EndTag(lay.htmllabeltag()); } inline void openItemTag(XHTMLStream & xs, Layout const & lay) { xs << html::StartTag(lay.htmlitemtag(), lay.htmlitemattr(), true); } void openItemTag(XHTMLStream & xs, Layout const & lay, ParagraphParameters const & params) { // FIXME Are there other things we should handle here? string const align = alignmentToCSS(params.align()); if (align.empty()) { openItemTag(xs, lay); return; } string attrs = lay.htmlattr() + " style='text-align: " + align + ";'"; xs << html::StartTag(lay.htmlitemtag(), attrs); } inline void closeItemTag(XHTMLStream & xs, Layout const & lay) { xs << html::EndTag(lay.htmlitemtag()); } // end of convenience functions ParagraphList::const_iterator findLastParagraph( ParagraphList::const_iterator p, ParagraphList::const_iterator const & pend) { for (++p; p != pend && p->layout().latextype == LATEX_PARAGRAPH; ++p) ; return p; } ParagraphList::const_iterator findEndOfEnvironment( ParagraphList::const_iterator const pstart, ParagraphList::const_iterator const & pend) { ParagraphList::const_iterator p = pstart; Layout const & bstyle = p->layout(); size_t const depth = p->params().depth(); for (++p; p != pend; ++p) { Layout const & style = p->layout(); // It shouldn't happen that e.g. a section command occurs inside // a quotation environment, at a higher depth, but as of 6/2009, // it can happen. We pretend that it's just at lowest depth. if (style.latextype == LATEX_COMMAND) return p; // If depth is down, we're done if (p->params().depth() < depth) return p; // If depth is up, we're not done if (p->params().depth() > depth) continue; // FIXME I am not sure about the first check. // Surely we *could* have different layouts that count as // LATEX_PARAGRAPH, right? if (style.latextype == LATEX_PARAGRAPH || style != bstyle) return p; } return pend; } ParagraphList::const_iterator makeParagraphs(Buffer const & buf, XHTMLStream & xs, OutputParams const & runparams, Text const & text, ParagraphList::const_iterator const & pbegin, ParagraphList::const_iterator const & pend) { ParagraphList::const_iterator const begin = text.paragraphs().begin(); ParagraphList::const_iterator par = pbegin; for (; par != pend; ++par) { Layout const & lay = par->layout(); if (!lay.counter.empty()) buf.masterBuffer()->params(). documentClass().counters().step(lay.counter, OutputUpdate); // FIXME We should see if there's a label to be output and // do something with it. if (par != pbegin) xs << html::CR(); // If we are already in a paragraph, and this is the first one, then we // do not want to open the paragraph tag. // we also do not want to open it if the current layout does not permit // multiple paragraphs. bool const opened = runparams.html_make_pars && (par != pbegin || !runparams.html_in_par); bool const make_parid = !runparams.for_toc && runparams.html_make_pars; if (opened) openParTag(xs, lay, par->params(), make_parid ? par->magicLabel() : ""); docstring const deferred = par->simpleLyXHTMLOnePar(buf, xs, runparams, text.outerFont(distance(begin, par))); // We want to issue the closing tag if either: // (i) We opened it, and either html_in_par is false, // or we're not in the last paragraph, anyway. // (ii) We didn't open it and html_in_par is true, // but we are in the first par, and there is a next par. ParagraphList::const_iterator nextpar = par; ++nextpar; bool const needclose = (opened && (!runparams.html_in_par || nextpar != pend)) || (!opened && runparams.html_in_par && par == pbegin && nextpar != pend); if (needclose) { closeTag(xs, lay); xs << html::CR(); } if (!deferred.empty()) { xs << XHTMLStream::ESCAPE_NONE << deferred << html::CR(); } } return pend; } ParagraphList::const_iterator makeBibliography(Buffer const & buf, XHTMLStream & xs, OutputParams const & runparams, Text const & text, ParagraphList::const_iterator const & pbegin, ParagraphList::const_iterator const & pend) { // FIXME XHTML // Use TextClass::htmlTOCLayout() to figure out how we should look. xs << html::StartTag("h2", "class='bibliography'") << pbegin->layout().labelstring(false) << html::EndTag("h2") << html::CR() << html::StartTag("div", "class='bibliography'") << html::CR(); makeParagraphs(buf, xs, runparams, text, pbegin, pend); xs << html::EndTag("div"); return pend; } bool isNormalEnv(Layout const & lay) { return lay.latextype == LATEX_ENVIRONMENT || lay.latextype == LATEX_BIB_ENVIRONMENT; } ParagraphList::const_iterator makeEnvironment(Buffer const & buf, XHTMLStream & xs, OutputParams const & runparams, Text const & text, ParagraphList::const_iterator const & pbegin, ParagraphList::const_iterator const & pend) { ParagraphList::const_iterator const begin = text.paragraphs().begin(); ParagraphList::const_iterator par = pbegin; Layout const & bstyle = par->layout(); depth_type const origdepth = pbegin->params().depth(); // open tag for this environment openParTag(xs, bstyle, pbegin->magicLabel()); xs << html::CR(); // we will on occasion need to remember a layout from before. Layout const * lastlay = 0; while (par != pend) { Layout const & style = par->layout(); // the counter only gets stepped if we're in some kind of list, // or if it's the first time through. // note that enum, etc, are handled automatically. // FIXME There may be a bug here about user defined enumeration // types. If so, then we'll need to take the counter and add "i", // "ii", etc, as with enum. Counters & cnts = buf.masterBuffer()->params().documentClass().counters(); docstring const & cntr = style.counter; if (!style.counter.empty() && (par == pbegin || !isNormalEnv(style)) && cnts.hasCounter(cntr) ) cnts.step(cntr, OutputUpdate); ParagraphList::const_iterator send; // this will be positive, if we want to skip the initial word // (if it's been taken for the label). pos_type sep = 0; switch (style.latextype) { case LATEX_ENVIRONMENT: case LATEX_LIST_ENVIRONMENT: case LATEX_ITEM_ENVIRONMENT: { // There are two possiblities in this case. // One is that we are still in the environment in which we // started---which we will be if the depth is the same. if (par->params().depth() == origdepth) { LATTEST(bstyle == style); if (lastlay != 0) { closeItemTag(xs, *lastlay); lastlay = 0; } bool const labelfirst = style.htmllabelfirst(); if (!labelfirst) openItemTag(xs, style, par->params()); // label output if (style.labeltype != LABEL_NO_LABEL && style.htmllabeltag() != "NONE") { if (isNormalEnv(style)) { // in this case, we print the label only for the first // paragraph (as in a theorem). if (par == pbegin) { docstring const lbl = pbegin->params().labelString(); if (!lbl.empty()) { openLabelTag(xs, style); xs << lbl; closeLabelTag(xs, style); } xs << html::CR(); } } else { // some kind of list if (style.labeltype == LABEL_MANUAL) { openLabelTag(xs, style); sep = par->firstWordLyXHTML(xs, runparams); closeLabelTag(xs, style); xs << html::CR(); } else { openLabelTag(xs, style); xs << par->params().labelString(); closeLabelTag(xs, style); xs << html::CR(); } } } // end label output if (labelfirst) openItemTag(xs, style, par->params()); par->simpleLyXHTMLOnePar(buf, xs, runparams, text.outerFont(distance(begin, par)), sep); ++par; // We may not want to close the tag yet, in particular: // If we're not at the end... if (par != pend // and are doing items... && !isNormalEnv(style) // and if the depth has changed... && par->params().depth() != origdepth) { // then we'll save this layout for later, and close it when // we get another item. lastlay = &style; } else closeItemTag(xs, style); xs << html::CR(); } // The other possibility is that the depth has increased, in which // case we need to recurse. else { send = findEndOfEnvironment(par, pend); par = makeEnvironment(buf, xs, runparams, text, par, send); } break; } case LATEX_PARAGRAPH: send = findLastParagraph(par, pend); par = makeParagraphs(buf, xs, runparams, text, par, send); break; // Shouldn't happen case LATEX_BIB_ENVIRONMENT: send = par; ++send; par = makeParagraphs(buf, xs, runparams, text, par, send); break; // Shouldn't happen case LATEX_COMMAND: ++par; break; } } if (lastlay != 0) closeItemTag(xs, *lastlay); closeTag(xs, bstyle); xs << html::CR(); return pend; } void makeCommand(Buffer const & buf, XHTMLStream & xs, OutputParams const & runparams, Text const & text, ParagraphList::const_iterator const & pbegin) { Layout const & style = pbegin->layout(); if (!style.counter.empty()) buf.masterBuffer()->params(). documentClass().counters().step(style.counter, OutputUpdate); bool const make_parid = !runparams.for_toc && runparams.html_make_pars; openParTag(xs, style, pbegin->params(), make_parid ? pbegin->magicLabel() : ""); // Label around sectioning number: // FIXME Probably need to account for LABEL_MANUAL // FIXME Probably also need now to account for labels ABOVE and CENTERED. if (style.labeltype != LABEL_NO_LABEL) { openLabelTag(xs, style); xs << pbegin->params().labelString(); closeLabelTag(xs, style); // Otherwise the label might run together with the text xs << from_ascii(" "); } ParagraphList::const_iterator const begin = text.paragraphs().begin(); pbegin->simpleLyXHTMLOnePar(buf, xs, runparams, text.outerFont(distance(begin, pbegin))); closeTag(xs, style); xs << html::CR(); } } // end anonymous namespace void xhtmlParagraphs(Text const & text, Buffer const & buf, XHTMLStream & xs, OutputParams const & runparams) { ParagraphList const & paragraphs = text.paragraphs(); if (runparams.par_begin == runparams.par_end) { runparams.par_begin = 0; runparams.par_end = paragraphs.size(); } pit_type bpit = runparams.par_begin; pit_type const epit = runparams.par_end; LASSERT(bpit < epit, { xs << XHTMLStream::ESCAPE_NONE << "<!-- XHTML output error! -->\n"; return; }); OutputParams ourparams = runparams; ParagraphList::const_iterator const pend = (epit == (int) paragraphs.size()) ? paragraphs.end() : paragraphs.constIterator(epit); while (bpit < epit) { ParagraphList::const_iterator par = paragraphs.constIterator(bpit); if (par->params().startOfAppendix()) { // We want to reset the counter corresponding to toplevel sectioning Layout const & lay = buf.masterBuffer()->params().documentClass().getTOCLayout(); docstring const cnt = lay.counter; if (!cnt.empty()) { Counters & cnts = buf.masterBuffer()->params().documentClass().counters(); cnts.reset(cnt); } } Layout const & style = par->layout(); ParagraphList::const_iterator const lastpar = par; ParagraphList::const_iterator send; switch (style.latextype) { case LATEX_COMMAND: { // The files with which we are working never have more than // one paragraph in a command structure. // FIXME // if (ourparams.html_in_par) // fix it so we don't get sections inside standard, e.g. // note that we may then need to make runparams not const, so we // can communicate that back. // FIXME Maybe this fix should be in the routines themselves, in case // they are called from elsewhere. makeCommand(buf, xs, ourparams, text, par); ++par; break; } case LATEX_ENVIRONMENT: case LATEX_LIST_ENVIRONMENT: case LATEX_ITEM_ENVIRONMENT: { // FIXME Same fix here. send = findEndOfEnvironment(par, pend); par = makeEnvironment(buf, xs, ourparams, text, par, send); break; } case LATEX_BIB_ENVIRONMENT: { // FIXME Same fix here. send = findEndOfEnvironment(par, pend); par = makeBibliography(buf, xs, ourparams, text, par, send); break; } case LATEX_PARAGRAPH: send = findLastParagraph(par, pend); par = makeParagraphs(buf, xs, ourparams, text, par, send); break; } bpit += distance(lastpar, par); } } string alignmentToCSS(LyXAlignment align) { switch (align) { case LYX_ALIGN_BLOCK: // we are NOT going to use text-align: justify!! case LYX_ALIGN_LEFT: return "left"; case LYX_ALIGN_RIGHT: return "right"; case LYX_ALIGN_CENTER: return "center"; default: break; } return ""; } } // namespace lyx
hashinisenaratne/HSTML
src/output_xhtml.cpp
C++
gpl-2.0
31,653
# # Makefile for the linux kernel. # # Common support obj-y := id.o io.o control.o mux.o devices.o serial.o gpmc.o timer-gp.o omap-2-3-common = irq.o sdrc.o omap_hwmod.o prcm-common = prcm.o powerdomain.o clock-common = clock.o clockdomain.o obj-$(CONFIG_ARCH_OMAP2) += $(omap-2-3-common) $(prcm-common) $(clock-common) obj-$(CONFIG_ARCH_OMAP3) += $(omap-2-3-common) $(prcm-common) $(clock-common) obj-$(CONFIG_OMAP_MCBSP) += mcbsp.o # SMP support ONLY available for OMAP4 obj-$(CONFIG_SMP) += omap-smp.o omap-headsmp.o obj-$(CONFIG_LOCAL_TIMERS) += timer-mpu.o # Functions loaded to SRAM obj-$(CONFIG_ARCH_OMAP2420) += sram242x.o obj-$(CONFIG_ARCH_OMAP2430) += sram243x.o obj-$(CONFIG_ARCH_OMAP3) += sram34xx.o # SMS/SDRC obj-$(CONFIG_ARCH_OMAP2) += sdrc2xxx.o # obj-$(CONFIG_ARCH_OMAP3) += sdrc3xxx.o # Power Management ifeq ($(CONFIG_PM),y) obj-$(CONFIG_ARCH_OMAP2) += pm24xx.o obj-$(CONFIG_ARCH_OMAP24XX) += sleep24xx.o obj-$(CONFIG_ARCH_OMAP3) += pm.o pm34xx.o sleep34xx.o cpuidle34xx.o obj-$(CONFIG_PM_DEBUG) += pm-debug.o obj-y += wakeup-timer.o obj-$(CONFIG_OMAP_SMARTREFLEX) += smartreflex.o endif # PRCM obj-$(CONFIG_ARCH_OMAP2) += cm.o obj-$(CONFIG_ARCH_OMAP3) += cm.o obj-$(CONFIG_ARCH_OMAP4) += cm4xxx.o # Clock framework obj-$(CONFIG_ARCH_OMAP2) += clock24xx.o obj-$(CONFIG_ARCH_OMAP3) += clock34xx.o obj-$(CONFIG_OMAP_PM_SRF) += resource34xx.o obj-$(CONFIG_OMAP_MBOX_FWK) += mailbox_mach.o mailbox_mach-objs := mailbox.o iommu-y += iommu2.o iommu-$(CONFIG_ARCH_OMAP3) += omap3-iommu.o obj-$(CONFIG_OMAP_IOMMU) += $(iommu-y) # Debobs obj-$(CONFIG_OMAP3_DEBOBS) += debobs.o ifneq ($(CONFIG_MPU_BRIDGE),) obj-y += dspbridge.o endif # Specific board support obj-$(CONFIG_MACH_OMAP_GENERIC) += board-generic.o obj-$(CONFIG_MACH_OMAP_H4) += board-h4.o obj-$(CONFIG_MACH_OMAP_2430SDP) += board-2430sdp.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OMAP_APOLLON) += board-apollon.o obj-$(CONFIG_MACH_OMAP3_BEAGLE) += board-omap3beagle.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OMAP_LDP) += board-ldp.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OVERO) += board-overo.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OMAP3EVM) += board-omap3evm.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OMAP3_PANDORA) += board-omap3pandora.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OMAP_3430SDP) += board-3430sdp.o \ mmc-twl4030.o obj-$(CONFIG_MACH_NOKIA_N8X0) += board-n8x0.o obj-$(CONFIG_MACH_OMAP_ZOOM2) += board-zoom2.o \ mmc-twl4030.o \ board-ldp-flash.o \ board-zoom2-camera.o \ board-zoom2-wifi.o obj-$(CONFIG_MACH_SHOLES) += board-sholes.o \ board-sholes-camera.o \ board-sholes-flash.o \ board-sholes-spi.o \ board-sholes-sensors.o \ board-sholes-hsmmc.o \ board-sholes-keypad.o \ board-sholes-wifi.o \ board-sholes-mmcprobe.o # usbnet temporarily disabled # board-sholes-usbnet.o \ obj-$(CONFIG_MACH_MAPPHONE) += board-mapphone.o \ board-mapphone-camera.o \ board-mapphone-flash.o \ board-mapphone-padconf.o \ board-mapphone-panel.o \ board-mapphone-spi.o \ board-mapphone-cpcap-client.o \ board-mapphone-sensors.o \ board-mapphone-hsmmc.o \ board-mapphone-keypad.o \ board-mapphone-wifi.o \ board-mapphone-gpio.o \ board-mapphone-mmcprobe.o obj-$(CONFIG_MACH_MAPPHONE_OVERCLOCK) += board-mapphone-overclock.o obj-$(CONFIG_MOT_FEAT_MDTV) += board-mapphone-mdtv.o obj-$(CONFIG_EMU_UART_DEBUG) += board-mapphone-emu_uart.o obj-$(CONFIG_MACH_NOKIA_RX51) += board-rx51.o \ board-rx51-sdram.o \ board-rx51-peripherals.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OMAP_ZOOM2) += board-zoom2.o \ board-zoom-peripherals.o \ mmc-twl4030.o \ board-zoom-debugboard.o obj-$(CONFIG_MACH_OMAP_ZOOM3) += board-zoom3.o \ board-zoom-peripherals.o \ mmc-twl4030.o \ board-zoom-debugboard.o obj-$(CONFIG_MACH_OMAP_3630SDP) += board-3630sdp.o \ board-zoom-peripherals.o \ mmc-twl4030.o obj-$(CONFIG_MACH_CM_T35) += board-cm-t35.o \ mmc-twl4030.o obj-$(CONFIG_MACH_IGEP0020) += board-igep0020.o \ mmc-twl4030.o obj-$(CONFIG_MACH_OMAP_4430SDP) += board-4430sdp.o obj-$(CONFIG_MACH_OMAP3517EVM) += board-am3517evm.o # Platform specific device init code obj-y += usb-musb.o obj-$(CONFIG_MACH_OMAP2_TUSB6010) += usb-tusb6010.o obj-y += usb-ehci.o onenand-$(CONFIG_MTD_ONENAND_OMAP2) := gpmc-onenand.o obj-y += $(onenand-m) $(onenand-y) smc91x-$(CONFIG_SMC91X) := gpmc-smc91x.o obj-y += $(smc91x-m) $(smc91x-y)
nadlabak/kernel
arch/arm/mach-omap2/Makefile
Makefile
gpl-2.0
5,173
<?php /** * @package Wright * @subpackage Parameters * * @copyright Copyright (C) 2005 - 2013 Joomlashack. Meritage Assets. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ jimport('joomla.form.formfield'); defined('_JEXEC') or die('You are not allowed to directly access this file'); if (file_exists(realpath(dirname(__FILE__).'/../../../parameters/templatecustom.php'))) require_once(realpath(dirname(__FILE__).'/../../../parameters/templatecustom.php')); else { class JFormFieldTemplateCustom extends JFormField { protected $type = 'templatecustom'; protected function getInput() { $html = ''; $html .= '<input type="text" name="'.$this->name.'" id="'.$this->name.'" value="'.$this->value.'" />'; return $html; } } }
cristhian-fe/ibn
templates/js_wright/wright/parameters/joomla_2.5/templatecustom.php
PHP
gpl-2.0
814
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2013 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 "Profile/UIProfile.hpp" #include "Profile/MapProfile.hpp" #include "Profile/InfoBoxConfig.hpp" #include "Profile/PageProfile.hpp" #include "Profile/Profile.hpp" #include "Profile/UnitsConfig.hpp" #include "UISettings.hpp" namespace Profile { static void Load(DisplaySettings &settings); static void Load(VarioSettings &settings); static void Load(TrafficSettings &settings); static void Load(DialogSettings &settings); static void Load(SoundSettings &settings); static void Load(VarioSoundSettings &settings); }; void Profile::Load(DisplaySettings &settings) { Get(ProfileKeys::AutoBlank, settings.enable_auto_blank); GetEnum(ProfileKeys::DisplayOrientation, settings.orientation); } void Profile::Load(VarioSettings &settings) { Get(ProfileKeys::AppGaugeVarioSpeedToFly, settings.show_speed_to_fly); Get(ProfileKeys::AppGaugeVarioAvgText, settings.show_average); Get(ProfileKeys::AppGaugeVarioMc, settings.show_mc); Get(ProfileKeys::AppGaugeVarioBugs, settings.show_bugs); Get(ProfileKeys::AppGaugeVarioBallast, settings.show_ballast); Get(ProfileKeys::AppGaugeVarioGross, settings.show_gross); Get(ProfileKeys::AppAveNeedle, settings.show_average_needle); } void Profile::Load(TrafficSettings &settings) { Get(ProfileKeys::EnableFLARMGauge, settings.enable_gauge); Get(ProfileKeys::AutoCloseFlarmDialog, settings.auto_close_dialog); Get(ProfileKeys::FlarmAutoZoom, settings.auto_zoom); Get(ProfileKeys::FlarmNorthUp, settings.north_up); GetEnum(ProfileKeys::FlarmLocation, settings.gauge_location); } void Profile::Load(DialogSettings &settings) { GetEnum(ProfileKeys::AppTextInputStyle, settings.text_input_style); GetEnum(ProfileKeys::AppDialogTabStyle, settings.tab_style); Get(ProfileKeys::UserLevel, settings.expert); } void Profile::Load(VarioSoundSettings &settings) { Get(ProfileKeys::SoundAudioVario, settings.enabled); Get(ProfileKeys::SoundVolume, settings.volume); Get(ProfileKeys::VarioDeadBandEnabled, settings.dead_band_enabled); Get(ProfileKeys::VarioMinFrequency, settings.min_frequency); Get(ProfileKeys::VarioZeroFrequency, settings.zero_frequency); Get(ProfileKeys::VarioMaxFrequency, settings.max_frequency); Get(ProfileKeys::VarioMinPeriod, settings.min_period_ms); Get(ProfileKeys::VarioMaxPeriod, settings.max_period_ms); Get(ProfileKeys::VarioDeadBandMin, settings.min_dead); Get(ProfileKeys::VarioDeadBandMax, settings.max_dead); } void Profile::Load(SoundSettings &settings) { Get(ProfileKeys::SoundTask, settings.sound_task_enabled); Get(ProfileKeys::SoundModes, settings.sound_modes_enabled); Get(ProfileKeys::SoundDeadband, settings.sound_deadband); Load(settings.vario); } void Profile::Load(UISettings &settings) { Load(settings.display); Get(ProfileKeys::MenuTimeout, settings.menu_timeout); #ifndef GNAV Get(ProfileKeys::UseCustomFonts, settings.custom_fonts); #endif Get(ProfileKeys::EnableTAGauge, settings.enable_thermal_assistant_gauge); GetEnum(ProfileKeys::AppStatusMessageAlignment, settings.popup_message_position); GetEnum(ProfileKeys::HapticFeedback, settings.haptic_feedback); GetEnum(ProfileKeys::LatLonUnits, settings.coordinate_format); LoadUnits(settings.units); Load(settings.map); Load(settings.info_boxes); Load(settings.vario); Load(settings.traffic); Load(settings.pages); Load(settings.dialog); Load(settings.sound); }
onkelhotte/test
src/Profile/UIProfile.cpp
C++
gpl-2.0
4,308
/*++ BUILD Version: 0001 // Increment this if a change has global effects Copyright (c) Microsoft Corporation. All rights reserved. Module Name: ntddndis.h Abstract: This is the include file that defines all constants and types for accessing the Network driver interface device. Author: NDIS/ATM Development Team Revision History: added the correct values for NDIS 3.0. added Pnp IoCTLs and structures added general co ndis oids. added PnP and PM OIDs. --*/ #ifndef _NTDDNDIS_ #define _NTDDNDIS_ #if _MSC_VER > 1000 #pragma once #endif #ifdef __cplusplus extern "C" { #endif // // Device Name - this string is the name of the device. It is the name // that should be passed to NtOpenFile when accessing the device. // // Note: For devices that support multiple units, it should be suffixed // with the Ascii representation of the unit number. // #define DD_NDIS_DEVICE_NAME "\\Device\\UNKNOWN" // // NtDeviceIoControlFile IoControlCode values for this device. // // Warning: Remember that the low two bits of the code specify how the // buffers are passed to the driver! // #define _NDIS_CONTROL_CODE(request,method) \ CTL_CODE(FILE_DEVICE_PHYSICAL_NETCARD, request, method, FILE_ANY_ACCESS) #define IOCTL_NDIS_QUERY_GLOBAL_STATS _NDIS_CONTROL_CODE(0, METHOD_OUT_DIRECT) #define IOCTL_NDIS_QUERY_ALL_STATS _NDIS_CONTROL_CODE(1, METHOD_OUT_DIRECT) #define IOCTL_NDIS_DO_PNP_OPERATION _NDIS_CONTROL_CODE(2, METHOD_BUFFERED) #define IOCTL_NDIS_QUERY_SELECTED_STATS _NDIS_CONTROL_CODE(3, METHOD_OUT_DIRECT) #define IOCTL_NDIS_ENUMERATE_INTERFACES _NDIS_CONTROL_CODE(4, METHOD_BUFFERED) #define IOCTL_NDIS_ADD_TDI_DEVICE _NDIS_CONTROL_CODE(5, METHOD_BUFFERED) #define IOCTL_NDIS_GET_LOG_DATA _NDIS_CONTROL_CODE(7, METHOD_OUT_DIRECT) #define IOCTL_NDIS_GET_VERSION _NDIS_CONTROL_CODE(8, METHOD_BUFFERED) #define IOCTL_NDIS_RESERVED7 _NDIS_CONTROL_CODE(0xF, METHOD_OUT_DIRECT) // // NtDeviceIoControlFile InputBuffer/OutputBuffer record structures for // this device. // // // This is the type of an NDIS OID value. // typedef ULONG NDIS_OID, *PNDIS_OID; // // IOCTL_NDIS_QUERY_ALL_STATS returns a sequence of these, packed // together. This structure is unaligned because not all statistics // have a length that is a ULONG multiple. // typedef UNALIGNED struct _NDIS_STATISTICS_VALUE { NDIS_OID Oid; ULONG DataLength; UCHAR Data[1]; // variable length } NDIS_STATISTICS_VALUE, *PNDIS_STATISTICS_VALUE; // // Structure used to define a self-contained variable data structure // typedef struct _NDIS_VAR_DATA_DESC { USHORT Length; // # of octects of data USHORT MaximumLength; // # of octects available ULONG_PTR Offset; // Offset of data relative to the descriptor } NDIS_VAR_DATA_DESC, *PNDIS_VAR_DATA_DESC; #ifndef GUID_DEFINED #include <guiddef.h> #endif // !GUID_DEFINED // // General Objects // // // Required OIDs // #define OID_GEN_SUPPORTED_LIST 0x00010101 #define OID_GEN_HARDWARE_STATUS 0x00010102 #define OID_GEN_MEDIA_SUPPORTED 0x00010103 #define OID_GEN_MEDIA_IN_USE 0x00010104 #define OID_GEN_MAXIMUM_LOOKAHEAD 0x00010105 #define OID_GEN_MAXIMUM_FRAME_SIZE 0x00010106 #define OID_GEN_LINK_SPEED 0x00010107 #define OID_GEN_TRANSMIT_BUFFER_SPACE 0x00010108 #define OID_GEN_RECEIVE_BUFFER_SPACE 0x00010109 #define OID_GEN_TRANSMIT_BLOCK_SIZE 0x0001010A #define OID_GEN_RECEIVE_BLOCK_SIZE 0x0001010B #define OID_GEN_VENDOR_ID 0x0001010C #define OID_GEN_VENDOR_DESCRIPTION 0x0001010D #define OID_GEN_CURRENT_PACKET_FILTER 0x0001010E #define OID_GEN_CURRENT_LOOKAHEAD 0x0001010F #define OID_GEN_DRIVER_VERSION 0x00010110 #define OID_GEN_MAXIMUM_TOTAL_SIZE 0x00010111 #define OID_GEN_PROTOCOL_OPTIONS 0x00010112 #define OID_GEN_MAC_OPTIONS 0x00010113 #define OID_GEN_MEDIA_CONNECT_STATUS 0x00010114 #define OID_GEN_MAXIMUM_SEND_PACKETS 0x00010115 // // Optional OIDs // #define OID_GEN_VENDOR_DRIVER_VERSION 0x00010116 #define OID_GEN_SUPPORTED_GUIDS 0x00010117 #define OID_GEN_NETWORK_LAYER_ADDRESSES 0x00010118 // Set only #define OID_GEN_TRANSPORT_HEADER_OFFSET 0x00010119 // Set only #define OID_GEN_MACHINE_NAME 0x0001021A #define OID_GEN_RNDIS_CONFIG_PARAMETER 0x0001021B // Set only #define OID_GEN_VLAN_ID 0x0001021C #define OID_GEN_MEDIA_CAPABILITIES 0x00010201 #define OID_GEN_PHYSICAL_MEDIUM 0x00010202 // // Required statistics // #define OID_GEN_XMIT_OK 0x00020101 #define OID_GEN_RCV_OK 0x00020102 #define OID_GEN_XMIT_ERROR 0x00020103 #define OID_GEN_RCV_ERROR 0x00020104 #define OID_GEN_RCV_NO_BUFFER 0x00020105 // // Optional statistics // #define OID_GEN_DIRECTED_BYTES_XMIT 0x00020201 #define OID_GEN_DIRECTED_FRAMES_XMIT 0x00020202 #define OID_GEN_MULTICAST_BYTES_XMIT 0x00020203 #define OID_GEN_MULTICAST_FRAMES_XMIT 0x00020204 #define OID_GEN_BROADCAST_BYTES_XMIT 0x00020205 #define OID_GEN_BROADCAST_FRAMES_XMIT 0x00020206 #define OID_GEN_DIRECTED_BYTES_RCV 0x00020207 #define OID_GEN_DIRECTED_FRAMES_RCV 0x00020208 #define OID_GEN_MULTICAST_BYTES_RCV 0x00020209 #define OID_GEN_MULTICAST_FRAMES_RCV 0x0002020A #define OID_GEN_BROADCAST_BYTES_RCV 0x0002020B #define OID_GEN_BROADCAST_FRAMES_RCV 0x0002020C #define OID_GEN_RCV_CRC_ERROR 0x0002020D #define OID_GEN_TRANSMIT_QUEUE_LENGTH 0x0002020E #define OID_GEN_GET_TIME_CAPS 0x0002020F #define OID_GEN_GET_NETCARD_TIME 0x00020210 #define OID_GEN_NETCARD_LOAD 0x00020211 #define OID_GEN_DEVICE_PROFILE 0x00020212 // // The following is exported by NDIS itself and is only queryable. It returns // the time in milliseconds a driver took to initialize. // #define OID_GEN_INIT_TIME_MS 0x00020213 #define OID_GEN_RESET_COUNTS 0x00020214 #define OID_GEN_MEDIA_SENSE_COUNTS 0x00020215 #define OID_GEN_FRIENDLY_NAME 0x00020216 #define OID_GEN_MINIPORT_INFO 0x00020217 #define OID_GEN_RESET_VERIFY_PARAMETERS 0x00020218 // // These are connection-oriented general OIDs. // These replace the above OIDs for connection-oriented media. // #define OID_GEN_CO_SUPPORTED_LIST OID_GEN_SUPPORTED_LIST #define OID_GEN_CO_HARDWARE_STATUS OID_GEN_HARDWARE_STATUS #define OID_GEN_CO_MEDIA_SUPPORTED OID_GEN_MEDIA_SUPPORTED #define OID_GEN_CO_MEDIA_IN_USE OID_GEN_MEDIA_IN_USE #define OID_GEN_CO_LINK_SPEED OID_GEN_LINK_SPEED #define OID_GEN_CO_VENDOR_ID OID_GEN_VENDOR_ID #define OID_GEN_CO_VENDOR_DESCRIPTION OID_GEN_VENDOR_DESCRIPTION #define OID_GEN_CO_DRIVER_VERSION OID_GEN_DRIVER_VERSION #define OID_GEN_CO_PROTOCOL_OPTIONS OID_GEN_PROTOCOL_OPTIONS #define OID_GEN_CO_MAC_OPTIONS OID_GEN_MAC_OPTIONS #define OID_GEN_CO_MEDIA_CONNECT_STATUS OID_GEN_MEDIA_CONNECT_STATUS #define OID_GEN_CO_VENDOR_DRIVER_VERSION OID_GEN_VENDOR_DRIVER_VERSION #define OID_GEN_CO_SUPPORTED_GUIDS OID_GEN_SUPPORTED_GUIDS #define OID_GEN_CO_GET_TIME_CAPS OID_GEN_GET_TIME_CAPS #define OID_GEN_CO_GET_NETCARD_TIME OID_GEN_GET_NETCARD_TIME #define OID_GEN_CO_MINIMUM_LINK_SPEED 0x00020120 // // These are connection-oriented statistics OIDs. // #define OID_GEN_CO_XMIT_PDUS_OK OID_GEN_XMIT_OK #define OID_GEN_CO_RCV_PDUS_OK OID_GEN_RCV_OK #define OID_GEN_CO_XMIT_PDUS_ERROR OID_GEN_XMIT_ERROR #define OID_GEN_CO_RCV_PDUS_ERROR OID_GEN_RCV_ERROR #define OID_GEN_CO_RCV_PDUS_NO_BUFFER OID_GEN_RCV_NO_BUFFER #define OID_GEN_CO_RCV_CRC_ERROR OID_GEN_RCV_CRC_ERROR #define OID_GEN_CO_TRANSMIT_QUEUE_LENGTH OID_GEN_TRANSMIT_QUEUE_LENGTH #define OID_GEN_CO_BYTES_XMIT OID_GEN_DIRECTED_BYTES_XMIT #define OID_GEN_CO_BYTES_RCV OID_GEN_DIRECTED_BYTES_RCV #define OID_GEN_CO_NETCARD_LOAD OID_GEN_NETCARD_LOAD #define OID_GEN_CO_DEVICE_PROFILE OID_GEN_DEVICE_PROFILE #define OID_GEN_CO_BYTES_XMIT_OUTSTANDING 0x00020221 // // 802.3 Objects (Ethernet) // #define OID_802_3_PERMANENT_ADDRESS 0x01010101 #define OID_802_3_CURRENT_ADDRESS 0x01010102 #define OID_802_3_MULTICAST_LIST 0x01010103 #define OID_802_3_MAXIMUM_LIST_SIZE 0x01010104 #define OID_802_3_MAC_OPTIONS 0x01010105 #define NDIS_802_3_MAC_OPTION_PRIORITY 0x00000001 #define OID_802_3_RCV_ERROR_ALIGNMENT 0x01020101 #define OID_802_3_XMIT_ONE_COLLISION 0x01020102 #define OID_802_3_XMIT_MORE_COLLISIONS 0x01020103 #define OID_802_3_XMIT_DEFERRED 0x01020201 #define OID_802_3_XMIT_MAX_COLLISIONS 0x01020202 #define OID_802_3_RCV_OVERRUN 0x01020203 #define OID_802_3_XMIT_UNDERRUN 0x01020204 #define OID_802_3_XMIT_HEARTBEAT_FAILURE 0x01020205 #define OID_802_3_XMIT_TIMES_CRS_LOST 0x01020206 #define OID_802_3_XMIT_LATE_COLLISIONS 0x01020207 // // 802.5 Objects (Token-Ring) // #define OID_802_5_PERMANENT_ADDRESS 0x02010101 #define OID_802_5_CURRENT_ADDRESS 0x02010102 #define OID_802_5_CURRENT_FUNCTIONAL 0x02010103 #define OID_802_5_CURRENT_GROUP 0x02010104 #define OID_802_5_LAST_OPEN_STATUS 0x02010105 #define OID_802_5_CURRENT_RING_STATUS 0x02010106 #define OID_802_5_CURRENT_RING_STATE 0x02010107 #define OID_802_5_LINE_ERRORS 0x02020101 #define OID_802_5_LOST_FRAMES 0x02020102 #define OID_802_5_BURST_ERRORS 0x02020201 #define OID_802_5_AC_ERRORS 0x02020202 #define OID_802_5_ABORT_DELIMETERS 0x02020203 #define OID_802_5_FRAME_COPIED_ERRORS 0x02020204 #define OID_802_5_FREQUENCY_ERRORS 0x02020205 #define OID_802_5_TOKEN_ERRORS 0x02020206 #define OID_802_5_INTERNAL_ERRORS 0x02020207 // // FDDI Objects // #define OID_FDDI_LONG_PERMANENT_ADDR 0x03010101 #define OID_FDDI_LONG_CURRENT_ADDR 0x03010102 #define OID_FDDI_LONG_MULTICAST_LIST 0x03010103 #define OID_FDDI_LONG_MAX_LIST_SIZE 0x03010104 #define OID_FDDI_SHORT_PERMANENT_ADDR 0x03010105 #define OID_FDDI_SHORT_CURRENT_ADDR 0x03010106 #define OID_FDDI_SHORT_MULTICAST_LIST 0x03010107 #define OID_FDDI_SHORT_MAX_LIST_SIZE 0x03010108 #define OID_FDDI_ATTACHMENT_TYPE 0x03020101 #define OID_FDDI_UPSTREAM_NODE_LONG 0x03020102 #define OID_FDDI_DOWNSTREAM_NODE_LONG 0x03020103 #define OID_FDDI_FRAME_ERRORS 0x03020104 #define OID_FDDI_FRAMES_LOST 0x03020105 #define OID_FDDI_RING_MGT_STATE 0x03020106 #define OID_FDDI_LCT_FAILURES 0x03020107 #define OID_FDDI_LEM_REJECTS 0x03020108 #define OID_FDDI_LCONNECTION_STATE 0x03020109 #define OID_FDDI_SMT_STATION_ID 0x03030201 #define OID_FDDI_SMT_OP_VERSION_ID 0x03030202 #define OID_FDDI_SMT_HI_VERSION_ID 0x03030203 #define OID_FDDI_SMT_LO_VERSION_ID 0x03030204 #define OID_FDDI_SMT_MANUFACTURER_DATA 0x03030205 #define OID_FDDI_SMT_USER_DATA 0x03030206 #define OID_FDDI_SMT_MIB_VERSION_ID 0x03030207 #define OID_FDDI_SMT_MAC_CT 0x03030208 #define OID_FDDI_SMT_NON_MASTER_CT 0x03030209 #define OID_FDDI_SMT_MASTER_CT 0x0303020A #define OID_FDDI_SMT_AVAILABLE_PATHS 0x0303020B #define OID_FDDI_SMT_CONFIG_CAPABILITIES 0x0303020C #define OID_FDDI_SMT_CONFIG_POLICY 0x0303020D #define OID_FDDI_SMT_CONNECTION_POLICY 0x0303020E #define OID_FDDI_SMT_T_NOTIFY 0x0303020F #define OID_FDDI_SMT_STAT_RPT_POLICY 0x03030210 #define OID_FDDI_SMT_TRACE_MAX_EXPIRATION 0x03030211 #define OID_FDDI_SMT_PORT_INDEXES 0x03030212 #define OID_FDDI_SMT_MAC_INDEXES 0x03030213 #define OID_FDDI_SMT_BYPASS_PRESENT 0x03030214 #define OID_FDDI_SMT_ECM_STATE 0x03030215 #define OID_FDDI_SMT_CF_STATE 0x03030216 #define OID_FDDI_SMT_HOLD_STATE 0x03030217 #define OID_FDDI_SMT_REMOTE_DISCONNECT_FLAG 0x03030218 #define OID_FDDI_SMT_STATION_STATUS 0x03030219 #define OID_FDDI_SMT_PEER_WRAP_FLAG 0x0303021A #define OID_FDDI_SMT_MSG_TIME_STAMP 0x0303021B #define OID_FDDI_SMT_TRANSITION_TIME_STAMP 0x0303021C #define OID_FDDI_SMT_SET_COUNT 0x0303021D #define OID_FDDI_SMT_LAST_SET_STATION_ID 0x0303021E #define OID_FDDI_MAC_FRAME_STATUS_FUNCTIONS 0x0303021F #define OID_FDDI_MAC_BRIDGE_FUNCTIONS 0x03030220 #define OID_FDDI_MAC_T_MAX_CAPABILITY 0x03030221 #define OID_FDDI_MAC_TVX_CAPABILITY 0x03030222 #define OID_FDDI_MAC_AVAILABLE_PATHS 0x03030223 #define OID_FDDI_MAC_CURRENT_PATH 0x03030224 #define OID_FDDI_MAC_UPSTREAM_NBR 0x03030225 #define OID_FDDI_MAC_DOWNSTREAM_NBR 0x03030226 #define OID_FDDI_MAC_OLD_UPSTREAM_NBR 0x03030227 #define OID_FDDI_MAC_OLD_DOWNSTREAM_NBR 0x03030228 #define OID_FDDI_MAC_DUP_ADDRESS_TEST 0x03030229 #define OID_FDDI_MAC_REQUESTED_PATHS 0x0303022A #define OID_FDDI_MAC_DOWNSTREAM_PORT_TYPE 0x0303022B #define OID_FDDI_MAC_INDEX 0x0303022C #define OID_FDDI_MAC_SMT_ADDRESS 0x0303022D #define OID_FDDI_MAC_LONG_GRP_ADDRESS 0x0303022E #define OID_FDDI_MAC_SHORT_GRP_ADDRESS 0x0303022F #define OID_FDDI_MAC_T_REQ 0x03030230 #define OID_FDDI_MAC_T_NEG 0x03030231 #define OID_FDDI_MAC_T_MAX 0x03030232 #define OID_FDDI_MAC_TVX_VALUE 0x03030233 #define OID_FDDI_MAC_T_PRI0 0x03030234 #define OID_FDDI_MAC_T_PRI1 0x03030235 #define OID_FDDI_MAC_T_PRI2 0x03030236 #define OID_FDDI_MAC_T_PRI3 0x03030237 #define OID_FDDI_MAC_T_PRI4 0x03030238 #define OID_FDDI_MAC_T_PRI5 0x03030239 #define OID_FDDI_MAC_T_PRI6 0x0303023A #define OID_FDDI_MAC_FRAME_CT 0x0303023B #define OID_FDDI_MAC_COPIED_CT 0x0303023C #define OID_FDDI_MAC_TRANSMIT_CT 0x0303023D #define OID_FDDI_MAC_TOKEN_CT 0x0303023E #define OID_FDDI_MAC_ERROR_CT 0x0303023F #define OID_FDDI_MAC_LOST_CT 0x03030240 #define OID_FDDI_MAC_TVX_EXPIRED_CT 0x03030241 #define OID_FDDI_MAC_NOT_COPIED_CT 0x03030242 #define OID_FDDI_MAC_LATE_CT 0x03030243 #define OID_FDDI_MAC_RING_OP_CT 0x03030244 #define OID_FDDI_MAC_FRAME_ERROR_THRESHOLD 0x03030245 #define OID_FDDI_MAC_FRAME_ERROR_RATIO 0x03030246 #define OID_FDDI_MAC_NOT_COPIED_THRESHOLD 0x03030247 #define OID_FDDI_MAC_NOT_COPIED_RATIO 0x03030248 #define OID_FDDI_MAC_RMT_STATE 0x03030249 #define OID_FDDI_MAC_DA_FLAG 0x0303024A #define OID_FDDI_MAC_UNDA_FLAG 0x0303024B #define OID_FDDI_MAC_FRAME_ERROR_FLAG 0x0303024C #define OID_FDDI_MAC_NOT_COPIED_FLAG 0x0303024D #define OID_FDDI_MAC_MA_UNITDATA_AVAILABLE 0x0303024E #define OID_FDDI_MAC_HARDWARE_PRESENT 0x0303024F #define OID_FDDI_MAC_MA_UNITDATA_ENABLE 0x03030250 #define OID_FDDI_PATH_INDEX 0x03030251 #define OID_FDDI_PATH_RING_LATENCY 0x03030252 #define OID_FDDI_PATH_TRACE_STATUS 0x03030253 #define OID_FDDI_PATH_SBA_PAYLOAD 0x03030254 #define OID_FDDI_PATH_SBA_OVERHEAD 0x03030255 #define OID_FDDI_PATH_CONFIGURATION 0x03030256 #define OID_FDDI_PATH_T_R_MODE 0x03030257 #define OID_FDDI_PATH_SBA_AVAILABLE 0x03030258 #define OID_FDDI_PATH_TVX_LOWER_BOUND 0x03030259 #define OID_FDDI_PATH_T_MAX_LOWER_BOUND 0x0303025A #define OID_FDDI_PATH_MAX_T_REQ 0x0303025B #define OID_FDDI_PORT_MY_TYPE 0x0303025C #define OID_FDDI_PORT_NEIGHBOR_TYPE 0x0303025D #define OID_FDDI_PORT_CONNECTION_POLICIES 0x0303025E #define OID_FDDI_PORT_MAC_INDICATED 0x0303025F #define OID_FDDI_PORT_CURRENT_PATH 0x03030260 #define OID_FDDI_PORT_REQUESTED_PATHS 0x03030261 #define OID_FDDI_PORT_MAC_PLACEMENT 0x03030262 #define OID_FDDI_PORT_AVAILABLE_PATHS 0x03030263 #define OID_FDDI_PORT_MAC_LOOP_TIME 0x03030264 #define OID_FDDI_PORT_PMD_CLASS 0x03030265 #define OID_FDDI_PORT_CONNECTION_CAPABILITIES 0x03030266 #define OID_FDDI_PORT_INDEX 0x03030267 #define OID_FDDI_PORT_MAINT_LS 0x03030268 #define OID_FDDI_PORT_BS_FLAG 0x03030269 #define OID_FDDI_PORT_PC_LS 0x0303026A #define OID_FDDI_PORT_EB_ERROR_CT 0x0303026B #define OID_FDDI_PORT_LCT_FAIL_CT 0x0303026C #define OID_FDDI_PORT_LER_ESTIMATE 0x0303026D #define OID_FDDI_PORT_LEM_REJECT_CT 0x0303026E #define OID_FDDI_PORT_LEM_CT 0x0303026F #define OID_FDDI_PORT_LER_CUTOFF 0x03030270 #define OID_FDDI_PORT_LER_ALARM 0x03030271 #define OID_FDDI_PORT_CONNNECT_STATE 0x03030272 #define OID_FDDI_PORT_PCM_STATE 0x03030273 #define OID_FDDI_PORT_PC_WITHHOLD 0x03030274 #define OID_FDDI_PORT_LER_FLAG 0x03030275 #define OID_FDDI_PORT_HARDWARE_PRESENT 0x03030276 #define OID_FDDI_SMT_STATION_ACTION 0x03030277 #define OID_FDDI_PORT_ACTION 0x03030278 #define OID_FDDI_IF_DESCR 0x03030279 #define OID_FDDI_IF_TYPE 0x0303027A #define OID_FDDI_IF_MTU 0x0303027B #define OID_FDDI_IF_SPEED 0x0303027C #define OID_FDDI_IF_PHYS_ADDRESS 0x0303027D #define OID_FDDI_IF_ADMIN_STATUS 0x0303027E #define OID_FDDI_IF_OPER_STATUS 0x0303027F #define OID_FDDI_IF_LAST_CHANGE 0x03030280 #define OID_FDDI_IF_IN_OCTETS 0x03030281 #define OID_FDDI_IF_IN_UCAST_PKTS 0x03030282 #define OID_FDDI_IF_IN_NUCAST_PKTS 0x03030283 #define OID_FDDI_IF_IN_DISCARDS 0x03030284 #define OID_FDDI_IF_IN_ERRORS 0x03030285 #define OID_FDDI_IF_IN_UNKNOWN_PROTOS 0x03030286 #define OID_FDDI_IF_OUT_OCTETS 0x03030287 #define OID_FDDI_IF_OUT_UCAST_PKTS 0x03030288 #define OID_FDDI_IF_OUT_NUCAST_PKTS 0x03030289 #define OID_FDDI_IF_OUT_DISCARDS 0x0303028A #define OID_FDDI_IF_OUT_ERRORS 0x0303028B #define OID_FDDI_IF_OUT_QLEN 0x0303028C #define OID_FDDI_IF_SPECIFIC 0x0303028D // // WAN objects // #define OID_WAN_PERMANENT_ADDRESS 0x04010101 #define OID_WAN_CURRENT_ADDRESS 0x04010102 #define OID_WAN_QUALITY_OF_SERVICE 0x04010103 #define OID_WAN_PROTOCOL_TYPE 0x04010104 #define OID_WAN_MEDIUM_SUBTYPE 0x04010105 #define OID_WAN_HEADER_FORMAT 0x04010106 #define OID_WAN_GET_INFO 0x04010107 #define OID_WAN_SET_LINK_INFO 0x04010108 #define OID_WAN_GET_LINK_INFO 0x04010109 #define OID_WAN_LINE_COUNT 0x0401010A #define OID_WAN_PROTOCOL_CAPS 0x0401010B #define OID_WAN_GET_BRIDGE_INFO 0x0401020A #define OID_WAN_SET_BRIDGE_INFO 0x0401020B #define OID_WAN_GET_COMP_INFO 0x0401020C #define OID_WAN_SET_COMP_INFO 0x0401020D #define OID_WAN_GET_STATS_INFO 0x0401020E // // These are connection-oriented WAN OIDs. // These replace the above OIDs for CoNDIS WAN Miniports // #define OID_WAN_CO_GET_INFO 0x04010180 #define OID_WAN_CO_SET_LINK_INFO 0x04010181 #define OID_WAN_CO_GET_LINK_INFO 0x04010182 #define OID_WAN_CO_GET_COMP_INFO 0x04010280 #define OID_WAN_CO_SET_COMP_INFO 0x04010281 #define OID_WAN_CO_GET_STATS_INFO 0x04010282 // // LocalTalk objects // #define OID_LTALK_CURRENT_NODE_ID 0x05010102 #define OID_LTALK_IN_BROADCASTS 0x05020101 #define OID_LTALK_IN_LENGTH_ERRORS 0x05020102 #define OID_LTALK_OUT_NO_HANDLERS 0x05020201 #define OID_LTALK_COLLISIONS 0x05020202 #define OID_LTALK_DEFERS 0x05020203 #define OID_LTALK_NO_DATA_ERRORS 0x05020204 #define OID_LTALK_RANDOM_CTS_ERRORS 0x05020205 #define OID_LTALK_FCS_ERRORS 0x05020206 // // Arcnet objects // #define OID_ARCNET_PERMANENT_ADDRESS 0x06010101 #define OID_ARCNET_CURRENT_ADDRESS 0x06010102 #define OID_ARCNET_RECONFIGURATIONS 0x06020201 // // TAPI objects // #define OID_TAPI_ACCEPT 0x07030101 #define OID_TAPI_ANSWER 0x07030102 #define OID_TAPI_CLOSE 0x07030103 #define OID_TAPI_CLOSE_CALL 0x07030104 #define OID_TAPI_CONDITIONAL_MEDIA_DETECTION 0x07030105 #define OID_TAPI_CONFIG_DIALOG 0x07030106 #define OID_TAPI_DEV_SPECIFIC 0x07030107 #define OID_TAPI_DIAL 0x07030108 #define OID_TAPI_DROP 0x07030109 #define OID_TAPI_GET_ADDRESS_CAPS 0x0703010A #define OID_TAPI_GET_ADDRESS_ID 0x0703010B #define OID_TAPI_GET_ADDRESS_STATUS 0x0703010C #define OID_TAPI_GET_CALL_ADDRESS_ID 0x0703010D #define OID_TAPI_GET_CALL_INFO 0x0703010E #define OID_TAPI_GET_CALL_STATUS 0x0703010F #define OID_TAPI_GET_DEV_CAPS 0x07030110 #define OID_TAPI_GET_DEV_CONFIG 0x07030111 #define OID_TAPI_GET_EXTENSION_ID 0x07030112 #define OID_TAPI_GET_ID 0x07030113 #define OID_TAPI_GET_LINE_DEV_STATUS 0x07030114 #define OID_TAPI_MAKE_CALL 0x07030115 #define OID_TAPI_NEGOTIATE_EXT_VERSION 0x07030116 #define OID_TAPI_OPEN 0x07030117 #define OID_TAPI_PROVIDER_INITIALIZE 0x07030118 #define OID_TAPI_PROVIDER_SHUTDOWN 0x07030119 #define OID_TAPI_SECURE_CALL 0x0703011A #define OID_TAPI_SELECT_EXT_VERSION 0x0703011B #define OID_TAPI_SEND_USER_USER_INFO 0x0703011C #define OID_TAPI_SET_APP_SPECIFIC 0x0703011D #define OID_TAPI_SET_CALL_PARAMS 0x0703011E #define OID_TAPI_SET_DEFAULT_MEDIA_DETECTION 0x0703011F #define OID_TAPI_SET_DEV_CONFIG 0x07030120 #define OID_TAPI_SET_MEDIA_MODE 0x07030121 #define OID_TAPI_SET_STATUS_MESSAGES 0x07030122 #define OID_TAPI_GATHER_DIGITS 0x07030123 #define OID_TAPI_MONITOR_DIGITS 0x07030124 // // ATM Connection Oriented OIDs // #define OID_ATM_SUPPORTED_VC_RATES 0x08010101 #define OID_ATM_SUPPORTED_SERVICE_CATEGORY 0x08010102 #define OID_ATM_SUPPORTED_AAL_TYPES 0x08010103 #define OID_ATM_HW_CURRENT_ADDRESS 0x08010104 #define OID_ATM_MAX_ACTIVE_VCS 0x08010105 #define OID_ATM_MAX_ACTIVE_VCI_BITS 0x08010106 #define OID_ATM_MAX_ACTIVE_VPI_BITS 0x08010107 #define OID_ATM_MAX_AAL0_PACKET_SIZE 0x08010108 #define OID_ATM_MAX_AAL1_PACKET_SIZE 0x08010109 #define OID_ATM_MAX_AAL34_PACKET_SIZE 0x0801010A #define OID_ATM_MAX_AAL5_PACKET_SIZE 0x0801010B #define OID_ATM_SIGNALING_VPIVCI 0x08010201 #define OID_ATM_ASSIGNED_VPI 0x08010202 #define OID_ATM_ACQUIRE_ACCESS_NET_RESOURCES 0x08010203 #define OID_ATM_RELEASE_ACCESS_NET_RESOURCES 0x08010204 #define OID_ATM_ILMI_VPIVCI 0x08010205 #define OID_ATM_DIGITAL_BROADCAST_VPIVCI 0x08010206 #define OID_ATM_GET_NEAREST_FLOW 0x08010207 #define OID_ATM_ALIGNMENT_REQUIRED 0x08010208 #define OID_ATM_LECS_ADDRESS 0x08010209 #define OID_ATM_SERVICE_ADDRESS 0x0801020A #define OID_ATM_CALL_PROCEEDING 0x0801020B // UNI 4.0 #define OID_ATM_CALL_ALERTING 0x0801020C // UNI 4.0 #define OID_ATM_PARTY_ALERTING 0x0801020D // UNI 4.0 #define OID_ATM_CALL_NOTIFY 0x0801020E // UNI 4.0 #define OID_ATM_MY_IP_NM_ADDRESS 0x0801020F // // ATM specific statistics OIDs. // #define OID_ATM_RCV_CELLS_OK 0x08020101 #define OID_ATM_XMIT_CELLS_OK 0x08020102 #define OID_ATM_RCV_CELLS_DROPPED 0x08020103 #define OID_ATM_RCV_INVALID_VPI_VCI 0x08020201 #define OID_ATM_CELLS_HEC_ERROR 0x08020202 #define OID_ATM_RCV_REASSEMBLY_ERROR 0x08020203 // // PCCA (Wireless) object // // // All WirelessWAN devices must support the following OIDs // #define OID_WW_GEN_NETWORK_TYPES_SUPPORTED 0x09010101 #define OID_WW_GEN_NETWORK_TYPE_IN_USE 0x09010102 #define OID_WW_GEN_HEADER_FORMATS_SUPPORTED 0x09010103 #define OID_WW_GEN_HEADER_FORMAT_IN_USE 0x09010104 #define OID_WW_GEN_INDICATION_REQUEST 0x09010105 #define OID_WW_GEN_DEVICE_INFO 0x09010106 #define OID_WW_GEN_OPERATION_MODE 0x09010107 #define OID_WW_GEN_LOCK_STATUS 0x09010108 #define OID_WW_GEN_DISABLE_TRANSMITTER 0x09010109 #define OID_WW_GEN_NETWORK_ID 0x0901010A #define OID_WW_GEN_PERMANENT_ADDRESS 0x0901010B #define OID_WW_GEN_CURRENT_ADDRESS 0x0901010C #define OID_WW_GEN_SUSPEND_DRIVER 0x0901010D #define OID_WW_GEN_BASESTATION_ID 0x0901010E #define OID_WW_GEN_CHANNEL_ID 0x0901010F #define OID_WW_GEN_ENCRYPTION_SUPPORTED 0x09010110 #define OID_WW_GEN_ENCRYPTION_IN_USE 0x09010111 #define OID_WW_GEN_ENCRYPTION_STATE 0x09010112 #define OID_WW_GEN_CHANNEL_QUALITY 0x09010113 #define OID_WW_GEN_REGISTRATION_STATUS 0x09010114 #define OID_WW_GEN_RADIO_LINK_SPEED 0x09010115 #define OID_WW_GEN_LATENCY 0x09010116 #define OID_WW_GEN_BATTERY_LEVEL 0x09010117 #define OID_WW_GEN_EXTERNAL_POWER 0x09010118 // // These are optional // #define OID_WW_GEN_PING_ADDRESS 0x09010201 #define OID_WW_GEN_RSSI 0x09010202 #define OID_WW_GEN_SIM_STATUS 0x09010203 #define OID_WW_GEN_ENABLE_SIM_PIN 0x09010204 #define OID_WW_GEN_CHANGE_SIM_PIN 0x09010205 #define OID_WW_GEN_SIM_PUK 0x09010206 #define OID_WW_GEN_SIM_EXCEPTION 0x09010207 // // Network Dependent OIDs - Mobitex: // #define OID_WW_MBX_SUBADDR 0x09050101 // OID 0x09050102 is reserved and may not be used #define OID_WW_MBX_FLEXLIST 0x09050103 #define OID_WW_MBX_GROUPLIST 0x09050104 #define OID_WW_MBX_TRAFFIC_AREA 0x09050105 #define OID_WW_MBX_LIVE_DIE 0x09050106 #define OID_WW_MBX_TEMP_DEFAULTLIST 0x09050107 // // Network Dependent OIDs - Pinpoint: // // // The following Pin Point characteristics have been deprecated by the // PCCA and are considered reserved values. They are include here only for // historical purposes and should not be used // #define OID_WW_PIN_LOC_AUTHORIZE 0x09090101 #define OID_WW_PIN_LAST_LOCATION 0x09090102 #define OID_WW_PIN_LOC_FIX 0x09090103 // // Network Dependent - CDPD: // #define OID_WW_CDPD_SPNI 0x090D0101 #define OID_WW_CDPD_WASI 0x090D0102 #define OID_WW_CDPD_AREA_COLOR 0x090D0103 #define OID_WW_CDPD_TX_POWER_LEVEL 0x090D0104 #define OID_WW_CDPD_EID 0x090D0105 #define OID_WW_CDPD_HEADER_COMPRESSION 0x090D0106 #define OID_WW_CDPD_DATA_COMPRESSION 0x090D0107 #define OID_WW_CDPD_CHANNEL_SELECT 0x090D0108 #define OID_WW_CDPD_CHANNEL_STATE 0x090D0109 #define OID_WW_CDPD_NEI 0x090D010A #define OID_WW_CDPD_NEI_STATE 0x090D010B #define OID_WW_CDPD_SERVICE_PROVIDER_IDENTIFIER 0x090D010C #define OID_WW_CDPD_SLEEP_MODE 0x090D010D // // At the request of the PCCA STD-201 Annex C working group the following OID // value has been superceeded by more specific objects. Its value is reserved by // the PCCA,is included here for historical purposes only, and should not be // used. // #define OID_WW_CDPD_CIRCUIT_SWITCHED 0x090D010E #define OID_WW_CDPD_TEI 0x090D010F #define OID_WW_CDPD_RSSI 0x090D0110 // // CDPD Circuit Switched objects // #define OID_WW_CDPD_CS_SERVICE_PREFERENCE 0x090D0111 #define OID_WW_CDPD_CS_SERVICE_STATUS 0x090D0112 #define OID_WW_CDPD_CS_INFO 0x090D0113 #define OID_WW_CDPD_CS_SUSPEND 0x090D0114 #define OID_WW_CDPD_CS_DEFAULT_DIAL_CODE 0x090D0115 #define OID_WW_CDPD_CS_CALLBACK 0x090D0116 #define OID_WW_CDPD_CS_SID_LIST 0x090D0117 #define OID_WW_CDPD_CS_CONFIGURATION 0x090D0118 // // Network Dependent - Ardis: // // // At the request of Ardis these OID value have been superceeded. Their // functionality has been merged with the DataTAC objects. Therefore // these values are reserved by the PCCA, are include here for // historical purposes only, and should not be used. // #define OID_WW_ARD_SNDCP 0x09110101 #define OID_WW_ARD_TMLY_MSG 0x09110102 #define OID_WW_ARD_DATAGRAM 0x09110103 // // Network Dependent - DataTac: // #define OID_WW_TAC_COMPRESSION 0x09150101 // // At the request of Motorola, the following two OID values have been // superceeded. Their functionality has been subsumed by other more specific // DataTac objects and should not be used. These values are reserved by the // PCCA and are include here only for historical purposes only. // #define OID_WW_TAC_SET_CONFIG 0x09150102 #define OID_WW_TAC_GET_STATUS 0x09150103 #define OID_WW_TAC_USER_HEADER 0x09150104 // // DataTAC characteristic object values // #define OID_WW_TAC_UNIQUE_SDU_TAG 0x09150105 #define OID_WW_TAC_SEND_COMMAND 0x09150106 #define OID_WW_TAC_GET_RESPONSE 0x09150107 #define OID_WW_TAC_DISABLE_RECEIVER 0x09150108 #define OID_WW_TAC_ANTENNA_MODE 0x09150109 #define OID_WW_TAC_FLUSH_DATA 0x0915010A #define OID_WW_TAC_SHUTDOWN_DEVICE 0x0915010B #define OID_WW_TAC_DEVICE_EXCEPTION 0x0915010C #define OID_WW_TAC_RECEIVE_EXCEPTION 0x0915010D #define OID_WW_TAC_BUFFER_EXCEPTION 0x0915010E #define OID_WW_TAC_BATTERY_EXCEPTION 0x0915010F #define OID_WW_TAC_TRANSMITTER_KEYED 0x09150110 #define OID_WW_TAC_SYSTEM_TABLE 0x09150111 #define OID_WW_TAC_CHANNEL_TABLE 0x09150112 #define OID_WW_TAC_DCHANNEL_TABLE 0x09150113 #define OID_WW_TAC_RECEIVE_QUEUE_COUNT 0x09150114 // // DataTac statistic object value // #define OID_WW_TAC_STATISTICS 0x09160101 // // Network Dependent - Metricom: // #define OID_WW_MET_FUNCTION 0x09190101 // // IEEE 802.11 OIDs // #define OID_802_11_BSSID 0x0D010101 #define OID_802_11_SSID 0x0D010102 #define OID_802_11_NETWORK_TYPES_SUPPORTED 0x0D010203 #define OID_802_11_NETWORK_TYPE_IN_USE 0x0D010204 #define OID_802_11_TX_POWER_LEVEL 0x0D010205 #define OID_802_11_RSSI 0x0D010206 #define OID_802_11_RSSI_TRIGGER 0x0D010207 #define OID_802_11_INFRASTRUCTURE_MODE 0x0D010108 #define OID_802_11_FRAGMENTATION_THRESHOLD 0x0D010209 #define OID_802_11_RTS_THRESHOLD 0x0D01020A #define OID_802_11_NUMBER_OF_ANTENNAS 0x0D01020B #define OID_802_11_RX_ANTENNA_SELECTED 0x0D01020C #define OID_802_11_TX_ANTENNA_SELECTED 0x0D01020D #define OID_802_11_SUPPORTED_RATES 0x0D01020E #define OID_802_11_DESIRED_RATES 0x0D010210 #define OID_802_11_CONFIGURATION 0x0D010211 #define OID_802_11_STATISTICS 0x0D020212 #define OID_802_11_ADD_WEP 0x0D010113 #define OID_802_11_REMOVE_WEP 0x0D010114 #define OID_802_11_DISASSOCIATE 0x0D010115 #define OID_802_11_POWER_MODE 0x0D010216 #define OID_802_11_BSSID_LIST 0x0D010217 #define OID_802_11_AUTHENTICATION_MODE 0x0D010118 #define OID_802_11_PRIVACY_FILTER 0x0D010119 #define OID_802_11_BSSID_LIST_SCAN 0x0D01011A #define OID_802_11_WEP_STATUS 0x0D01011B // Renamed to reflect better the extended set of encryption status #define OID_802_11_ENCRYPTION_STATUS OID_802_11_WEP_STATUS #define OID_802_11_RELOAD_DEFAULTS 0x0D01011C // Added to allow key mapping and default keys #define OID_802_11_ADD_KEY 0x0D01011D #define OID_802_11_REMOVE_KEY 0x0D01011E #define OID_802_11_ASSOCIATION_INFORMATION 0x0D01011F #define OID_802_11_TEST 0x0D010120 #define OID_802_11_MEDIA_STREAM_MODE 0x0D010121 // // IEEE 802.11 Structures and definitions // // new types for Media Specific Indications #define NDIS_802_11_LENGTH_SSID 32 #define NDIS_802_11_LENGTH_RATES 8 #define NDIS_802_11_LENGTH_RATES_EX 16 typedef enum _NDIS_802_11_STATUS_TYPE { Ndis802_11StatusType_Authentication, Ndis802_11StatusType_MediaStreamMode, Ndis802_11StatusTypeMax // not a real type, defined as an upper bound } NDIS_802_11_STATUS_TYPE, *PNDIS_802_11_STATUS_TYPE; typedef UCHAR NDIS_802_11_MAC_ADDRESS[6]; typedef struct _NDIS_802_11_STATUS_INDICATION { NDIS_802_11_STATUS_TYPE StatusType; } NDIS_802_11_STATUS_INDICATION, *PNDIS_802_11_STATUS_INDICATION; // mask for authentication/integrity fields #define NDIS_802_11_AUTH_REQUEST_AUTH_FIELDS 0x0f #define NDIS_802_11_AUTH_REQUEST_REAUTH 0x01 #define NDIS_802_11_AUTH_REQUEST_KEYUPDATE 0x02 #define NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR 0x06 #define NDIS_802_11_AUTH_REQUEST_GROUP_ERROR 0x0E typedef struct _NDIS_802_11_AUTHENTICATION_REQUEST { ULONG Length; // Length of structure NDIS_802_11_MAC_ADDRESS Bssid; ULONG Flags; } NDIS_802_11_AUTHENTICATION_REQUEST, *PNDIS_802_11_AUTHENTICATION_REQUEST; // Added new types for OFDM 5G and 2.4G typedef enum _NDIS_802_11_NETWORK_TYPE { Ndis802_11FH, Ndis802_11DS, Ndis802_11OFDM5, Ndis802_11OFDM24, Ndis802_11NetworkTypeMax // not a real type, defined as an upper bound } NDIS_802_11_NETWORK_TYPE, *PNDIS_802_11_NETWORK_TYPE; typedef struct _NDIS_802_11_NETWORK_TYPE_LIST { ULONG NumberOfItems; // in list below, at least 1 NDIS_802_11_NETWORK_TYPE NetworkType [1]; } NDIS_802_11_NETWORK_TYPE_LIST, *PNDIS_802_11_NETWORK_TYPE_LIST; typedef enum _NDIS_802_11_POWER_MODE { Ndis802_11PowerModeCAM, Ndis802_11PowerModeMAX_PSP, Ndis802_11PowerModeFast_PSP, Ndis802_11PowerModeMax // not a real mode, defined as an upper bound } NDIS_802_11_POWER_MODE, *PNDIS_802_11_POWER_MODE; typedef ULONG NDIS_802_11_TX_POWER_LEVEL; // in milliwatts // // Received Signal Strength Indication // typedef LONG NDIS_802_11_RSSI; // in dBm typedef struct _NDIS_802_11_CONFIGURATION_FH { ULONG Length; // Length of structure ULONG HopPattern; // As defined by 802.11, MSB set ULONG HopSet; // to one if non-802.11 ULONG DwellTime; // units are Kusec } NDIS_802_11_CONFIGURATION_FH, *PNDIS_802_11_CONFIGURATION_FH; typedef struct _NDIS_802_11_CONFIGURATION { ULONG Length; // Length of structure ULONG BeaconPeriod; // units are Kusec ULONG ATIMWindow; // units are Kusec ULONG DSConfig; // Frequency, units are kHz NDIS_802_11_CONFIGURATION_FH FHConfig; } NDIS_802_11_CONFIGURATION, *PNDIS_802_11_CONFIGURATION; typedef struct _NDIS_802_11_STATISTICS { ULONG Length; // Length of structure LARGE_INTEGER TransmittedFragmentCount; LARGE_INTEGER MulticastTransmittedFrameCount; LARGE_INTEGER FailedCount; LARGE_INTEGER RetryCount; LARGE_INTEGER MultipleRetryCount; LARGE_INTEGER RTSSuccessCount; LARGE_INTEGER RTSFailureCount; LARGE_INTEGER ACKFailureCount; LARGE_INTEGER FrameDuplicateCount; LARGE_INTEGER ReceivedFragmentCount; LARGE_INTEGER MulticastReceivedFrameCount; LARGE_INTEGER FCSErrorCount; } NDIS_802_11_STATISTICS, *PNDIS_802_11_STATISTICS; typedef ULONG NDIS_802_11_KEY_INDEX; typedef ULONGLONG NDIS_802_11_KEY_RSC; // Key mapping keys require a BSSID typedef struct _NDIS_802_11_KEY { ULONG Length; // Length of this structure ULONG KeyIndex; ULONG KeyLength; // length of key in bytes NDIS_802_11_MAC_ADDRESS BSSID; NDIS_802_11_KEY_RSC KeyRSC; UCHAR KeyMaterial[1]; // variable length depending on above field } NDIS_802_11_KEY, *PNDIS_802_11_KEY; typedef struct _NDIS_802_11_REMOVE_KEY { ULONG Length; // Length of this structure ULONG KeyIndex; NDIS_802_11_MAC_ADDRESS BSSID; } NDIS_802_11_REMOVE_KEY, *PNDIS_802_11_REMOVE_KEY; typedef struct _NDIS_802_11_WEP { ULONG Length; // Length of this structure ULONG KeyIndex; // 0 is the per-client key, 1-N are the // global keys ULONG KeyLength; // length of key in bytes UCHAR KeyMaterial[1]; // variable length depending on above field } NDIS_802_11_WEP, *PNDIS_802_11_WEP; typedef enum _NDIS_802_11_NETWORK_INFRASTRUCTURE { Ndis802_11IBSS, Ndis802_11Infrastructure, Ndis802_11AutoUnknown, Ndis802_11InfrastructureMax // Not a real value, defined as upper bound } NDIS_802_11_NETWORK_INFRASTRUCTURE, *PNDIS_802_11_NETWORK_INFRASTRUCTURE; // Add new authentication modes typedef enum _NDIS_802_11_AUTHENTICATION_MODE { Ndis802_11AuthModeOpen, Ndis802_11AuthModeShared, Ndis802_11AuthModeAutoSwitch, Ndis802_11AuthModeWPA, Ndis802_11AuthModeWPAPSK, Ndis802_11AuthModeWPANone, Ndis802_11AuthModeMax // Not a real mode, defined as upper bound } NDIS_802_11_AUTHENTICATION_MODE, *PNDIS_802_11_AUTHENTICATION_MODE; typedef UCHAR NDIS_802_11_RATES[NDIS_802_11_LENGTH_RATES]; // Set of 8 data rates typedef UCHAR NDIS_802_11_RATES_EX[NDIS_802_11_LENGTH_RATES_EX]; // Set of 16 data rates typedef struct _NDIS_802_11_SSID { ULONG SsidLength; // length of SSID field below, in bytes; // this can be zero. UCHAR Ssid[NDIS_802_11_LENGTH_SSID]; // SSID information field } NDIS_802_11_SSID, *PNDIS_802_11_SSID; typedef struct _NDIS_WLAN_BSSID { ULONG Length; // Length of this structure NDIS_802_11_MAC_ADDRESS MacAddress; // BSSID UCHAR Reserved[2]; NDIS_802_11_SSID Ssid; // SSID ULONG Privacy; // WEP encryption requirement NDIS_802_11_RSSI Rssi; // receive signal // strength in dBm NDIS_802_11_NETWORK_TYPE NetworkTypeInUse; NDIS_802_11_CONFIGURATION Configuration; NDIS_802_11_NETWORK_INFRASTRUCTURE InfrastructureMode; NDIS_802_11_RATES SupportedRates; } NDIS_WLAN_BSSID, *PNDIS_WLAN_BSSID; typedef struct _NDIS_802_11_BSSID_LIST { ULONG NumberOfItems; // in list below, at least 1 NDIS_WLAN_BSSID Bssid[1]; } NDIS_802_11_BSSID_LIST, *PNDIS_802_11_BSSID_LIST; // Added Capabilities, IELength and IEs for each BSSID typedef struct _NDIS_WLAN_BSSID_EX { ULONG Length; // Length of this structure NDIS_802_11_MAC_ADDRESS MacAddress; // BSSID UCHAR Reserved[2]; NDIS_802_11_SSID Ssid; // SSID ULONG Privacy; // WEP encryption requirement NDIS_802_11_RSSI Rssi; // receive signal // strength in dBm NDIS_802_11_NETWORK_TYPE NetworkTypeInUse; NDIS_802_11_CONFIGURATION Configuration; NDIS_802_11_NETWORK_INFRASTRUCTURE InfrastructureMode; NDIS_802_11_RATES_EX SupportedRates; ULONG IELength; UCHAR IEs[1]; } NDIS_WLAN_BSSID_EX, *PNDIS_WLAN_BSSID_EX; typedef struct _NDIS_802_11_BSSID_LIST_EX { ULONG NumberOfItems; // in list below, at least 1 NDIS_WLAN_BSSID_EX Bssid[1]; } NDIS_802_11_BSSID_LIST_EX, *PNDIS_802_11_BSSID_LIST_EX; typedef struct _NDIS_802_11_FIXED_IEs { UCHAR Timestamp[8]; USHORT BeaconInterval; USHORT Capabilities; } NDIS_802_11_FIXED_IEs, *PNDIS_802_11_FIXED_IEs; typedef struct _NDIS_802_11_VARIABLE_IEs { UCHAR ElementID; UCHAR Length; // Number of bytes in data field UCHAR data[1]; } NDIS_802_11_VARIABLE_IEs, *PNDIS_802_11_VARIABLE_IEs; typedef ULONG NDIS_802_11_FRAGMENTATION_THRESHOLD; typedef ULONG NDIS_802_11_RTS_THRESHOLD; typedef ULONG NDIS_802_11_ANTENNA; typedef enum _NDIS_802_11_PRIVACY_FILTER { Ndis802_11PrivFilterAcceptAll, Ndis802_11PrivFilter8021xWEP } NDIS_802_11_PRIVACY_FILTER, *PNDIS_802_11_PRIVACY_FILTER; // Added new encryption types // Also aliased typedef to new name typedef enum _NDIS_802_11_WEP_STATUS { Ndis802_11WEPEnabled, Ndis802_11Encryption1Enabled = Ndis802_11WEPEnabled, Ndis802_11WEPDisabled, Ndis802_11EncryptionDisabled = Ndis802_11WEPDisabled, Ndis802_11WEPKeyAbsent, Ndis802_11Encryption1KeyAbsent = Ndis802_11WEPKeyAbsent, Ndis802_11WEPNotSupported, Ndis802_11EncryptionNotSupported = Ndis802_11WEPNotSupported, Ndis802_11Encryption2Enabled, Ndis802_11Encryption2KeyAbsent, Ndis802_11Encryption3Enabled, Ndis802_11Encryption3KeyAbsent } NDIS_802_11_WEP_STATUS, *PNDIS_802_11_WEP_STATUS, NDIS_802_11_ENCRYPTION_STATUS, *PNDIS_802_11_ENCRYPTION_STATUS; typedef enum _NDIS_802_11_RELOAD_DEFAULTS { Ndis802_11ReloadWEPKeys } NDIS_802_11_RELOAD_DEFAULTS, *PNDIS_802_11_RELOAD_DEFAULTS; #define NDIS_802_11_AI_REQFI_CAPABILITIES 1 #define NDIS_802_11_AI_REQFI_LISTENINTERVAL 2 #define NDIS_802_11_AI_REQFI_CURRENTAPADDRESS 4 #define NDIS_802_11_AI_RESFI_CAPABILITIES 1 #define NDIS_802_11_AI_RESFI_STATUSCODE 2 #define NDIS_802_11_AI_RESFI_ASSOCIATIONID 4 typedef struct _NDIS_802_11_AI_REQFI { USHORT Capabilities; USHORT ListenInterval; NDIS_802_11_MAC_ADDRESS CurrentAPAddress; } NDIS_802_11_AI_REQFI, *PNDIS_802_11_AI_REQFI; typedef struct _NDIS_802_11_AI_RESFI { USHORT Capabilities; USHORT StatusCode; USHORT AssociationId; } NDIS_802_11_AI_RESFI, *PNDIS_802_11_AI_RESFI; typedef struct _NDIS_802_11_ASSOCIATION_INFORMATION { ULONG Length; USHORT AvailableRequestFixedIEs; NDIS_802_11_AI_REQFI RequestFixedIEs; ULONG RequestIELength; ULONG OffsetRequestIEs; USHORT AvailableResponseFixedIEs; NDIS_802_11_AI_RESFI ResponseFixedIEs; ULONG ResponseIELength; ULONG OffsetResponseIEs; } NDIS_802_11_ASSOCIATION_INFORMATION, *PNDIS_802_11_ASSOCIATION_INFORMATION; typedef struct _NDIS_802_11_AUTHENTICATION_EVENT { NDIS_802_11_STATUS_INDICATION Status; NDIS_802_11_AUTHENTICATION_REQUEST Request[1]; } NDIS_802_11_AUTHENTICATION_EVENT, *PNDIS_802_11_AUTHENTICATION_EVENT; typedef struct _NDIS_802_11_TEST { ULONG Length; ULONG Type; union { NDIS_802_11_AUTHENTICATION_EVENT AuthenticationEvent; NDIS_802_11_RSSI RssiTrigger; }; } NDIS_802_11_TEST, *PNDIS_802_11_TEST; // 802.11 Media stream constraints, associated with OID_802_11_MEDIA_STREAM_MODE typedef enum _NDIS_802_11_MEDIA_STREAM_MODE { Ndis802_11MediaStreamOff, Ndis802_11MediaStreamOn, } NDIS_802_11_MEDIA_STREAM_MODE, *PNDIS_802_11_MEDIA_STREAM_MODE; // // IRDA objects // #define OID_IRDA_RECEIVING 0x0A010100 #define OID_IRDA_TURNAROUND_TIME 0x0A010101 #define OID_IRDA_SUPPORTED_SPEEDS 0x0A010102 #define OID_IRDA_LINK_SPEED 0x0A010103 #define OID_IRDA_MEDIA_BUSY 0x0A010104 #define OID_IRDA_EXTRA_RCV_BOFS 0x0A010200 #define OID_IRDA_RATE_SNIFF 0x0A010201 #define OID_IRDA_UNICAST_LIST 0x0A010202 #define OID_IRDA_MAX_UNICAST_LIST_SIZE 0x0A010203 #define OID_IRDA_MAX_RECEIVE_WINDOW_SIZE 0x0A010204 #define OID_IRDA_MAX_SEND_WINDOW_SIZE 0x0A010205 #define OID_IRDA_RESERVED1 0x0A01020A // The range between OID_IRDA_RESERVED1 #define OID_IRDA_RESERVED2 0x0A01020F // and OID_IRDA_RESERVED2 is reserved // // BPC OIDs // #define OID_BPC_ADAPTER_CAPS 0x0B010100 #define OID_BPC_DEVICES 0x0B010101 #define OID_BPC_DEVICE_CAPS 0x0B010102 #define OID_BPC_DEVICE_SETTINGS 0x0B010103 #define OID_BPC_CONNECTION_STATUS 0x0B010104 #define OID_BPC_ADDRESS_COMPARE 0x0B010105 #define OID_BPC_PROGRAM_GUIDE 0x0B010106 #define OID_BPC_LAST_ERROR 0x0B020107 #define OID_BPC_POOL 0x0B010108 #define OID_BPC_PROVIDER_SPECIFIC 0x0B020109 #define OID_BPC_ADAPTER_SPECIFIC 0x0B02010A #define OID_BPC_CONNECT 0x0B01010B #define OID_BPC_COMMIT 0x0B01010C #define OID_BPC_DISCONNECT 0x0B01010D #define OID_BPC_CONNECTION_ENABLE 0x0B01010E #define OID_BPC_POOL_RESERVE 0x0B01010F #define OID_BPC_POOL_RETURN 0x0B010110 #define OID_BPC_FORCE_RECEIVE 0x0B010111 #define OID_BPC_LAST 0x0B020112 // // IEEE1394 mandatory general OIDs. // #define OID_1394_LOCAL_NODE_INFO 0x0C010101 #define OID_1394_VC_INFO 0x0C010102 // // The following OIDs are not specific to a media. // // // These are objects for Connection-oriented media call-managers. // #define OID_CO_ADD_PVC 0xFE000001 #define OID_CO_DELETE_PVC 0xFE000002 #define OID_CO_GET_CALL_INFORMATION 0xFE000003 #define OID_CO_ADD_ADDRESS 0xFE000004 #define OID_CO_DELETE_ADDRESS 0xFE000005 #define OID_CO_GET_ADDRESSES 0xFE000006 #define OID_CO_ADDRESS_CHANGE 0xFE000007 #define OID_CO_SIGNALING_ENABLED 0xFE000008 #define OID_CO_SIGNALING_DISABLED 0xFE000009 #define OID_CO_AF_CLOSE 0xFE00000A // // Objects for call-managers and MCMs that support TAPI access. // #define OID_CO_TAPI_CM_CAPS 0xFE001001 #define OID_CO_TAPI_LINE_CAPS 0xFE001002 #define OID_CO_TAPI_ADDRESS_CAPS 0xFE001003 #define OID_CO_TAPI_TRANSLATE_TAPI_CALLPARAMS 0xFE001004 #define OID_CO_TAPI_TRANSLATE_NDIS_CALLPARAMS 0xFE001005 #define OID_CO_TAPI_TRANSLATE_TAPI_SAP 0xFE001006 #define OID_CO_TAPI_GET_CALL_DIAGNOSTICS 0xFE001007 #define OID_CO_TAPI_REPORT_DIGITS 0xFE001008 #define OID_CO_TAPI_DONT_REPORT_DIGITS 0xFE001009 // // PnP and PM OIDs // #define OID_PNP_CAPABILITIES 0xFD010100 #define OID_PNP_SET_POWER 0xFD010101 #define OID_PNP_QUERY_POWER 0xFD010102 #define OID_PNP_ADD_WAKE_UP_PATTERN 0xFD010103 #define OID_PNP_REMOVE_WAKE_UP_PATTERN 0xFD010104 #define OID_PNP_WAKE_UP_PATTERN_LIST 0xFD010105 #define OID_PNP_ENABLE_WAKE_UP 0xFD010106 // // PnP/PM Statistics (Optional). // #define OID_PNP_WAKE_UP_OK 0xFD020200 #define OID_PNP_WAKE_UP_ERROR 0xFD020201 // // The following bits are defined for OID_PNP_ENABLE_WAKE_UP // #define NDIS_PNP_WAKE_UP_MAGIC_PACKET 0x00000001 #define NDIS_PNP_WAKE_UP_PATTERN_MATCH 0x00000002 #define NDIS_PNP_WAKE_UP_LINK_CHANGE 0x00000004 // // TCP/IP OIDs // #define OID_TCP_TASK_OFFLOAD 0xFC010201 #define OID_TCP_TASK_IPSEC_ADD_SA 0xFC010202 #define OID_TCP_TASK_IPSEC_DELETE_SA 0xFC010203 #define OID_TCP_SAN_SUPPORT 0xFC010204 #define OID_TCP_TASK_IPSEC_ADD_UDPESP_SA 0xFC010205 #define OID_TCP_TASK_IPSEC_DELETE_UDPESP_SA 0xFC010206 // // Defines for FFP // #define OID_FFP_SUPPORT 0xFC010210 #define OID_FFP_FLUSH 0xFC010211 #define OID_FFP_CONTROL 0xFC010212 #define OID_FFP_PARAMS 0xFC010213 #define OID_FFP_DATA 0xFC010214 #define OID_FFP_DRIVER_STATS 0xFC020210 #define OID_FFP_ADAPTER_STATS 0xFC020211 // // Defines for QOS // #define OID_QOS_TC_SUPPORTED 0xFB010100 #define OID_QOS_REMAINING_BANDWIDTH 0xFB010101 #define OID_QOS_ISSLOW_FLOW 0xFB010102 #define OID_QOS_BESTEFFORT_BANDWIDTH 0xFB010103 #define OID_QOS_LATENCY 0xFB010104 #define OID_QOS_FLOW_IP_CONFORMING 0xFB010105 #define OID_QOS_FLOW_COUNT 0xFB010106 #define OID_QOS_NON_BESTEFFORT_LIMIT 0xFB010107 #define OID_QOS_SCHEDULING_PROFILES_SUPPORTED 0xFB010108 #define OID_QOS_CURRENT_SCHEDULING_PROFILE 0xFB010109 #define OID_QOS_TIMER_RESOLUTION 0xFB01010A #define OID_QOS_STATISTICS_BUFFER 0xFB01010B #define OID_QOS_HIERARCHY_CLASS 0xFB01010C #define OID_QOS_FLOW_MODE 0xFB01010D #define OID_QOS_ISSLOW_FRAGMENT_SIZE 0xFB01010E #define OID_QOS_FLOW_IP_NONCONFORMING 0xFB01010F #define OID_QOS_FLOW_8021P_CONFORMING 0xFB010110 #define OID_QOS_FLOW_8021P_NONCONFORMING 0xFB010111 #define OID_QOS_ENABLE_AVG_STATS 0xFB010112 #define OID_QOS_ENABLE_WINDOW_ADJUSTMENT 0xFB010113 // // NDIS Proxy OID_GEN_CO_DEVICE_PROFILE structure. The optional OID and // this structure is a generic means of describing a CO device's // capabilites, and is used by the NDIS Proxy to construct a TAPI device // capabilities structure. // typedef struct NDIS_CO_DEVICE_PROFILE { NDIS_VAR_DATA_DESC DeviceDescription; // e.g. 'GigabitATMNet' NDIS_VAR_DATA_DESC DevSpecificInfo; // special features ULONG ulTAPISupplementaryPassThru;// reserved in NT5 ULONG ulAddressModes; ULONG ulNumAddresses; ULONG ulBearerModes; ULONG ulMaxTxRate; // bytes per second ULONG ulMinTxRate; // bytes per second ULONG ulMaxRxRate; // bytes per second ULONG ulMinRxRate; // bytes per second ULONG ulMediaModes; // // Tone/digit generation and recognition capabilities // ULONG ulGenerateToneModes; ULONG ulGenerateToneMaxNumFreq; ULONG ulGenerateDigitModes; ULONG ulMonitorToneMaxNumFreq; ULONG ulMonitorToneMaxNumEntries; ULONG ulMonitorDigitModes; ULONG ulGatherDigitsMinTimeout;// milliseconds ULONG ulGatherDigitsMaxTimeout;// milliseconds ULONG ulDevCapFlags; // Misc. capabilities ULONG ulMaxNumActiveCalls; // (This * ulMinRate) = total bandwidth (which may equal ulMaxRate) ULONG ulAnswerMode; // Effect of answering a new call when an // existing call is non-idle // // User-User info sizes allowed to accompany each operation // ULONG ulUUIAcceptSize; // bytes ULONG ulUUIAnswerSize; // bytes ULONG ulUUIMakeCallSize; // bytes ULONG ulUUIDropSize; // bytes ULONG ulUUISendUserUserInfoSize; // bytes ULONG ulUUICallInfoSize; // bytes } NDIS_CO_DEVICE_PROFILE, *PNDIS_CO_DEVICE_PROFILE; // // Structures for TCP IPSec. // typedef ULONG IPAddr, IPMask; typedef ULONG SPI_TYPE; typedef enum _OFFLOAD_OPERATION_E { AUTHENTICATE = 1, ENCRYPT } OFFLOAD_OPERATION_E; typedef struct _OFFLOAD_ALGO_INFO { ULONG algoIdentifier; ULONG algoKeylen; ULONG algoRounds; } OFFLOAD_ALGO_INFO, *POFFLOAD_ALGO_INFO; typedef enum _OFFLOAD_CONF_ALGO { OFFLOAD_IPSEC_CONF_NONE, OFFLOAD_IPSEC_CONF_DES, OFFLOAD_IPSEC_CONF_RESERVED, OFFLOAD_IPSEC_CONF_3_DES, OFFLOAD_IPSEC_CONF_MAX } OFFLOAD_CONF_ALGO; typedef enum _OFFLOAD_INTEGRITY_ALGO { OFFLOAD_IPSEC_INTEGRITY_NONE, OFFLOAD_IPSEC_INTEGRITY_MD5, OFFLOAD_IPSEC_INTEGRITY_SHA, OFFLOAD_IPSEC_INTEGRITY_MAX } OFFLOAD_INTEGRITY_ALGO; typedef struct _OFFLOAD_SECURITY_ASSOCIATION { OFFLOAD_OPERATION_E Operation; SPI_TYPE SPI; OFFLOAD_ALGO_INFO IntegrityAlgo; OFFLOAD_ALGO_INFO ConfAlgo; OFFLOAD_ALGO_INFO Reserved; } OFFLOAD_SECURITY_ASSOCIATION, *POFFLOAD_SECURITY_ASSOCIATION; #define OFFLOAD_MAX_SAS 3 #define OFFLOAD_INBOUND_SA 0x0001 #define OFFLOAD_OUTBOUND_SA 0x0002 typedef struct _OFFLOAD_IPSEC_ADD_SA { IPAddr SrcAddr; IPMask SrcMask; IPAddr DestAddr; IPMask DestMask; ULONG Protocol; USHORT SrcPort; USHORT DestPort; IPAddr SrcTunnelAddr; IPAddr DestTunnelAddr; USHORT Flags; SHORT NumSAs; OFFLOAD_SECURITY_ASSOCIATION SecAssoc[OFFLOAD_MAX_SAS]; HANDLE OffloadHandle; ULONG KeyLen; UCHAR KeyMat[1]; } OFFLOAD_IPSEC_ADD_SA, *POFFLOAD_IPSEC_ADD_SA; typedef struct _OFFLOAD_IPSEC_DELETE_SA { HANDLE OffloadHandle; } OFFLOAD_IPSEC_DELETE_SA, *POFFLOAD_IPSEC_DELETE_SA; typedef enum _UDP_ENCAP_TYPE { OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_IKE, OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_OTHER } UDP_ENCAP_TYPE, * PUDP_ENCAP_TYPE; typedef struct _OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_ENTRY { UDP_ENCAP_TYPE UdpEncapType; USHORT DstEncapPort; } OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_ENTRY, * POFFLOAD_IPSEC_UDPESP_ENCAPTYPE_ENTRY; typedef struct _OFFLOAD_IPSEC_ADD_UDPESP_SA { IPAddr SrcAddr; IPMask SrcMask; IPAddr DstAddr; IPMask DstMask; ULONG Protocol; USHORT SrcPort; USHORT DstPort; IPAddr SrcTunnelAddr; IPAddr DstTunnelAddr; USHORT Flags; SHORT NumSAs; OFFLOAD_SECURITY_ASSOCIATION SecAssoc[OFFLOAD_MAX_SAS]; HANDLE OffloadHandle; OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_ENTRY EncapTypeEntry; HANDLE EncapTypeEntryOffldHandle; ULONG KeyLen; UCHAR KeyMat[1]; } OFFLOAD_IPSEC_ADD_UDPESP_SA, * POFFLOAD_IPSEC_ADD_UDPESP_SA; typedef struct _OFFLOAD_IPSEC_DELETE_UDPESP_SA { HANDLE OffloadHandle; HANDLE EncapTypeEntryOffldHandle; } OFFLOAD_IPSEC_DELETE_UDPESP_SA, * POFFLOAD_IPSEC_DELETE_UDPESP_SA; // // Type to go with OID_GEN_VLAN_ID: the least significant 12 bits are // used as the VLAN ID (VID) per IEEE 802.1Q. Higher order bits are // reserved and must be set to 0. // typedef ULONG NDIS_VLAN_ID; // // Medium the Ndis Driver is running on (OID_GEN_MEDIA_SUPPORTED/ OID_GEN_MEDIA_IN_USE). // typedef enum _NDIS_MEDIUM { NdisMedium802_3, NdisMedium802_5, NdisMediumFddi, NdisMediumWan, NdisMediumLocalTalk, NdisMediumDix, // defined for convenience, not a real medium NdisMediumArcnetRaw, NdisMediumArcnet878_2, NdisMediumAtm, NdisMediumWirelessWan, NdisMediumIrda, NdisMediumBpc, NdisMediumCoWan, NdisMedium1394, NdisMediumInfiniBand, NdisMediumMax // Not a real medium, defined as an upper-bound } NDIS_MEDIUM, *PNDIS_MEDIUM; // // Physical Medium Type definitions. Used with OID_GEN_PHYSICAL_MEDIUM. // typedef enum _NDIS_PHYSICAL_MEDIUM { NdisPhysicalMediumUnspecified, NdisPhysicalMediumWirelessLan, NdisPhysicalMediumCableModem, NdisPhysicalMediumPhoneLine, NdisPhysicalMediumPowerLine, NdisPhysicalMediumDSL, // includes ADSL and UADSL (G.Lite) NdisPhysicalMediumFibreChannel, NdisPhysicalMedium1394, NdisPhysicalMediumWirelessWan, NdisPhysicalMediumNative802_11, NdisPhysicalMediumBluetooth, NdisPhysicalMediumMax // Not a real physical type, defined as an upper-bound } NDIS_PHYSICAL_MEDIUM, *PNDIS_PHYSICAL_MEDIUM; // // Protocol types supported by ndis. These values need to be consistent with ADDRESS_TYPE_XXX defined in TDI.H // #define NDIS_PROTOCOL_ID_DEFAULT 0x00 #define NDIS_PROTOCOL_ID_TCP_IP 0x02 #define NDIS_PROTOCOL_ID_IPX 0x06 #define NDIS_PROTOCOL_ID_NBF 0x07 #define NDIS_PROTOCOL_ID_MAX 0x0F #define NDIS_PROTOCOL_ID_MASK 0x0F // // The following is used with OID_GEN_TRANSPORT_HEADER_OFFSET to indicate the length of the layer-2 header // for packets sent by a particular protocol. // typedef struct _TRANSPORT_HEADER_OFFSET { USHORT ProtocolType; // The protocol that is sending this OID (NDIS_PROTOCOL_ID_XXX above) USHORT HeaderOffset; // The header offset } TRANSPORT_HEADER_OFFSET, *PTRANSPORT_HEADER_OFFSET; // // The structures below need to be consistent with TRANSPORT_ADDRESS structures in TDI.H // typedef struct _NETWORK_ADDRESS { USHORT AddressLength; // length in bytes of Address[] in this USHORT AddressType; // type of this address (NDIS_PROTOCOL_ID_XXX above) UCHAR Address[1]; // actually AddressLength bytes long } NETWORK_ADDRESS, *PNETWORK_ADDRESS; // // The following is used with OID_GEN_NETWORK_LAYER_ADDRESSES to set network layer addresses on an interface // typedef struct _NETWORK_ADDRESS_LIST { LONG AddressCount; // number of addresses following USHORT AddressType; // type of this address (NDIS_PROTOCOL_ID_XXX above) NETWORK_ADDRESS Address[1]; // actually AddressCount elements long } NETWORK_ADDRESS_LIST, *PNETWORK_ADDRESS_LIST; // // IP address - This must remain consistent with TDI_ADDRESS_IP in tdi.h // typedef struct _NETWORK_ADDRESS_IP { USHORT sin_port; ULONG in_addr; UCHAR sin_zero[8]; } NETWORK_ADDRESS_IP, *PNETWORK_ADDRESS_IP; #define NETWORK_ADDRESS_LENGTH_IP sizeof (NETWORK_ADDRESS_IP) // // IPX address - This must remain consistent with TDI_ADDRESS_IPX in tdi.h. // typedef struct _NETWORK_ADDRESS_IPX { ULONG NetworkAddress; UCHAR NodeAddress[6]; USHORT Socket; } NETWORK_ADDRESS_IPX, *PNETWORK_ADDRESS_IPX; #define NETWORK_ADDRESS_LENGTH_IPX sizeof (NETWORK_ADDRESS_IPX) // // Hardware status codes (OID_GEN_HARDWARE_STATUS). // typedef enum _NDIS_HARDWARE_STATUS { NdisHardwareStatusReady, NdisHardwareStatusInitializing, NdisHardwareStatusReset, NdisHardwareStatusClosing, NdisHardwareStatusNotReady } NDIS_HARDWARE_STATUS, *PNDIS_HARDWARE_STATUS; // // this is the type passed in the OID_GEN_GET_TIME_CAPS request // typedef struct _GEN_GET_TIME_CAPS { ULONG Flags; // Bits defined below ULONG ClockPrecision; } GEN_GET_TIME_CAPS, *PGEN_GET_TIME_CAPS; #define READABLE_LOCAL_CLOCK 0x00000001 #define CLOCK_NETWORK_DERIVED 0x00000002 #define CLOCK_PRECISION 0x00000004 #define RECEIVE_TIME_INDICATION_CAPABLE 0x00000008 #define TIMED_SEND_CAPABLE 0x00000010 #define TIME_STAMP_CAPABLE 0x00000020 // // this is the type passed in the OID_GEN_GET_NETCARD_TIME request // typedef struct _GEN_GET_NETCARD_TIME { ULONGLONG ReadTime; } GEN_GET_NETCARD_TIME, *PGEN_GET_NETCARD_TIME; // // NDIS PnP routines and definitions. // typedef struct _NDIS_PM_PACKET_PATTERN { ULONG Priority; // Importance of the given pattern. ULONG Reserved; // Context information for transports. ULONG MaskSize; // Size in bytes of the pattern mask. ULONG PatternOffset; // Offset from beginning of this // structure to the pattern bytes. ULONG PatternSize; // Size in bytes of the pattern. ULONG PatternFlags; // Flags (TBD). } NDIS_PM_PACKET_PATTERN, *PNDIS_PM_PACKET_PATTERN; // // The following structure defines the device power states. // typedef enum _NDIS_DEVICE_POWER_STATE { NdisDeviceStateUnspecified = 0, NdisDeviceStateD0, NdisDeviceStateD1, NdisDeviceStateD2, NdisDeviceStateD3, NdisDeviceStateMaximum } NDIS_DEVICE_POWER_STATE, *PNDIS_DEVICE_POWER_STATE; // // The following structure defines the wake-up capabilities of the device. // typedef struct _NDIS_PM_WAKE_UP_CAPABILITIES { NDIS_DEVICE_POWER_STATE MinMagicPacketWakeUp; NDIS_DEVICE_POWER_STATE MinPatternWakeUp; NDIS_DEVICE_POWER_STATE MinLinkChangeWakeUp; } NDIS_PM_WAKE_UP_CAPABILITIES, *PNDIS_PM_WAKE_UP_CAPABILITIES; // // the following flags define the -enabled- wake-up capabilities of the device // passed in the Flags field of NDIS_PNP_CAPABILITIES structure // #define NDIS_DEVICE_WAKE_UP_ENABLE 0x00000001 #define NDIS_DEVICE_WAKE_ON_PATTERN_MATCH_ENABLE 0x00000002 #define NDIS_DEVICE_WAKE_ON_MAGIC_PACKET_ENABLE 0x00000004 // // This structure defines general PnP capabilities of the miniport driver. // typedef struct _NDIS_PNP_CAPABILITIES { ULONG Flags; NDIS_PM_WAKE_UP_CAPABILITIES WakeUpCapabilities; } NDIS_PNP_CAPABILITIES, *PNDIS_PNP_CAPABILITIES; // // Defines the attachment types for FDDI (OID_FDDI_ATTACHMENT_TYPE). // typedef enum _NDIS_FDDI_ATTACHMENT_TYPE { NdisFddiTypeIsolated = 1, NdisFddiTypeLocalA, NdisFddiTypeLocalB, NdisFddiTypeLocalAB, NdisFddiTypeLocalS, NdisFddiTypeWrapA, NdisFddiTypeWrapB, NdisFddiTypeWrapAB, NdisFddiTypeWrapS, NdisFddiTypeCWrapA, NdisFddiTypeCWrapB, NdisFddiTypeCWrapS, NdisFddiTypeThrough } NDIS_FDDI_ATTACHMENT_TYPE, *PNDIS_FDDI_ATTACHMENT_TYPE; // // Defines the ring management states for FDDI (OID_FDDI_RING_MGT_STATE). // typedef enum _NDIS_FDDI_RING_MGT_STATE { NdisFddiRingIsolated = 1, NdisFddiRingNonOperational, NdisFddiRingOperational, NdisFddiRingDetect, NdisFddiRingNonOperationalDup, NdisFddiRingOperationalDup, NdisFddiRingDirected, NdisFddiRingTrace } NDIS_FDDI_RING_MGT_STATE, *PNDIS_FDDI_RING_MGT_STATE; // // Defines the Lconnection state for FDDI (OID_FDDI_LCONNECTION_STATE). // typedef enum _NDIS_FDDI_LCONNECTION_STATE { NdisFddiStateOff = 1, NdisFddiStateBreak, NdisFddiStateTrace, NdisFddiStateConnect, NdisFddiStateNext, NdisFddiStateSignal, NdisFddiStateJoin, NdisFddiStateVerify, NdisFddiStateActive, NdisFddiStateMaintenance } NDIS_FDDI_LCONNECTION_STATE, *PNDIS_FDDI_LCONNECTION_STATE; // // Defines the medium subtypes for WAN medium (OID_WAN_MEDIUM_SUBTYPE). // Sub-medium used only by connection-oriented WAN devices // i.e. NdisMediumWan, NdisMediumCoWan. // typedef enum _NDIS_WAN_MEDIUM_SUBTYPE { NdisWanMediumHub, NdisWanMediumX_25, NdisWanMediumIsdn, NdisWanMediumSerial, NdisWanMediumFrameRelay, NdisWanMediumAtm, NdisWanMediumSonet, NdisWanMediumSW56K, NdisWanMediumPPTP, NdisWanMediumL2TP, NdisWanMediumIrda, NdisWanMediumParallel, NdisWanMediumPppoe } NDIS_WAN_MEDIUM_SUBTYPE, *PNDIS_WAN_MEDIUM_SUBTYPE; // // Defines the header format for WAN medium (OID_WAN_HEADER_FORMAT). // typedef enum _NDIS_WAN_HEADER_FORMAT { NdisWanHeaderNative, // src/dest based on subtype, followed by NLPID NdisWanHeaderEthernet // emulation of ethernet header } NDIS_WAN_HEADER_FORMAT, *PNDIS_WAN_HEADER_FORMAT; // // Defines the line quality on a WAN line (OID_WAN_QUALITY_OF_SERVICE). // typedef enum _NDIS_WAN_QUALITY { NdisWanRaw, NdisWanErrorControl, NdisWanReliable } NDIS_WAN_QUALITY, *PNDIS_WAN_QUALITY; // // Defines a protocol's WAN specific capabilities (OID_WAN_PROTOCOL_CAPS). // typedef struct _NDIS_WAN_PROTOCOL_CAPS { IN ULONG Flags; IN ULONG Reserved; } NDIS_WAN_PROTOCOL_CAPS, *PNDIS_WAN_PROTOCOL_CAPS; // // Flags used in NDIS_WAN_PROTOCOL_CAPS // #define WAN_PROTOCOL_KEEPS_STATS 0x00000001 // // Defines the state of a token-ring adapter (OID_802_5_CURRENT_RING_STATE). // typedef enum _NDIS_802_5_RING_STATE { NdisRingStateOpened = 1, NdisRingStateClosed, NdisRingStateOpening, NdisRingStateClosing, NdisRingStateOpenFailure, NdisRingStateRingFailure } NDIS_802_5_RING_STATE, *PNDIS_802_5_RING_STATE; // // Defines the state of the LAN media // typedef enum _NDIS_MEDIA_STATE { NdisMediaStateConnected, NdisMediaStateDisconnected } NDIS_MEDIA_STATE, *PNDIS_MEDIA_STATE; // // The following is set on a per-packet basis as OOB data with NdisClass802_3Priority // typedef ULONG Priority_802_3; // 0-7 priority levels // // The following structure is used to query OID_GEN_CO_LINK_SPEED and // OID_GEN_CO_MINIMUM_LINK_SPEED. The first OID will return the current // link speed of the adapter. The second will return the minimum link speed // the adapter is capable of. // typedef struct _NDIS_CO_LINK_SPEED { ULONG Outbound; ULONG Inbound; } NDIS_CO_LINK_SPEED, *PNDIS_CO_LINK_SPEED; #ifndef _NDIS_ typedef int NDIS_STATUS, *PNDIS_STATUS; #endif // // Structure to be used for OID_GEN_SUPPORTED_GUIDS. // This structure describes an OID to GUID mapping. // Or a Status to GUID mapping. // When ndis receives a request for a give GUID it will // query the miniport with the supplied OID. // typedef struct _NDIS_GUID { GUID Guid; union { NDIS_OID Oid; NDIS_STATUS Status; }; ULONG Size; // Size of the data element. If the GUID // represents an array then this is the // size of an element in the array. // This is -1 for strings. ULONG Flags; } NDIS_GUID, *PNDIS_GUID; #define fNDIS_GUID_TO_OID 0x00000001 #define fNDIS_GUID_TO_STATUS 0x00000002 #define fNDIS_GUID_ANSI_STRING 0x00000004 #define fNDIS_GUID_UNICODE_STRING 0x00000008 #define fNDIS_GUID_ARRAY 0x00000010 #define fNDIS_GUID_ALLOW_READ 0x00000020 #define fNDIS_GUID_ALLOW_WRITE 0x00000040 // // Ndis Packet Filter Bits (OID_GEN_CURRENT_PACKET_FILTER). // #define NDIS_PACKET_TYPE_DIRECTED 0x00000001 #define NDIS_PACKET_TYPE_MULTICAST 0x00000002 #define NDIS_PACKET_TYPE_ALL_MULTICAST 0x00000004 #define NDIS_PACKET_TYPE_BROADCAST 0x00000008 #define NDIS_PACKET_TYPE_SOURCE_ROUTING 0x00000010 #define NDIS_PACKET_TYPE_PROMISCUOUS 0x00000020 #define NDIS_PACKET_TYPE_SMT 0x00000040 #define NDIS_PACKET_TYPE_ALL_LOCAL 0x00000080 #define NDIS_PACKET_TYPE_GROUP 0x00001000 #define NDIS_PACKET_TYPE_ALL_FUNCTIONAL 0x00002000 #define NDIS_PACKET_TYPE_FUNCTIONAL 0x00004000 #define NDIS_PACKET_TYPE_MAC_FRAME 0x00008000 // // Ndis Token-Ring Ring Status Codes (OID_802_5_CURRENT_RING_STATUS). // #define NDIS_RING_SIGNAL_LOSS 0x00008000 #define NDIS_RING_HARD_ERROR 0x00004000 #define NDIS_RING_SOFT_ERROR 0x00002000 #define NDIS_RING_TRANSMIT_BEACON 0x00001000 #define NDIS_RING_LOBE_WIRE_FAULT 0x00000800 #define NDIS_RING_AUTO_REMOVAL_ERROR 0x00000400 #define NDIS_RING_REMOVE_RECEIVED 0x00000200 #define NDIS_RING_COUNTER_OVERFLOW 0x00000100 #define NDIS_RING_SINGLE_STATION 0x00000080 #define NDIS_RING_RING_RECOVERY 0x00000040 // // Ndis protocol option bits (OID_GEN_PROTOCOL_OPTIONS). // #define NDIS_PROT_OPTION_ESTIMATED_LENGTH 0x00000001 #define NDIS_PROT_OPTION_NO_LOOPBACK 0x00000002 #define NDIS_PROT_OPTION_NO_RSVD_ON_RCVPKT 0x00000004 #define NDIS_PROT_OPTION_SEND_RESTRICTED 0x00000008 // // Ndis MAC option bits (OID_GEN_MAC_OPTIONS). // #define NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA 0x00000001 #define NDIS_MAC_OPTION_RECEIVE_SERIALIZED 0x00000002 #define NDIS_MAC_OPTION_TRANSFERS_NOT_PEND 0x00000004 #define NDIS_MAC_OPTION_NO_LOOPBACK 0x00000008 #define NDIS_MAC_OPTION_FULL_DUPLEX 0x00000010 #define NDIS_MAC_OPTION_EOTX_INDICATION 0x00000020 #define NDIS_MAC_OPTION_8021P_PRIORITY 0x00000040 #define NDIS_MAC_OPTION_SUPPORTS_MAC_ADDRESS_OVERWRITE 0x00000080 #define NDIS_MAC_OPTION_RECEIVE_AT_DPC 0x00000100 #define NDIS_MAC_OPTION_8021Q_VLAN 0x00000200 #define NDIS_MAC_OPTION_RESERVED 0x80000000 // // NDIS media capabilities bits (OID_GEN_MEDIA_CAPABILITIES). // #define NDIS_MEDIA_CAP_TRANSMIT 0x00000001 // Supports sending data #define NDIS_MEDIA_CAP_RECEIVE 0x00000002 // Supports receiving data // // NDIS MAC option bits for OID_GEN_CO_MAC_OPTIONS. // #define NDIS_CO_MAC_OPTION_DYNAMIC_LINK_SPEED 0x00000001 // // The following is set on a per-packet basis as OOB data with NdisClassIrdaPacketInfo // This is the per-packet info specified on a per-packet basis // typedef struct _NDIS_IRDA_PACKET_INFO { ULONG ExtraBOFs; ULONG MinTurnAroundTime; } NDIS_IRDA_PACKET_INFO, *PNDIS_IRDA_PACKET_INFO; #ifdef WIRELESS_WAN // // Wireless WAN structure definitions // // // currently defined Wireless network subtypes // typedef enum _NDIS_WW_NETWORK_TYPE { NdisWWGeneric, NdisWWMobitex, NdisWWPinpoint, NdisWWCDPD, NdisWWArdis, NdisWWDataTAC, NdisWWMetricom, NdisWWGSM, NdisWWCDMA, NdisWWTDMA, NdisWWAMPS, NdisWWInmarsat, NdisWWpACT, NdisWWFlex, NdisWWIDEN } NDIS_WW_NETWORK_TYPE; // // currently defined header formats // typedef enum _NDIS_WW_HEADER_FORMAT { NdisWWDIXEthernetFrames, NdisWWMPAKFrames, NdisWWRDLAPFrames, NdisWWMDC4800Frames, NdisWWNCLFrames } NDIS_WW_HEADER_FORMAT; // // currently defined encryption types // typedef enum _NDIS_WW_ENCRYPTION_TYPE { NdisWWUnknownEncryption = -1, NdisWWNoEncryption, NdisWWDefaultEncryption, NdisWWDESEncryption, NdisWWRC2Encryption, NdisWWRC4Encryption, NdisWWRC5Encryption } NDIS_WW_ENCRYPTION_TYPE, *PNDIS_WW_ENCRYPTION_TYPE; typedef enum _WW_ADDRESS_FORMAT { WW_IEEE_ADDRESS = 0, WW_MOBITEX_MAN_ADDRESS, WW_DATATAC_RDLAP_ADDRESS, WW_DATATAC_MDC4800_ADDRESS, WW_DATATAC_RESERVED, WW_IPv4_ADDRESS, WW_IPv6_ADDRESS, WW_PROPRIETARY_ADDRESS, } WW_ADDRESS_FORMAT; typedef enum _WW_GEN_SUM_EXCEPTION { SIM_STATUS_OK = 0, SIM_STATUS_ERROR, SIM_STATUS_MISSING, SIM_STATUS_NO_RESPONSE, SIM_STATUS_REMOVED, SIM_STATUS_CRYPT_ERROR, SIM_STATUS_AUTH_ERROR, SIM_STATUS_NEED_PIN, SIM_STATUS_NEED_PUK, SIM_STATUS_WRONG, } WW_GEN_SIM_EXCEPTION; // // OID_WW_GEN_INDICATION_REQUEST // typedef struct _NDIS_WW_INDICATION_REQUEST { NDIS_OID Oid; // IN ULONG uIndicationFlag; // IN ULONG uApplicationToken; // IN OUT HANDLE hIndicationHandle; // IN OUT INT iPollingInterval; // IN OUT NDIS_VAR_DATA_DESC InitialValue; // IN OUT NDIS_VAR_DATA_DESC OIDIndicationValue; // OUT - only valid after indication NDIS_VAR_DATA_DESC TriggerValue; // IN } NDIS_WW_INDICATION_REQUEST, *PNDIS_WW_INDICATION_REQUEST; #define OID_INDICATION_REQUEST_ENABLE 0x0000 #define OID_INDICATION_REQUEST_CANCEL 0x0001 // // OID_WW_GEN_DEVICE_INFO // typedef struct _WW_DEVICE_INFO { NDIS_VAR_DATA_DESC Manufacturer; NDIS_VAR_DATA_DESC ModelNum; NDIS_VAR_DATA_DESC SWVersionNum; NDIS_VAR_DATA_DESC SerialNum; } WW_DEVICE_INFO, *PWW_DEVICE_INFO; // // OID_WW_GEN_OPERATION_MODE // typedef INT WW_OPERATION_MODE; // 0 = Normal mode // 1 = Power saving mode // -1 = mode unknown // // OID_WW_GEN_LOCK_STATUS // typedef INT WW_LOCK_STATUS; // 0 = unlocked // 1 = locked // -1 = unknown lock status // // OID_WW_GEN_DISABLE_TRANSMITTER // typedef INT WW_DISABLE_TRANSMITTER; // 0 = transmitter enabled // 1 = transmitter disabled // -1 = unknown value // // OID_WW_GEN_NETWORK_ID // typedef NDIS_VAR_DATA_DESC WW_NETWORK_ID; // // OID_WW_GEN_PERMANENT_ADDRESS // typedef NDIS_VAR_DATA_DESC WW_PERMANENT_ADDRESS; // // OID_WW_GEN_CURRENT_ADDRESS // typedef struct _WW_CURRENT_ADDRESS { NDIS_WW_HEADER_FORMAT Format; NDIS_VAR_DATA_DESC Address; } WW_CURRENT_ADDRESS, *PWW_CURRENT_ADDRESS; // // OID_WW_GEN_SUSPEND_DRIVER // typedef BOOLEAN WW_SUSPEND_DRIVER; // 0 = driver operational // 1 = driver suspended // // OID_WW_GEN_BASESTATION_ID // typedef NDIS_VAR_DATA_DESC WW_BASESTATION_ID; // // OID_WW_GEN_CHANNEL_ID // typedef NDIS_VAR_DATA_DESC WW_CHANNEL_ID; // // OID_WW_GEN_ENCRYPTION_STATE // typedef BOOLEAN WW_ENCRYPTION_STATE; // 0 = if encryption is disabled // 1 = if encryption is enabled // // OID_WW_GEN_CHANNEL_QUALITY // typedef INT WW_CHANNEL_QUALITY; // 0 = Not in network contact, // 1-100 = Quality of Channel (100 is highest quality). // -1 = channel quality is unknown // // OID_WW_GEN_REGISTRATION_STATUS // typedef INT WW_REGISTRATION_STATUS; // 0 = Registration denied // 1 = Registration pending // 2 = Registered // -1 = unknown registration status // // OID_WW_GEN_RADIO_LINK_SPEED // typedef ULONG WW_RADIO_LINK_SPEED; // Bits per second. // // OID_WW_GEN_LATENCY // typedef ULONG WW_LATENCY; // milliseconds // // OID_WW_GEN_BATTERY_LEVEL // typedef INT WW_BATTERY_LEVEL; // 0-100 = battery level in percentage // (100=fully charged) // -1 = unknown battery level. // // OID_WW_GEN_EXTERNAL_POWER // typedef INT WW_EXTERNAL_POWER; // 0 = no external power connected // 1 = external power connected // -1 = unknown // // Ping Address structure // typedef struct _WW_PING_ADDRESS { WW_ADDRESS_FORMAT Format; // IN NDIS_VAR_DATA_DESC TargetAddress; // IN UINT uTime; // OUT in milleseconds } WW_PING_ADDRESS; // // RSSI structure // typedef struct _WW_RECEIVE_SIGNAL_STRENGTH_INDICATOR { INT iDecibels; // value in DB INT iFactor; // power of 10 } WW_RECEIVE_SIGNAL_STRENGTH_INDICATOR; // // SIM status structure // typedef struct _WW_SIM_STATUS { BOOLEAN bHasSIM; // TRUE = SIM required BOOLEAN bBlocked; // TRUE = SIM PIN access blocked BOOLEAN bLocked; // TRUE = PIN need to access device BOOLEAN bInitialized; // TRUE = SIM initialized UINT uCountdown; // = remaining number of attempt to // enter correct PIN } WW_SIM_STATUS; // // enable SIM PIN structure // typedef struct _WW_ENABLE_SIM_PIN { BOOLEAN bEnabled; // TRUE = security feature of SIM enabled NDIS_VAR_DATA_DESC CurrentPIN; // describes buffer containing PIN value } WW_ENABLE_SIM_PIN; // // SIM PIN structure // typedef struct _WW_CHANGE_SIM_PIN { NDIS_VAR_DATA_DESC OldPIN; // describes buffer containing OLD PIN NDIS_VAR_DATA_DESC NewPIN; // describes buffer containing new PIN } WW_CHANGE_SIM_PIN; // // new change SIM PUK structure // typedef NDIS_VAR_DATA_DESC WW_ENABLE_SIM_PUK; // // OID_WW_MET_FUNCTION // typedef NDIS_VAR_DATA_DESC WW_MET_FUNCTION; // // OID_WW_TAC_COMPRESSION // typedef BOOLEAN WW_TAC_COMPRESSION; // Determines whether or not network level compression // is being used. // // OID_WW_TAC_SET_CONFIG // // The DataTAC OID that referenced this object has been superceeded. The // definition is still included for historical purposes only and should not // be used // typedef struct _WW_TAC_SETCONFIG { NDIS_VAR_DATA_DESC RCV_MODE; // Select confirmed/unconfirmed // receive mode NDIS_VAR_DATA_DESC TX_CONTROL; // Enable or Disable transmitter NDIS_VAR_DATA_DESC RX_CONTROL; // Enable or disable radio in // the modem NDIS_VAR_DATA_DESC FLOW_CONTROL; // Set flow control between DTE // and DCE NDIS_VAR_DATA_DESC RESET_CNF; // Reset configuration to // default NDIS_VAR_DATA_DESC READ_CNF; // Read the current // configuration } WW_TAC_SETCONFIG, *PWW_TAC_SETCONFIG; // // OID_WW_TAC_GET_STATUS // // The DataTAC OID that referenced this object has been superceeded. The // definition is still included for historical purposes only and should not // be used // typedef struct _WW_TAC_GETSTATUS { BOOLEAN Action; // Set = Execute command. NDIS_VAR_DATA_DESC Command; NDIS_VAR_DATA_DESC Option; NDIS_VAR_DATA_DESC Response; // The response to the requested command // - max. length of string is 256 octets. } WW_TAC_GETSTATUS, *PWW_TAC_GETSTATUS; // // OID_WW_TAC_USER_HEADER // typedef NDIS_VAR_DATA_DESC WW_TAC_USERHEADER; // This will hold the user header - Max. 64 octets. // August 25, 1998 @14:16 EDT by Emil Sturniolo - WRQ // added new DataTAC get response structure typedef struct _WW_TAC_GET_RESPONSE { UINT SDUTag; // previousl assigned token NDIS_VAR_DATA_DESC Response; // response - max 2048 octets } WW_TAC_GET_RESPONSE; // // DataTAC disable receiver structure // typedef INT WW_TAC_DISABLE_RECEIVER; // 0 = receiver enabled // 1 = receiver disabled // -1 = state of recevier unknown // // DataTAC antenna mode structure // typedef INT WW_TAC_ANTENNA_MODE; // 0 = Automatic Antenna selection // 1 = Always use primary antenna // 2 = Always use secondary antenna // -1 = Antenna algorithm unknown // // DataTAC get response structure // typedef INT WW_TAC_FLUSH_DATA; // 1 = flush buffered data destine to net // 2 = flush buffered data received from net // 3 = flush all buffered data // // DataTAC shutdown device structure // typedef INT WW_TAC_SHUTDOWN_DEVICE; // 0 = device enabled // 1 = device disabled // -1 = state of device unknown // // DataTAC transmitter keyed structure // typedef BOOLEAN WW_TAC_TRANSMITTER_KEYED; // // added new DataTAC system table structure // typedef struct _WW_TAC_SYSTEM_TABLE { UINT SystemCount; UCHAR ContryTable[32]; UCHAR PrefixTable[32]; UCHAR IDTable[32]; } WW_TAC_SYSTEM_TABLE; // // added new DataTAC channel table structure // typedef struct _WW_TAC_CHANNEL_TABLE { UINT ChannelCount; UCHAR ChannelTable[64]; UCHAR AttrTable[64]; } WW_TAC_CHANNEL_TABLE; // // added new DataTAC statistics structure // typedef NDIS_VAR_DATA_DESC WW_TAC_STATISTICS; // // OID_WW_ARD_SNDCP // // The ARDIS OIDs that referenced these object have been deprecated and merged // with the new DataTAC objects. Their definition are still included for // historical purposes only and should not be used. // typedef struct _WW_ARD_SNDCP { NDIS_VAR_DATA_DESC Version; // The version of SNDCP protocol supported. INT BlockSize; // The block size used for SNDCP INT Window; // The window size used in SNDCP } WW_ARD_SNDCP, *PWW_ARD_SNDCP; // // OID_WW_ARD_TMLY_MSG // typedef BOOLEAN WW_ARD_CHANNEL_STATUS; // The current status of the inbound RF Channel. // // OID_WW_ARD_DATAGRAM // typedef struct _WW_ARD_DATAGRAM { BOOLEAN LoadLevel; // Byte that contains the load level info. INT SessionTime; // Datagram session time remaining. NDIS_VAR_DATA_DESC HostAddr; // Host address. NDIS_VAR_DATA_DESC THostAddr; // Test host address. } WW_ARD_DATAGRAM, *PWW_ARD_DATAGRAM; // // OID_WW_CDPD_SPNI // typedef struct _WW_CDPD_SPNI { ULONG SPNI[10]; //10 16-bit service provider network IDs INT OperatingMode; // 0 = ignore SPNI, // 1 = require SPNI from list, // 2 = prefer SPNI from list. // 3 = exclude SPNI from list. } WW_CDPD_SPNI, *PWW_CDPD_SPNI; // // OID_WW_CDPD_WASI // typedef struct _WW_CDPD_WIDE_AREA_SERVICE_ID { ULONG WASI[10]; //10 16-bit wide area service IDs INT OperatingMode; // 0 = ignore WASI, // 1 = Require WASI from list, // 2 = prefer WASI from list // 3 = exclude WASI from list. } WW_CDPD_WIDE_AREA_SERVICE_ID, *PWW_CDPD_WIDE_AREA_SERVICE_ID; // // OID_WW_CDPD_AREA_COLOR // typedef INT WW_CDPD_AREA_COLOR; // // OID_WW_CDPD_TX_POWER_LEVEL // typedef ULONG WW_CDPD_TX_POWER_LEVEL; // // OID_WW_CDPD_EID // typedef NDIS_VAR_DATA_DESC WW_CDPD_EID; // // OID_WW_CDPD_HEADER_COMPRESSION // typedef INT WW_CDPD_HEADER_COMPRESSION; // 0 = no header compression, // 1 = always compress headers, // 2 = compress headers if MD-IS does // -1 = unknown // // OID_WW_CDPD_DATA_COMPRESSION // typedef INT WW_CDPD_DATA_COMPRESSION; // 0 = no data compression, // 1 = data compression enabled // -1 = unknown // // OID_WW_CDPD_CHANNEL_SELECT // typedef struct _WW_CDPD_CHANNEL_SELECT { ULONG ChannelID; // channel number ULONG fixedDuration; // duration in seconds } WW_CDPD_CHANNEL_SELECT, *PWW_CDPD_CHANNEL_SELECT; // // OID_WW_CDPD_CHANNEL_STATE // typedef enum _WW_CDPD_CHANNEL_STATE { CDPDChannelNotAvail, CDPDChannelScanning, CDPDChannelInitAcquired, CDPDChannelAcquired, CDPDChannelSleeping, CDPDChannelWaking, CDPDChannelCSDialing, CDPDChannelCSRedial, CDPDChannelCSAnswering, CDPDChannelCSConnected, CDPDChannelCSSuspended } WW_CDPD_CHANNEL_STATE, *PWW_CDPD_CHANNEL_STATE; // // OID_WW_CDPD_NEI // typedef enum _WW_CDPD_NEI_FORMAT { CDPDNeiIPv4, CDPDNeiCLNP, CDPDNeiIPv6 } WW_CDPD_NEI_FORMAT, *PWW_CDPD_NEI_FORMAT; typedef enum _WW_CDPD_NEI_TYPE { CDPDNeiIndividual, CDPDNeiMulticast, CDPDNeiBroadcast } WW_CDPD_NEI_TYPE; typedef struct _WW_CDPD_NEI { ULONG uNeiIndex; WW_CDPD_NEI_FORMAT NeiFormat; WW_CDPD_NEI_TYPE NeiType; WORD NeiGmid; // group member identifier, only // meaningful if NeiType == // CDPDNeiMulticast NDIS_VAR_DATA_DESC NeiAddress; } WW_CDPD_NEI; // // OID_WW_CDPD_NEI_STATE // typedef enum _WW_CDPD_NEI_STATE { CDPDUnknown, CDPDRegistered, CDPDDeregistered } WW_CDPD_NEI_STATE, *PWW_CDPD_NEI_STATE; typedef enum _WW_CDPD_NEI_SUB_STATE { CDPDPending, // Registration pending CDPDNoReason, // Registration denied - no reason given CDPDMDISNotCapable, // Registration denied - MD-IS not capable of // handling M-ES at this time CDPDNEINotAuthorized, // Registration denied - NEI is not authorized to // use this subnetwork CDPDInsufficientAuth, // Registration denied - M-ES gave insufficient // authentication credentials CDPDUnsupportedAuth, // Registration denied - M-ES gave unsupported // authentication credentials CDPDUsageExceeded, // Registration denied - NEI has exceeded usage // limitations CDPDDeniedThisNetwork // Registration denied on this network, service // may be obtained on alternate Service Provider // network } WW_CDPD_NEI_SUB_STATE; typedef struct _WW_CDPD_NEI_REG_STATE { ULONG uNeiIndex; WW_CDPD_NEI_STATE NeiState; WW_CDPD_NEI_SUB_STATE NeiSubState; } WW_CDPD_NEI_REG_STATE, *PWW_CDPD_NEI_REG_STATE; // // OID_WW_CDPD_SERVICE_PROVIDER_IDENTIFIER // typedef struct _WW_CDPD_SERVICE_PROVIDER_ID { ULONG SPI[10]; //10 16-bit service provider IDs INT OperatingMode; // 0 = ignore SPI, // 1 = require SPI from list, // 2 = prefer SPI from list. // 3 = SPI from list is excluded } WW_CDPD_SERVICE_PROVIDER_ID, *PWW_CDPD_SERVICE_PROVIDER_ID; // // OID_WW_CDPD_SLEEP_MODE // typedef INT WW_CDPD_SLEEP_MODE; // // OID_WW_CDPD_TEI // typedef ULONG WW_CDPD_TEI; // // OID_WW_CDPD_CIRCUIT_SWITCHED // // The CDPD OID that referenced this object has been deprecated and superceeded // by new discrete CDPD objects. The definition is still included for // historical purposes only and should not be used. // typedef struct _WW_CDPD_CIRCUIT_SWITCHED { INT service_preference; // -1 = unknown, // 0 = always use packet switched CDPD, // 1 = always use CS CDPD via AMPS, // 2 = always use CS CDPD via PSTN, // 3 = use circuit switched via AMPS only // when packet switched is not available. // 4 = use packet switched only when circuit // switched via AMPS is not available. // 5 = device manuf. defined service // preference. // 6 = device manuf. defined service // preference. INT service_status; // -1 = unknown, // 0 = packet switched CDPD, // 1 = circuit switched CDPD via AMPS, // 2 = circuit switched CDPD via PSTN. INT connect_rate; // CS connection bit rate (bits per second). // 0 = no active connection, // -1 = unknown // Dial code last used to dial. NDIS_VAR_DATA_DESC dial_code[20]; ULONG sid; // Current AMPS system ID INT a_b_side_selection; // -1 = unknown, // 0 = no AMPS service // 1 = AMPS "A" side channels selected // 2 = AMPS "B" side channels selected INT AMPS_channel; // -1= unknown // 0 = no AMPS service. // 1-1023 = AMPS channel number in use ULONG action; // 0 = no action // 1 = suspend (hangup) // 2 = dial // Default dial code for CS CDPD service // encoded as specified in the CS CDPD // implementor guidelines. NDIS_VAR_DATA_DESC default_dial[20]; // Number for the CS CDPD network to call // back the mobile, encoded as specified in // the CS CDPD implementor guidelines. NDIS_VAR_DATA_DESC call_back[20]; ULONG sid_list[10]; // List of 10 16-bit preferred AMPS // system IDs for CS CDPD. ULONG inactivity_timer; // Wait time after last data before dropping // call. // 0-65535 = inactivity time limit (seconds). ULONG receive_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG conn_resp_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG reconn_resp_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG disconn_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG NEI_reg_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG reconn_retry_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG link_reset_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG link_reset_ack_timer; // secs. per CS-CDPD Implementor Guidelines. ULONG n401_retry_limit; // per CS-CDPD Implementor Guidelines. ULONG n402_retry_limit; // per CS-CDPD Implementor Guidelines. ULONG n404_retry_limit; // per CS-CDPD Implementor Guidelines. ULONG n405_retry_limit; // per CS-CDPD Implementor Guidelines. } WW_CDPD_CIRCUIT_SWITCHED, *WW_PCDPD_CIRCUIT_SWITCHED; typedef ULONG WW_CDPD_RSSI; // // cs-cdpd service preference structure // typedef INT WW_CDPD_CS_SERVICE_PREFERENCE; // 0 = use packet switched CDPD only // 1 = use CS-CDPD via AMPS only // 2 = use CS-CDPD via PSTN only // 3 = use CS-CDPD via AMPS only // when packet switched is N/A // 4 = use packet switched CDPD only // when CS-CDPD via AMPS is N/A // 5 = Device manufacture defined // service preference // 6 = device manufacture defined // service preference // -1 = unknown // // cs-cdpd service status structure // typedef INT WW_CDPD_CS_SERVICE_STATUS; // 0 = Packet switched CDPD // 1 = CS-CDPD via AMPS // 2 = CS-CDPD via PSTN // -1 = unknown // // cs-cdpd info structure // typedef struct _WW_CDPD_CS_INFO { INT ConnectRage; // 0 = no active connection // -1 = unknown // all other values represent BPS NDIS_VAR_DATA_DESC DialCode; // describes buffer of last dial code UINT SID; // Current AMPS System ID INT ABSideSelection; // 0 = no AMPS service // 1 = AMPS "A" side channel selected // 2 = AMPS "B" side channel selected INT AMPSChannel; // 0 = no AMPS service // 1-1023 = current AMPS channel // -1 = Unknown // all other values reserved } WW_CDPD_CS_INFO; // // cs-cdpd suspend structure // typedef UINT WW_CDPD_CS_SUSPEND; // 0 = nop; 1 = hang up // // cs-cdpd default dial code structure // typedef NDIS_VAR_DATA_DESC WW_CDPD_DEFAULT_DIAL_CODE; // max 20 octets // // cs-cdpd callback structure // typedef struct _WW_CDPD_CS_CALLBACK { UINT Enabled; // 0 = disable; 1 = enable; -1 = unknown NDIS_VAR_DATA_DESC Number; // descibes buffer contianing dial code // max 20 octets } WW_CDPD_CS_CALLBACK; // // cs-cdpd system id list structure // typedef struct _WW_CDPD_CS_SID_LIST { UINT AMPSystemId[10]; } WW_CDPD_CS_SID_LIST; // // cs-cdpd configuration structure // typedef struct _WW_CDPD_CS_CONFIGURATION { UINT InactivityTimer; // in seconds UINT ReceiveTimer; // in seconds UINT ConnResTimer; // in seconds UINT ReconnRespTimer; // in seconds UINT DisconnTimer; // in seconds UINT NEIRegTimer; // in seconds UINT ReconnRetryTimer; // in seconds UINT LinkResetTimer; // in seconds UINT LinkResetAckTimer; // in seconds UINT n401RetryLimit; // per CS-CDPD Implementers guidelines UINT n402RetryLimit; // per CS-CDPD Implementers guidelines UINT n404RetryLimit; // per CS-CDPD Implementers guidelines UINT n405RetryLimit; // per CS-CDPD Implementers guidelines } WW_CDPD_CS_CONFIGURATION; // // OID_WW_PIN_LOC_AUTHORIZE // // The Pin Point OIDs that referenced the structures below have been // deprecated from the PCCA STD-201 standard. Their definitions are still // included for historical purposes only and should not be used. // typedef INT WW_PIN_AUTHORIZED; // 0 = unauthorized // 1 = authorized // -1 = unknown // // OID_WW_PIN_LAST_LOCATION // OID_WW_PIN_LOC_FIX // typedef struct _WW_PIN_LOCATION { INT Latitude; // Latitude in hundredths of a second INT Longitude; // Longitude in hundredths of a second INT Altitude; // Altitude in feet INT FixTime; // Time of the location fix, since midnight, local time (of the // current day), in tenths of a second INT NetTime; // Current local network time of the current day, since midnight, // in tenths of a second INT LocQuality; // 0-100 = location quality INT LatReg; // Latitude registration offset, in hundredths of a second INT LongReg; // Longitude registration offset, in hundredths of a second INT GMTOffset; // Offset in minutes of the local time zone from GMT } WW_PIN_LOCATION, *PWW_PIN_LOCATION; // // The following is set on a per-packet basis as OOB data with NdisClassWirelessWanMbxMailbox // typedef ULONG WW_MBX_MAILBOX_FLAG; // 1 = set mailbox flag, 0 = do not set mailbox flag // // OID_WW_MBX_SUBADDR // typedef struct _WW_MBX_PMAN { BOOLEAN ACTION; // 0 = Login PMAN, 1 = Logout PMAN ULONG MAN; UCHAR PASSWORD[8]; // Password should be null for Logout and indications. // Maximum length of password is 8 chars. } WW_MBX_PMAN, *PWW_MBX_PMAN; // // OID_WW_MBX_FLEXLIST // typedef struct _WW_MBX_FLEXLIST { INT count; // Number of MAN entries used. // -1=unknown. ULONG MAN[7]; // List of MANs. } WW_MBX_FLEXLIST; // // OID_WW_MBX_GROUPLIST // typedef struct _WW_MBX_GROUPLIST { INT count; // Number of MAN entries used. // -1=unknown. ULONG MAN[15]; // List of MANs. } WW_MBX_GROUPLIST; // // OID_WW_MBX_TRAFFIC_AREA // typedef enum _WW_MBX_TRAFFIC_AREA { unknown_traffic_area, // The driver has no information about the current traffic area. in_traffic_area, // Mobile unit has entered a subscribed traffic area. in_auth_traffic_area, // Mobile unit is outside traffic area but is authorized. unauth_traffic_area // Mobile unit is outside traffic area but is un-authorized. } WW_MBX_TRAFFIC_AREA; // // OID_WW_MBX_LIVE_DIE // typedef INT WW_MBX_LIVE_DIE; // 0 = DIE last received // 1 = LIVE last received // -1 = unknown // // OID_WW_MBX_TEMP_DEFAULTLIST // typedef struct _WW_MBX_CHANNEL_PAIR { ULONG Mobile_Tx; ULONG Mobile_Rx; } WW_MBX_CHANNEL_PAIR, *PWW_MBX_CHANNEL_PAIR; typedef struct _WW_MBX_TEMPDEFAULTLIST { ULONG Length; WW_MBX_CHANNEL_PAIR ChannelPair[1]; } WW_MBX_TEMPDEFAULTLIST, *WW_PMBX_TEMPDEFAULTLIST; #endif // WIRELESS_WAN // // // Base types that were redefined for BPC // // BPC_FILETIME is used exactly like FILETIME in Win32 // // BPC_HANDLE is opaque to everything except the Miniport // typedef struct _BPC_FILETIME { ULONG dwLowDateTime; ULONG dwHighDateTime; } BPC_FILETIME, *PBPC_FILETIME; typedef PVOID BPC_HANDLE; // // BPC Extension Globals // // #define BPC_MIN_DIMENSION 1 #define BPC_MAX_BUFFER_SIZE 64 #define BPC_MIN_BUFFER_SIZE 4 #define BPC_DEVICE_ANY ((BPC_HANDLE) 0xFFFFFFFF) // // Buffer indicate reason codes // // typedef enum _NDIS_BPC_INDICATE_REASON { bpcBufferFull = 0, bpcBufferForced, bpcBufferTimeOut, bpcBufferDiscontinuity, bpcBufferOverflow, bpcBufferStatusEvent } NDIS_BPC_INDICATE_REASON, *PNDIS_BPC_INDICATE_REASON; // // BPC Stream Types // #define BPC_STREAM_TYPE_GENERIC_MIN 0x01000000 #define BPC_STREAM_TYPE_RAW 0x01000000 #define BPC_STREAM_TYPE_MPT_128 0x01000001 #define BPC_STREAM_TYPE_MPT_128_CRC 0x01000002 #define BPC_STREAM_TYPE_IP 0x01000003 #define BPC_STREAM_TYPE_PROVIDER_MIN 0x02000000 #define BPC_STREAM_TYPE_PROVIDER_MAX 0x02ffffff #define BPC_STREAM_TYPE_ADAPTER_MIN 0x03000000 #define BPC_STREAM_TYPE_ADAPTER_MAX 0x03ffffff // // BPC Adapter Capabilities // typedef struct _NDIS_BPC_ADAPTER_CAPS { ULONG ulBPCMajorRev; ULONG ulBPCMinorRev; ULONG ulcHSDataDevices; ULONG ulbpsHSDeviceMax; ULONG ulcLSDataDevices; ULONG ulbpsLSDeviceMax; ULONG ulcTuningDevices; ULONG ulcbLargestStatus; ULONG ulVendorId; ULONG ulAdapterId; GUID guidProvider; } NDIS_BPC_ADAPTER_CAPS, *PNDIS_BPC_ADAPTER_CAPS; // // BPC Device Enumeration // typedef struct _NDIS_BPC_DEVICES { ULONG ulcDevices; BPC_HANDLE rgnhDevices[BPC_MIN_DIMENSION]; } NDIS_BPC_DEVICES, *PNDIS_BPC_DEVICES; #define CbDevices(cnt) (FIELD_OFFSET(NDIS_BPC_DEVICES, rgnhDevices) + (cnt) * sizeof(BPC_HANDLE)) // // BPC Device Capabilities Structure // typedef struct NDIS_BPC_DEVICE_CAPS { BPC_HANDLE nhDevice; ULONG ulBPCCaps; ULONG ulbpsMax; ULONG ulcStreamTypes; ULONG rgulStreamTypes[BPC_MIN_DIMENSION]; } NDIS_BPC_DEVICE_CAPS, *PNDIS_BPC_DEVICE_CAPS; #define CbDeviceCaps(cnt) (FIELD_OFFSET(NDIS_BPC_DEVICE_CAPS, rgulStreamTypes) + (cnt) * sizeof(ULONG)) // // BPC Device Capability Definitions // (ie Flags that can be set in ulBPCCaps // #define BPCCapBusMasteredData 0x01 #define BPCCapIndependentTuner 0x02 #define BPCCapExternalDataBus 0x04 #define BPCCapLowSpeedData 0x10 #define BPCCapHighSpeedData 0x20 // // BPC Device Settings Structure // typedef struct NDIS_BPC_DEVICE_SETTINGS { BPC_HANDLE nhDevice; ULONG ulBPCCaps; ULONG ulcConnections; BOOLEAN fEnabled; ULONG ulStreamType; ULONG ulcbAddressConnection; ULONG rgulAddressConnection[BPC_MIN_DIMENSION]; } NDIS_BPC_DEVICE_SETTINGS, *PNDIS_BPC_DEVICE_SETTINGS; #define CbDeviceSettings(cnt) (FIELD_OFFSET(NDIS_BPC_DEVICE_SETTINGS, rgulAddressConnection) + (cnt) * sizeof(ULONG)) // // BPC Connection State Definitions // (ie Acceptable values for ulState) // #define BPC_CONNECT_STATE_UNCOMMITTED 0 #define BPC_CONNECT_STATE_QUEUED 1 #define BPC_CONNECT_STATE_ACTIVE 2 #define BPC_CONNECT_STATE_DISCONNECTING 3 // // BPC Connections Status Structure // typedef struct NDIS_BPC_CONNECTION_STATUS { BPC_HANDLE nhConnection; BPC_HANDLE nhDevice; ULONG ulConnectPriority; ULONG ulDisconnectPriority; ULONG ulbpsAverage; ULONG ulbpsBurst; ULONG ulState; BOOLEAN fEnabled; } NDIS_BPC_CONNECTION_STATUS, *PNDIS_BPC_CONNECTION_STATUS; // // BPC Address Comparison Structure // typedef struct NDIS_BPC_ADDRESS_COMPARE { BOOLEAN fEqual; ULONG ulcbFirstOffset; ULONG ulcbFirstLength; ULONG ulcbSecondOffset; ULONG ulcbSecondLength; } NDIS_BPC_ADDRESS_COMPARE, *PNDIS_BPC_ADDRESS_COMPARE; // // BPC Program Guide Types // // Currently there are no Generic BPC Program Guide types. // #define BPC_GUIDE_GENERIC_MIN 0x01000000 #define BPC_GUIDE_GENERIC_MAX 0x01ffffff #define BPC_GUIDE_PROVIDER_MIN 0x02000000 #define BPC_GUIDE_PROVIDER_MAX 0x02ffffff #define BPC_GUIDE_ADAPTER_MIN 0x03000000 #define BPC_GUIDE_ADAPTER_MAX 0x03ffffff // // BPC Program Guide Structure // typedef struct NDIS_BPC_PROGRAM_GUIDE { ULONG ulGuideType; BPC_FILETIME ftLastUpdate; ULONG ulChangeNumber; ULONG ulcbGuideSize; ULONG rgulGuideData[BPC_MIN_DIMENSION]; } NDIS_BPC_PROGRAM_GUIDE, *PNDIS_BPC_PROGRAM_GUIDE; // // BPC Extension Errors // (ie Acceptable values for ulBPCError) // typedef enum _NDIS_BPC_ERROR { bpcErrorUnknownFailure = 0xc0ff0000, bpcErrorHardwareFailure, bpcErrorProviderFailure, bpcErrorNoDataDevice, bpcErrorNoTuningDevice, bpcErrorDeviceNotCapable, bpcErrorConflictingDevice, bpcErrorConflictingCapability, bpcErrorNoBufferMemory, bpcErrorNoResources, bpcErrorAdapterClosing, bpcErrorConnectionClosing, bpcErrorTooComplex, bpcErrorProviderNotSupported, bpcErrorUnknownProviderStructure, bpcErrorAddressNotSupported, bpcErrorInvalidAddress, bpcErrorUnknownAdapterStructure } NDIS_BPC_ERROR, *PNDIS_BPC_ERROR; // // BPC Last Error Structure // typedef struct NDIS_BPC_LAST_ERROR { ULONG ulErrorContext; ULONG ulBPCError; ULONG ulAdapterError; ULONG ulAdapterContext; } NDIS_BPC_LAST_ERROR, *PNDIS_BPC_LAST_ERROR; // // BPC Buffer Pool Request/Report Structure // typedef struct NDIS_BPC_POOL { BPC_HANDLE nhConnection; ULONG ulcbPoolSize; ULONG ulcbMaxBufferSize; ULONG ulcbBufferReserved; } NDIS_BPC_POOL, *PNDIS_BPC_POOL; // // BPC Provider and Adapter Specific Structures are defined in the // BpcXXXX.H file which the Provider/Adapter Manufacturer supplies. // // // BPC Connect Structure // typedef struct NDIS_BPC_CONNECT { BPC_HANDLE nhConnection; BPC_HANDLE nhDevice; ULONG ulConnectPriority; ULONG ulDisconnectPriority; BOOLEAN fImmediate; ULONG ulcbAddress; GUID guidProvider; ULONG rgulAddress[BPC_MIN_DIMENSION]; } NDIS_BPC_CONNECT, *PNDIS_BPC_CONNECT; #define CbConnect(cnt) (FIELD_OFFSET(NDIS_BPC_CONNECT, rgulAddress) + (cnt) * sizeof(ULONG)) // // BPC Commit Connections Structure // typedef struct NDIS_BPC_COMMIT { ULONG ulcConnections; BPC_HANDLE rgnhConnections[BPC_MIN_DIMENSION]; } NDIS_BPC_COMMIT, *PNDIS_BPC_COMMIT; // // BPC Disconnect Structure // typedef struct NDIS_BPC_DISCONNECT { BPC_HANDLE nhConnection; } NDIS_BPC_DISCONNECT, *PNDIS_BPC_DISCONNECT; // // BPC Enable Connection Structure // typedef struct NDIS_BPC_CONNECTION_ENABLE { BPC_HANDLE nhConnection; BOOLEAN fEnabled; } NDIS_BPC_CONNECTION_ENABLE, *PNDIS_BPC_CONNECTION_ENABLE; // // BPC Pool Return Structure // typedef struct NDIS_BPC_POOL_RETURN { BPC_HANDLE nhConnection; } NDIS_BPC_POOL_RETURN, *PNDIS_BPC_POOL_RETURN; typedef struct NDIS_BPC_FORCE_RECEIVE { BPC_HANDLE nhConnection; ULONG ulReasonCode; } NDIS_BPC_FORCE_RECEIVE, *PNDIS_BPC_FORCE_RECEIVE; // // BPC Media Specific Information Structure // typedef struct NDIS_BPC_MEDIA_SPECIFIC_INFORMATION { BPC_HANDLE nhConnection; // The handle to the data device. ULONG ulBPCStreamType; // The stream type of the data in packet ULONG ulReasonCode; // The reason the buffer was indicated PVOID pvMiniportReserved1; ULONG ulMiniportReserved2; } NDIS_BPC_MEDIA_SPECIFIC_INFORMATION, *PNDIS_BPC_MEDIA_SPECIFIC_INFORMATION; // // BPC Status Categories // #define BPC_CATEGORY_BPC 0x01000000 #define BPC_CATEGORY_PROVIDER 0x02000000 #define BPC_CATEGORY_ADAPTER 0x03000000 // // BPC Status Types for Category BPC_CATEGORY_BPC // #define BPC_STATUS_CONNECTED 0x00000001 #define BPC_STATUS_QUEUED 0x00000002 #define BPC_STATUS_ACTIVE 0x00000003 #define BPC_STATUS_DISCONNECTED 0x00000004 #define BPC_STATUS_OVERFLOW 0x00000005 #define BPC_STATUS_DATA_STOP 0x00000006 #define BPC_STATUS_DATA_START 0x00000007 #define BPC_STATUS_DATA_ERROR 0x00000008 // // BPC Status Indication Structure // typedef struct NDIS_BPC_STATUS { ULONG ulStatusCategory; ULONG ulStatusType; ULONG ulcbStatus; ULONG rgulStatus; } NDIS_BPC_STATUS, *PNDIS_BPC_STATUS; // // BPC Connection Status Structure // // All BPC Generic Connection Status package this structure // in rgulStatus to indicate to which connection and device // the status pertains. // typedef struct NDIS_BPC_STATUS_CONNECTION { BPC_HANDLE nhConnection; BPC_HANDLE nhDevice; } NDIS_BPC_STATUS_CONNECTED, *PNDIS_BPC_STATUS_CONNECTED; #ifdef __cplusplus } #endif // // flags used for OID_GEN_MINIPORT_INFO // #define NDIS_MINIPORT_BUS_MASTER 0x00000001 #define NDIS_MINIPORT_WDM_DRIVER 0x00000002 #define NDIS_MINIPORT_SG_LIST 0x00000004 #define NDIS_MINIPORT_SUPPORTS_MEDIA_QUERY 0x00000008 #define NDIS_MINIPORT_INDICATES_PACKETS 0x00000010 #define NDIS_MINIPORT_IGNORE_PACKET_QUEUE 0x00000020 #define NDIS_MINIPORT_IGNORE_REQUEST_QUEUE 0x00000040 #define NDIS_MINIPORT_IGNORE_TOKEN_RING_ERRORS 0x00000080 #define NDIS_MINIPORT_INTERMEDIATE_DRIVER 0x00000100 #define NDIS_MINIPORT_IS_NDIS_5 0x00000200 #define NDIS_MINIPORT_IS_CO 0x00000400 #define NDIS_MINIPORT_DESERIALIZE 0x00000800 #define NDIS_MINIPORT_REQUIRES_MEDIA_POLLING 0x00001000 #define NDIS_MINIPORT_SUPPORTS_MEDIA_SENSE 0x00002000 #define NDIS_MINIPORT_NETBOOT_CARD 0x00004000 #define NDIS_MINIPORT_PM_SUPPORTED 0x00008000 #define NDIS_MINIPORT_SUPPORTS_MAC_ADDRESS_OVERWRITE 0x00010000 #define NDIS_MINIPORT_USES_SAFE_BUFFER_APIS 0x00020000 #define NDIS_MINIPORT_HIDDEN 0x00040000 #define NDIS_MINIPORT_SWENUM 0x00080000 #define NDIS_MINIPORT_SURPRISE_REMOVE_OK 0x00100000 #define NDIS_MINIPORT_NO_HALT_ON_SUSPEND 0x00200000 #define NDIS_MINIPORT_HARDWARE_DEVICE 0x00400000 #define NDIS_MINIPORT_SUPPORTS_CANCEL_SEND_PACKETS 0x00800000 #define NDIS_MINIPORT_64BITS_DMA 0x01000000 #define NDIS_MINIPORT_USE_NEW_BITS 0x02000000 #define NDIS_MINIPORT_EXCLUSIVE_INTERRUPT 0x04000000 #define NDIS_MINIPORT_SENDS_PACKET_ARRAY 0x08000000 #define NDIS_MINIPORT_FILTER_IM 0x10000000 #define NDIS_MINIPORT_SHORT_PACKETS_ARE_PADDED 0x20000000 #endif // _NTDDNDIS_
EmulatorArchive/yabause-rr
src/windows/ddk/ntddndis.h
C
gpl-2.0
119,930
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Class URIError</title> <link rel="stylesheet" type="text/css" href="doc.css" /> </head> <body> <div class='body'> <div class="content"> <a name='top'></a> <h1 class='className'>URIError</h1> <div class='classBlock'> <table class='classHead' summary='URIError'> <tr><td><strong>Module</strong></td><td>ejs</td></tr> <tr><td><strong>Namespace</strong></td><td>intrinsic</td></tr> <tr><td><strong>Definition</strong></td><td>dynamic class URIError</td></tr> <tr><td><strong>Inheritance</strong></td><td>URIError <img src='images/inherit.gif' alt='inherit'/> <a href='intrinsic-Error.html'>Error</a> <img src='images/inherit.gif' alt='inherit'/> <a href='intrinsic-Object.html'>Object</a> </td></tr> </table> <p class='classBrief'>URI error exception class.</p> <p class='classDescription'>Thrown a URI fails to parse.</p> </div> <hr /> <a name='Properties'></a> <h2 class='classSection'>Properties</h2> <table class='itemTable' summary='properties'> <tr><th>Qualifiers</th><th>Property</th><th>Type</th><th width='95%'>Description</th></tr> <tr><td colspan='4'>No properties defined</td></tr></table> <p class='inheritedLink'><a href='intrinsic-Error.html#Properties'><i>Inherited Properties</i></a></p> <hr /> <a name='Methods'></a> <h2 class='classSection'>URIError Methods</h2> <table class='apiIndex' summary='methods'> <tr><th>Qualifiers</th><th width='95%'>Method</th></tr> <tr class='apiDef'><td class='apiType'> </td><td><a href='#URIError'><b>URIError</b></a>(message: <a href='intrinsic-String.html'>String</a>)</tr><tr class='apiBrief'><td>&nbsp;</td><td>URIError constructor.</td></tr> </table> <p class='inheritedLink'><a href='intrinsic-Error.html#Methods'><i>Inherited Methods</i></a></p> <hr /> <h2>Method Detail</h2> <a name='URIError'></a> <div class='api'> <div class='apiSig'> URIError(message: <a href='intrinsic-String.html'>String</a>) </div> <div class='apiDetail'> <p>URIError constructor.</p> <dl><dt>Parameters</dt> <dd><table class='parameters' summary ='parameters'> <tr><td class='param'>message: <a href='intrinsic-String.html'>String</a> </td><td>Message to use when defining the Error.message property</td></tr></table></dd> </dl></div> </div> <hr /> <div class="terms"> <p class="terms"> <a href="http://www.embedthis.com/"> Embedthis Software LLC, 2003-2009. All rights reserved. Embedthis is a trademark of Embedthis Software LLC.</a> </p> </div></div> </div> </body> </html>
jsjohnst/appweb
doc/ejs/api/ejscript/intrinsic-URIError.html
HTML
gpl-2.0
2,646
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ /** * @package OpenX * @author Andriy Petlyovanyy <apetlyovanyy@lohika.com> * */ // Require Publisher Service Implementation require_once MAX_PATH . '/www/api/v2/xmlrpc/PublisherServiceImpl.php'; /** * Base Publisher Service * */ class BasePublisherService { /** * Reference to Publisher Service implementation. * * @var PublisherServiceImpl $_oPublisherServiceImp */ var $_oPublisherServiceImp; /** * This method initialises Service implementation object field. * */ function BasePublisherService() { $this->_oPublisherServiceImp = new PublisherServiceImpl(); } } ?>
adqio/revive-adserver
www/api/v2/common/BasePublisherService.php
PHP
gpl-2.0
1,212
Alba Mantenimiento ================= Implementación del Sistema de Gestión de Incidencias y Mantenimiento Preventivo / Correctivo bajo el Framework KumbiaPHP utilizando como Backend Postgresql
ArrozAlba/mantenimiento
README.md
Markdown
gpl-2.0
197
/* Copyright 2016 Jack Humbert * * 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/>. */ // Sendstring lookup tables for Dvorak layouts #pragma once #include "keymap_dvorak.h" const uint8_t ascii_to_keycode_lut[128] PROGMEM = { // NUL SOH STX ETX EOT ENQ ACK BEL XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, // BS TAB LF VT FF CR SO SI KC_BSPC, KC_TAB, KC_ENT, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, // DLE DC1 DC2 DC3 DC4 NAK SYN ETB XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, // CAN EM SUB ESC FS GS RS US XXXXXXX, XXXXXXX, XXXXXXX, KC_ESC, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, // ! " # $ % & ' KC_SPC, DV_1, DV_QUOT, DV_3, DV_4, DV_5, DV_7, DV_QUOT, // ( ) * + , - . / DV_9, DV_0, DV_8, DV_EQL, DV_COMM, DV_MINS, DV_DOT, DV_SLSH, // 0 1 2 3 4 5 6 7 DV_0, DV_1, DV_2, DV_3, DV_4, DV_5, DV_6, DV_7, // 8 9 : ; < = > ? DV_8, DV_9, DV_SCLN, DV_SCLN, DV_COMM, DV_EQL, DV_DOT, DV_SLSH, // @ A B C D E F G DV_2, DV_A, DV_B, DV_C, DV_D, DV_E, DV_F, DV_G, // H I J K L M N O DV_H, DV_I, DV_J, DV_K, DV_L, DV_M, DV_N, DV_O, // P Q R S T U V W DV_P, DV_Q, DV_R, DV_S, DV_T, DV_U, DV_V, DV_W, // X Y Z [ \ ] ^ _ DV_X, DV_Y, DV_Z, DV_LBRC, DV_BSLS, DV_RBRC, DV_6, DV_MINS, // ` a b c d e f g DV_GRV, DV_A, DV_B, DV_C, DV_D, DV_E, DV_F, DV_G, // h i j k l m n o DV_H, DV_I, DV_J, DV_K, DV_L, DV_M, DV_N, DV_O, // p q r s t u v w DV_P, DV_Q, DV_R, DV_S, DV_T, DV_U, DV_V, DV_W, // x y z { | } ~ DEL DV_X, DV_Y, DV_Z, DV_LBRC, DV_BSLS, DV_RBRC, DV_GRV, KC_DEL };
paxy97/qmk_firmware
quantum/keymap_extras/sendstring_dvorak.h
C
gpl-2.0
3,136
/* * Copyright (c) 1998 Adrian Sun (asun@zoology.washington.edu) * All rights reserved. See COPYRIGHT. * * this file provides the following functions: * dsi_stream_write: just write a bunch of bytes. * dsi_stream_read: just read a bunch of bytes. * dsi_stream_send: send a DSI header + data. * dsi_stream_receive: read a DSI header + data. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/uio.h> #include <atalk/logger.h> #include <atalk/dsi.h> #include <netatalk/endian.h> #include <atalk/util.h> #define min(a,b) ((a) < (b) ? (a) : (b)) #ifndef MSG_MORE #define MSG_MORE 0x8000 #endif #ifndef MSG_DONTWAIT #define MSG_DONTWAIT 0x40 #endif /* * afpd is sleeping too much while trying to send something. * May be there's no reader or the reader is also sleeping in write, * look if there's some data for us to read, hopefully it will wake up * the reader so we can write again. * * @returns 0 when is possible to send again, -1 on error */ static int dsi_peek(DSI *dsi) { static int warned = 0; fd_set readfds, writefds; int len; int maxfd; int ret; LOG(log_debug, logtype_dsi, "dsi_peek"); maxfd = dsi->socket + 1; while (1) { FD_ZERO(&readfds); FD_ZERO(&writefds); if (dsi->eof < dsi->end) { /* space in read buffer */ FD_SET( dsi->socket, &readfds); } else { if (!warned) { warned = 1; LOG(log_note, logtype_dsi, "dsi_peek: readahead buffer is full, possibly increase -dsireadbuf option"); LOG(log_note, logtype_dsi, "dsi_peek: dsireadbuf: %d, DSI quantum: %d, effective buffer size: %d", dsi->dsireadbuf, dsi->server_quantum ? dsi->server_quantum : DSI_SERVQUANT_DEF, dsi->end - dsi->buffer); } } FD_SET( dsi->socket, &writefds); /* No timeout: if there's nothing to read nor nothing to write, * we've got nothing to do at all */ if ((ret = select( maxfd, &readfds, &writefds, NULL, NULL)) <= 0) { if (ret == -1 && errno == EINTR) /* we might have been interrupted by out timer, so restart select */ continue; /* give up */ LOG(log_error, logtype_dsi, "dsi_peek: unexpected select return: %d %s", ret, ret < 0 ? strerror(errno) : ""); return -1; } if (FD_ISSET(dsi->socket, &writefds)) { /* we can write again */ LOG(log_debug, logtype_dsi, "dsi_peek: can write again"); break; } /* Check if there's sth to read, hopefully reading that will unblock the client */ if (FD_ISSET(dsi->socket, &readfds)) { len = dsi->end - dsi->eof; /* it's ensured above that there's space */ if ((len = read(dsi->socket, dsi->eof, len)) <= 0) { if (len == 0) { LOG(log_error, logtype_dsi, "dsi_peek: EOF"); return -1; } LOG(log_error, logtype_dsi, "dsi_peek: read: %s", strerror(errno)); if (errno == EAGAIN) continue; return -1; } LOG(log_debug, logtype_dsi, "dsi_peek: read %d bytes", len); dsi->eof += len; } } return 0; } /* * Return all bytes up to count from dsi->buffer if there are any buffered there */ static size_t from_buf(DSI *dsi, u_int8_t *buf, size_t count) { size_t nbe = 0; if (dsi->buffer == NULL) /* afpd master has no DSI buffering */ return 0; LOG(log_maxdebug, logtype_dsi, "from_buf: %u bytes", count); nbe = dsi->eof - dsi->start; if (nbe > 0) { nbe = min((size_t)nbe, count); memcpy(buf, dsi->start, nbe); dsi->start += nbe; if (dsi->eof == dsi->start) dsi->start = dsi->eof = dsi->buffer; } LOG(log_debug, logtype_dsi, "from_buf(read: %u, unread:%u , space left: %u): returning %u", dsi->start - dsi->buffer, dsi->eof - dsi->start, dsi->end - dsi->eof, nbe); return nbe; } /* * Get bytes from buffer dsi->buffer or read from socket * * 1. Check if there are bytes in the the dsi->buffer buffer. * 2. Return bytes from (1) if yes. * Note: this may return fewer bytes then requested in count !! * 3. If the buffer was empty, read from the socket. */ static ssize_t buf_read(DSI *dsi, u_int8_t *buf, size_t count) { ssize_t len; LOG(log_maxdebug, logtype_dsi, "buf_read(%u bytes)", count); if (!count) return 0; len = from_buf(dsi, buf, count); /* 1. */ if (len) return len; /* 2. */ len = readt(dsi->socket, buf, count, 0, 1); /* 3. */ LOG(log_maxdebug, logtype_dsi, "buf_read(%u bytes): got: %d", count, len); return len; } /* * Get "length" bytes from buffer and/or socket. In order to avoid frequent small reads * this tries to read larger chunks (8192 bytes) into a buffer. */ static size_t dsi_buffered_stream_read(DSI *dsi, u_int8_t *data, const size_t length) { size_t len; size_t buflen; LOG(log_maxdebug, logtype_dsi, "dsi_buffered_stream_read: %u bytes", length); len = from_buf(dsi, data, length); /* read from buffer dsi->buffer */ dsi->read_count += len; if (len == length) { /* got enough bytes from there ? */ return len; /* yes */ } /* fill the buffer with 8192 bytes or until buffer is full */ buflen = min(8192, dsi->end - dsi->eof); if (buflen > 0) { ssize_t ret; ret = read(dsi->socket, dsi->eof, buflen); if (ret > 0) dsi->eof += ret; } /* now get the remaining data */ if ((buflen = dsi_stream_read(dsi, data + len, length - len)) != length - len) return 0; len += buflen; return len; } /* --------------------------------------- */ static void block_sig(DSI *dsi) { dsi->in_write++; } /* --------------------------------------- */ static void unblock_sig(DSI *dsi) { dsi->in_write--; } /********************************************************************************* * Public functions *********************************************************************************/ /*! * Communication error with the client, enter disconnected state * * 1. close the socket * 2. set the DSI_DISCONNECTED flag, remove possible sleep flags * * @returns 0 if successfully entered disconnected state * -1 if ppid is 1 which means afpd master died * or euid == 0 ie where still running as root (unauthenticated session) */ int dsi_disconnect(DSI *dsi) { LOG(log_note, logtype_dsi, "dsi_disconnect: entering disconnected state"); dsi->proto_close(dsi); /* 1 */ dsi->flags &= ~(DSI_SLEEPING | DSI_EXTSLEEP); /* 2 */ dsi->flags |= DSI_DISCONNECTED; if (geteuid() == 0) return -1; return 0; } /* ------------------------------ * write raw data. return actual bytes read. checks against EINTR * aren't necessary if all of the signals have SA_RESTART * specified. */ ssize_t dsi_stream_write(DSI *dsi, void *data, const size_t length, int mode) { size_t written; ssize_t len; unsigned int flags = 0; dsi->in_write++; written = 0; LOG(log_maxdebug, logtype_dsi, "dsi_stream_write(send: %zd bytes): START", length); if (dsi->flags & DSI_DISCONNECTED) return -1; while (written < length) { len = send(dsi->socket, (u_int8_t *) data + written, length - written, flags); if (len >= 0) { written += len; continue; } if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) { LOG(log_debug, logtype_dsi, "dsi_stream_write: send: %s", strerror(errno)); if (mode == DSI_NOWAIT && written == 0) { /* DSI_NOWAIT is used by attention give up in this case. */ written = -1; goto exit; } /* Try to read sth. in order to break up possible deadlock */ if (dsi_peek(dsi) != 0) { written = -1; goto exit; } /* Now try writing again */ continue; } LOG(log_error, logtype_dsi, "dsi_stream_write: %s", strerror(errno)); written = -1; goto exit; } dsi->write_count += written; LOG(log_maxdebug, logtype_dsi, "dsi_stream_write(send: %zd bytes): END", length); exit: dsi->in_write--; return written; } /* --------------------------------- */ #ifdef WITH_SENDFILE ssize_t dsi_stream_read_file(DSI *dsi, int fromfd, off_t offset, const size_t length) { int ret = 0; size_t written; ssize_t len; off_t pos = offset; LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file(send %zd bytes): START", length); if (dsi->flags & DSI_DISCONNECTED) return -1; dsi->in_write++; written = 0; while (written < length) { len = sys_sendfile(dsi->socket, fromfd, &pos, length - written); if (len < 0) { if (errno == EINTR) continue; if (errno == EINVAL || errno == ENOSYS) { ret = -1; goto exit; } if (errno == EAGAIN || errno == EWOULDBLOCK) { #if defined(SOLARIS) || defined(FREEBSD) if (pos > offset) { /* we actually have sent sth., adjust counters and keep trying */ len = pos - offset; written += len; offset = pos; } #endif if (dsi_peek(dsi)) { /* can't go back to blocking mode, exit, the next read will return with an error and afpd will die. */ break; } continue; } LOG(log_error, logtype_dsi, "dsi_stream_read_file: %s", strerror(errno)); break; } else if (!len) { /* afpd is going to exit */ ret = -1; goto exit; } else written += len; } dsi->write_count += written; exit: dsi->in_write--; LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: sent: %zd", written); if (ret != 0) return -1; return written; } #endif /* * Essentially a loop around buf_read() to ensure "length" bytes are read * from dsi->buffer and/or the socket. * * @returns length on success, some value smaller then length indicates an error */ size_t dsi_stream_read(DSI *dsi, void *data, const size_t length) { size_t stored; ssize_t len; if (dsi->flags & DSI_DISCONNECTED) return 0; LOG(log_maxdebug, logtype_dsi, "dsi_stream_read(%u bytes)", length); stored = 0; while (stored < length) { len = buf_read(dsi, (u_int8_t *) data + stored, length - stored); if (len == -1 && (errno == EINTR || errno == EAGAIN)) { LOG(log_maxdebug, logtype_dsi, "dsi_stream_read: select read loop"); continue; } else if (len > 0) { stored += len; } else { /* eof or error */ /* don't log EOF error if it's just after connect (OSX 10.3 probe) */ #if 0 if (errno == ECONNRESET) dsi->flags |= DSI_GOT_ECONNRESET; #endif if (len || stored || dsi->read_count) { if (! (dsi->flags & DSI_DISCONNECTED)) { LOG(log_error, logtype_dsi, "dsi_stream_read: len:%d, %s", len, (len < 0) ? strerror(errno) : "unexpected EOF"); } return 0; } break; } } dsi->read_count += stored; LOG(log_maxdebug, logtype_dsi, "dsi_stream_read(%u bytes): got: %u", length, stored); return stored; } /* --------------------------------------- * write data. 0 on failure. this assumes that dsi_len will never * cause an overflow in the data buffer. */ int dsi_stream_send(DSI *dsi, void *buf, size_t length) { char block[DSI_BLOCKSIZ]; struct iovec iov[2]; size_t towrite; ssize_t len; LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): START", length); if (dsi->flags & DSI_DISCONNECTED) return 0; block[0] = dsi->header.dsi_flags; block[1] = dsi->header.dsi_command; memcpy(block + 2, &dsi->header.dsi_requestID, sizeof(dsi->header.dsi_requestID)); memcpy(block + 4, &dsi->header.dsi_code, sizeof(dsi->header.dsi_code)); memcpy(block + 8, &dsi->header.dsi_len, sizeof(dsi->header.dsi_len)); memcpy(block + 12, &dsi->header.dsi_reserved, sizeof(dsi->header.dsi_reserved)); if (!length) { /* just write the header */ LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): DSI header, no data", sizeof(block)); length = (dsi_stream_write(dsi, block, sizeof(block), 0) == sizeof(block)); return length; /* really 0 on failure, 1 on success */ } /* block signals */ block_sig(dsi); iov[0].iov_base = block; iov[0].iov_len = sizeof(block); iov[1].iov_base = buf; iov[1].iov_len = length; towrite = sizeof(block) + length; dsi->write_count += towrite; while (towrite > 0) { if (((len = writev(dsi->socket, iov, 2)) == -1 && errno == EINTR) || (len == 0)) continue; if ((size_t)len == towrite) /* wrote everything out */ break; else if (len < 0) { /* error */ if (errno == EAGAIN || errno == EWOULDBLOCK) { if (!dsi_peek(dsi)) { continue; } } LOG(log_error, logtype_dsi, "dsi_stream_send: %s", strerror(errno)); unblock_sig(dsi); return 0; } towrite -= len; if (towrite > length) { /* skip part of header */ iov[0].iov_base = (char *) iov[0].iov_base + len; iov[0].iov_len -= len; } else { /* skip to data */ if (iov[0].iov_len) { len -= iov[0].iov_len; iov[0].iov_len = 0; } iov[1].iov_base = (char *) iov[1].iov_base + len; iov[1].iov_len -= len; } } LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): END", length); unblock_sig(dsi); return 1; } /*! * Read DSI command and data * * @param dsi (rw) DSI handle * * @return DSI function on success, 0 on failure */ int dsi_stream_receive(DSI *dsi) { char block[DSI_BLOCKSIZ]; LOG(log_maxdebug, logtype_dsi, "dsi_stream_receive: START"); if (dsi->flags & DSI_DISCONNECTED) return 0; /* read in the header */ if (dsi_buffered_stream_read(dsi, (u_int8_t *)block, sizeof(block)) != sizeof(block)) return 0; dsi->header.dsi_flags = block[0]; dsi->header.dsi_command = block[1]; if (dsi->header.dsi_command == 0) return 0; memcpy(&dsi->header.dsi_requestID, block + 2, sizeof(dsi->header.dsi_requestID)); memcpy(&dsi->header.dsi_code, block + 4, sizeof(dsi->header.dsi_code)); memcpy(&dsi->header.dsi_len, block + 8, sizeof(dsi->header.dsi_len)); memcpy(&dsi->header.dsi_reserved, block + 12, sizeof(dsi->header.dsi_reserved)); dsi->clientID = ntohs(dsi->header.dsi_requestID); /* make sure we don't over-write our buffers. */ dsi->cmdlen = min(ntohl(dsi->header.dsi_len), DSI_CMDSIZ); if (dsi_stream_read(dsi, dsi->commands, dsi->cmdlen) != dsi->cmdlen) return 0; LOG(log_debug, logtype_dsi, "dsi_stream_receive: DSI cmdlen: %zd", dsi->cmdlen); return block[1]; }
SaM-Solutions/netatalk
libatalk/dsi/dsi_stream.c
C
gpl-2.0
15,570
/*- * BSD LICENSE * * Copyright(c) 2010-2017 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <rte_ethdev.h> #include "base/ixgbe_api.h" #include "ixgbe_ethdev.h" #include "rte_pmd_ixgbe.h" int rte_pmd_ixgbe_set_vf_mac_addr(uint8_t port, uint16_t vf, struct ether_addr *mac_addr) { struct ixgbe_hw *hw; struct ixgbe_vf_info *vfinfo; int rar_entry; uint8_t *new_mac = (uint8_t *)(mac_addr); struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); vfinfo = *(IXGBE_DEV_PRIVATE_TO_P_VFDATA(dev->data->dev_private)); rar_entry = hw->mac.num_rar_entries - (vf + 1); if (is_valid_assigned_ether_addr((struct ether_addr *)new_mac)) { rte_memcpy(vfinfo[vf].vf_mac_addresses, new_mac, ETHER_ADDR_LEN); return hw->mac.ops.set_rar(hw, rar_entry, new_mac, vf, IXGBE_RAH_AV); } return -EINVAL; } int rte_pmd_ixgbe_ping_vf(uint8_t port, uint16_t vf) { struct ixgbe_hw *hw; struct ixgbe_vf_info *vfinfo; struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; uint32_t ctrl; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); vfinfo = *(IXGBE_DEV_PRIVATE_TO_P_VFDATA(dev->data->dev_private)); ctrl = IXGBE_PF_CONTROL_MSG; if (vfinfo[vf].clear_to_send) ctrl |= IXGBE_VT_MSGTYPE_CTS; ixgbe_write_mbx(hw, &ctrl, 1, vf); return 0; } int rte_pmd_ixgbe_set_vf_vlan_anti_spoof(uint8_t port, uint16_t vf, uint8_t on) { struct ixgbe_hw *hw; struct ixgbe_mac_info *mac; struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); mac = &hw->mac; mac->ops.set_vlan_anti_spoofing(hw, on, vf); return 0; } int rte_pmd_ixgbe_set_vf_mac_anti_spoof(uint8_t port, uint16_t vf, uint8_t on) { struct ixgbe_hw *hw; struct ixgbe_mac_info *mac; struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); mac = &hw->mac; mac->ops.set_mac_anti_spoofing(hw, on, vf); return 0; } int rte_pmd_ixgbe_set_vf_vlan_insert(uint8_t port, uint16_t vf, uint16_t vlan_id) { struct ixgbe_hw *hw; uint32_t ctrl; struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; if (vlan_id > ETHER_MAX_VLAN_ID) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); ctrl = IXGBE_READ_REG(hw, IXGBE_VMVIR(vf)); if (vlan_id) { ctrl = vlan_id; ctrl |= IXGBE_VMVIR_VLANA_DEFAULT; } else { ctrl = 0; } IXGBE_WRITE_REG(hw, IXGBE_VMVIR(vf), ctrl); return 0; } int rte_pmd_ixgbe_set_tx_loopback(uint8_t port, uint8_t on) { struct ixgbe_hw *hw; uint32_t ctrl; struct rte_eth_dev *dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); ctrl = IXGBE_READ_REG(hw, IXGBE_PFDTXGSWC); /* enable or disable VMDQ loopback */ if (on) ctrl |= IXGBE_PFDTXGSWC_VT_LBEN; else ctrl &= ~IXGBE_PFDTXGSWC_VT_LBEN; IXGBE_WRITE_REG(hw, IXGBE_PFDTXGSWC, ctrl); return 0; } int rte_pmd_ixgbe_set_all_queues_drop_en(uint8_t port, uint8_t on) { struct ixgbe_hw *hw; uint32_t reg_value; int i; int num_queues = (int)(IXGBE_QDE_IDX_MASK >> IXGBE_QDE_IDX_SHIFT); struct rte_eth_dev *dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); for (i = 0; i <= num_queues; i++) { reg_value = IXGBE_QDE_WRITE | (i << IXGBE_QDE_IDX_SHIFT) | (on & IXGBE_QDE_ENABLE); IXGBE_WRITE_REG(hw, IXGBE_QDE, reg_value); } return 0; } int rte_pmd_ixgbe_set_vf_split_drop_en(uint8_t port, uint16_t vf, uint8_t on) { struct ixgbe_hw *hw; uint32_t reg_value; struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; /* only support VF's 0 to 63 */ if ((vf >= pci_dev->max_vfs) || (vf > 63)) return -EINVAL; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); reg_value = IXGBE_READ_REG(hw, IXGBE_SRRCTL(vf)); if (on) reg_value |= IXGBE_SRRCTL_DROP_EN; else reg_value &= ~IXGBE_SRRCTL_DROP_EN; IXGBE_WRITE_REG(hw, IXGBE_SRRCTL(vf), reg_value); return 0; } int rte_pmd_ixgbe_set_vf_vlan_stripq(uint8_t port, uint16_t vf, uint8_t on) { struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; struct ixgbe_hw *hw; uint16_t queues_per_pool; uint32_t q; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; if (on > 1) return -EINVAL; RTE_FUNC_PTR_OR_ERR_RET(*dev->dev_ops->vlan_strip_queue_set, -ENOTSUP); /* The PF has 128 queue pairs and in SRIOV configuration * those queues will be assigned to VF's, so RXDCTL * registers will be dealing with queues which will be * assigned to VF's. * Let's say we have SRIOV configured with 31 VF's then the * first 124 queues 0-123 will be allocated to VF's and only * the last 4 queues 123-127 will be assigned to the PF. */ if (hw->mac.type == ixgbe_mac_82598EB) queues_per_pool = (uint16_t)hw->mac.max_rx_queues / ETH_16_POOLS; else queues_per_pool = (uint16_t)hw->mac.max_rx_queues / ETH_64_POOLS; for (q = 0; q < queues_per_pool; q++) (*dev->dev_ops->vlan_strip_queue_set)(dev, q + vf * queues_per_pool, on); return 0; } int rte_pmd_ixgbe_set_vf_rxmode(uint8_t port, uint16_t vf, uint16_t rx_mask, uint8_t on) { int val = 0; struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; struct ixgbe_hw *hw; uint32_t vmolr; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); vmolr = IXGBE_READ_REG(hw, IXGBE_VMOLR(vf)); if (hw->mac.type == ixgbe_mac_82598EB) { PMD_INIT_LOG(ERR, "setting VF receive mode set should be done" " on 82599 hardware and newer"); return -ENOTSUP; } if (ixgbe_vt_check(hw) < 0) return -ENOTSUP; val = ixgbe_convert_vm_rx_mask_to_val(rx_mask, val); if (on) vmolr |= val; else vmolr &= ~val; IXGBE_WRITE_REG(hw, IXGBE_VMOLR(vf), vmolr); return 0; } int rte_pmd_ixgbe_set_vf_rx(uint8_t port, uint16_t vf, uint8_t on) { struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; uint32_t reg, addr; uint32_t val; const uint8_t bit1 = 0x1; struct ixgbe_hw *hw; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); if (ixgbe_vt_check(hw) < 0) return -ENOTSUP; /* for vf >= 32, set bit in PFVFRE[1], otherwise PFVFRE[0] */ if (vf >= 32) { addr = IXGBE_VFRE(1); val = bit1 << (vf - 32); } else { addr = IXGBE_VFRE(0); val = bit1 << vf; } reg = IXGBE_READ_REG(hw, addr); if (on) reg |= val; else reg &= ~val; IXGBE_WRITE_REG(hw, addr, reg); return 0; } int rte_pmd_ixgbe_set_vf_tx(uint8_t port, uint16_t vf, uint8_t on) { struct rte_eth_dev *dev; struct rte_pci_device *pci_dev; uint32_t reg, addr; uint32_t val; const uint8_t bit1 = 0x1; struct ixgbe_hw *hw; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; pci_dev = IXGBE_DEV_TO_PCI(dev); if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (vf >= pci_dev->max_vfs) return -EINVAL; if (on > 1) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); if (ixgbe_vt_check(hw) < 0) return -ENOTSUP; /* for vf >= 32, set bit in PFVFTE[1], otherwise PFVFTE[0] */ if (vf >= 32) { addr = IXGBE_VFTE(1); val = bit1 << (vf - 32); } else { addr = IXGBE_VFTE(0); val = bit1 << vf; } reg = IXGBE_READ_REG(hw, addr); if (on) reg |= val; else reg &= ~val; IXGBE_WRITE_REG(hw, addr, reg); return 0; } int rte_pmd_ixgbe_set_vf_vlan_filter(uint8_t port, uint16_t vlan, uint64_t vf_mask, uint8_t vlan_on) { struct rte_eth_dev *dev; int ret = 0; uint16_t vf_idx; struct ixgbe_hw *hw; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; if ((vlan > ETHER_MAX_VLAN_ID) || (vf_mask == 0)) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); if (ixgbe_vt_check(hw) < 0) return -ENOTSUP; for (vf_idx = 0; vf_idx < 64; vf_idx++) { if (vf_mask & ((uint64_t)(1ULL << vf_idx))) { ret = hw->mac.ops.set_vfta(hw, vlan, vf_idx, vlan_on, false); if (ret < 0) return ret; } } return ret; } int rte_pmd_ixgbe_set_vf_rate_limit(uint8_t port, uint16_t vf, uint16_t tx_rate, uint64_t q_msk) { struct rte_eth_dev *dev; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; return ixgbe_set_vf_rate_limit(dev, vf, tx_rate, q_msk); } int rte_pmd_ixgbe_macsec_enable(uint8_t port, uint8_t en, uint8_t rp) { struct ixgbe_hw *hw; struct rte_eth_dev *dev; uint32_t ctrl; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); /* Stop the data paths */ if (ixgbe_disable_sec_rx_path(hw) != IXGBE_SUCCESS) return -ENOTSUP; /** * Workaround: * As no ixgbe_disable_sec_rx_path equivalent is * implemented for tx in the base code, and we are * not allowed to modify the base code in DPDK, so * just call the hand-written one directly for now. * The hardware support has been checked by * ixgbe_disable_sec_rx_path(). */ ixgbe_disable_sec_tx_path_generic(hw); /* Enable Ethernet CRC (required by MACsec offload) */ ctrl = IXGBE_READ_REG(hw, IXGBE_HLREG0); ctrl |= IXGBE_HLREG0_TXCRCEN | IXGBE_HLREG0_RXCRCSTRP; IXGBE_WRITE_REG(hw, IXGBE_HLREG0, ctrl); /* Enable the TX and RX crypto engines */ ctrl = IXGBE_READ_REG(hw, IXGBE_SECTXCTRL); ctrl &= ~IXGBE_SECTXCTRL_SECTX_DIS; IXGBE_WRITE_REG(hw, IXGBE_SECTXCTRL, ctrl); ctrl = IXGBE_READ_REG(hw, IXGBE_SECRXCTRL); ctrl &= ~IXGBE_SECRXCTRL_SECRX_DIS; IXGBE_WRITE_REG(hw, IXGBE_SECRXCTRL, ctrl); ctrl = IXGBE_READ_REG(hw, IXGBE_SECTXMINIFG); ctrl &= ~IXGBE_SECTX_MINSECIFG_MASK; ctrl |= 0x3; IXGBE_WRITE_REG(hw, IXGBE_SECTXMINIFG, ctrl); /* Enable SA lookup */ ctrl = IXGBE_READ_REG(hw, IXGBE_LSECTXCTRL); ctrl &= ~IXGBE_LSECTXCTRL_EN_MASK; ctrl |= en ? IXGBE_LSECTXCTRL_AUTH_ENCRYPT : IXGBE_LSECTXCTRL_AUTH; ctrl |= IXGBE_LSECTXCTRL_AISCI; ctrl &= ~IXGBE_LSECTXCTRL_PNTHRSH_MASK; ctrl |= IXGBE_MACSEC_PNTHRSH & IXGBE_LSECTXCTRL_PNTHRSH_MASK; IXGBE_WRITE_REG(hw, IXGBE_LSECTXCTRL, ctrl); ctrl = IXGBE_READ_REG(hw, IXGBE_LSECRXCTRL); ctrl &= ~IXGBE_LSECRXCTRL_EN_MASK; ctrl |= IXGBE_LSECRXCTRL_STRICT << IXGBE_LSECRXCTRL_EN_SHIFT; ctrl &= ~IXGBE_LSECRXCTRL_PLSH; if (rp) ctrl |= IXGBE_LSECRXCTRL_RP; else ctrl &= ~IXGBE_LSECRXCTRL_RP; IXGBE_WRITE_REG(hw, IXGBE_LSECRXCTRL, ctrl); /* Start the data paths */ ixgbe_enable_sec_rx_path(hw); /** * Workaround: * As no ixgbe_enable_sec_rx_path equivalent is * implemented for tx in the base code, and we are * not allowed to modify the base code in DPDK, so * just call the hand-written one directly for now. */ ixgbe_enable_sec_tx_path_generic(hw); return 0; } int rte_pmd_ixgbe_macsec_disable(uint8_t port) { struct ixgbe_hw *hw; struct rte_eth_dev *dev; uint32_t ctrl; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); /* Stop the data paths */ if (ixgbe_disable_sec_rx_path(hw) != IXGBE_SUCCESS) return -ENOTSUP; /** * Workaround: * As no ixgbe_disable_sec_rx_path equivalent is * implemented for tx in the base code, and we are * not allowed to modify the base code in DPDK, so * just call the hand-written one directly for now. * The hardware support has been checked by * ixgbe_disable_sec_rx_path(). */ ixgbe_disable_sec_tx_path_generic(hw); /* Disable the TX and RX crypto engines */ ctrl = IXGBE_READ_REG(hw, IXGBE_SECTXCTRL); ctrl |= IXGBE_SECTXCTRL_SECTX_DIS; IXGBE_WRITE_REG(hw, IXGBE_SECTXCTRL, ctrl); ctrl = IXGBE_READ_REG(hw, IXGBE_SECRXCTRL); ctrl |= IXGBE_SECRXCTRL_SECRX_DIS; IXGBE_WRITE_REG(hw, IXGBE_SECRXCTRL, ctrl); /* Disable SA lookup */ ctrl = IXGBE_READ_REG(hw, IXGBE_LSECTXCTRL); ctrl &= ~IXGBE_LSECTXCTRL_EN_MASK; ctrl |= IXGBE_LSECTXCTRL_DISABLE; IXGBE_WRITE_REG(hw, IXGBE_LSECTXCTRL, ctrl); ctrl = IXGBE_READ_REG(hw, IXGBE_LSECRXCTRL); ctrl &= ~IXGBE_LSECRXCTRL_EN_MASK; ctrl |= IXGBE_LSECRXCTRL_DISABLE << IXGBE_LSECRXCTRL_EN_SHIFT; IXGBE_WRITE_REG(hw, IXGBE_LSECRXCTRL, ctrl); /* Start the data paths */ ixgbe_enable_sec_rx_path(hw); /** * Workaround: * As no ixgbe_enable_sec_rx_path equivalent is * implemented for tx in the base code, and we are * not allowed to modify the base code in DPDK, so * just call the hand-written one directly for now. */ ixgbe_enable_sec_tx_path_generic(hw); return 0; } int rte_pmd_ixgbe_macsec_config_txsc(uint8_t port, uint8_t *mac) { struct ixgbe_hw *hw; struct rte_eth_dev *dev; uint32_t ctrl; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); ctrl = mac[0] | (mac[1] << 8) | (mac[2] << 16) | (mac[3] << 24); IXGBE_WRITE_REG(hw, IXGBE_LSECTXSCL, ctrl); ctrl = mac[4] | (mac[5] << 8); IXGBE_WRITE_REG(hw, IXGBE_LSECTXSCH, ctrl); return 0; } int rte_pmd_ixgbe_macsec_config_rxsc(uint8_t port, uint8_t *mac, uint16_t pi) { struct ixgbe_hw *hw; struct rte_eth_dev *dev; uint32_t ctrl; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); ctrl = mac[0] | (mac[1] << 8) | (mac[2] << 16) | (mac[3] << 24); IXGBE_WRITE_REG(hw, IXGBE_LSECRXSCL, ctrl); pi = rte_cpu_to_be_16(pi); ctrl = mac[4] | (mac[5] << 8) | (pi << 16); IXGBE_WRITE_REG(hw, IXGBE_LSECRXSCH, ctrl); return 0; } int rte_pmd_ixgbe_macsec_select_txsa(uint8_t port, uint8_t idx, uint8_t an, uint32_t pn, uint8_t *key) { struct ixgbe_hw *hw; struct rte_eth_dev *dev; uint32_t ctrl, i; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); if (idx != 0 && idx != 1) return -EINVAL; if (an >= 4) return -EINVAL; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); /* Set the PN and key */ pn = rte_cpu_to_be_32(pn); if (idx == 0) { IXGBE_WRITE_REG(hw, IXGBE_LSECTXPN0, pn); for (i = 0; i < 4; i++) { ctrl = (key[i * 4 + 0] << 0) | (key[i * 4 + 1] << 8) | (key[i * 4 + 2] << 16) | (key[i * 4 + 3] << 24); IXGBE_WRITE_REG(hw, IXGBE_LSECTXKEY0(i), ctrl); } } else { IXGBE_WRITE_REG(hw, IXGBE_LSECTXPN1, pn); for (i = 0; i < 4; i++) { ctrl = (key[i * 4 + 0] << 0) | (key[i * 4 + 1] << 8) | (key[i * 4 + 2] << 16) | (key[i * 4 + 3] << 24); IXGBE_WRITE_REG(hw, IXGBE_LSECTXKEY1(i), ctrl); } } /* Set AN and select the SA */ ctrl = (an << idx * 2) | (idx << 4); IXGBE_WRITE_REG(hw, IXGBE_LSECTXSA, ctrl); return 0; } int rte_pmd_ixgbe_macsec_select_rxsa(uint8_t port, uint8_t idx, uint8_t an, uint32_t pn, uint8_t *key) { struct ixgbe_hw *hw; struct rte_eth_dev *dev; uint32_t ctrl, i; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; hw = IXGBE_DEV_PRIVATE_TO_HW(dev->data->dev_private); if (idx != 0 && idx != 1) return -EINVAL; if (an >= 4) return -EINVAL; /* Set the PN */ pn = rte_cpu_to_be_32(pn); IXGBE_WRITE_REG(hw, IXGBE_LSECRXPN(idx), pn); /* Set the key */ for (i = 0; i < 4; i++) { ctrl = (key[i * 4 + 0] << 0) | (key[i * 4 + 1] << 8) | (key[i * 4 + 2] << 16) | (key[i * 4 + 3] << 24); IXGBE_WRITE_REG(hw, IXGBE_LSECRXKEY(idx, i), ctrl); } /* Set the AN and validate the SA */ ctrl = an | (1 << 2); IXGBE_WRITE_REG(hw, IXGBE_LSECRXSA(idx), ctrl); return 0; } int rte_pmd_ixgbe_set_tc_bw_alloc(uint8_t port, uint8_t tc_num, uint8_t *bw_weight) { struct rte_eth_dev *dev; struct ixgbe_dcb_config *dcb_config; struct ixgbe_dcb_tc_config *tc; struct rte_eth_conf *eth_conf; struct ixgbe_bw_conf *bw_conf; uint8_t i; uint8_t nb_tcs; uint16_t sum; RTE_ETH_VALID_PORTID_OR_ERR_RET(port, -ENODEV); dev = &rte_eth_devices[port]; if (!is_ixgbe_supported(dev)) return -ENOTSUP; if (tc_num > IXGBE_DCB_MAX_TRAFFIC_CLASS) { PMD_DRV_LOG(ERR, "TCs should be no more than %d.", IXGBE_DCB_MAX_TRAFFIC_CLASS); return -EINVAL; } dcb_config = IXGBE_DEV_PRIVATE_TO_DCB_CFG(dev->data->dev_private); bw_conf = IXGBE_DEV_PRIVATE_TO_BW_CONF(dev->data->dev_private); eth_conf = &dev->data->dev_conf; if (eth_conf->txmode.mq_mode == ETH_MQ_TX_DCB) { nb_tcs = eth_conf->tx_adv_conf.dcb_tx_conf.nb_tcs; } else if (eth_conf->txmode.mq_mode == ETH_MQ_TX_VMDQ_DCB) { if (eth_conf->tx_adv_conf.vmdq_dcb_tx_conf.nb_queue_pools == ETH_32_POOLS) nb_tcs = ETH_4_TCS; else nb_tcs = ETH_8_TCS; } else { nb_tcs = 1; } if (nb_tcs != tc_num) { PMD_DRV_LOG(ERR, "Weight should be set for all %d enabled TCs.", nb_tcs); return -EINVAL; } sum = 0; for (i = 0; i < nb_tcs; i++) sum += bw_weight[i]; if (sum != 100) { PMD_DRV_LOG(ERR, "The summary of the TC weight should be 100."); return -EINVAL; } for (i = 0; i < nb_tcs; i++) { tc = &dcb_config->tc_config[i]; tc->path[IXGBE_DCB_TX_CONFIG].bwg_percent = bw_weight[i]; } for (; i < IXGBE_DCB_MAX_TRAFFIC_CLASS; i++) { tc = &dcb_config->tc_config[i]; tc->path[IXGBE_DCB_TX_CONFIG].bwg_percent = 0; } bw_conf->tc_num = nb_tcs; return 0; }
RehiveTech/dpdk
drivers/net/ixgbe/rte_pmd_ixgbe.c
C
gpl-2.0
21,390
/* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifndef __ARCH_ARM_MACH_MSM_IOMMU_HW_8XXX_H #define __ARCH_ARM_MACH_MSM_IOMMU_HW_8XXX_H #define CTX_SHIFT 12 #define GET_GLOBAL_REG(reg, base) (readl((base) + (reg))) #define GET_CTX_REG(reg, base, ctx) \ (readl((base) + (reg) + ((ctx) << CTX_SHIFT))) #define SET_GLOBAL_REG(reg, base, val) writel((val), ((base) + (reg))) #define SET_CTX_REG(reg, base, ctx, val) \ writel((val), ((base) + (reg) + ((ctx) << CTX_SHIFT))) /* Wrappers for numbered registers */ #define SET_GLOBAL_REG_N(b, n, r, v) SET_GLOBAL_REG(b, ((r) + (n << 2)), (v)) #define GET_GLOBAL_REG_N(b, n, r) GET_GLOBAL_REG(b, ((r) + (n << 2))) /* Field wrappers */ #define GET_GLOBAL_FIELD(b, r, F) GET_FIELD(((b) + (r)), F##_MASK, F##_SHIFT) #define GET_CONTEXT_FIELD(b, c, r, F) \ GET_FIELD(((b) + (r) + ((c) << CTX_SHIFT)), F##_MASK, F##_SHIFT) #define SET_GLOBAL_FIELD(b, r, F, v) \ SET_FIELD(((b) + (r)), F##_MASK, F##_SHIFT, (v)) #define SET_CONTEXT_FIELD(b, c, r, F, v) \ SET_FIELD(((b) + (r) + ((c) << CTX_SHIFT)), F##_MASK, F##_SHIFT, (v)) #define GET_FIELD(addr, mask, shift) ((readl(addr) >> (shift)) & (mask)) #define SET_FIELD(addr, mask, shift, v) \ do { \ int t = readl(addr); \ writel((t & ~((mask) << (shift))) + (((v) & (mask)) << (shift)), addr);\ } while (0) #define NUM_FL_PTE 4096 #define NUM_SL_PTE 256 #define NUM_TEX_CLASS 8 /* First-level page table bits */ #define FL_BASE_MASK 0xFFFFFC00 #define FL_TYPE_TABLE (1 << 0) #define FL_TYPE_SECT (2 << 0) #define FL_SUPERSECTION (1 << 18) #define FL_AP_WRITE (1 << 10) #define FL_AP_READ (1 << 11) #define FL_SHARED (1 << 16) #define FL_BUFFERABLE (1 << 2) #define FL_CACHEABLE (1 << 3) #define FL_TEX0 (1 << 12) #define FL_OFFSET(va) (((va) & 0xFFF00000) >> 20) #define FL_NG (1 << 17) /* Second-level page table bits */ #define SL_BASE_MASK_LARGE 0xFFFF0000 #define SL_BASE_MASK_SMALL 0xFFFFF000 #define SL_TYPE_LARGE (1 << 0) #define SL_TYPE_SMALL (2 << 0) #define SL_AP0 (1 << 4) #define SL_AP1 (2 << 4) #define SL_SHARED (1 << 10) #define SL_BUFFERABLE (1 << 2) #define SL_CACHEABLE (1 << 3) #define SL_TEX0 (1 << 6) #define SL_OFFSET(va) (((va) & 0xFF000) >> 12) #define SL_NG (1 << 11) /* Memory type and cache policy attributes */ #define MT_SO 0 #define MT_DEV 1 #define MT_NORMAL 2 #define CP_NONCACHED 0 #define CP_WB_WA 1 #define CP_WT 2 #define CP_WB_NWA 3 /* Global register setters / getters */ #define SET_M2VCBR_N(b, N, v) SET_GLOBAL_REG_N(M2VCBR_N, N, (b), (v)) #define SET_CBACR_N(b, N, v) SET_GLOBAL_REG_N(CBACR_N, N, (b), (v)) #define SET_TLBRSW(b, v) SET_GLOBAL_REG(TLBRSW, (b), (v)) #define SET_TLBTR0(b, v) SET_GLOBAL_REG(TLBTR0, (b), (v)) #define SET_TLBTR1(b, v) SET_GLOBAL_REG(TLBTR1, (b), (v)) #define SET_TLBTR2(b, v) SET_GLOBAL_REG(TLBTR2, (b), (v)) #define SET_TESTBUSCR(b, v) SET_GLOBAL_REG(TESTBUSCR, (b), (v)) #define SET_GLOBAL_TLBIALL(b, v) SET_GLOBAL_REG(GLOBAL_TLBIALL, (b), (v)) #define SET_TLBIVMID(b, v) SET_GLOBAL_REG(TLBIVMID, (b), (v)) #define SET_CR(b, v) SET_GLOBAL_REG(CR, (b), (v)) #define SET_EAR(b, v) SET_GLOBAL_REG(EAR, (b), (v)) #define SET_ESR(b, v) SET_GLOBAL_REG(ESR, (b), (v)) #define SET_ESRRESTORE(b, v) SET_GLOBAL_REG(ESRRESTORE, (b), (v)) #define SET_ESYNR0(b, v) SET_GLOBAL_REG(ESYNR0, (b), (v)) #define SET_ESYNR1(b, v) SET_GLOBAL_REG(ESYNR1, (b), (v)) #define SET_RPU_ACR(b, v) SET_GLOBAL_REG(RPU_ACR, (b), (v)) #define GET_M2VCBR_N(b, N) GET_GLOBAL_REG_N(M2VCBR_N, N, (b)) #define GET_CBACR_N(b, N) GET_GLOBAL_REG_N(CBACR_N, N, (b)) #define GET_TLBTR0(b) GET_GLOBAL_REG(TLBTR0, (b)) #define GET_TLBTR1(b) GET_GLOBAL_REG(TLBTR1, (b)) #define GET_TLBTR2(b) GET_GLOBAL_REG(TLBTR2, (b)) #define GET_TESTBUSCR(b) GET_GLOBAL_REG(TESTBUSCR, (b)) #define GET_GLOBAL_TLBIALL(b) GET_GLOBAL_REG(GLOBAL_TLBIALL, (b)) #define GET_TLBIVMID(b) GET_GLOBAL_REG(TLBIVMID, (b)) #define GET_CR(b) GET_GLOBAL_REG(CR, (b)) #define GET_EAR(b) GET_GLOBAL_REG(EAR, (b)) #define GET_ESR(b) GET_GLOBAL_REG(ESR, (b)) #define GET_ESRRESTORE(b) GET_GLOBAL_REG(ESRRESTORE, (b)) #define GET_ESYNR0(b) GET_GLOBAL_REG(ESYNR0, (b)) #define GET_ESYNR1(b) GET_GLOBAL_REG(ESYNR1, (b)) #define GET_REV(b) GET_GLOBAL_REG(REV, (b)) #define GET_IDR(b) GET_GLOBAL_REG(IDR, (b)) #define GET_RPU_ACR(b) GET_GLOBAL_REG(RPU_ACR, (b)) /* Context register setters/getters */ #define SET_SCTLR(b, c, v) SET_CTX_REG(SCTLR, (b), (c), (v)) #define SET_ACTLR(b, c, v) SET_CTX_REG(ACTLR, (b), (c), (v)) #define SET_CONTEXTIDR(b, c, v) SET_CTX_REG(CONTEXTIDR, (b), (c), (v)) #define SET_TTBR0(b, c, v) SET_CTX_REG(TTBR0, (b), (c), (v)) #define SET_TTBR1(b, c, v) SET_CTX_REG(TTBR1, (b), (c), (v)) #define SET_TTBCR(b, c, v) SET_CTX_REG(TTBCR, (b), (c), (v)) #define SET_PAR(b, c, v) SET_CTX_REG(PAR, (b), (c), (v)) #define SET_FSR(b, c, v) SET_CTX_REG(FSR, (b), (c), (v)) #define SET_FSRRESTORE(b, c, v) SET_CTX_REG(FSRRESTORE, (b), (c), (v)) #define SET_FAR(b, c, v) SET_CTX_REG(FAR, (b), (c), (v)) #define SET_FSYNR0(b, c, v) SET_CTX_REG(FSYNR0, (b), (c), (v)) #define SET_FSYNR1(b, c, v) SET_CTX_REG(FSYNR1, (b), (c), (v)) #define SET_PRRR(b, c, v) SET_CTX_REG(PRRR, (b), (c), (v)) #define SET_NMRR(b, c, v) SET_CTX_REG(NMRR, (b), (c), (v)) #define SET_TLBLKCR(b, c, v) SET_CTX_REG(TLBLCKR, (b), (c), (v)) #define SET_V2PSR(b, c, v) SET_CTX_REG(V2PSR, (b), (c), (v)) #define SET_TLBFLPTER(b, c, v) SET_CTX_REG(TLBFLPTER, (b), (c), (v)) #define SET_TLBSLPTER(b, c, v) SET_CTX_REG(TLBSLPTER, (b), (c), (v)) #define SET_BFBCR(b, c, v) SET_CTX_REG(BFBCR, (b), (c), (v)) #define SET_CTX_TLBIALL(b, c, v) SET_CTX_REG(CTX_TLBIALL, (b), (c), (v)) #define SET_TLBIASID(b, c, v) SET_CTX_REG(TLBIASID, (b), (c), (v)) #define SET_TLBIVA(b, c, v) SET_CTX_REG(TLBIVA, (b), (c), (v)) #define SET_TLBIVAA(b, c, v) SET_CTX_REG(TLBIVAA, (b), (c), (v)) #define SET_V2PPR(b, c, v) SET_CTX_REG(V2PPR, (b), (c), (v)) #define SET_V2PPW(b, c, v) SET_CTX_REG(V2PPW, (b), (c), (v)) #define SET_V2PUR(b, c, v) SET_CTX_REG(V2PUR, (b), (c), (v)) #define SET_V2PUW(b, c, v) SET_CTX_REG(V2PUW, (b), (c), (v)) #define SET_RESUME(b, c, v) SET_CTX_REG(RESUME, (b), (c), (v)) #define GET_SCTLR(b, c) GET_CTX_REG(SCTLR, (b), (c)) #define GET_ACTLR(b, c) GET_CTX_REG(ACTLR, (b), (c)) #define GET_CONTEXTIDR(b, c) GET_CTX_REG(CONTEXTIDR, (b), (c)) #define GET_TTBR0(b, c) GET_CTX_REG(TTBR0, (b), (c)) #define GET_TTBR1(b, c) GET_CTX_REG(TTBR1, (b), (c)) #define GET_TTBCR(b, c) GET_CTX_REG(TTBCR, (b), (c)) #define GET_PAR(b, c) GET_CTX_REG(PAR, (b), (c)) #define GET_FSR(b, c) GET_CTX_REG(FSR, (b), (c)) #define GET_FSRRESTORE(b, c) GET_CTX_REG(FSRRESTORE, (b), (c)) #define GET_FAR(b, c) GET_CTX_REG(FAR, (b), (c)) #define GET_FSYNR0(b, c) GET_CTX_REG(FSYNR0, (b), (c)) #define GET_FSYNR1(b, c) GET_CTX_REG(FSYNR1, (b), (c)) #define GET_PRRR(b, c) GET_CTX_REG(PRRR, (b), (c)) #define GET_NMRR(b, c) GET_CTX_REG(NMRR, (b), (c)) #define GET_TLBLCKR(b, c) GET_CTX_REG(TLBLCKR, (b), (c)) #define GET_V2PSR(b, c) GET_CTX_REG(V2PSR, (b), (c)) #define GET_TLBFLPTER(b, c) GET_CTX_REG(TLBFLPTER, (b), (c)) #define GET_TLBSLPTER(b, c) GET_CTX_REG(TLBSLPTER, (b), (c)) #define GET_BFBCR(b, c) GET_CTX_REG(BFBCR, (b), (c)) #define GET_CTX_TLBIALL(b, c) GET_CTX_REG(CTX_TLBIALL, (b), (c)) #define GET_TLBIASID(b, c) GET_CTX_REG(TLBIASID, (b), (c)) #define GET_TLBIVA(b, c) GET_CTX_REG(TLBIVA, (b), (c)) #define GET_TLBIVAA(b, c) GET_CTX_REG(TLBIVAA, (b), (c)) #define GET_V2PPR(b, c) GET_CTX_REG(V2PPR, (b), (c)) #define GET_V2PPW(b, c) GET_CTX_REG(V2PPW, (b), (c)) #define GET_V2PUR(b, c) GET_CTX_REG(V2PUR, (b), (c)) #define GET_V2PUW(b, c) GET_CTX_REG(V2PUW, (b), (c)) #define GET_RESUME(b, c) GET_CTX_REG(RESUME, (b), (c)) /* Global field setters / getters */ /* Global Field Setters: */ /* CBACR_N */ #define SET_RWVMID(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), RWVMID, v) #define SET_RWE(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), RWE, v) #define SET_RWGE(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), RWGE, v) #define SET_CBVMID(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), CBVMID, v) #define SET_IRPTNDX(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), IRPTNDX, v) /* M2VCBR_N */ #define SET_VMID(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), VMID, v) #define SET_CBNDX(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), CBNDX, v) #define SET_BYPASSD(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BYPASSD, v) #define SET_BPRCOSH(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPRCOSH, v) #define SET_BPRCISH(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPRCISH, v) #define SET_BPRCNSH(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPRCNSH, v) #define SET_BPSHCFG(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPSHCFG, v) #define SET_NSCFG(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), NSCFG, v) #define SET_BPMTCFG(b, n, v) SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPMTCFG, v) #define SET_BPMEMTYPE(b, n, v) \ SET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPMEMTYPE, v) /* CR */ #define SET_RPUE(b, v) SET_GLOBAL_FIELD(b, CR, RPUE, v) #define SET_RPUERE(b, v) SET_GLOBAL_FIELD(b, CR, RPUERE, v) #define SET_RPUEIE(b, v) SET_GLOBAL_FIELD(b, CR, RPUEIE, v) #define SET_DCDEE(b, v) SET_GLOBAL_FIELD(b, CR, DCDEE, v) #define SET_CLIENTPD(b, v) SET_GLOBAL_FIELD(b, CR, CLIENTPD, v) #define SET_STALLD(b, v) SET_GLOBAL_FIELD(b, CR, STALLD, v) #define SET_TLBLKCRWE(b, v) SET_GLOBAL_FIELD(b, CR, TLBLKCRWE, v) #define SET_CR_TLBIALLCFG(b, v) SET_GLOBAL_FIELD(b, CR, CR_TLBIALLCFG, v) #define SET_TLBIVMIDCFG(b, v) SET_GLOBAL_FIELD(b, CR, TLBIVMIDCFG, v) #define SET_CR_HUME(b, v) SET_GLOBAL_FIELD(b, CR, CR_HUME, v) /* ESR */ #define SET_CFG(b, v) SET_GLOBAL_FIELD(b, ESR, CFG, v) #define SET_BYPASS(b, v) SET_GLOBAL_FIELD(b, ESR, BYPASS, v) #define SET_ESR_MULTI(b, v) SET_GLOBAL_FIELD(b, ESR, ESR_MULTI, v) /* ESYNR0 */ #define SET_ESYNR0_AMID(b, v) SET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_AMID, v) #define SET_ESYNR0_APID(b, v) SET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_APID, v) #define SET_ESYNR0_ABID(b, v) SET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_ABID, v) #define SET_ESYNR0_AVMID(b, v) SET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_AVMID, v) #define SET_ESYNR0_ATID(b, v) SET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_ATID, v) /* ESYNR1 */ #define SET_ESYNR1_AMEMTYPE(b, v) \ SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AMEMTYPE, v) #define SET_ESYNR1_ASHARED(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ASHARED, v) #define SET_ESYNR1_AINNERSHARED(b, v) \ SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AINNERSHARED, v) #define SET_ESYNR1_APRIV(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_APRIV, v) #define SET_ESYNR1_APROTNS(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_APROTNS, v) #define SET_ESYNR1_AINST(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AINST, v) #define SET_ESYNR1_AWRITE(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AWRITE, v) #define SET_ESYNR1_ABURST(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ABURST, v) #define SET_ESYNR1_ALEN(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ALEN, v) #define SET_ESYNR1_ASIZE(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ASIZE, v) #define SET_ESYNR1_ALOCK(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ALOCK, v) #define SET_ESYNR1_AOOO(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AOOO, v) #define SET_ESYNR1_AFULL(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AFULL, v) #define SET_ESYNR1_AC(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AC, v) #define SET_ESYNR1_DCD(b, v) SET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_DCD, v) /* TESTBUSCR */ #define SET_TBE(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, TBE, v) #define SET_SPDMBE(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, SPDMBE, v) #define SET_WGSEL(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, WGSEL, v) #define SET_TBLSEL(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, TBLSEL, v) #define SET_TBHSEL(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, TBHSEL, v) #define SET_SPDM0SEL(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, SPDM0SEL, v) #define SET_SPDM1SEL(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, SPDM1SEL, v) #define SET_SPDM2SEL(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, SPDM2SEL, v) #define SET_SPDM3SEL(b, v) SET_GLOBAL_FIELD(b, TESTBUSCR, SPDM3SEL, v) /* TLBIVMID */ #define SET_TLBIVMID_VMID(b, v) SET_GLOBAL_FIELD(b, TLBIVMID, TLBIVMID_VMID, v) /* TLBRSW */ #define SET_TLBRSW_INDEX(b, v) SET_GLOBAL_FIELD(b, TLBRSW, TLBRSW_INDEX, v) #define SET_TLBBFBS(b, v) SET_GLOBAL_FIELD(b, TLBRSW, TLBBFBS, v) /* TLBTR0 */ #define SET_PR(b, v) SET_GLOBAL_FIELD(b, TLBTR0, PR, v) #define SET_PW(b, v) SET_GLOBAL_FIELD(b, TLBTR0, PW, v) #define SET_UR(b, v) SET_GLOBAL_FIELD(b, TLBTR0, UR, v) #define SET_UW(b, v) SET_GLOBAL_FIELD(b, TLBTR0, UW, v) #define SET_XN(b, v) SET_GLOBAL_FIELD(b, TLBTR0, XN, v) #define SET_NSDESC(b, v) SET_GLOBAL_FIELD(b, TLBTR0, NSDESC, v) #define SET_ISH(b, v) SET_GLOBAL_FIELD(b, TLBTR0, ISH, v) #define SET_SH(b, v) SET_GLOBAL_FIELD(b, TLBTR0, SH, v) #define SET_MT(b, v) SET_GLOBAL_FIELD(b, TLBTR0, MT, v) #define SET_DPSIZR(b, v) SET_GLOBAL_FIELD(b, TLBTR0, DPSIZR, v) #define SET_DPSIZC(b, v) SET_GLOBAL_FIELD(b, TLBTR0, DPSIZC, v) /* TLBTR1 */ #define SET_TLBTR1_VMID(b, v) SET_GLOBAL_FIELD(b, TLBTR1, TLBTR1_VMID, v) #define SET_TLBTR1_PA(b, v) SET_GLOBAL_FIELD(b, TLBTR1, TLBTR1_PA, v) /* TLBTR2 */ #define SET_TLBTR2_ASID(b, v) SET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_ASID, v) #define SET_TLBTR2_V(b, v) SET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_V, v) #define SET_TLBTR2_NSTID(b, v) SET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_NSTID, v) #define SET_TLBTR2_NV(b, v) SET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_NV, v) #define SET_TLBTR2_VA(b, v) SET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_VA, v) /* Global Field Getters */ /* CBACR_N */ #define GET_RWVMID(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), RWVMID) #define GET_RWE(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), RWE) #define GET_RWGE(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), RWGE) #define GET_CBVMID(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), CBVMID) #define GET_IRPTNDX(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(CBACR_N), IRPTNDX) /* M2VCBR_N */ #define GET_VMID(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), VMID) #define GET_CBNDX(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), CBNDX) #define GET_BYPASSD(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BYPASSD) #define GET_BPRCOSH(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPRCOSH) #define GET_BPRCISH(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPRCISH) #define GET_BPRCNSH(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPRCNSH) #define GET_BPSHCFG(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPSHCFG) #define GET_NSCFG(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), NSCFG) #define GET_BPMTCFG(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPMTCFG) #define GET_BPMEMTYPE(b, n) GET_GLOBAL_FIELD(b, (n<<2)|(M2VCBR_N), BPMEMTYPE) /* CR */ #define GET_RPUE(b) GET_GLOBAL_FIELD(b, CR, RPUE) #define GET_RPUERE(b) GET_GLOBAL_FIELD(b, CR, RPUERE) #define GET_RPUEIE(b) GET_GLOBAL_FIELD(b, CR, RPUEIE) #define GET_DCDEE(b) GET_GLOBAL_FIELD(b, CR, DCDEE) #define GET_CLIENTPD(b) GET_GLOBAL_FIELD(b, CR, CLIENTPD) #define GET_STALLD(b) GET_GLOBAL_FIELD(b, CR, STALLD) #define GET_TLBLKCRWE(b) GET_GLOBAL_FIELD(b, CR, TLBLKCRWE) #define GET_CR_TLBIALLCFG(b) GET_GLOBAL_FIELD(b, CR, CR_TLBIALLCFG) #define GET_TLBIVMIDCFG(b) GET_GLOBAL_FIELD(b, CR, TLBIVMIDCFG) #define GET_CR_HUME(b) GET_GLOBAL_FIELD(b, CR, CR_HUME) /* ESR */ #define GET_CFG(b) GET_GLOBAL_FIELD(b, ESR, CFG) #define GET_BYPASS(b) GET_GLOBAL_FIELD(b, ESR, BYPASS) #define GET_ESR_MULTI(b) GET_GLOBAL_FIELD(b, ESR, ESR_MULTI) /* ESYNR0 */ #define GET_ESYNR0_AMID(b) GET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_AMID) #define GET_ESYNR0_APID(b) GET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_APID) #define GET_ESYNR0_ABID(b) GET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_ABID) #define GET_ESYNR0_AVMID(b) GET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_AVMID) #define GET_ESYNR0_ATID(b) GET_GLOBAL_FIELD(b, ESYNR0, ESYNR0_ATID) /* ESYNR1 */ #define GET_ESYNR1_AMEMTYPE(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AMEMTYPE) #define GET_ESYNR1_ASHARED(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ASHARED) #define GET_ESYNR1_AINNERSHARED(b) \ GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AINNERSHARED) #define GET_ESYNR1_APRIV(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_APRIV) #define GET_ESYNR1_APROTNS(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_APROTNS) #define GET_ESYNR1_AINST(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AINST) #define GET_ESYNR1_AWRITE(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AWRITE) #define GET_ESYNR1_ABURST(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ABURST) #define GET_ESYNR1_ALEN(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ALEN) #define GET_ESYNR1_ASIZE(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ASIZE) #define GET_ESYNR1_ALOCK(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_ALOCK) #define GET_ESYNR1_AOOO(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AOOO) #define GET_ESYNR1_AFULL(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AFULL) #define GET_ESYNR1_AC(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_AC) #define GET_ESYNR1_DCD(b) GET_GLOBAL_FIELD(b, ESYNR1, ESYNR1_DCD) /* IDR */ #define GET_NM2VCBMT(b) GET_GLOBAL_FIELD(b, IDR, NM2VCBMT) #define GET_HTW(b) GET_GLOBAL_FIELD(b, IDR, HTW) #define GET_HUM(b) GET_GLOBAL_FIELD(b, IDR, HUM) #define GET_TLBSIZE(b) GET_GLOBAL_FIELD(b, IDR, TLBSIZE) #define GET_NCB(b) GET_GLOBAL_FIELD(b, IDR, NCB) #define GET_NIRPT(b) GET_GLOBAL_FIELD(b, IDR, NIRPT) /* REV */ #define GET_MAJOR(b) GET_GLOBAL_FIELD(b, REV, MAJOR) #define GET_MINOR(b) GET_GLOBAL_FIELD(b, REV, MINOR) /* TESTBUSCR */ #define GET_TBE(b) GET_GLOBAL_FIELD(b, TESTBUSCR, TBE) #define GET_SPDMBE(b) GET_GLOBAL_FIELD(b, TESTBUSCR, SPDMBE) #define GET_WGSEL(b) GET_GLOBAL_FIELD(b, TESTBUSCR, WGSEL) #define GET_TBLSEL(b) GET_GLOBAL_FIELD(b, TESTBUSCR, TBLSEL) #define GET_TBHSEL(b) GET_GLOBAL_FIELD(b, TESTBUSCR, TBHSEL) #define GET_SPDM0SEL(b) GET_GLOBAL_FIELD(b, TESTBUSCR, SPDM0SEL) #define GET_SPDM1SEL(b) GET_GLOBAL_FIELD(b, TESTBUSCR, SPDM1SEL) #define GET_SPDM2SEL(b) GET_GLOBAL_FIELD(b, TESTBUSCR, SPDM2SEL) #define GET_SPDM3SEL(b) GET_GLOBAL_FIELD(b, TESTBUSCR, SPDM3SEL) /* TLBIVMID */ #define GET_TLBIVMID_VMID(b) GET_GLOBAL_FIELD(b, TLBIVMID, TLBIVMID_VMID) /* TLBTR0 */ #define GET_PR(b) GET_GLOBAL_FIELD(b, TLBTR0, PR) #define GET_PW(b) GET_GLOBAL_FIELD(b, TLBTR0, PW) #define GET_UR(b) GET_GLOBAL_FIELD(b, TLBTR0, UR) #define GET_UW(b) GET_GLOBAL_FIELD(b, TLBTR0, UW) #define GET_XN(b) GET_GLOBAL_FIELD(b, TLBTR0, XN) #define GET_NSDESC(b) GET_GLOBAL_FIELD(b, TLBTR0, NSDESC) #define GET_ISH(b) GET_GLOBAL_FIELD(b, TLBTR0, ISH) #define GET_SH(b) GET_GLOBAL_FIELD(b, TLBTR0, SH) #define GET_MT(b) GET_GLOBAL_FIELD(b, TLBTR0, MT) #define GET_DPSIZR(b) GET_GLOBAL_FIELD(b, TLBTR0, DPSIZR) #define GET_DPSIZC(b) GET_GLOBAL_FIELD(b, TLBTR0, DPSIZC) /* TLBTR1 */ #define GET_TLBTR1_VMID(b) GET_GLOBAL_FIELD(b, TLBTR1, TLBTR1_VMID) #define GET_TLBTR1_PA(b) GET_GLOBAL_FIELD(b, TLBTR1, TLBTR1_PA) /* TLBTR2 */ #define GET_TLBTR2_ASID(b) GET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_ASID) #define GET_TLBTR2_V(b) GET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_V) #define GET_TLBTR2_NSTID(b) GET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_NSTID) #define GET_TLBTR2_NV(b) GET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_NV) #define GET_TLBTR2_VA(b) GET_GLOBAL_FIELD(b, TLBTR2, TLBTR2_VA) /* Context Register setters / getters */ /* Context Register setters */ /* ACTLR */ #define SET_CFERE(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, CFERE, v) #define SET_CFEIE(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, CFEIE, v) #define SET_PTSHCFG(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, PTSHCFG, v) #define SET_RCOSH(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, RCOSH, v) #define SET_RCISH(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, RCISH, v) #define SET_RCNSH(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, RCNSH, v) #define SET_PRIVCFG(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, PRIVCFG, v) #define SET_DNA(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, DNA, v) #define SET_DNLV2PA(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, DNLV2PA, v) #define SET_TLBMCFG(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, TLBMCFG, v) #define SET_CFCFG(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, CFCFG, v) #define SET_TIPCF(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, TIPCF, v) #define SET_V2PCFG(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, V2PCFG, v) #define SET_HUME(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, HUME, v) #define SET_PTMTCFG(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, PTMTCFG, v) #define SET_PTMEMTYPE(b, c, v) SET_CONTEXT_FIELD(b, c, ACTLR, PTMEMTYPE, v) /* BFBCR */ #define SET_BFBDFE(b, c, v) SET_CONTEXT_FIELD(b, c, BFBCR, BFBDFE, v) #define SET_BFBSFE(b, c, v) SET_CONTEXT_FIELD(b, c, BFBCR, BFBSFE, v) #define SET_SFVS(b, c, v) SET_CONTEXT_FIELD(b, c, BFBCR, SFVS, v) #define SET_FLVIC(b, c, v) SET_CONTEXT_FIELD(b, c, BFBCR, FLVIC, v) #define SET_SLVIC(b, c, v) SET_CONTEXT_FIELD(b, c, BFBCR, SLVIC, v) /* CONTEXTIDR */ #define SET_CONTEXTIDR_ASID(b, c, v) \ SET_CONTEXT_FIELD(b, c, CONTEXTIDR, CONTEXTIDR_ASID, v) #define SET_CONTEXTIDR_PROCID(b, c, v) \ SET_CONTEXT_FIELD(b, c, CONTEXTIDR, PROCID, v) /* FSR */ #define SET_TF(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, TF, v) #define SET_AFF(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, AFF, v) #define SET_APF(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, APF, v) #define SET_TLBMF(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, TLBMF, v) #define SET_HTWDEEF(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, HTWDEEF, v) #define SET_HTWSEEF(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, HTWSEEF, v) #define SET_MHF(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, MHF, v) #define SET_SL(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, SL, v) #define SET_SS(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, SS, v) #define SET_MULTI(b, c, v) SET_CONTEXT_FIELD(b, c, FSR, MULTI, v) /* FSYNR0 */ #define SET_AMID(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR0, AMID, v) #define SET_APID(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR0, APID, v) #define SET_ABID(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR0, ABID, v) #define SET_ATID(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR0, ATID, v) /* FSYNR1 */ #define SET_AMEMTYPE(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, AMEMTYPE, v) #define SET_ASHARED(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, ASHARED, v) #define SET_AINNERSHARED(b, c, v) \ SET_CONTEXT_FIELD(b, c, FSYNR1, AINNERSHARED, v) #define SET_APRIV(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, APRIV, v) #define SET_APROTNS(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, APROTNS, v) #define SET_AINST(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, AINST, v) #define SET_AWRITE(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, AWRITE, v) #define SET_ABURST(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, ABURST, v) #define SET_ALEN(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, ALEN, v) #define SET_FSYNR1_ASIZE(b, c, v) \ SET_CONTEXT_FIELD(b, c, FSYNR1, FSYNR1_ASIZE, v) #define SET_ALOCK(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, ALOCK, v) #define SET_AFULL(b, c, v) SET_CONTEXT_FIELD(b, c, FSYNR1, AFULL, v) /* NMRR */ #define SET_ICPC0(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC0, v) #define SET_ICPC1(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC1, v) #define SET_ICPC2(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC2, v) #define SET_ICPC3(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC3, v) #define SET_ICPC4(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC4, v) #define SET_ICPC5(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC5, v) #define SET_ICPC6(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC6, v) #define SET_ICPC7(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, ICPC7, v) #define SET_OCPC0(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC0, v) #define SET_OCPC1(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC1, v) #define SET_OCPC2(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC2, v) #define SET_OCPC3(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC3, v) #define SET_OCPC4(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC4, v) #define SET_OCPC5(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC5, v) #define SET_OCPC6(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC6, v) #define SET_OCPC7(b, c, v) SET_CONTEXT_FIELD(b, c, NMRR, OCPC7, v) /* PAR */ #define SET_FAULT(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT, v) #define SET_FAULT_TF(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT_TF, v) #define SET_FAULT_AFF(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT_AFF, v) #define SET_FAULT_APF(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT_APF, v) #define SET_FAULT_TLBMF(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT_TLBMF, v) #define SET_FAULT_HTWDEEF(b, c, v) \ SET_CONTEXT_FIELD(b, c, PAR, FAULT_HTWDEEF, v) #define SET_FAULT_HTWSEEF(b, c, v) \ SET_CONTEXT_FIELD(b, c, PAR, FAULT_HTWSEEF, v) #define SET_FAULT_MHF(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT_MHF, v) #define SET_FAULT_SL(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT_SL, v) #define SET_FAULT_SS(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, FAULT_SS, v) #define SET_NOFAULT_SS(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, NOFAULT_SS, v) #define SET_NOFAULT_MT(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, NOFAULT_MT, v) #define SET_NOFAULT_SH(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, NOFAULT_SH, v) #define SET_NOFAULT_NS(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, NOFAULT_NS, v) #define SET_NOFAULT_NOS(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, NOFAULT_NOS, v) #define SET_NPFAULT_PA(b, c, v) SET_CONTEXT_FIELD(b, c, PAR, NPFAULT_PA, v) /* PRRR */ #define SET_MTC0(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC0, v) #define SET_MTC1(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC1, v) #define SET_MTC2(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC2, v) #define SET_MTC3(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC3, v) #define SET_MTC4(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC4, v) #define SET_MTC5(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC5, v) #define SET_MTC6(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC6, v) #define SET_MTC7(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, MTC7, v) #define SET_SHDSH0(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, SHDSH0, v) #define SET_SHDSH1(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, SHDSH1, v) #define SET_SHNMSH0(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, SHNMSH0, v) #define SET_SHNMSH1(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, SHNMSH1, v) #define SET_NOS0(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS0, v) #define SET_NOS1(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS1, v) #define SET_NOS2(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS2, v) #define SET_NOS3(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS3, v) #define SET_NOS4(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS4, v) #define SET_NOS5(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS5, v) #define SET_NOS6(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS6, v) #define SET_NOS7(b, c, v) SET_CONTEXT_FIELD(b, c, PRRR, NOS7, v) /* RESUME */ #define SET_TNR(b, c, v) SET_CONTEXT_FIELD(b, c, RESUME, TNR, v) /* SCTLR */ #define SET_M(b, c, v) SET_CONTEXT_FIELD(b, c, SCTLR, M, v) #define SET_TRE(b, c, v) SET_CONTEXT_FIELD(b, c, SCTLR, TRE, v) #define SET_AFE(b, c, v) SET_CONTEXT_FIELD(b, c, SCTLR, AFE, v) #define SET_HAF(b, c, v) SET_CONTEXT_FIELD(b, c, SCTLR, HAF, v) #define SET_BE(b, c, v) SET_CONTEXT_FIELD(b, c, SCTLR, BE, v) #define SET_AFFD(b, c, v) SET_CONTEXT_FIELD(b, c, SCTLR, AFFD, v) /* TLBLKCR */ #define SET_LKE(b, c, v) SET_CONTEXT_FIELD(b, c, TLBLKCR, LKE, v) #define SET_TLBLKCR_TLBIALLCFG(b, c, v) \ SET_CONTEXT_FIELD(b, c, TLBLKCR, TLBLCKR_TLBIALLCFG, v) #define SET_TLBIASIDCFG(b, c, v) \ SET_CONTEXT_FIELD(b, c, TLBLKCR, TLBIASIDCFG, v) #define SET_TLBIVAACFG(b, c, v) SET_CONTEXT_FIELD(b, c, TLBLKCR, TLBIVAACFG, v) #define SET_FLOOR(b, c, v) SET_CONTEXT_FIELD(b, c, TLBLKCR, FLOOR, v) #define SET_VICTIM(b, c, v) SET_CONTEXT_FIELD(b, c, TLBLKCR, VICTIM, v) /* TTBCR */ #define SET_N(b, c, v) SET_CONTEXT_FIELD(b, c, TTBCR, N, v) #define SET_PD0(b, c, v) SET_CONTEXT_FIELD(b, c, TTBCR, PD0, v) #define SET_PD1(b, c, v) SET_CONTEXT_FIELD(b, c, TTBCR, PD1, v) /* TTBR0 */ #define SET_TTBR0_IRGNH(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_IRGNH, v) #define SET_TTBR0_SH(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_SH, v) #define SET_TTBR0_ORGN(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_ORGN, v) #define SET_TTBR0_NOS(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_NOS, v) #define SET_TTBR0_IRGNL(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_IRGNL, v) #define SET_TTBR0_PA(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_PA, v) /* TTBR1 */ #define SET_TTBR1_IRGNH(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_IRGNH, v) #define SET_TTBR1_SH(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_SH, v) #define SET_TTBR1_ORGN(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_ORGN, v) #define SET_TTBR1_NOS(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_NOS, v) #define SET_TTBR1_IRGNL(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_IRGNL, v) #define SET_TTBR1_PA(b, c, v) SET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_PA, v) /* V2PSR */ #define SET_HIT(b, c, v) SET_CONTEXT_FIELD(b, c, V2PSR, HIT, v) #define SET_INDEX(b, c, v) SET_CONTEXT_FIELD(b, c, V2PSR, INDEX, v) /* Context Register getters */ /* ACTLR */ #define GET_CFERE(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, CFERE) #define GET_CFEIE(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, CFEIE) #define GET_PTSHCFG(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, PTSHCFG) #define GET_RCOSH(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, RCOSH) #define GET_RCISH(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, RCISH) #define GET_RCNSH(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, RCNSH) #define GET_PRIVCFG(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, PRIVCFG) #define GET_DNA(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, DNA) #define GET_DNLV2PA(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, DNLV2PA) #define GET_TLBMCFG(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, TLBMCFG) #define GET_CFCFG(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, CFCFG) #define GET_TIPCF(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, TIPCF) #define GET_V2PCFG(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, V2PCFG) #define GET_HUME(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, HUME) #define GET_PTMTCFG(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, PTMTCFG) #define GET_PTMEMTYPE(b, c) GET_CONTEXT_FIELD(b, c, ACTLR, PTMEMTYPE) /* BFBCR */ #define GET_BFBDFE(b, c) GET_CONTEXT_FIELD(b, c, BFBCR, BFBDFE) #define GET_BFBSFE(b, c) GET_CONTEXT_FIELD(b, c, BFBCR, BFBSFE) #define GET_SFVS(b, c) GET_CONTEXT_FIELD(b, c, BFBCR, SFVS) #define GET_FLVIC(b, c) GET_CONTEXT_FIELD(b, c, BFBCR, FLVIC) #define GET_SLVIC(b, c) GET_CONTEXT_FIELD(b, c, BFBCR, SLVIC) /* CONTEXTIDR */ #define GET_CONTEXTIDR_ASID(b, c) \ GET_CONTEXT_FIELD(b, c, CONTEXTIDR, CONTEXTIDR_ASID) #define GET_CONTEXTIDR_PROCID(b, c) GET_CONTEXT_FIELD(b, c, CONTEXTIDR, PROCID) /* FSR */ #define GET_TF(b, c) GET_CONTEXT_FIELD(b, c, FSR, TF) #define GET_AFF(b, c) GET_CONTEXT_FIELD(b, c, FSR, AFF) #define GET_APF(b, c) GET_CONTEXT_FIELD(b, c, FSR, APF) #define GET_TLBMF(b, c) GET_CONTEXT_FIELD(b, c, FSR, TLBMF) #define GET_HTWDEEF(b, c) GET_CONTEXT_FIELD(b, c, FSR, HTWDEEF) #define GET_HTWSEEF(b, c) GET_CONTEXT_FIELD(b, c, FSR, HTWSEEF) #define GET_MHF(b, c) GET_CONTEXT_FIELD(b, c, FSR, MHF) #define GET_SL(b, c) GET_CONTEXT_FIELD(b, c, FSR, SL) #define GET_SS(b, c) GET_CONTEXT_FIELD(b, c, FSR, SS) #define GET_MULTI(b, c) GET_CONTEXT_FIELD(b, c, FSR, MULTI) /* FSYNR0 */ #define GET_AMID(b, c) GET_CONTEXT_FIELD(b, c, FSYNR0, AMID) #define GET_APID(b, c) GET_CONTEXT_FIELD(b, c, FSYNR0, APID) #define GET_ABID(b, c) GET_CONTEXT_FIELD(b, c, FSYNR0, ABID) #define GET_ATID(b, c) GET_CONTEXT_FIELD(b, c, FSYNR0, ATID) /* FSYNR1 */ #define GET_AMEMTYPE(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, AMEMTYPE) #define GET_ASHARED(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, ASHARED) #define GET_AINNERSHARED(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, AINNERSHARED) #define GET_APRIV(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, APRIV) #define GET_APROTNS(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, APROTNS) #define GET_AINST(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, AINST) #define GET_AWRITE(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, AWRITE) #define GET_ABURST(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, ABURST) #define GET_ALEN(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, ALEN) #define GET_FSYNR1_ASIZE(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, FSYNR1_ASIZE) #define GET_ALOCK(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, ALOCK) #define GET_AFULL(b, c) GET_CONTEXT_FIELD(b, c, FSYNR1, AFULL) /* NMRR */ #define GET_ICPC0(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC0) #define GET_ICPC1(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC1) #define GET_ICPC2(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC2) #define GET_ICPC3(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC3) #define GET_ICPC4(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC4) #define GET_ICPC5(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC5) #define GET_ICPC6(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC6) #define GET_ICPC7(b, c) GET_CONTEXT_FIELD(b, c, NMRR, ICPC7) #define GET_OCPC0(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC0) #define GET_OCPC1(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC1) #define GET_OCPC2(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC2) #define GET_OCPC3(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC3) #define GET_OCPC4(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC4) #define GET_OCPC5(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC5) #define GET_OCPC6(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC6) #define GET_OCPC7(b, c) GET_CONTEXT_FIELD(b, c, NMRR, OCPC7) #define NMRR_ICP(nmrr, n) (((nmrr) & (3 << ((n) * 2))) >> ((n) * 2)) #define NMRR_OCP(nmrr, n) (((nmrr) & (3 << ((n) * 2 + 16))) >> \ ((n) * 2 + 16)) /* PAR */ #define GET_FAULT(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT) #define GET_FAULT_TF(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_TF) #define GET_FAULT_AFF(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_AFF) #define GET_FAULT_APF(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_APF) #define GET_FAULT_TLBMF(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_TLBMF) #define GET_FAULT_HTWDEEF(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_HTWDEEF) #define GET_FAULT_HTWSEEF(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_HTWSEEF) #define GET_FAULT_MHF(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_MHF) #define GET_FAULT_SL(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_SL) #define GET_FAULT_SS(b, c) GET_CONTEXT_FIELD(b, c, PAR, FAULT_SS) #define GET_NOFAULT_SS(b, c) GET_CONTEXT_FIELD(b, c, PAR, PAR_NOFAULT_SS) #define GET_NOFAULT_MT(b, c) GET_CONTEXT_FIELD(b, c, PAR, PAR_NOFAULT_MT) #define GET_NOFAULT_SH(b, c) GET_CONTEXT_FIELD(b, c, PAR, PAR_NOFAULT_SH) #define GET_NOFAULT_NS(b, c) GET_CONTEXT_FIELD(b, c, PAR, PAR_NOFAULT_NS) #define GET_NOFAULT_NOS(b, c) GET_CONTEXT_FIELD(b, c, PAR, PAR_NOFAULT_NOS) #define GET_NPFAULT_PA(b, c) GET_CONTEXT_FIELD(b, c, PAR, PAR_NPFAULT_PA) /* PRRR */ #define GET_MTC0(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC0) #define GET_MTC1(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC1) #define GET_MTC2(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC2) #define GET_MTC3(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC3) #define GET_MTC4(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC4) #define GET_MTC5(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC5) #define GET_MTC6(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC6) #define GET_MTC7(b, c) GET_CONTEXT_FIELD(b, c, PRRR, MTC7) #define GET_SHDSH0(b, c) GET_CONTEXT_FIELD(b, c, PRRR, SHDSH0) #define GET_SHDSH1(b, c) GET_CONTEXT_FIELD(b, c, PRRR, SHDSH1) #define GET_SHNMSH0(b, c) GET_CONTEXT_FIELD(b, c, PRRR, SHNMSH0) #define GET_SHNMSH1(b, c) GET_CONTEXT_FIELD(b, c, PRRR, SHNMSH1) #define GET_NOS0(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS0) #define GET_NOS1(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS1) #define GET_NOS2(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS2) #define GET_NOS3(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS3) #define GET_NOS4(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS4) #define GET_NOS5(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS5) #define GET_NOS6(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS6) #define GET_NOS7(b, c) GET_CONTEXT_FIELD(b, c, PRRR, NOS7) #define PRRR_NOS(prrr, n) ((prrr) & (1 << ((n) + 24)) ? 1 : 0) #define PRRR_MT(prrr, n) ((((prrr) & (3 << ((n) * 2))) >> ((n) * 2))) /* RESUME */ #define GET_TNR(b, c) GET_CONTEXT_FIELD(b, c, RESUME, TNR) /* SCTLR */ #define GET_M(b, c) GET_CONTEXT_FIELD(b, c, SCTLR, M) #define GET_TRE(b, c) GET_CONTEXT_FIELD(b, c, SCTLR, TRE) #define GET_AFE(b, c) GET_CONTEXT_FIELD(b, c, SCTLR, AFE) #define GET_HAF(b, c) GET_CONTEXT_FIELD(b, c, SCTLR, HAF) #define GET_BE(b, c) GET_CONTEXT_FIELD(b, c, SCTLR, BE) #define GET_AFFD(b, c) GET_CONTEXT_FIELD(b, c, SCTLR, AFFD) /* TLBLKCR */ #define GET_LKE(b, c) GET_CONTEXT_FIELD(b, c, TLBLKCR, LKE) #define GET_TLBLCKR_TLBIALLCFG(b, c) \ GET_CONTEXT_FIELD(b, c, TLBLKCR, TLBLCKR_TLBIALLCFG) #define GET_TLBIASIDCFG(b, c) GET_CONTEXT_FIELD(b, c, TLBLKCR, TLBIASIDCFG) #define GET_TLBIVAACFG(b, c) GET_CONTEXT_FIELD(b, c, TLBLKCR, TLBIVAACFG) #define GET_FLOOR(b, c) GET_CONTEXT_FIELD(b, c, TLBLKCR, FLOOR) #define GET_VICTIM(b, c) GET_CONTEXT_FIELD(b, c, TLBLKCR, VICTIM) /* TTBCR */ #define GET_N(b, c) GET_CONTEXT_FIELD(b, c, TTBCR, N) #define GET_PD0(b, c) GET_CONTEXT_FIELD(b, c, TTBCR, PD0) #define GET_PD1(b, c) GET_CONTEXT_FIELD(b, c, TTBCR, PD1) /* TTBR0 */ #define GET_TTBR0_IRGNH(b, c) GET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_IRGNH) #define GET_TTBR0_SH(b, c) GET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_SH) #define GET_TTBR0_ORGN(b, c) GET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_ORGN) #define GET_TTBR0_NOS(b, c) GET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_NOS) #define GET_TTBR0_IRGNL(b, c) GET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_IRGNL) #define GET_TTBR0_PA(b, c) GET_CONTEXT_FIELD(b, c, TTBR0, TTBR0_PA) /* TTBR1 */ #define GET_TTBR1_IRGNH(b, c) GET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_IRGNH) #define GET_TTBR1_SH(b, c) GET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_SH) #define GET_TTBR1_ORGN(b, c) GET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_ORGN) #define GET_TTBR1_NOS(b, c) GET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_NOS) #define GET_TTBR1_IRGNL(b, c) GET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_IRGNL) #define GET_TTBR1_PA(b, c) GET_CONTEXT_FIELD(b, c, TTBR1, TTBR1_PA) /* V2PSR */ #define GET_HIT(b, c) GET_CONTEXT_FIELD(b, c, V2PSR, HIT) #define GET_INDEX(b, c) GET_CONTEXT_FIELD(b, c, V2PSR, INDEX) /* Global Registers */ #define M2VCBR_N (0xFF000) #define CBACR_N (0xFF800) #define TLBRSW (0xFFE00) #define TLBTR0 (0xFFE80) #define TLBTR1 (0xFFE84) #define TLBTR2 (0xFFE88) #define TESTBUSCR (0xFFE8C) #define GLOBAL_TLBIALL (0xFFF00) #define TLBIVMID (0xFFF04) #define CR (0xFFF80) #define EAR (0xFFF84) #define ESR (0xFFF88) #define ESRRESTORE (0xFFF8C) #define ESYNR0 (0xFFF90) #define ESYNR1 (0xFFF94) #define REV (0xFFFF4) #define IDR (0xFFFF8) #define RPU_ACR (0xFFFFC) /* Context Bank Registers */ #define SCTLR (0x000) #define ACTLR (0x004) #define CONTEXTIDR (0x008) #define TTBR0 (0x010) #define TTBR1 (0x014) #define TTBCR (0x018) #define PAR (0x01C) #define FSR (0x020) #define FSRRESTORE (0x024) #define FAR (0x028) #define FSYNR0 (0x02C) #define FSYNR1 (0x030) #define PRRR (0x034) #define NMRR (0x038) #define TLBLCKR (0x03C) #define V2PSR (0x040) #define TLBFLPTER (0x044) #define TLBSLPTER (0x048) #define BFBCR (0x04C) #define CTX_TLBIALL (0x800) #define TLBIASID (0x804) #define TLBIVA (0x808) #define TLBIVAA (0x80C) #define V2PPR (0x810) #define V2PPW (0x814) #define V2PUR (0x818) #define V2PUW (0x81C) #define RESUME (0x820) /* Global Register Fields */ /* CBACRn */ #define RWVMID (RWVMID_MASK << RWVMID_SHIFT) #define RWE (RWE_MASK << RWE_SHIFT) #define RWGE (RWGE_MASK << RWGE_SHIFT) #define CBVMID (CBVMID_MASK << CBVMID_SHIFT) #define IRPTNDX (IRPTNDX_MASK << IRPTNDX_SHIFT) /* CR */ #define RPUE (RPUE_MASK << RPUE_SHIFT) #define RPUERE (RPUERE_MASK << RPUERE_SHIFT) #define RPUEIE (RPUEIE_MASK << RPUEIE_SHIFT) #define DCDEE (DCDEE_MASK << DCDEE_SHIFT) #define CLIENTPD (CLIENTPD_MASK << CLIENTPD_SHIFT) #define STALLD (STALLD_MASK << STALLD_SHIFT) #define TLBLKCRWE (TLBLKCRWE_MASK << TLBLKCRWE_SHIFT) #define CR_TLBIALLCFG (CR_TLBIALLCFG_MASK << CR_TLBIALLCFG_SHIFT) #define TLBIVMIDCFG (TLBIVMIDCFG_MASK << TLBIVMIDCFG_SHIFT) #define CR_HUME (CR_HUME_MASK << CR_HUME_SHIFT) /* ESR */ #define CFG (CFG_MASK << CFG_SHIFT) #define BYPASS (BYPASS_MASK << BYPASS_SHIFT) #define ESR_MULTI (ESR_MULTI_MASK << ESR_MULTI_SHIFT) /* ESYNR0 */ #define ESYNR0_AMID (ESYNR0_AMID_MASK << ESYNR0_AMID_SHIFT) #define ESYNR0_APID (ESYNR0_APID_MASK << ESYNR0_APID_SHIFT) #define ESYNR0_ABID (ESYNR0_ABID_MASK << ESYNR0_ABID_SHIFT) #define ESYNR0_AVMID (ESYNR0_AVMID_MASK << ESYNR0_AVMID_SHIFT) #define ESYNR0_ATID (ESYNR0_ATID_MASK << ESYNR0_ATID_SHIFT) /* ESYNR1 */ #define ESYNR1_AMEMTYPE (ESYNR1_AMEMTYPE_MASK << ESYNR1_AMEMTYPE_SHIFT) #define ESYNR1_ASHARED (ESYNR1_ASHARED_MASK << ESYNR1_ASHARED_SHIFT) #define ESYNR1_AINNERSHARED (ESYNR1_AINNERSHARED_MASK<< \ ESYNR1_AINNERSHARED_SHIFT) #define ESYNR1_APRIV (ESYNR1_APRIV_MASK << ESYNR1_APRIV_SHIFT) #define ESYNR1_APROTNS (ESYNR1_APROTNS_MASK << ESYNR1_APROTNS_SHIFT) #define ESYNR1_AINST (ESYNR1_AINST_MASK << ESYNR1_AINST_SHIFT) #define ESYNR1_AWRITE (ESYNR1_AWRITE_MASK << ESYNR1_AWRITE_SHIFT) #define ESYNR1_ABURST (ESYNR1_ABURST_MASK << ESYNR1_ABURST_SHIFT) #define ESYNR1_ALEN (ESYNR1_ALEN_MASK << ESYNR1_ALEN_SHIFT) #define ESYNR1_ASIZE (ESYNR1_ASIZE_MASK << ESYNR1_ASIZE_SHIFT) #define ESYNR1_ALOCK (ESYNR1_ALOCK_MASK << ESYNR1_ALOCK_SHIFT) #define ESYNR1_AOOO (ESYNR1_AOOO_MASK << ESYNR1_AOOO_SHIFT) #define ESYNR1_AFULL (ESYNR1_AFULL_MASK << ESYNR1_AFULL_SHIFT) #define ESYNR1_AC (ESYNR1_AC_MASK << ESYNR1_AC_SHIFT) #define ESYNR1_DCD (ESYNR1_DCD_MASK << ESYNR1_DCD_SHIFT) /* IDR */ #define NM2VCBMT (NM2VCBMT_MASK << NM2VCBMT_SHIFT) #define HTW (HTW_MASK << HTW_SHIFT) #define HUM (HUM_MASK << HUM_SHIFT) #define TLBSIZE (TLBSIZE_MASK << TLBSIZE_SHIFT) #define NCB (NCB_MASK << NCB_SHIFT) #define NIRPT (NIRPT_MASK << NIRPT_SHIFT) /* M2VCBRn */ #define VMID (VMID_MASK << VMID_SHIFT) #define CBNDX (CBNDX_MASK << CBNDX_SHIFT) #define BYPASSD (BYPASSD_MASK << BYPASSD_SHIFT) #define BPRCOSH (BPRCOSH_MASK << BPRCOSH_SHIFT) #define BPRCISH (BPRCISH_MASK << BPRCISH_SHIFT) #define BPRCNSH (BPRCNSH_MASK << BPRCNSH_SHIFT) #define BPSHCFG (BPSHCFG_MASK << BPSHCFG_SHIFT) #define NSCFG (NSCFG_MASK << NSCFG_SHIFT) #define BPMTCFG (BPMTCFG_MASK << BPMTCFG_SHIFT) #define BPMEMTYPE (BPMEMTYPE_MASK << BPMEMTYPE_SHIFT) /* REV */ #define IDR_MINOR (MINOR_MASK << MINOR_SHIFT) #define IDR_MAJOR (MAJOR_MASK << MAJOR_SHIFT) /* TESTBUSCR */ #define TBE (TBE_MASK << TBE_SHIFT) #define SPDMBE (SPDMBE_MASK << SPDMBE_SHIFT) #define WGSEL (WGSEL_MASK << WGSEL_SHIFT) #define TBLSEL (TBLSEL_MASK << TBLSEL_SHIFT) #define TBHSEL (TBHSEL_MASK << TBHSEL_SHIFT) #define SPDM0SEL (SPDM0SEL_MASK << SPDM0SEL_SHIFT) #define SPDM1SEL (SPDM1SEL_MASK << SPDM1SEL_SHIFT) #define SPDM2SEL (SPDM2SEL_MASK << SPDM2SEL_SHIFT) #define SPDM3SEL (SPDM3SEL_MASK << SPDM3SEL_SHIFT) /* TLBIVMID */ #define TLBIVMID_VMID (TLBIVMID_VMID_MASK << TLBIVMID_VMID_SHIFT) /* TLBRSW */ #define TLBRSW_INDEX (TLBRSW_INDEX_MASK << TLBRSW_INDEX_SHIFT) #define TLBBFBS (TLBBFBS_MASK << TLBBFBS_SHIFT) /* TLBTR0 */ #define PR (PR_MASK << PR_SHIFT) #define PW (PW_MASK << PW_SHIFT) #define UR (UR_MASK << UR_SHIFT) #define UW (UW_MASK << UW_SHIFT) #define XN (XN_MASK << XN_SHIFT) #define NSDESC (NSDESC_MASK << NSDESC_SHIFT) #define ISH (ISH_MASK << ISH_SHIFT) #define SH (SH_MASK << SH_SHIFT) #define MT (MT_MASK << MT_SHIFT) #define DPSIZR (DPSIZR_MASK << DPSIZR_SHIFT) #define DPSIZC (DPSIZC_MASK << DPSIZC_SHIFT) /* TLBTR1 */ #define TLBTR1_VMID (TLBTR1_VMID_MASK << TLBTR1_VMID_SHIFT) #define TLBTR1_PA (TLBTR1_PA_MASK << TLBTR1_PA_SHIFT) /* TLBTR2 */ #define TLBTR2_ASID (TLBTR2_ASID_MASK << TLBTR2_ASID_SHIFT) #define TLBTR2_V (TLBTR2_V_MASK << TLBTR2_V_SHIFT) #define TLBTR2_NSTID (TLBTR2_NSTID_MASK << TLBTR2_NSTID_SHIFT) #define TLBTR2_NV (TLBTR2_NV_MASK << TLBTR2_NV_SHIFT) #define TLBTR2_VA (TLBTR2_VA_MASK << TLBTR2_VA_SHIFT) /* Context Register Fields */ /* ACTLR */ #define CFERE (CFERE_MASK << CFERE_SHIFT) #define CFEIE (CFEIE_MASK << CFEIE_SHIFT) #define PTSHCFG (PTSHCFG_MASK << PTSHCFG_SHIFT) #define RCOSH (RCOSH_MASK << RCOSH_SHIFT) #define RCISH (RCISH_MASK << RCISH_SHIFT) #define RCNSH (RCNSH_MASK << RCNSH_SHIFT) #define PRIVCFG (PRIVCFG_MASK << PRIVCFG_SHIFT) #define DNA (DNA_MASK << DNA_SHIFT) #define DNLV2PA (DNLV2PA_MASK << DNLV2PA_SHIFT) #define TLBMCFG (TLBMCFG_MASK << TLBMCFG_SHIFT) #define CFCFG (CFCFG_MASK << CFCFG_SHIFT) #define TIPCF (TIPCF_MASK << TIPCF_SHIFT) #define V2PCFG (V2PCFG_MASK << V2PCFG_SHIFT) #define HUME (HUME_MASK << HUME_SHIFT) #define PTMTCFG (PTMTCFG_MASK << PTMTCFG_SHIFT) #define PTMEMTYPE (PTMEMTYPE_MASK << PTMEMTYPE_SHIFT) /* BFBCR */ #define BFBDFE (BFBDFE_MASK << BFBDFE_SHIFT) #define BFBSFE (BFBSFE_MASK << BFBSFE_SHIFT) #define SFVS (SFVS_MASK << SFVS_SHIFT) #define FLVIC (FLVIC_MASK << FLVIC_SHIFT) #define SLVIC (SLVIC_MASK << SLVIC_SHIFT) /* CONTEXTIDR */ #define CONTEXTIDR_ASID (CONTEXTIDR_ASID_MASK << CONTEXTIDR_ASID_SHIFT) #define PROCID (PROCID_MASK << PROCID_SHIFT) /* FSR */ #define TF (TF_MASK << TF_SHIFT) #define AFF (AFF_MASK << AFF_SHIFT) #define APF (APF_MASK << APF_SHIFT) #define TLBMF (TLBMF_MASK << TLBMF_SHIFT) #define HTWDEEF (HTWDEEF_MASK << HTWDEEF_SHIFT) #define HTWSEEF (HTWSEEF_MASK << HTWSEEF_SHIFT) #define MHF (MHF_MASK << MHF_SHIFT) #define SL (SL_MASK << SL_SHIFT) #define SS (SS_MASK << SS_SHIFT) #define MULTI (MULTI_MASK << MULTI_SHIFT) /* FSYNR0 */ #define AMID (AMID_MASK << AMID_SHIFT) #define APID (APID_MASK << APID_SHIFT) #define ABID (ABID_MASK << ABID_SHIFT) #define ATID (ATID_MASK << ATID_SHIFT) /* FSYNR1 */ #define AMEMTYPE (AMEMTYPE_MASK << AMEMTYPE_SHIFT) #define ASHARED (ASHARED_MASK << ASHARED_SHIFT) #define AINNERSHARED (AINNERSHARED_MASK << AINNERSHARED_SHIFT) #define APRIV (APRIV_MASK << APRIV_SHIFT) #define APROTNS (APROTNS_MASK << APROTNS_SHIFT) #define AINST (AINST_MASK << AINST_SHIFT) #define AWRITE (AWRITE_MASK << AWRITE_SHIFT) #define ABURST (ABURST_MASK << ABURST_SHIFT) #define ALEN (ALEN_MASK << ALEN_SHIFT) #define FSYNR1_ASIZE (FSYNR1_ASIZE_MASK << FSYNR1_ASIZE_SHIFT) #define ALOCK (ALOCK_MASK << ALOCK_SHIFT) #define AFULL (AFULL_MASK << AFULL_SHIFT) /* NMRR */ #define ICPC0 (ICPC0_MASK << ICPC0_SHIFT) #define ICPC1 (ICPC1_MASK << ICPC1_SHIFT) #define ICPC2 (ICPC2_MASK << ICPC2_SHIFT) #define ICPC3 (ICPC3_MASK << ICPC3_SHIFT) #define ICPC4 (ICPC4_MASK << ICPC4_SHIFT) #define ICPC5 (ICPC5_MASK << ICPC5_SHIFT) #define ICPC6 (ICPC6_MASK << ICPC6_SHIFT) #define ICPC7 (ICPC7_MASK << ICPC7_SHIFT) #define OCPC0 (OCPC0_MASK << OCPC0_SHIFT) #define OCPC1 (OCPC1_MASK << OCPC1_SHIFT) #define OCPC2 (OCPC2_MASK << OCPC2_SHIFT) #define OCPC3 (OCPC3_MASK << OCPC3_SHIFT) #define OCPC4 (OCPC4_MASK << OCPC4_SHIFT) #define OCPC5 (OCPC5_MASK << OCPC5_SHIFT) #define OCPC6 (OCPC6_MASK << OCPC6_SHIFT) #define OCPC7 (OCPC7_MASK << OCPC7_SHIFT) /* PAR */ #define FAULT (FAULT_MASK << FAULT_SHIFT) /* If a fault is present, these are the same as the fault fields in the FAR */ #define FAULT_TF (FAULT_TF_MASK << FAULT_TF_SHIFT) #define FAULT_AFF (FAULT_AFF_MASK << FAULT_AFF_SHIFT) #define FAULT_APF (FAULT_APF_MASK << FAULT_APF_SHIFT) #define FAULT_TLBMF (FAULT_TLBMF_MASK << FAULT_TLBMF_SHIFT) #define FAULT_HTWDEEF (FAULT_HTWDEEF_MASK << FAULT_HTWDEEF_SHIFT) #define FAULT_HTWSEEF (FAULT_HTWSEEF_MASK << FAULT_HTWSEEF_SHIFT) #define FAULT_MHF (FAULT_MHF_MASK << FAULT_MHF_SHIFT) #define FAULT_SL (FAULT_SL_MASK << FAULT_SL_SHIFT) #define FAULT_SS (FAULT_SS_MASK << FAULT_SS_SHIFT) /* If NO fault is present, the following fields are in effect */ /* (FAULT remains as before) */ #define PAR_NOFAULT_SS (PAR_NOFAULT_SS_MASK << PAR_NOFAULT_SS_SHIFT) #define PAR_NOFAULT_MT (PAR_NOFAULT_MT_MASK << PAR_NOFAULT_MT_SHIFT) #define PAR_NOFAULT_SH (PAR_NOFAULT_SH_MASK << PAR_NOFAULT_SH_SHIFT) #define PAR_NOFAULT_NS (PAR_NOFAULT_NS_MASK << PAR_NOFAULT_NS_SHIFT) #define PAR_NOFAULT_NOS (PAR_NOFAULT_NOS_MASK << PAR_NOFAULT_NOS_SHIFT) #define PAR_NPFAULT_PA (PAR_NPFAULT_PA_MASK << PAR_NPFAULT_PA_SHIFT) /* PRRR */ #define MTC0 (MTC0_MASK << MTC0_SHIFT) #define MTC1 (MTC1_MASK << MTC1_SHIFT) #define MTC2 (MTC2_MASK << MTC2_SHIFT) #define MTC3 (MTC3_MASK << MTC3_SHIFT) #define MTC4 (MTC4_MASK << MTC4_SHIFT) #define MTC5 (MTC5_MASK << MTC5_SHIFT) #define MTC6 (MTC6_MASK << MTC6_SHIFT) #define MTC7 (MTC7_MASK << MTC7_SHIFT) #define SHDSH0 (SHDSH0_MASK << SHDSH0_SHIFT) #define SHDSH1 (SHDSH1_MASK << SHDSH1_SHIFT) #define SHNMSH0 (SHNMSH0_MASK << SHNMSH0_SHIFT) #define SHNMSH1 (SHNMSH1_MASK << SHNMSH1_SHIFT) #define NOS0 (NOS0_MASK << NOS0_SHIFT) #define NOS1 (NOS1_MASK << NOS1_SHIFT) #define NOS2 (NOS2_MASK << NOS2_SHIFT) #define NOS3 (NOS3_MASK << NOS3_SHIFT) #define NOS4 (NOS4_MASK << NOS4_SHIFT) #define NOS5 (NOS5_MASK << NOS5_SHIFT) #define NOS6 (NOS6_MASK << NOS6_SHIFT) #define NOS7 (NOS7_MASK << NOS7_SHIFT) /* RESUME */ #define TNR (TNR_MASK << TNR_SHIFT) /* SCTLR */ #define M (M_MASK << M_SHIFT) #define TRE (TRE_MASK << TRE_SHIFT) #define AFE (AFE_MASK << AFE_SHIFT) #define HAF (HAF_MASK << HAF_SHIFT) #define BE (BE_MASK << BE_SHIFT) #define AFFD (AFFD_MASK << AFFD_SHIFT) /* TLBIASID */ #define TLBIASID_ASID (TLBIASID_ASID_MASK << TLBIASID_ASID_SHIFT) /* TLBIVA */ #define TLBIVA_ASID (TLBIVA_ASID_MASK << TLBIVA_ASID_SHIFT) #define TLBIVA_VA (TLBIVA_VA_MASK << TLBIVA_VA_SHIFT) /* TLBIVAA */ #define TLBIVAA_VA (TLBIVAA_VA_MASK << TLBIVAA_VA_SHIFT) /* TLBLCKR */ #define LKE (LKE_MASK << LKE_SHIFT) #define TLBLCKR_TLBIALLCFG (TLBLCKR_TLBIALLCFG_MASK<<TLBLCKR_TLBIALLCFG_SHIFT) #define TLBIASIDCFG (TLBIASIDCFG_MASK << TLBIASIDCFG_SHIFT) #define TLBIVAACFG (TLBIVAACFG_MASK << TLBIVAACFG_SHIFT) #define FLOOR (FLOOR_MASK << FLOOR_SHIFT) #define VICTIM (VICTIM_MASK << VICTIM_SHIFT) /* TTBCR */ #define N (N_MASK << N_SHIFT) #define PD0 (PD0_MASK << PD0_SHIFT) #define PD1 (PD1_MASK << PD1_SHIFT) /* TTBR0 */ #define TTBR0_IRGNH (TTBR0_IRGNH_MASK << TTBR0_IRGNH_SHIFT) #define TTBR0_SH (TTBR0_SH_MASK << TTBR0_SH_SHIFT) #define TTBR0_ORGN (TTBR0_ORGN_MASK << TTBR0_ORGN_SHIFT) #define TTBR0_NOS (TTBR0_NOS_MASK << TTBR0_NOS_SHIFT) #define TTBR0_IRGNL (TTBR0_IRGNL_MASK << TTBR0_IRGNL_SHIFT) #define TTBR0_PA (TTBR0_PA_MASK << TTBR0_PA_SHIFT) /* TTBR1 */ #define TTBR1_IRGNH (TTBR1_IRGNH_MASK << TTBR1_IRGNH_SHIFT) #define TTBR1_SH (TTBR1_SH_MASK << TTBR1_SH_SHIFT) #define TTBR1_ORGN (TTBR1_ORGN_MASK << TTBR1_ORGN_SHIFT) #define TTBR1_NOS (TTBR1_NOS_MASK << TTBR1_NOS_SHIFT) #define TTBR1_IRGNL (TTBR1_IRGNL_MASK << TTBR1_IRGNL_SHIFT) #define TTBR1_PA (TTBR1_PA_MASK << TTBR1_PA_SHIFT) /* V2PSR */ #define HIT (HIT_MASK << HIT_SHIFT) #define INDEX (INDEX_MASK << INDEX_SHIFT) /* V2Pxx */ #define V2Pxx_INDEX (V2Pxx_INDEX_MASK << V2Pxx_INDEX_SHIFT) #define V2Pxx_VA (V2Pxx_VA_MASK << V2Pxx_VA_SHIFT) /* Global Register Masks */ /* CBACRn */ #define RWVMID_MASK 0x1F #define RWE_MASK 0x01 #define RWGE_MASK 0x01 #define CBVMID_MASK 0x1F #define IRPTNDX_MASK 0xFF /* CR */ #define RPUE_MASK 0x01 #define RPUERE_MASK 0x01 #define RPUEIE_MASK 0x01 #define DCDEE_MASK 0x01 #define CLIENTPD_MASK 0x01 #define STALLD_MASK 0x01 #define TLBLKCRWE_MASK 0x01 #define CR_TLBIALLCFG_MASK 0x01 #define TLBIVMIDCFG_MASK 0x01 #define CR_HUME_MASK 0x01 /* ESR */ #define CFG_MASK 0x01 #define BYPASS_MASK 0x01 #define ESR_MULTI_MASK 0x01 /* ESYNR0 */ #define ESYNR0_AMID_MASK 0xFF #define ESYNR0_APID_MASK 0x1F #define ESYNR0_ABID_MASK 0x07 #define ESYNR0_AVMID_MASK 0x1F #define ESYNR0_ATID_MASK 0xFF /* ESYNR1 */ #define ESYNR1_AMEMTYPE_MASK 0x07 #define ESYNR1_ASHARED_MASK 0x01 #define ESYNR1_AINNERSHARED_MASK 0x01 #define ESYNR1_APRIV_MASK 0x01 #define ESYNR1_APROTNS_MASK 0x01 #define ESYNR1_AINST_MASK 0x01 #define ESYNR1_AWRITE_MASK 0x01 #define ESYNR1_ABURST_MASK 0x01 #define ESYNR1_ALEN_MASK 0x0F #define ESYNR1_ASIZE_MASK 0x01 #define ESYNR1_ALOCK_MASK 0x03 #define ESYNR1_AOOO_MASK 0x01 #define ESYNR1_AFULL_MASK 0x01 #define ESYNR1_AC_MASK 0x01 #define ESYNR1_DCD_MASK 0x01 /* IDR */ #define NM2VCBMT_MASK 0x1FF #define HTW_MASK 0x01 #define HUM_MASK 0x01 #define TLBSIZE_MASK 0x0F #define NCB_MASK 0xFF #define NIRPT_MASK 0xFF /* M2VCBRn */ #define VMID_MASK 0x1F #define CBNDX_MASK 0xFF #define BYPASSD_MASK 0x01 #define BPRCOSH_MASK 0x01 #define BPRCISH_MASK 0x01 #define BPRCNSH_MASK 0x01 #define BPSHCFG_MASK 0x03 #define NSCFG_MASK 0x03 #define BPMTCFG_MASK 0x01 #define BPMEMTYPE_MASK 0x07 /* REV */ #define MINOR_MASK 0x0F #define MAJOR_MASK 0x0F /* TESTBUSCR */ #define TBE_MASK 0x01 #define SPDMBE_MASK 0x01 #define WGSEL_MASK 0x03 #define TBLSEL_MASK 0x03 #define TBHSEL_MASK 0x03 #define SPDM0SEL_MASK 0x0F #define SPDM1SEL_MASK 0x0F #define SPDM2SEL_MASK 0x0F #define SPDM3SEL_MASK 0x0F /* TLBIMID */ #define TLBIVMID_VMID_MASK 0x1F /* TLBRSW */ #define TLBRSW_INDEX_MASK 0xFF #define TLBBFBS_MASK 0x03 /* TLBTR0 */ #define PR_MASK 0x01 #define PW_MASK 0x01 #define UR_MASK 0x01 #define UW_MASK 0x01 #define XN_MASK 0x01 #define NSDESC_MASK 0x01 #define ISH_MASK 0x01 #define SH_MASK 0x01 #define MT_MASK 0x07 #define DPSIZR_MASK 0x07 #define DPSIZC_MASK 0x07 /* TLBTR1 */ #define TLBTR1_VMID_MASK 0x1F #define TLBTR1_PA_MASK 0x000FFFFF /* TLBTR2 */ #define TLBTR2_ASID_MASK 0xFF #define TLBTR2_V_MASK 0x01 #define TLBTR2_NSTID_MASK 0x01 #define TLBTR2_NV_MASK 0x01 #define TLBTR2_VA_MASK 0x000FFFFF /* Global Register Shifts */ /* CBACRn */ #define RWVMID_SHIFT 0 #define RWE_SHIFT 8 #define RWGE_SHIFT 9 #define CBVMID_SHIFT 16 #define IRPTNDX_SHIFT 24 /* CR */ #define RPUE_SHIFT 0 #define RPUERE_SHIFT 1 #define RPUEIE_SHIFT 2 #define DCDEE_SHIFT 3 #define CLIENTPD_SHIFT 4 #define STALLD_SHIFT 5 #define TLBLKCRWE_SHIFT 6 #define CR_TLBIALLCFG_SHIFT 7 #define TLBIVMIDCFG_SHIFT 8 #define CR_HUME_SHIFT 9 /* ESR */ #define CFG_SHIFT 0 #define BYPASS_SHIFT 1 #define ESR_MULTI_SHIFT 31 /* ESYNR0 */ #define ESYNR0_AMID_SHIFT 0 #define ESYNR0_APID_SHIFT 8 #define ESYNR0_ABID_SHIFT 13 #define ESYNR0_AVMID_SHIFT 16 #define ESYNR0_ATID_SHIFT 24 /* ESYNR1 */ #define ESYNR1_AMEMTYPE_SHIFT 0 #define ESYNR1_ASHARED_SHIFT 3 #define ESYNR1_AINNERSHARED_SHIFT 4 #define ESYNR1_APRIV_SHIFT 5 #define ESYNR1_APROTNS_SHIFT 6 #define ESYNR1_AINST_SHIFT 7 #define ESYNR1_AWRITE_SHIFT 8 #define ESYNR1_ABURST_SHIFT 10 #define ESYNR1_ALEN_SHIFT 12 #define ESYNR1_ASIZE_SHIFT 16 #define ESYNR1_ALOCK_SHIFT 20 #define ESYNR1_AOOO_SHIFT 22 #define ESYNR1_AFULL_SHIFT 24 #define ESYNR1_AC_SHIFT 30 #define ESYNR1_DCD_SHIFT 31 /* IDR */ #define NM2VCBMT_SHIFT 0 #define HTW_SHIFT 9 #define HUM_SHIFT 10 #define TLBSIZE_SHIFT 12 #define NCB_SHIFT 16 #define NIRPT_SHIFT 24 /* M2VCBRn */ #define VMID_SHIFT 0 #define CBNDX_SHIFT 8 #define BYPASSD_SHIFT 16 #define BPRCOSH_SHIFT 17 #define BPRCISH_SHIFT 18 #define BPRCNSH_SHIFT 19 #define BPSHCFG_SHIFT 20 #define NSCFG_SHIFT 22 #define BPMTCFG_SHIFT 24 #define BPMEMTYPE_SHIFT 25 /* REV */ #define MINOR_SHIFT 0 #define MAJOR_SHIFT 4 /* TESTBUSCR */ #define TBE_SHIFT 0 #define SPDMBE_SHIFT 1 #define WGSEL_SHIFT 8 #define TBLSEL_SHIFT 12 #define TBHSEL_SHIFT 14 #define SPDM0SEL_SHIFT 16 #define SPDM1SEL_SHIFT 20 #define SPDM2SEL_SHIFT 24 #define SPDM3SEL_SHIFT 28 /* TLBIMID */ #define TLBIVMID_VMID_SHIFT 0 /* TLBRSW */ #define TLBRSW_INDEX_SHIFT 0 #define TLBBFBS_SHIFT 8 /* TLBTR0 */ #define PR_SHIFT 0 #define PW_SHIFT 1 #define UR_SHIFT 2 #define UW_SHIFT 3 #define XN_SHIFT 4 #define NSDESC_SHIFT 6 #define ISH_SHIFT 7 #define SH_SHIFT 8 #define MT_SHIFT 9 #define DPSIZR_SHIFT 16 #define DPSIZC_SHIFT 20 /* TLBTR1 */ #define TLBTR1_VMID_SHIFT 0 #define TLBTR1_PA_SHIFT 12 /* TLBTR2 */ #define TLBTR2_ASID_SHIFT 0 #define TLBTR2_V_SHIFT 8 #define TLBTR2_NSTID_SHIFT 9 #define TLBTR2_NV_SHIFT 10 #define TLBTR2_VA_SHIFT 12 /* Context Register Masks */ /* ACTLR */ #define CFERE_MASK 0x01 #define CFEIE_MASK 0x01 #define PTSHCFG_MASK 0x03 #define RCOSH_MASK 0x01 #define RCISH_MASK 0x01 #define RCNSH_MASK 0x01 #define PRIVCFG_MASK 0x03 #define DNA_MASK 0x01 #define DNLV2PA_MASK 0x01 #define TLBMCFG_MASK 0x03 #define CFCFG_MASK 0x01 #define TIPCF_MASK 0x01 #define V2PCFG_MASK 0x03 #define HUME_MASK 0x01 #define PTMTCFG_MASK 0x01 #define PTMEMTYPE_MASK 0x07 /* BFBCR */ #define BFBDFE_MASK 0x01 #define BFBSFE_MASK 0x01 #define SFVS_MASK 0x01 #define FLVIC_MASK 0x0F #define SLVIC_MASK 0x0F /* CONTEXTIDR */ #define CONTEXTIDR_ASID_MASK 0xFF #define PROCID_MASK 0x00FFFFFF /* FSR */ #define TF_MASK 0x01 #define AFF_MASK 0x01 #define APF_MASK 0x01 #define TLBMF_MASK 0x01 #define HTWDEEF_MASK 0x01 #define HTWSEEF_MASK 0x01 #define MHF_MASK 0x01 #define SL_MASK 0x01 #define SS_MASK 0x01 #define MULTI_MASK 0x01 /* FSYNR0 */ #define AMID_MASK 0xFF #define APID_MASK 0x1F #define ABID_MASK 0x07 #define ATID_MASK 0xFF /* FSYNR1 */ #define AMEMTYPE_MASK 0x07 #define ASHARED_MASK 0x01 #define AINNERSHARED_MASK 0x01 #define APRIV_MASK 0x01 #define APROTNS_MASK 0x01 #define AINST_MASK 0x01 #define AWRITE_MASK 0x01 #define ABURST_MASK 0x01 #define ALEN_MASK 0x0F #define FSYNR1_ASIZE_MASK 0x07 #define ALOCK_MASK 0x03 #define AFULL_MASK 0x01 /* NMRR */ #define ICPC0_MASK 0x03 #define ICPC1_MASK 0x03 #define ICPC2_MASK 0x03 #define ICPC3_MASK 0x03 #define ICPC4_MASK 0x03 #define ICPC5_MASK 0x03 #define ICPC6_MASK 0x03 #define ICPC7_MASK 0x03 #define OCPC0_MASK 0x03 #define OCPC1_MASK 0x03 #define OCPC2_MASK 0x03 #define OCPC3_MASK 0x03 #define OCPC4_MASK 0x03 #define OCPC5_MASK 0x03 #define OCPC6_MASK 0x03 #define OCPC7_MASK 0x03 /* PAR */ #define FAULT_MASK 0x01 /* If a fault is present, these are the same as the fault fields in the FAR */ #define FAULT_TF_MASK 0x01 #define FAULT_AFF_MASK 0x01 #define FAULT_APF_MASK 0x01 #define FAULT_TLBMF_MASK 0x01 #define FAULT_HTWDEEF_MASK 0x01 #define FAULT_HTWSEEF_MASK 0x01 #define FAULT_MHF_MASK 0x01 #define FAULT_SL_MASK 0x01 #define FAULT_SS_MASK 0x01 /* If NO fault is present, the following * fields are in effect * (FAULT remains as before) */ #define PAR_NOFAULT_SS_MASK 0x01 #define PAR_NOFAULT_MT_MASK 0x07 #define PAR_NOFAULT_SH_MASK 0x01 #define PAR_NOFAULT_NS_MASK 0x01 #define PAR_NOFAULT_NOS_MASK 0x01 #define PAR_NPFAULT_PA_MASK 0x000FFFFF /* PRRR */ #define MTC0_MASK 0x03 #define MTC1_MASK 0x03 #define MTC2_MASK 0x03 #define MTC3_MASK 0x03 #define MTC4_MASK 0x03 #define MTC5_MASK 0x03 #define MTC6_MASK 0x03 #define MTC7_MASK 0x03 #define SHDSH0_MASK 0x01 #define SHDSH1_MASK 0x01 #define SHNMSH0_MASK 0x01 #define SHNMSH1_MASK 0x01 #define NOS0_MASK 0x01 #define NOS1_MASK 0x01 #define NOS2_MASK 0x01 #define NOS3_MASK 0x01 #define NOS4_MASK 0x01 #define NOS5_MASK 0x01 #define NOS6_MASK 0x01 #define NOS7_MASK 0x01 /* RESUME */ #define TNR_MASK 0x01 /* SCTLR */ #define M_MASK 0x01 #define TRE_MASK 0x01 #define AFE_MASK 0x01 #define HAF_MASK 0x01 #define BE_MASK 0x01 #define AFFD_MASK 0x01 /* TLBIASID */ #define TLBIASID_ASID_MASK 0xFF /* TLBIVA */ #define TLBIVA_ASID_MASK 0xFF #define TLBIVA_VA_MASK 0x000FFFFF /* TLBIVAA */ #define TLBIVAA_VA_MASK 0x000FFFFF /* TLBLCKR */ #define LKE_MASK 0x01 #define TLBLCKR_TLBIALLCFG_MASK 0x01 #define TLBIASIDCFG_MASK 0x01 #define TLBIVAACFG_MASK 0x01 #define FLOOR_MASK 0xFF #define VICTIM_MASK 0xFF /* TTBCR */ #define N_MASK 0x07 #define PD0_MASK 0x01 #define PD1_MASK 0x01 /* TTBR0 */ #define TTBR0_IRGNH_MASK 0x01 #define TTBR0_SH_MASK 0x01 #define TTBR0_ORGN_MASK 0x03 #define TTBR0_NOS_MASK 0x01 #define TTBR0_IRGNL_MASK 0x01 #define TTBR0_PA_MASK 0x0003FFFF /* TTBR1 */ #define TTBR1_IRGNH_MASK 0x01 #define TTBR1_SH_MASK 0x01 #define TTBR1_ORGN_MASK 0x03 #define TTBR1_NOS_MASK 0x01 #define TTBR1_IRGNL_MASK 0x01 #define TTBR1_PA_MASK 0x0003FFFF /* V2PSR */ #define HIT_MASK 0x01 #define INDEX_MASK 0xFF /* V2Pxx */ #define V2Pxx_INDEX_MASK 0xFF #define V2Pxx_VA_MASK 0x000FFFFF /* Context Register Shifts */ /* ACTLR */ #define CFERE_SHIFT 0 #define CFEIE_SHIFT 1 #define PTSHCFG_SHIFT 2 #define RCOSH_SHIFT 4 #define RCISH_SHIFT 5 #define RCNSH_SHIFT 6 #define PRIVCFG_SHIFT 8 #define DNA_SHIFT 10 #define DNLV2PA_SHIFT 11 #define TLBMCFG_SHIFT 12 #define CFCFG_SHIFT 14 #define TIPCF_SHIFT 15 #define V2PCFG_SHIFT 16 #define HUME_SHIFT 18 #define PTMTCFG_SHIFT 20 #define PTMEMTYPE_SHIFT 21 /* BFBCR */ #define BFBDFE_SHIFT 0 #define BFBSFE_SHIFT 1 #define SFVS_SHIFT 2 #define FLVIC_SHIFT 4 #define SLVIC_SHIFT 8 /* CONTEXTIDR */ #define CONTEXTIDR_ASID_SHIFT 0 #define PROCID_SHIFT 8 /* FSR */ #define TF_SHIFT 1 #define AFF_SHIFT 2 #define APF_SHIFT 3 #define TLBMF_SHIFT 4 #define HTWDEEF_SHIFT 5 #define HTWSEEF_SHIFT 6 #define MHF_SHIFT 7 #define SL_SHIFT 16 #define SS_SHIFT 30 #define MULTI_SHIFT 31 /* FSYNR0 */ #define AMID_SHIFT 0 #define APID_SHIFT 8 #define ABID_SHIFT 13 #define ATID_SHIFT 24 /* FSYNR1 */ #define AMEMTYPE_SHIFT 0 #define ASHARED_SHIFT 3 #define AINNERSHARED_SHIFT 4 #define APRIV_SHIFT 5 #define APROTNS_SHIFT 6 #define AINST_SHIFT 7 #define AWRITE_SHIFT 8 #define ABURST_SHIFT 10 #define ALEN_SHIFT 12 #define FSYNR1_ASIZE_SHIFT 16 #define ALOCK_SHIFT 20 #define AFULL_SHIFT 24 /* NMRR */ #define ICPC0_SHIFT 0 #define ICPC1_SHIFT 2 #define ICPC2_SHIFT 4 #define ICPC3_SHIFT 6 #define ICPC4_SHIFT 8 #define ICPC5_SHIFT 10 #define ICPC6_SHIFT 12 #define ICPC7_SHIFT 14 #define OCPC0_SHIFT 16 #define OCPC1_SHIFT 18 #define OCPC2_SHIFT 20 #define OCPC3_SHIFT 22 #define OCPC4_SHIFT 24 #define OCPC5_SHIFT 26 #define OCPC6_SHIFT 28 #define OCPC7_SHIFT 30 /* PAR */ #define FAULT_SHIFT 0 /* If a fault is present, these are the same as the fault fields in the FAR */ #define FAULT_TF_SHIFT 1 #define FAULT_AFF_SHIFT 2 #define FAULT_APF_SHIFT 3 #define FAULT_TLBMF_SHIFT 4 #define FAULT_HTWDEEF_SHIFT 5 #define FAULT_HTWSEEF_SHIFT 6 #define FAULT_MHF_SHIFT 7 #define FAULT_SL_SHIFT 16 #define FAULT_SS_SHIFT 30 /* If NO fault is present, the following * fields are in effect * (FAULT remains as before) */ #define PAR_NOFAULT_SS_SHIFT 1 #define PAR_NOFAULT_MT_SHIFT 4 #define PAR_NOFAULT_SH_SHIFT 7 #define PAR_NOFAULT_NS_SHIFT 9 #define PAR_NOFAULT_NOS_SHIFT 10 #define PAR_NPFAULT_PA_SHIFT 12 /* PRRR */ #define MTC0_SHIFT 0 #define MTC1_SHIFT 2 #define MTC2_SHIFT 4 #define MTC3_SHIFT 6 #define MTC4_SHIFT 8 #define MTC5_SHIFT 10 #define MTC6_SHIFT 12 #define MTC7_SHIFT 14 #define SHDSH0_SHIFT 16 #define SHDSH1_SHIFT 17 #define SHNMSH0_SHIFT 18 #define SHNMSH1_SHIFT 19 #define NOS0_SHIFT 24 #define NOS1_SHIFT 25 #define NOS2_SHIFT 26 #define NOS3_SHIFT 27 #define NOS4_SHIFT 28 #define NOS5_SHIFT 29 #define NOS6_SHIFT 30 #define NOS7_SHIFT 31 /* RESUME */ #define TNR_SHIFT 0 /* SCTLR */ #define M_SHIFT 0 #define TRE_SHIFT 1 #define AFE_SHIFT 2 #define HAF_SHIFT 3 #define BE_SHIFT 4 #define AFFD_SHIFT 5 /* TLBIASID */ #define TLBIASID_ASID_SHIFT 0 /* TLBIVA */ #define TLBIVA_ASID_SHIFT 0 #define TLBIVA_VA_SHIFT 12 /* TLBIVAA */ #define TLBIVAA_VA_SHIFT 12 /* TLBLCKR */ #define LKE_SHIFT 0 #define TLBLCKR_TLBIALLCFG_SHIFT 1 #define TLBIASIDCFG_SHIFT 2 #define TLBIVAACFG_SHIFT 3 #define FLOOR_SHIFT 8 #define VICTIM_SHIFT 8 /* TTBCR */ #define N_SHIFT 3 #define PD0_SHIFT 4 #define PD1_SHIFT 5 /* TTBR0 */ #define TTBR0_IRGNH_SHIFT 0 #define TTBR0_SH_SHIFT 1 #define TTBR0_ORGN_SHIFT 3 #define TTBR0_NOS_SHIFT 5 #define TTBR0_IRGNL_SHIFT 6 #define TTBR0_PA_SHIFT 14 /* TTBR1 */ #define TTBR1_IRGNH_SHIFT 0 #define TTBR1_SH_SHIFT 1 #define TTBR1_ORGN_SHIFT 3 #define TTBR1_NOS_SHIFT 5 #define TTBR1_IRGNL_SHIFT 6 #define TTBR1_PA_SHIFT 14 /* V2PSR */ #define HIT_SHIFT 0 #define INDEX_SHIFT 8 /* V2Pxx */ #define V2Pxx_INDEX_SHIFT 0 #define V2Pxx_VA_SHIFT 12 #endif
andi34/kernel_samsung_espresso-cm
arch/arm/mach-msm/include/mach/iommu_hw-8xxx.h
C
gpl-2.0
75,609
/* * AVR_SPI.h * * Created on: 21 Feb 2015 * Author: RobThePyro */ #ifndef AVR_SPI_H_ #define AVR_SPI_H_ // Includes: #include <avr/io.h> // Defines: #define SPI_SS_DDR DDRB #define SPI_SS_PORT PORTB #define SPI_SS 2 #define SPI_MOSI_DDR DDRB #define SPI_MOSI 3 #define SPI_MISO_PORT PORTB #define SPI_MISO 4 #define SPI_SCK_DDR DDRB #define SPI_SCK 5 // Functions: void SPI_Init(void); uint8_t spi_putc(uint8_t); #endif /* AVR_SPI_H_ */
robthepyro/SolarForce1
CAN Embedded/Test Code/Test_LCD_I2C_2004/AVR_SPI.h
C
gpl-2.0
459
# -*- coding: utf-8 -*- import fauxfactory import pytest from cfme import test_requirements from cfme.rest.gen_data import a_provider as _a_provider from cfme.rest.gen_data import vm as _vm from cfme.utils import error from cfme.utils.rest import assert_response, delete_resources_from_collection from cfme.utils.wait import wait_for pytestmark = [test_requirements.provision] @pytest.fixture(scope="function") def a_provider(request): return _a_provider(request) @pytest.fixture(scope="function") def vm_name(request, a_provider, appliance): return _vm(request, a_provider, appliance.rest_api) @pytest.mark.parametrize( 'from_detail', [True, False], ids=['from_detail', 'from_collection']) def test_edit_vm(request, vm_name, appliance, from_detail): """Tests edit VMs using REST API. Testing BZ 1428250. Metadata: test_flag: rest """ vm = appliance.rest_api.collections.vms.get(name=vm_name) request.addfinalizer(vm.action.delete) new_description = 'Test REST VM {}'.format(fauxfactory.gen_alphanumeric(5)) payload = {'description': new_description} if from_detail: edited = vm.action.edit(**payload) assert_response(appliance) else: payload.update(vm._ref_repr()) edited = appliance.rest_api.collections.vms.action.edit(payload) assert_response(appliance) edited = edited[0] record, __ = wait_for( lambda: appliance.rest_api.collections.vms.find_by( description=new_description) or False, num_sec=100, delay=5, ) vm.reload() assert vm.description == edited.description == record[0].description @pytest.mark.tier(3) @pytest.mark.parametrize('method', ['post', 'delete'], ids=['POST', 'DELETE']) def test_delete_vm_from_detail(vm_name, appliance, method): vm = appliance.rest_api.collections.vms.get(name=vm_name) del_action = getattr(vm.action.delete, method.upper()) del_action() assert_response(appliance) wait_for( lambda: not appliance.rest_api.collections.vms.find_by(name=vm_name), num_sec=300, delay=10) with error.expected('ActiveRecord::RecordNotFound'): del_action() assert_response(appliance, http_status=404) @pytest.mark.tier(3) def test_delete_vm_from_collection(vm_name, appliance): vm = appliance.rest_api.collections.vms.get(name=vm_name) collection = appliance.rest_api.collections.vms delete_resources_from_collection(collection, [vm], not_found=True, num_sec=300, delay=10)
jkandasa/integration_tests
cfme/tests/infrastructure/test_vm_rest.py
Python
gpl-2.0
2,531
#ifndef K3DSDK_HYPERBOLOID_H #define K3DSDK_HYPERBOLOID_H // K-3D // Copyright (c) 1995-2008, Timothy M. Shead // // Contact: tshead@k-3d.com // // 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 <k3dsdk/mesh.h> namespace k3d { namespace hyperboloid { /// Gathers the member arrays of a hyperboloid primitive into a convenient package class const_primitive { public: const_primitive( const mesh::matrices_t& Matrices, const mesh::materials_t& Materials, const mesh::points_t& StartPoints, const mesh::points_t& EndPoints, const mesh::doubles_t& SweepAngles, const mesh::selection_t& Selections, const mesh::table_t& ConstantAttributes, const mesh::table_t& SurfaceAttributes, const mesh::table_t& ParameterAttributes); const mesh::matrices_t& matrices; const mesh::materials_t& materials; const mesh::points_t& start_points; const mesh::points_t& end_points; const mesh::doubles_t& sweep_angles; const mesh::selection_t& selections; const mesh::table_t& constant_attributes; const mesh::table_t& surface_attributes; const mesh::table_t& parameter_attributes; }; /// Gathers the member arrays of a hyperboloid primitive into a convenient package class primitive { public: primitive( mesh::matrices_t& Matrices, mesh::materials_t& Materials, mesh::points_t& StartPoints, mesh::points_t& EndPoints, mesh::doubles_t& SweepAngles, mesh::selection_t& Selections, mesh::table_t& ConstantAttributes, mesh::table_t& SurfaceAttributes, mesh::table_t& ParameterAttributes); mesh::matrices_t& matrices; mesh::materials_t& materials; mesh::points_t& start_points; mesh::points_t& end_points; mesh::doubles_t& sweep_angles; mesh::selection_t& selections; mesh::table_t& constant_attributes; mesh::table_t& surface_attributes; mesh::table_t& parameter_attributes; }; /// Creates a new hyperboloid mesh primitive, returning references to its member arrays. /// The caller is responsible for the lifetime of the returned object. primitive* create(mesh& Mesh); /// Tests the given mesh primitive to see if it is a valid hyperboloid primitive, returning references to its member arrays, or NULL. /// The caller is responsible for the lifetime of the returned object. const_primitive* validate(const mesh& Mesh, const mesh::primitive& GenericPrimitive); /// Tests the given mesh primitive to see if it is a valid hyperboloid primitive, returning references to its member arrays, or NULL. /// The caller is responsible for the lifetime of the returned object. primitive* validate(const mesh& Mesh, mesh::primitive& GenericPrimitive); /// Tests the given mesh primitive to see if it is a valid hyperboloid primitive, returning references to its member arrays, or NULL. /// The caller is responsible for the lifetime of the returned object. primitive* validate(const mesh& Mesh, pipeline_data<mesh::primitive>& GenericPrimitive); } // namespace hyperboloid } // namespace k3d #endif // !K3DSDK_HYPERBOLOID_H
barche/k3d
k3dsdk/hyperboloid.h
C
gpl-2.0
3,626
# -*- coding: utf-8 -*- # This file is part of the Horus Project __author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>' __copyright__ = 'Copyright (C) 2014-2016 Mundo Reader S.L.' __license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html' from horus.engine.driver.driver import Driver from horus.engine.scan.ciclop_scan import CiclopScan from horus.engine.scan.current_video import CurrentVideo from horus.engine.calibration.pattern import Pattern from horus.engine.calibration.calibration_data import CalibrationData from horus.engine.calibration.camera_intrinsics import CameraIntrinsics from horus.engine.calibration.autocheck import Autocheck from horus.engine.calibration.laser_triangulation import LaserTriangulation from horus.engine.calibration.platform_extrinsics import PlatformExtrinsics from horus.engine.calibration.combo_calibration import ComboCalibration from horus.engine.algorithms.image_capture import ImageCapture from horus.engine.algorithms.image_detection import ImageDetection from horus.engine.algorithms.laser_segmentation import LaserSegmentation from horus.engine.algorithms.point_cloud_generation import PointCloudGeneration from horus.engine.algorithms.point_cloud_roi import PointCloudROI # Instances of engine modules driver = Driver() ciclop_scan = CiclopScan() current_video = CurrentVideo() pattern = Pattern() calibration_data = CalibrationData() camera_intrinsics = CameraIntrinsics() scanner_autocheck = Autocheck() laser_triangulation = LaserTriangulation() platform_extrinsics = PlatformExtrinsics() combo_calibration = ComboCalibration() image_capture = ImageCapture() image_detection = ImageDetection() laser_segmentation = LaserSegmentation() point_cloud_generation = PointCloudGeneration() point_cloud_roi = PointCloudROI()
bqlabs/horus
src/horus/gui/engine.py
Python
gpl-2.0
1,802
/* * cdc-acm.c * * Copyright (c) 1999 Armin Fuerst <fuerst@in.tum.de> * Copyright (c) 1999 Pavel Machek <pavel@ucw.cz> * Copyright (c) 1999 Johannes Erdfelt <johannes@erdfelt.com> * Copyright (c) 2000 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2004 Oliver Neukum <oliver@neukum.name> * Copyright (c) 2005 David Kubicek <dave@awk.cz> * Copyright (c) 2011 Johan Hovold <jhovold@gmail.com> * * USB Abstract Control Model driver for USB modems and ISDN adapters * * Sponsored by SuSE * * 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 */ #undef DEBUG #undef VERBOSE_DEBUG #include <linux/kernel.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/serial.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/cdc.h> #include <asm/byteorder.h> #include <asm/unaligned.h> #include <linux/list.h> #include "cdc-acm.h" #define DRIVER_AUTHOR "Armin Fuerst, Pavel Machek, Johannes Erdfelt, Vojtech Pavlik, David Kubicek, Johan Hovold" #define DRIVER_DESC "USB Abstract Control Model driver for USB modems and ISDN adapters" static struct usb_driver acm_driver; static struct tty_driver *acm_tty_driver; static struct acm *acm_table[ACM_TTY_MINORS]; static DEFINE_MUTEX(acm_table_lock); /* * acm_table accessors */ /* * Look up an ACM structure by index. If found and not disconnected, increment * its refcount and return it with its mutex held. */ static struct acm *acm_get_by_index(unsigned index) { struct acm *acm; mutex_lock(&acm_table_lock); acm = acm_table[index]; if (acm) { mutex_lock(&acm->mutex); if (acm->disconnected) { mutex_unlock(&acm->mutex); acm = NULL; } else { tty_port_get(&acm->port); mutex_unlock(&acm->mutex); } } mutex_unlock(&acm_table_lock); return acm; } /* * Try to find an available minor number and if found, associate it with 'acm'. */ static int acm_alloc_minor(struct acm *acm) { int minor; mutex_lock(&acm_table_lock); for (minor = 0; minor < ACM_TTY_MINORS; minor++) { if (!acm_table[minor]) { acm_table[minor] = acm; break; } } mutex_unlock(&acm_table_lock); return minor; } /* Release the minor number associated with 'acm'. */ static void acm_release_minor(struct acm *acm) { mutex_lock(&acm_table_lock); acm_table[acm->minor] = NULL; mutex_unlock(&acm_table_lock); } /* * Functions for ACM control messages. */ static int acm_ctrl_msg(struct acm *acm, int request, int value, void *buf, int len) { int retval = usb_control_msg(acm->dev, usb_sndctrlpipe(acm->dev, 0), request, USB_RT_ACM, value, acm->control->altsetting[0].desc.bInterfaceNumber, buf, len, 5000); dev_dbg(&acm->control->dev, "%s - rq 0x%02x, val %#x, len %#x, result %d\n", __func__, request, value, len, retval); return retval < 0 ? retval : 0; } /* devices aren't required to support these requests. * the cdc acm descriptor tells whether they do... */ #define acm_set_control(acm, control) \ acm_ctrl_msg(acm, USB_CDC_REQ_SET_CONTROL_LINE_STATE, control, NULL, 0) #define acm_set_line(acm, line) \ acm_ctrl_msg(acm, USB_CDC_REQ_SET_LINE_CODING, 0, line, sizeof *(line)) #define acm_send_break(acm, ms) \ acm_ctrl_msg(acm, USB_CDC_REQ_SEND_BREAK, ms, NULL, 0) /* * Write buffer management. * All of these assume proper locks taken by the caller. */ static int acm_wb_alloc(struct acm *acm) { int i, wbn; struct acm_wb *wb; wbn = 0; i = 0; for (;;) { wb = &acm->wb[wbn]; if (!wb->use) { wb->use = 1; return wbn; } wbn = (wbn + 1) % ACM_NW; if (++i >= ACM_NW) return -1; } } static int acm_wb_is_avail(struct acm *acm) { int i, n; unsigned long flags; n = ACM_NW; spin_lock_irqsave(&acm->write_lock, flags); for (i = 0; i < ACM_NW; i++) n -= acm->wb[i].use; spin_unlock_irqrestore(&acm->write_lock, flags); return n; } /* * Finish write. Caller must hold acm->write_lock */ static void acm_write_done(struct acm *acm, struct acm_wb *wb) { wb->use = 0; acm->transmitting--; usb_autopm_put_interface_async(acm->control); } /* * Poke write. * * the caller is responsible for locking */ static int acm_start_wb(struct acm *acm, struct acm_wb *wb) { int rc; acm->transmitting++; wb->urb->transfer_buffer = wb->buf; wb->urb->transfer_dma = wb->dmah; wb->urb->transfer_buffer_length = wb->len; wb->urb->dev = acm->dev; rc = usb_submit_urb(wb->urb, GFP_ATOMIC); if (rc < 0) { dev_err(&acm->data->dev, "%s - usb_submit_urb(write bulk) failed: %d\n", __func__, rc); acm_write_done(acm, wb); } return rc; } /* * attributes exported through sysfs */ static ssize_t show_caps (struct device *dev, struct device_attribute *attr, char *buf) { struct usb_interface *intf = to_usb_interface(dev); struct acm *acm = usb_get_intfdata(intf); return sprintf(buf, "%d", acm->ctrl_caps); } static DEVICE_ATTR(bmCapabilities, S_IRUGO, show_caps, NULL); static ssize_t show_country_codes (struct device *dev, struct device_attribute *attr, char *buf) { struct usb_interface *intf = to_usb_interface(dev); struct acm *acm = usb_get_intfdata(intf); memcpy(buf, acm->country_codes, acm->country_code_size); return acm->country_code_size; } static DEVICE_ATTR(wCountryCodes, S_IRUGO, show_country_codes, NULL); static ssize_t show_country_rel_date (struct device *dev, struct device_attribute *attr, char *buf) { struct usb_interface *intf = to_usb_interface(dev); struct acm *acm = usb_get_intfdata(intf); return sprintf(buf, "%d", acm->country_rel_date); } static DEVICE_ATTR(iCountryCodeRelDate, S_IRUGO, show_country_rel_date, NULL); /* * Interrupt handlers for various ACM device responses */ /* control interface reports status changes with "interrupt" transfers */ static void acm_ctrl_irq(struct urb *urb) { struct acm *acm = urb->context; struct usb_cdc_notification *dr = urb->transfer_buffer; unsigned char *data; int newctrl; int difference; int retval; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&acm->control->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_dbg(&acm->control->dev, "%s - nonzero urb status received: %d\n", __func__, status); goto exit; } usb_mark_last_busy(acm->dev); data = (unsigned char *)(dr + 1); switch (dr->bNotificationType) { case USB_CDC_NOTIFY_NETWORK_CONNECTION: dev_dbg(&acm->control->dev, "%s - network connection: %d\n", __func__, dr->wValue); break; case USB_CDC_NOTIFY_SERIAL_STATE: newctrl = get_unaligned_le16(data); if (!acm->clocal && (acm->ctrlin & ~newctrl & ACM_CTRL_DCD)) { dev_dbg(&acm->control->dev, "%s - calling hangup\n", __func__); tty_port_tty_hangup(&acm->port, false); } difference = acm->ctrlin ^ newctrl; spin_lock(&acm->read_lock); acm->ctrlin = newctrl; acm->oldcount = acm->iocount; if (difference & ACM_CTRL_DSR) acm->iocount.dsr++; if (difference & ACM_CTRL_BRK) acm->iocount.brk++; if (difference & ACM_CTRL_RI) acm->iocount.rng++; if (difference & ACM_CTRL_DCD) acm->iocount.dcd++; if (difference & ACM_CTRL_FRAMING) acm->iocount.frame++; if (difference & ACM_CTRL_PARITY) acm->iocount.parity++; if (difference & ACM_CTRL_OVERRUN) acm->iocount.overrun++; spin_unlock(&acm->read_lock); if (difference) wake_up_all(&acm->wioctl); break; default: dev_dbg(&acm->control->dev, "%s - unknown notification %d received: index %d " "len %d data0 %d data1 %d\n", __func__, dr->bNotificationType, dr->wIndex, dr->wLength, data[0], data[1]); break; } exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&acm->control->dev, "%s - usb_submit_urb failed: %d\n", __func__, retval); } static int acm_submit_read_urb(struct acm *acm, int index, gfp_t mem_flags) { int res; if (!test_and_clear_bit(index, &acm->read_urbs_free)) return 0; dev_vdbg(&acm->data->dev, "%s - urb %d\n", __func__, index); res = usb_submit_urb(acm->read_urbs[index], mem_flags); if (res) { if (res != -EPERM) { dev_err(&acm->data->dev, "%s - usb_submit_urb failed: %d\n", __func__, res); } set_bit(index, &acm->read_urbs_free); return res; } return 0; } static int acm_submit_read_urbs(struct acm *acm, gfp_t mem_flags) { int res; int i; for (i = 0; i < acm->rx_buflimit; ++i) { res = acm_submit_read_urb(acm, i, mem_flags); if (res) return res; } return 0; } static void acm_process_read_urb(struct acm *acm, struct urb *urb) { if (!urb->actual_length) return; tty_insert_flip_string(&acm->port, urb->transfer_buffer, urb->actual_length); tty_flip_buffer_push(&acm->port); } static void acm_read_bulk_callback(struct urb *urb) { struct acm_rb *rb = urb->context; struct acm *acm = rb->instance; unsigned long flags; dev_vdbg(&acm->data->dev, "%s - urb %d, len %d\n", __func__, rb->index, urb->actual_length); set_bit(rb->index, &acm->read_urbs_free); if (!acm->dev) { dev_dbg(&acm->data->dev, "%s - disconnected\n", __func__); return; } usb_mark_last_busy(acm->dev); if (urb->status) { dev_dbg(&acm->data->dev, "%s - non-zero urb status: %d\n", __func__, urb->status); return; } acm_process_read_urb(acm, urb); /* throttle device if requested by tty */ spin_lock_irqsave(&acm->read_lock, flags); acm->throttled = acm->throttle_req; if (!acm->throttled && !acm->susp_count) { spin_unlock_irqrestore(&acm->read_lock, flags); acm_submit_read_urb(acm, rb->index, GFP_ATOMIC); } else { spin_unlock_irqrestore(&acm->read_lock, flags); } } /* data interface wrote those outgoing bytes */ static void acm_write_bulk(struct urb *urb) { struct acm_wb *wb = urb->context; struct acm *acm = wb->instance; unsigned long flags; if (urb->status || (urb->actual_length != urb->transfer_buffer_length)) dev_vdbg(&acm->data->dev, "%s - len %d/%d, status %d\n", __func__, urb->actual_length, urb->transfer_buffer_length, urb->status); spin_lock_irqsave(&acm->write_lock, flags); acm_write_done(acm, wb); spin_unlock_irqrestore(&acm->write_lock, flags); schedule_work(&acm->work); } static void acm_softint(struct work_struct *work) { struct acm *acm = container_of(work, struct acm, work); dev_vdbg(&acm->data->dev, "%s\n", __func__); tty_port_tty_wakeup(&acm->port); } /* * TTY handlers */ static int acm_tty_install(struct tty_driver *driver, struct tty_struct *tty) { struct acm *acm; int retval; dev_dbg(tty->dev, "%s\n", __func__); acm = acm_get_by_index(tty->index); if (!acm) return -ENODEV; retval = tty_standard_install(driver, tty); if (retval) goto error_init_termios; tty->driver_data = acm; return 0; error_init_termios: tty_port_put(&acm->port); return retval; } static int acm_tty_open(struct tty_struct *tty, struct file *filp) { struct acm *acm = tty->driver_data; dev_dbg(tty->dev, "%s\n", __func__); return tty_port_open(&acm->port, tty, filp); } static int acm_port_activate(struct tty_port *port, struct tty_struct *tty) { struct acm *acm = container_of(port, struct acm, port); int retval = -ENODEV; dev_dbg(&acm->control->dev, "%s\n", __func__); mutex_lock(&acm->mutex); if (acm->disconnected) goto disconnected; retval = usb_autopm_get_interface(acm->control); if (retval) goto error_get_interface; /* * FIXME: Why do we need this? Allocating 64K of physically contiguous * memory is really nasty... */ set_bit(TTY_NO_WRITE_SPLIT, &tty->flags); acm->control->needs_remote_wakeup = 1; acm->ctrlurb->dev = acm->dev; if (usb_submit_urb(acm->ctrlurb, GFP_KERNEL)) { dev_err(&acm->control->dev, "%s - usb_submit_urb(ctrl irq) failed\n", __func__); goto error_submit_urb; } acm->ctrlout = ACM_CTRL_DTR | ACM_CTRL_RTS; if (acm_set_control(acm, acm->ctrlout) < 0 && (acm->ctrl_caps & USB_CDC_CAP_LINE)) goto error_set_control; usb_autopm_put_interface(acm->control); /* * Unthrottle device in case the TTY was closed while throttled. */ spin_lock_irq(&acm->read_lock); acm->throttled = 0; acm->throttle_req = 0; spin_unlock_irq(&acm->read_lock); if (acm_submit_read_urbs(acm, GFP_KERNEL)) goto error_submit_read_urbs; mutex_unlock(&acm->mutex); return 0; error_submit_read_urbs: acm->ctrlout = 0; acm_set_control(acm, acm->ctrlout); error_set_control: usb_kill_urb(acm->ctrlurb); error_submit_urb: usb_autopm_put_interface(acm->control); error_get_interface: disconnected: mutex_unlock(&acm->mutex); return retval; } static void acm_port_destruct(struct tty_port *port) { struct acm *acm = container_of(port, struct acm, port); dev_dbg(&acm->control->dev, "%s\n", __func__); acm_release_minor(acm); usb_put_intf(acm->control); kfree(acm->country_codes); kfree(acm); } static void acm_port_shutdown(struct tty_port *port) { struct acm *acm = container_of(port, struct acm, port); int i; dev_dbg(&acm->control->dev, "%s\n", __func__); mutex_lock(&acm->mutex); if (!acm->disconnected) { usb_autopm_get_interface(acm->control); acm_set_control(acm, acm->ctrlout = 0); usb_kill_urb(acm->ctrlurb); for (i = 0; i < ACM_NW; i++) usb_kill_urb(acm->wb[i].urb); for (i = 0; i < acm->rx_buflimit; i++) usb_kill_urb(acm->read_urbs[i]); acm->control->needs_remote_wakeup = 0; usb_autopm_put_interface(acm->control); } mutex_unlock(&acm->mutex); } static void acm_tty_cleanup(struct tty_struct *tty) { struct acm *acm = tty->driver_data; dev_dbg(&acm->control->dev, "%s\n", __func__); tty_port_put(&acm->port); } static void acm_tty_hangup(struct tty_struct *tty) { struct acm *acm = tty->driver_data; dev_dbg(&acm->control->dev, "%s\n", __func__); tty_port_hangup(&acm->port); } static void acm_tty_close(struct tty_struct *tty, struct file *filp) { struct acm *acm = tty->driver_data; dev_dbg(&acm->control->dev, "%s\n", __func__); tty_port_close(&acm->port, tty, filp); } static int acm_tty_write(struct tty_struct *tty, const unsigned char *buf, int count) { struct acm *acm = tty->driver_data; int stat; unsigned long flags; int wbn; struct acm_wb *wb; if (!count) return 0; dev_vdbg(&acm->data->dev, "%s - count %d\n", __func__, count); spin_lock_irqsave(&acm->write_lock, flags); wbn = acm_wb_alloc(acm); if (wbn < 0) { spin_unlock_irqrestore(&acm->write_lock, flags); return 0; } wb = &acm->wb[wbn]; if (!acm->dev) { wb->use = 0; spin_unlock_irqrestore(&acm->write_lock, flags); return -ENODEV; } count = (count > acm->writesize) ? acm->writesize : count; dev_vdbg(&acm->data->dev, "%s - write %d\n", __func__, count); memcpy(wb->buf, buf, count); wb->len = count; usb_autopm_get_interface_async(acm->control); if (acm->susp_count) { if (!acm->delayed_wb) acm->delayed_wb = wb; else usb_autopm_put_interface_async(acm->control); spin_unlock_irqrestore(&acm->write_lock, flags); return count; /* A white lie */ } usb_mark_last_busy(acm->dev); stat = acm_start_wb(acm, wb); spin_unlock_irqrestore(&acm->write_lock, flags); if (stat < 0) return stat; return count; } static int acm_tty_write_room(struct tty_struct *tty) { struct acm *acm = tty->driver_data; /* * Do not let the line discipline to know that we have a reserve, * or it might get too enthusiastic. */ return acm_wb_is_avail(acm) ? acm->writesize : 0; } static int acm_tty_chars_in_buffer(struct tty_struct *tty) { struct acm *acm = tty->driver_data; /* * if the device was unplugged then any remaining characters fell out * of the connector ;) */ if (acm->disconnected) return 0; /* * This is inaccurate (overcounts), but it works. */ return (ACM_NW - acm_wb_is_avail(acm)) * acm->writesize; } static void acm_tty_throttle(struct tty_struct *tty) { struct acm *acm = tty->driver_data; spin_lock_irq(&acm->read_lock); acm->throttle_req = 1; spin_unlock_irq(&acm->read_lock); } static void acm_tty_unthrottle(struct tty_struct *tty) { struct acm *acm = tty->driver_data; unsigned int was_throttled; spin_lock_irq(&acm->read_lock); was_throttled = acm->throttled; acm->throttled = 0; acm->throttle_req = 0; spin_unlock_irq(&acm->read_lock); if (was_throttled) acm_submit_read_urbs(acm, GFP_KERNEL); } static int acm_tty_break_ctl(struct tty_struct *tty, int state) { struct acm *acm = tty->driver_data; int retval; retval = acm_send_break(acm, state ? 0xffff : 0); if (retval < 0) dev_dbg(&acm->control->dev, "%s - send break failed\n", __func__); return retval; } static int acm_tty_tiocmget(struct tty_struct *tty) { struct acm *acm = tty->driver_data; return (acm->ctrlout & ACM_CTRL_DTR ? TIOCM_DTR : 0) | (acm->ctrlout & ACM_CTRL_RTS ? TIOCM_RTS : 0) | (acm->ctrlin & ACM_CTRL_DSR ? TIOCM_DSR : 0) | (acm->ctrlin & ACM_CTRL_RI ? TIOCM_RI : 0) | (acm->ctrlin & ACM_CTRL_DCD ? TIOCM_CD : 0) | TIOCM_CTS; } static int acm_tty_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct acm *acm = tty->driver_data; unsigned int newctrl; newctrl = acm->ctrlout; set = (set & TIOCM_DTR ? ACM_CTRL_DTR : 0) | (set & TIOCM_RTS ? ACM_CTRL_RTS : 0); clear = (clear & TIOCM_DTR ? ACM_CTRL_DTR : 0) | (clear & TIOCM_RTS ? ACM_CTRL_RTS : 0); newctrl = (newctrl & ~clear) | set; if (acm->ctrlout == newctrl) return 0; return acm_set_control(acm, acm->ctrlout = newctrl); } static int get_serial_info(struct acm *acm, struct serial_struct __user *info) { struct serial_struct tmp; if (!info) return -EINVAL; memset(&tmp, 0, sizeof(tmp)); tmp.flags = ASYNC_LOW_LATENCY; tmp.xmit_fifo_size = acm->writesize; tmp.baud_base = le32_to_cpu(acm->line.dwDTERate); tmp.close_delay = acm->port.close_delay / 10; tmp.closing_wait = acm->port.closing_wait == ASYNC_CLOSING_WAIT_NONE ? ASYNC_CLOSING_WAIT_NONE : acm->port.closing_wait / 10; if (copy_to_user(info, &tmp, sizeof(tmp))) return -EFAULT; else return 0; } static int set_serial_info(struct acm *acm, struct serial_struct __user *newinfo) { struct serial_struct new_serial; unsigned int closing_wait, close_delay; int retval = 0; if (copy_from_user(&new_serial, newinfo, sizeof(new_serial))) return -EFAULT; close_delay = new_serial.close_delay * 10; closing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ? ASYNC_CLOSING_WAIT_NONE : new_serial.closing_wait * 10; mutex_lock(&acm->port.mutex); if (!capable(CAP_SYS_ADMIN)) { if ((close_delay != acm->port.close_delay) || (closing_wait != acm->port.closing_wait)) retval = -EPERM; else retval = -EOPNOTSUPP; } else { acm->port.close_delay = close_delay; acm->port.closing_wait = closing_wait; } mutex_unlock(&acm->port.mutex); return retval; } static int wait_serial_change(struct acm *acm, unsigned long arg) { int rv = 0; DECLARE_WAITQUEUE(wait, current); struct async_icount old, new; if (arg & (TIOCM_DSR | TIOCM_RI | TIOCM_CD )) return -EINVAL; do { spin_lock_irq(&acm->read_lock); old = acm->oldcount; new = acm->iocount; acm->oldcount = new; spin_unlock_irq(&acm->read_lock); if ((arg & TIOCM_DSR) && old.dsr != new.dsr) break; if ((arg & TIOCM_CD) && old.dcd != new.dcd) break; if ((arg & TIOCM_RI) && old.rng != new.rng) break; add_wait_queue(&acm->wioctl, &wait); set_current_state(TASK_INTERRUPTIBLE); schedule(); remove_wait_queue(&acm->wioctl, &wait); if (acm->disconnected) { if (arg & TIOCM_CD) break; else rv = -ENODEV; } else { if (signal_pending(current)) rv = -ERESTARTSYS; } } while (!rv); return rv; } static int get_serial_usage(struct acm *acm, struct serial_icounter_struct __user *count) { struct serial_icounter_struct icount; int rv = 0; memset(&icount, 0, sizeof(icount)); icount.dsr = acm->iocount.dsr; icount.rng = acm->iocount.rng; icount.dcd = acm->iocount.dcd; icount.frame = acm->iocount.frame; icount.overrun = acm->iocount.overrun; icount.parity = acm->iocount.parity; icount.brk = acm->iocount.brk; if (copy_to_user(count, &icount, sizeof(icount)) > 0) rv = -EFAULT; return rv; } static int acm_tty_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct acm *acm = tty->driver_data; int rv = -ENOIOCTLCMD; switch (cmd) { case TIOCGSERIAL: /* gets serial port data */ rv = get_serial_info(acm, (struct serial_struct __user *) arg); break; case TIOCSSERIAL: rv = set_serial_info(acm, (struct serial_struct __user *) arg); break; case TIOCMIWAIT: rv = usb_autopm_get_interface(acm->control); if (rv < 0) { rv = -EIO; break; } rv = wait_serial_change(acm, arg); usb_autopm_put_interface(acm->control); break; case TIOCGICOUNT: rv = get_serial_usage(acm, (struct serial_icounter_struct __user *) arg); break; } return rv; } static void acm_tty_set_termios(struct tty_struct *tty, struct ktermios *termios_old) { struct acm *acm = tty->driver_data; struct ktermios *termios = &tty->termios; struct usb_cdc_line_coding newline; int newctrl = acm->ctrlout; newline.dwDTERate = cpu_to_le32(tty_get_baud_rate(tty)); newline.bCharFormat = termios->c_cflag & CSTOPB ? 2 : 0; newline.bParityType = termios->c_cflag & PARENB ? (termios->c_cflag & PARODD ? 1 : 2) + (termios->c_cflag & CMSPAR ? 2 : 0) : 0; switch (termios->c_cflag & CSIZE) { case CS5: newline.bDataBits = 5; break; case CS6: newline.bDataBits = 6; break; case CS7: newline.bDataBits = 7; break; case CS8: default: newline.bDataBits = 8; break; } /* FIXME: Needs to clear unsupported bits in the termios */ acm->clocal = ((termios->c_cflag & CLOCAL) != 0); if (!newline.dwDTERate) { newline.dwDTERate = acm->line.dwDTERate; newctrl &= ~ACM_CTRL_DTR; } else newctrl |= ACM_CTRL_DTR; if (newctrl != acm->ctrlout) acm_set_control(acm, acm->ctrlout = newctrl); if (memcmp(&acm->line, &newline, sizeof newline)) { memcpy(&acm->line, &newline, sizeof newline); dev_dbg(&acm->control->dev, "%s - set line: %d %d %d %d\n", __func__, le32_to_cpu(newline.dwDTERate), newline.bCharFormat, newline.bParityType, newline.bDataBits); acm_set_line(acm, &acm->line); } } static const struct tty_port_operations acm_port_ops = { .shutdown = acm_port_shutdown, .activate = acm_port_activate, .destruct = acm_port_destruct, }; /* * USB probe and disconnect routines. */ /* Little helpers: write/read buffers free */ static void acm_write_buffers_free(struct acm *acm) { int i; struct acm_wb *wb; struct usb_device *usb_dev = interface_to_usbdev(acm->control); for (wb = &acm->wb[0], i = 0; i < ACM_NW; i++, wb++) usb_free_coherent(usb_dev, acm->writesize, wb->buf, wb->dmah); } static void acm_read_buffers_free(struct acm *acm) { struct usb_device *usb_dev = interface_to_usbdev(acm->control); int i; for (i = 0; i < acm->rx_buflimit; i++) usb_free_coherent(usb_dev, acm->readsize, acm->read_buffers[i].base, acm->read_buffers[i].dma); } /* Little helper: write buffers allocate */ static int acm_write_buffers_alloc(struct acm *acm) { int i; struct acm_wb *wb; for (wb = &acm->wb[0], i = 0; i < ACM_NW; i++, wb++) { wb->buf = usb_alloc_coherent(acm->dev, acm->writesize, GFP_KERNEL, &wb->dmah); if (!wb->buf) { while (i != 0) { --i; --wb; usb_free_coherent(acm->dev, acm->writesize, wb->buf, wb->dmah); } return -ENOMEM; } } return 0; } static int acm_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_cdc_union_desc *union_header = NULL; struct usb_cdc_country_functional_desc *cfd = NULL; unsigned char *buffer = intf->altsetting->extra; int buflen = intf->altsetting->extralen; struct usb_interface *control_interface; struct usb_interface *data_interface; struct usb_endpoint_descriptor *epctrl = NULL; struct usb_endpoint_descriptor *epread = NULL; struct usb_endpoint_descriptor *epwrite = NULL; struct usb_device *usb_dev = interface_to_usbdev(intf); struct acm *acm; int minor; int ctrlsize, readsize; u8 *buf; u8 ac_management_function = 0; u8 call_management_function = 0; int call_interface_num = -1; int data_interface_num = -1; unsigned long quirks; int num_rx_buf; int i; int combined_interfaces = 0; struct device *tty_dev; int rv = -ENOMEM; /* normal quirks */ quirks = (unsigned long)id->driver_info; if (quirks == IGNORE_DEVICE) return -ENODEV; num_rx_buf = (quirks == SINGLE_RX_URB) ? 1 : ACM_NR; /* handle quirks deadly to normal probing*/ if (quirks == NO_UNION_NORMAL) { data_interface = usb_ifnum_to_if(usb_dev, 1); control_interface = usb_ifnum_to_if(usb_dev, 0); goto skip_normal_probe; } /* normal probing*/ if (!buffer) { dev_err(&intf->dev, "Weird descriptor references\n"); return -EINVAL; } if (!buflen) { if (intf->cur_altsetting->endpoint && intf->cur_altsetting->endpoint->extralen && intf->cur_altsetting->endpoint->extra) { dev_dbg(&intf->dev, "Seeking extra descriptors on endpoint\n"); buflen = intf->cur_altsetting->endpoint->extralen; buffer = intf->cur_altsetting->endpoint->extra; } else { dev_err(&intf->dev, "Zero length descriptor references\n"); return -EINVAL; } } while (buflen > 0) { if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (union_header) { dev_err(&intf->dev, "More than one " "union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: /* export through sysfs*/ cfd = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: /* maybe check version */ break; /* for now we ignore it */ case USB_CDC_ACM_TYPE: ac_management_function = buffer[3]; break; case USB_CDC_CALL_MANAGEMENT_TYPE: call_management_function = buffer[3]; call_interface_num = buffer[4]; if ((quirks & NOT_A_MODEM) == 0 && (call_management_function & 3) != 3) dev_err(&intf->dev, "This device cannot do calls on its own. It is not a modem.\n"); break; default: /* there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: " "type %02x, length %d\n", buffer[2], buffer[0]); break; } next_desc: buflen -= buffer[0]; buffer += buffer[0]; } if (!union_header) { if (call_interface_num > 0) { dev_dbg(&intf->dev, "No union descriptor, using call management descriptor\n"); /* quirks for Droids MuIn LCD */ if (quirks & NO_DATA_INTERFACE) data_interface = usb_ifnum_to_if(usb_dev, 0); else data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = call_interface_num)); control_interface = intf; } else { if (intf->cur_altsetting->desc.bNumEndpoints != 3) { dev_dbg(&intf->dev,"No union descriptor, giving up\n"); return -ENODEV; } else { dev_warn(&intf->dev,"No union descriptor, testing for castrated device\n"); combined_interfaces = 1; control_interface = data_interface = intf; goto look_for_collapsed_interface; } } } else { control_interface = usb_ifnum_to_if(usb_dev, union_header->bMasterInterface0); data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = union_header->bSlaveInterface0)); if (!control_interface || !data_interface) { dev_dbg(&intf->dev, "no interfaces\n"); return -ENODEV; } } if (data_interface_num != call_interface_num) dev_dbg(&intf->dev, "Separate call control interface. That is not fully supported.\n"); if (control_interface == data_interface) { /* some broken devices designed for windows work this way */ dev_warn(&intf->dev,"Control and data interfaces are not separated!\n"); combined_interfaces = 1; /* a popular other OS doesn't use it */ quirks |= NO_CAP_LINE; if (data_interface->cur_altsetting->desc.bNumEndpoints != 3) { dev_err(&intf->dev, "This needs exactly 3 endpoints\n"); return -EINVAL; } look_for_collapsed_interface: for (i = 0; i < 3; i++) { struct usb_endpoint_descriptor *ep; ep = &data_interface->cur_altsetting->endpoint[i].desc; if (usb_endpoint_is_int_in(ep)) epctrl = ep; else if (usb_endpoint_is_bulk_out(ep)) epwrite = ep; else if (usb_endpoint_is_bulk_in(ep)) epread = ep; else return -EINVAL; } if (!epctrl || !epread || !epwrite) return -ENODEV; else goto made_compressed_probe; } skip_normal_probe: /*workaround for switched interfaces */ if (data_interface->cur_altsetting->desc.bInterfaceClass != CDC_DATA_INTERFACE_TYPE) { if (control_interface->cur_altsetting->desc.bInterfaceClass == CDC_DATA_INTERFACE_TYPE) { struct usb_interface *t; dev_dbg(&intf->dev, "Your device has switched interfaces.\n"); t = control_interface; control_interface = data_interface; data_interface = t; } else { return -EINVAL; } } /* Accept probe requests only for the control interface */ if (!combined_interfaces && intf != control_interface) return -ENODEV; if (!combined_interfaces && usb_interface_claimed(data_interface)) { /* valid in this context */ dev_dbg(&intf->dev, "The data interface isn't available\n"); return -EBUSY; } if (data_interface->cur_altsetting->desc.bNumEndpoints < 2 || control_interface->cur_altsetting->desc.bNumEndpoints == 0) return -EINVAL; epctrl = &control_interface->cur_altsetting->endpoint[0].desc; epread = &data_interface->cur_altsetting->endpoint[0].desc; epwrite = &data_interface->cur_altsetting->endpoint[1].desc; /* workaround for switched endpoints */ if (!usb_endpoint_dir_in(epread)) { /* descriptors are swapped */ struct usb_endpoint_descriptor *t; dev_dbg(&intf->dev, "The data interface has switched endpoints\n"); t = epread; epread = epwrite; epwrite = t; } made_compressed_probe: dev_dbg(&intf->dev, "interfaces are valid\n"); acm = kzalloc(sizeof(struct acm), GFP_KERNEL); if (acm == NULL) { dev_err(&intf->dev, "out of memory (acm kzalloc)\n"); goto alloc_fail; } minor = acm_alloc_minor(acm); if (minor == ACM_TTY_MINORS) { dev_err(&intf->dev, "no more free acm devices\n"); kfree(acm); return -ENODEV; } ctrlsize = usb_endpoint_maxp(epctrl); readsize = usb_endpoint_maxp(epread) * (quirks == SINGLE_RX_URB ? 1 : 2); acm->combined_interfaces = combined_interfaces; acm->writesize = usb_endpoint_maxp(epwrite) * 20; acm->control = control_interface; acm->data = data_interface; acm->minor = minor; acm->dev = usb_dev; acm->ctrl_caps = ac_management_function; if (quirks & NO_CAP_LINE) acm->ctrl_caps &= ~USB_CDC_CAP_LINE; acm->ctrlsize = ctrlsize; acm->readsize = readsize; acm->rx_buflimit = num_rx_buf; INIT_WORK(&acm->work, acm_softint); init_waitqueue_head(&acm->wioctl); spin_lock_init(&acm->write_lock); spin_lock_init(&acm->read_lock); mutex_init(&acm->mutex); acm->rx_endpoint = usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress); acm->is_int_ep = usb_endpoint_xfer_int(epread); if (acm->is_int_ep) acm->bInterval = epread->bInterval; tty_port_init(&acm->port); acm->port.ops = &acm_port_ops; buf = usb_alloc_coherent(usb_dev, ctrlsize, GFP_KERNEL, &acm->ctrl_dma); if (!buf) { dev_err(&intf->dev, "out of memory (ctrl buffer alloc)\n"); goto alloc_fail2; } acm->ctrl_buffer = buf; if (acm_write_buffers_alloc(acm) < 0) { dev_err(&intf->dev, "out of memory (write buffer alloc)\n"); goto alloc_fail4; } acm->ctrlurb = usb_alloc_urb(0, GFP_KERNEL); if (!acm->ctrlurb) { dev_err(&intf->dev, "out of memory (ctrlurb kmalloc)\n"); goto alloc_fail5; } for (i = 0; i < num_rx_buf; i++) { struct acm_rb *rb = &(acm->read_buffers[i]); struct urb *urb; rb->base = usb_alloc_coherent(acm->dev, readsize, GFP_KERNEL, &rb->dma); if (!rb->base) { dev_err(&intf->dev, "out of memory " "(read bufs usb_alloc_coherent)\n"); goto alloc_fail6; } rb->index = i; rb->instance = acm; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) { dev_err(&intf->dev, "out of memory (read urbs usb_alloc_urb)\n"); goto alloc_fail6; } urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; urb->transfer_dma = rb->dma; if (acm->is_int_ep) { usb_fill_int_urb(urb, acm->dev, acm->rx_endpoint, rb->base, acm->readsize, acm_read_bulk_callback, rb, acm->bInterval); } else { usb_fill_bulk_urb(urb, acm->dev, acm->rx_endpoint, rb->base, acm->readsize, acm_read_bulk_callback, rb); } acm->read_urbs[i] = urb; __set_bit(i, &acm->read_urbs_free); } for (i = 0; i < ACM_NW; i++) { struct acm_wb *snd = &(acm->wb[i]); snd->urb = usb_alloc_urb(0, GFP_KERNEL); if (snd->urb == NULL) { dev_err(&intf->dev, "out of memory (write urbs usb_alloc_urb)\n"); goto alloc_fail7; } if (usb_endpoint_xfer_int(epwrite)) usb_fill_int_urb(snd->urb, usb_dev, usb_sndintpipe(usb_dev, epwrite->bEndpointAddress), NULL, acm->writesize, acm_write_bulk, snd, epwrite->bInterval); else usb_fill_bulk_urb(snd->urb, usb_dev, usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress), NULL, acm->writesize, acm_write_bulk, snd); snd->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; snd->instance = acm; } usb_set_intfdata(intf, acm); i = device_create_file(&intf->dev, &dev_attr_bmCapabilities); if (i < 0) goto alloc_fail7; if (cfd) { /* export the country data */ acm->country_codes = kmalloc(cfd->bLength - 4, GFP_KERNEL); if (!acm->country_codes) goto skip_countries; acm->country_code_size = cfd->bLength - 4; memcpy(acm->country_codes, (u8 *)&cfd->wCountyCode0, cfd->bLength - 4); acm->country_rel_date = cfd->iCountryCodeRelDate; i = device_create_file(&intf->dev, &dev_attr_wCountryCodes); if (i < 0) { kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } i = device_create_file(&intf->dev, &dev_attr_iCountryCodeRelDate); if (i < 0) { device_remove_file(&intf->dev, &dev_attr_wCountryCodes); kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } } skip_countries: usb_fill_int_urb(acm->ctrlurb, usb_dev, usb_rcvintpipe(usb_dev, epctrl->bEndpointAddress), acm->ctrl_buffer, ctrlsize, acm_ctrl_irq, acm, /* works around buggy devices */ epctrl->bInterval ? epctrl->bInterval : 16); acm->ctrlurb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; acm->ctrlurb->transfer_dma = acm->ctrl_dma; dev_info(&intf->dev, "ttyACM%d: USB ACM device\n", minor); acm_set_control(acm, acm->ctrlout); acm->line.dwDTERate = cpu_to_le32(9600); acm->line.bDataBits = 8; acm_set_line(acm, &acm->line); usb_driver_claim_interface(&acm_driver, data_interface, acm); usb_set_intfdata(data_interface, acm); usb_get_intf(control_interface); tty_dev = tty_port_register_device(&acm->port, acm_tty_driver, minor, &control_interface->dev); if (IS_ERR(tty_dev)) { rv = PTR_ERR(tty_dev); goto alloc_fail8; } return 0; alloc_fail8: if (acm->country_codes) { device_remove_file(&acm->control->dev, &dev_attr_wCountryCodes); device_remove_file(&acm->control->dev, &dev_attr_iCountryCodeRelDate); } device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities); alloc_fail7: usb_set_intfdata(intf, NULL); for (i = 0; i < ACM_NW; i++) usb_free_urb(acm->wb[i].urb); alloc_fail6: for (i = 0; i < num_rx_buf; i++) usb_free_urb(acm->read_urbs[i]); acm_read_buffers_free(acm); usb_free_urb(acm->ctrlurb); alloc_fail5: acm_write_buffers_free(acm); alloc_fail4: usb_free_coherent(usb_dev, ctrlsize, acm->ctrl_buffer, acm->ctrl_dma); alloc_fail2: acm_release_minor(acm); kfree(acm); alloc_fail: return rv; } static void stop_data_traffic(struct acm *acm) { int i; dev_dbg(&acm->control->dev, "%s\n", __func__); usb_kill_urb(acm->ctrlurb); for (i = 0; i < ACM_NW; i++) usb_kill_urb(acm->wb[i].urb); for (i = 0; i < acm->rx_buflimit; i++) usb_kill_urb(acm->read_urbs[i]); cancel_work_sync(&acm->work); } static void acm_disconnect(struct usb_interface *intf) { struct acm *acm = usb_get_intfdata(intf); struct usb_device *usb_dev = interface_to_usbdev(intf); struct tty_struct *tty; int i; dev_dbg(&intf->dev, "%s\n", __func__); /* sibling interface is already cleaning up */ if (!acm) return; mutex_lock(&acm->mutex); acm->disconnected = true; if (acm->country_codes) { device_remove_file(&acm->control->dev, &dev_attr_wCountryCodes); device_remove_file(&acm->control->dev, &dev_attr_iCountryCodeRelDate); } wake_up_all(&acm->wioctl); device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities); usb_set_intfdata(acm->control, NULL); usb_set_intfdata(acm->data, NULL); mutex_unlock(&acm->mutex); tty = tty_port_tty_get(&acm->port); if (tty) { tty_vhangup(tty); tty_kref_put(tty); } stop_data_traffic(acm); tty_unregister_device(acm_tty_driver, acm->minor); usb_free_urb(acm->ctrlurb); for (i = 0; i < ACM_NW; i++) usb_free_urb(acm->wb[i].urb); for (i = 0; i < acm->rx_buflimit; i++) usb_free_urb(acm->read_urbs[i]); acm_write_buffers_free(acm); usb_free_coherent(usb_dev, acm->ctrlsize, acm->ctrl_buffer, acm->ctrl_dma); acm_read_buffers_free(acm); if (!acm->combined_interfaces) usb_driver_release_interface(&acm_driver, intf == acm->control ? acm->data : acm->control); tty_port_put(&acm->port); } #ifdef CONFIG_PM static int acm_suspend(struct usb_interface *intf, pm_message_t message) { struct acm *acm = usb_get_intfdata(intf); int cnt; if (PMSG_IS_AUTO(message)) { int b; spin_lock_irq(&acm->write_lock); b = acm->transmitting; spin_unlock_irq(&acm->write_lock); if (b) return -EBUSY; } spin_lock_irq(&acm->read_lock); spin_lock(&acm->write_lock); cnt = acm->susp_count++; spin_unlock(&acm->write_lock); spin_unlock_irq(&acm->read_lock); if (cnt) return 0; if (test_bit(ASYNCB_INITIALIZED, &acm->port.flags)) stop_data_traffic(acm); return 0; } static int acm_resume(struct usb_interface *intf) { struct acm *acm = usb_get_intfdata(intf); struct acm_wb *wb; int rv = 0; int cnt; spin_lock_irq(&acm->read_lock); acm->susp_count -= 1; cnt = acm->susp_count; spin_unlock_irq(&acm->read_lock); if (cnt) return 0; if (test_bit(ASYNCB_INITIALIZED, &acm->port.flags)) { rv = usb_submit_urb(acm->ctrlurb, GFP_NOIO); spin_lock_irq(&acm->write_lock); if (acm->delayed_wb) { wb = acm->delayed_wb; acm->delayed_wb = NULL; spin_unlock_irq(&acm->write_lock); acm_start_wb(acm, wb); } else { spin_unlock_irq(&acm->write_lock); } /* * delayed error checking because we must * do the write path at all cost */ if (rv < 0) goto err_out; rv = acm_submit_read_urbs(acm, GFP_NOIO); } err_out: return rv; } static int acm_reset_resume(struct usb_interface *intf) { struct acm *acm = usb_get_intfdata(intf); if (test_bit(ASYNCB_INITIALIZED, &acm->port.flags)) tty_port_tty_hangup(&acm->port, false); return acm_resume(intf); } #endif /* CONFIG_PM */ #define NOKIA_PCSUITE_ACM_INFO(x) \ USB_DEVICE_AND_INTERFACE_INFO(0x0421, x, \ USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, \ USB_CDC_ACM_PROTO_VENDOR) #define SAMSUNG_PCSUITE_ACM_INFO(x) \ USB_DEVICE_AND_INTERFACE_INFO(0x04e7, x, \ USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, \ USB_CDC_ACM_PROTO_VENDOR) /* * USB driver structure. */ static const struct usb_device_id acm_ids[] = { /* quirky and broken devices */ { USB_DEVICE(0x17ef, 0x7000), /* Lenovo USB modem */ .driver_info = NO_UNION_NORMAL, },/* has no union descriptor */ { USB_DEVICE(0x0870, 0x0001), /* Metricom GS Modem */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0e8d, 0x0003), /* FIREFLY, MediaTek Inc; andrey.arapov@gmail.com */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0e8d, 0x3329), /* MediaTek Inc GPS */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0482, 0x0203), /* KYOCERA AH-K3001V */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x079b, 0x000f), /* BT On-Air USB MODEM */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0ace, 0x1602), /* ZyDAS 56K USB MODEM */ .driver_info = SINGLE_RX_URB, }, { USB_DEVICE(0x0ace, 0x1608), /* ZyDAS 56K USB MODEM */ .driver_info = SINGLE_RX_URB, /* firmware bug */ }, { USB_DEVICE(0x0ace, 0x1611), /* ZyDAS 56K USB MODEM - new version */ .driver_info = SINGLE_RX_URB, /* firmware bug */ }, { USB_DEVICE(0x22b8, 0x7000), /* Motorola Q Phone */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0803, 0x3095), /* Zoom Telephonics Model 3095F USB MODEM */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0572, 0x1321), /* Conexant USB MODEM CX93010 */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0572, 0x1324), /* Conexant USB MODEM RD02-D400 */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x0572, 0x1328), /* Shiro / Aztech USB MODEM UM-3100 */ .driver_info = NO_UNION_NORMAL, /* has no union descriptor */ }, { USB_DEVICE(0x22b8, 0x6425), /* Motorola MOTOMAGX phones */ }, /* Motorola H24 HSPA module: */ { USB_DEVICE(0x22b8, 0x2d91) }, /* modem */ { USB_DEVICE(0x22b8, 0x2d92), /* modem + diagnostics */ .driver_info = NO_UNION_NORMAL, /* handle only modem interface */ }, { USB_DEVICE(0x22b8, 0x2d93), /* modem + AT port */ .driver_info = NO_UNION_NORMAL, /* handle only modem interface */ }, { USB_DEVICE(0x22b8, 0x2d95), /* modem + AT port + diagnostics */ .driver_info = NO_UNION_NORMAL, /* handle only modem interface */ }, { USB_DEVICE(0x22b8, 0x2d96), /* modem + NMEA */ .driver_info = NO_UNION_NORMAL, /* handle only modem interface */ }, { USB_DEVICE(0x22b8, 0x2d97), /* modem + diagnostics + NMEA */ .driver_info = NO_UNION_NORMAL, /* handle only modem interface */ }, { USB_DEVICE(0x22b8, 0x2d99), /* modem + AT port + NMEA */ .driver_info = NO_UNION_NORMAL, /* handle only modem interface */ }, { USB_DEVICE(0x22b8, 0x2d9a), /* modem + AT port + diagnostics + NMEA */ .driver_info = NO_UNION_NORMAL, /* handle only modem interface */ }, { USB_DEVICE(0x0572, 0x1329), /* Hummingbird huc56s (Conexant) */ .driver_info = NO_UNION_NORMAL, /* union descriptor misplaced on data interface instead of communications interface. Maybe we should define a new quirk for this. */ }, { USB_DEVICE(0x0572, 0x1340), /* Conexant CX93010-2x UCMxx */ .driver_info = NO_UNION_NORMAL, }, { USB_DEVICE(0x05f9, 0x4002), /* PSC Scanning, Magellan 800i */ .driver_info = NO_UNION_NORMAL, }, { USB_DEVICE(0x1bbb, 0x0003), /* Alcatel OT-I650 */ .driver_info = NO_UNION_NORMAL, /* reports zero length descriptor */ }, { USB_DEVICE(0x1576, 0x03b1), /* Maretron USB100 */ .driver_info = NO_UNION_NORMAL, /* reports zero length descriptor */ }, /* Nokia S60 phones expose two ACM channels. The first is * a modem and is picked up by the standard AT-command * information below. The second is 'vendor-specific' but * is treated as a serial device at the S60 end, so we want * to expose it on Linux too. */ { NOKIA_PCSUITE_ACM_INFO(0x042D), }, /* Nokia 3250 */ { NOKIA_PCSUITE_ACM_INFO(0x04D8), }, /* Nokia 5500 Sport */ { NOKIA_PCSUITE_ACM_INFO(0x04C9), }, /* Nokia E50 */ { NOKIA_PCSUITE_ACM_INFO(0x0419), }, /* Nokia E60 */ { NOKIA_PCSUITE_ACM_INFO(0x044D), }, /* Nokia E61 */ { NOKIA_PCSUITE_ACM_INFO(0x0001), }, /* Nokia E61i */ { NOKIA_PCSUITE_ACM_INFO(0x0475), }, /* Nokia E62 */ { NOKIA_PCSUITE_ACM_INFO(0x0508), }, /* Nokia E65 */ { NOKIA_PCSUITE_ACM_INFO(0x0418), }, /* Nokia E70 */ { NOKIA_PCSUITE_ACM_INFO(0x0425), }, /* Nokia N71 */ { NOKIA_PCSUITE_ACM_INFO(0x0486), }, /* Nokia N73 */ { NOKIA_PCSUITE_ACM_INFO(0x04DF), }, /* Nokia N75 */ { NOKIA_PCSUITE_ACM_INFO(0x000e), }, /* Nokia N77 */ { NOKIA_PCSUITE_ACM_INFO(0x0445), }, /* Nokia N80 */ { NOKIA_PCSUITE_ACM_INFO(0x042F), }, /* Nokia N91 & N91 8GB */ { NOKIA_PCSUITE_ACM_INFO(0x048E), }, /* Nokia N92 */ { NOKIA_PCSUITE_ACM_INFO(0x0420), }, /* Nokia N93 */ { NOKIA_PCSUITE_ACM_INFO(0x04E6), }, /* Nokia N93i */ { NOKIA_PCSUITE_ACM_INFO(0x04B2), }, /* Nokia 5700 XpressMusic */ { NOKIA_PCSUITE_ACM_INFO(0x0134), }, /* Nokia 6110 Navigator (China) */ { NOKIA_PCSUITE_ACM_INFO(0x046E), }, /* Nokia 6110 Navigator */ { NOKIA_PCSUITE_ACM_INFO(0x002f), }, /* Nokia 6120 classic & */ { NOKIA_PCSUITE_ACM_INFO(0x0088), }, /* Nokia 6121 classic */ { NOKIA_PCSUITE_ACM_INFO(0x00fc), }, /* Nokia 6124 classic */ { NOKIA_PCSUITE_ACM_INFO(0x0042), }, /* Nokia E51 */ { NOKIA_PCSUITE_ACM_INFO(0x00b0), }, /* Nokia E66 */ { NOKIA_PCSUITE_ACM_INFO(0x00ab), }, /* Nokia E71 */ { NOKIA_PCSUITE_ACM_INFO(0x0481), }, /* Nokia N76 */ { NOKIA_PCSUITE_ACM_INFO(0x0007), }, /* Nokia N81 & N81 8GB */ { NOKIA_PCSUITE_ACM_INFO(0x0071), }, /* Nokia N82 */ { NOKIA_PCSUITE_ACM_INFO(0x04F0), }, /* Nokia N95 & N95-3 NAM */ { NOKIA_PCSUITE_ACM_INFO(0x0070), }, /* Nokia N95 8GB */ { NOKIA_PCSUITE_ACM_INFO(0x00e9), }, /* Nokia 5320 XpressMusic */ { NOKIA_PCSUITE_ACM_INFO(0x0099), }, /* Nokia 6210 Navigator, RM-367 */ { NOKIA_PCSUITE_ACM_INFO(0x0128), }, /* Nokia 6210 Navigator, RM-419 */ { NOKIA_PCSUITE_ACM_INFO(0x008f), }, /* Nokia 6220 Classic */ { NOKIA_PCSUITE_ACM_INFO(0x00a0), }, /* Nokia 6650 */ { NOKIA_PCSUITE_ACM_INFO(0x007b), }, /* Nokia N78 */ { NOKIA_PCSUITE_ACM_INFO(0x0094), }, /* Nokia N85 */ { NOKIA_PCSUITE_ACM_INFO(0x003a), }, /* Nokia N96 & N96-3 */ { NOKIA_PCSUITE_ACM_INFO(0x00e9), }, /* Nokia 5320 XpressMusic */ { NOKIA_PCSUITE_ACM_INFO(0x0108), }, /* Nokia 5320 XpressMusic 2G */ { NOKIA_PCSUITE_ACM_INFO(0x01f5), }, /* Nokia N97, RM-505 */ { NOKIA_PCSUITE_ACM_INFO(0x02e3), }, /* Nokia 5230, RM-588 */ { NOKIA_PCSUITE_ACM_INFO(0x0178), }, /* Nokia E63 */ { NOKIA_PCSUITE_ACM_INFO(0x010e), }, /* Nokia E75 */ { NOKIA_PCSUITE_ACM_INFO(0x02d9), }, /* Nokia 6760 Slide */ { NOKIA_PCSUITE_ACM_INFO(0x01d0), }, /* Nokia E52 */ { NOKIA_PCSUITE_ACM_INFO(0x0223), }, /* Nokia E72 */ { NOKIA_PCSUITE_ACM_INFO(0x0275), }, /* Nokia X6 */ { NOKIA_PCSUITE_ACM_INFO(0x026c), }, /* Nokia N97 Mini */ { NOKIA_PCSUITE_ACM_INFO(0x0154), }, /* Nokia 5800 XpressMusic */ { NOKIA_PCSUITE_ACM_INFO(0x04ce), }, /* Nokia E90 */ { NOKIA_PCSUITE_ACM_INFO(0x01d4), }, /* Nokia E55 */ { NOKIA_PCSUITE_ACM_INFO(0x0302), }, /* Nokia N8 */ { NOKIA_PCSUITE_ACM_INFO(0x0335), }, /* Nokia E7 */ { NOKIA_PCSUITE_ACM_INFO(0x03cd), }, /* Nokia C7 */ { SAMSUNG_PCSUITE_ACM_INFO(0x6651), }, /* Samsung GTi8510 (INNOV8) */ /* Support for Owen devices */ { USB_DEVICE(0x03eb, 0x0030), }, /* Owen SI30 */ /* NOTE: non-Nokia COMM/ACM/0xff is likely MSFT RNDIS... NOT a modem! */ /* Support Lego NXT using pbLua firmware */ { USB_DEVICE(0x0694, 0xff00), .driver_info = NOT_A_MODEM, }, /* Support for Droids MuIn LCD */ { USB_DEVICE(0x04d8, 0x000b), .driver_info = NO_DATA_INTERFACE, }, #if IS_ENABLED(CONFIG_INPUT_IMS_PCU) { USB_DEVICE(0x04d8, 0x0082), /* Application mode */ .driver_info = IGNORE_DEVICE, }, { USB_DEVICE(0x04d8, 0x0083), /* Bootloader mode */ .driver_info = IGNORE_DEVICE, }, #endif /* control interfaces without any protocol set */ { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, USB_CDC_PROTO_NONE) }, /* control interfaces with various AT-command sets */ { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, USB_CDC_ACM_PROTO_AT_V25TER) }, { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, USB_CDC_ACM_PROTO_AT_PCCA101) }, { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, USB_CDC_ACM_PROTO_AT_PCCA101_WAKE) }, { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, USB_CDC_ACM_PROTO_AT_GSM) }, { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, USB_CDC_ACM_PROTO_AT_3G) }, { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, USB_CDC_ACM_PROTO_AT_CDMA) }, { } }; MODULE_DEVICE_TABLE(usb, acm_ids); static struct usb_driver acm_driver = { .name = "cdc_acm", .probe = acm_probe, .disconnect = acm_disconnect, #ifdef CONFIG_PM .suspend = acm_suspend, .resume = acm_resume, .reset_resume = acm_reset_resume, #endif .id_table = acm_ids, #ifdef CONFIG_PM .supports_autosuspend = 1, #endif .disable_hub_initiated_lpm = 1, }; /* * TTY driver structures. */ static const struct tty_operations acm_ops = { .install = acm_tty_install, .open = acm_tty_open, .close = acm_tty_close, .cleanup = acm_tty_cleanup, .hangup = acm_tty_hangup, .write = acm_tty_write, .write_room = acm_tty_write_room, .ioctl = acm_tty_ioctl, .throttle = acm_tty_throttle, .unthrottle = acm_tty_unthrottle, .chars_in_buffer = acm_tty_chars_in_buffer, .break_ctl = acm_tty_break_ctl, .set_termios = acm_tty_set_termios, .tiocmget = acm_tty_tiocmget, .tiocmset = acm_tty_tiocmset, }; /* * Init / exit. */ static int __init acm_init(void) { int retval; acm_tty_driver = alloc_tty_driver(ACM_TTY_MINORS); if (!acm_tty_driver) return -ENOMEM; acm_tty_driver->driver_name = "acm", acm_tty_driver->name = "ttyACM", acm_tty_driver->major = ACM_TTY_MAJOR, acm_tty_driver->minor_start = 0, acm_tty_driver->type = TTY_DRIVER_TYPE_SERIAL, acm_tty_driver->subtype = SERIAL_TYPE_NORMAL, acm_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV; acm_tty_driver->init_termios = tty_std_termios; acm_tty_driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL; tty_set_operations(acm_tty_driver, &acm_ops); retval = tty_register_driver(acm_tty_driver); if (retval) { put_tty_driver(acm_tty_driver); return retval; } retval = usb_register(&acm_driver); if (retval) { tty_unregister_driver(acm_tty_driver); put_tty_driver(acm_tty_driver); return retval; } printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_DESC "\n"); return 0; } static void __exit acm_exit(void) { usb_deregister(&acm_driver); tty_unregister_driver(acm_tty_driver); put_tty_driver(acm_tty_driver); } module_init(acm_init); module_exit(acm_exit); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); MODULE_ALIAS_CHARDEV_MAJOR(ACM_TTY_MAJOR);
drod2169/Linux-3.14.x
drivers/usb/class/cdc-acm.c
C
gpl-2.0
51,584
<? class Demo { function get_content(){ $form = "<form method='post'> What is your name? <input name='name' type='text'/> <input type='submit' value='Submit'/> </form>"; if(!isset($_POST['name'])) { return $form; } else { return "Hi, ".$_POST['name'].", This is my demo"; } } } ?>
netharbour/netharbour
plugins/Demo Plugin/plugin.php
PHP
gpl-2.0
325
/* * FreeSec: libcrypt for NetBSD * * Copyright (c) 1994 David Burren * All rights reserved. * * Adapted for FreeBSD-2.0 by Geoffrey M. Rehmet * this file should now *only* export crypt(), in order to make * binaries of libcrypt exportable from the USA * * Adapted for FreeBSD-4.0 by Mark R V Murray * this file should now *only* export crypt_des(), in order to make * a module that can be optionally included in libcrypt. * * Adapted for pxelinux menu environment by Th.Gebhardt * removed dependencies of standard C libs * added LOWSPACE option (using common space for different arrays) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the names of other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This is an original implementation of the DES and the crypt(3) interfaces * by David Burren <davidb@werj.com.au>. * * An excellent reference on the underlying algorithm (and related * algorithms) is: * * B. Schneier, Applied Cryptography: protocols, algorithms, * and source code in C, John Wiley & Sons, 1994. * * Note that in that book's description of DES the lookups for the initial, * pbox, and final permutations are inverted (this has been brought to the * attention of the author). A list of errata for this book has been * posted to the sci.crypt newsgroup by the author and is available for FTP. * * ARCHITECTURE ASSUMPTIONS: * It is assumed that the 8-byte arrays passed by reference can be * addressed as arrays of u_int32_t's (ie. the CPU is not picky about * alignment). */ #define LOWSPACE #ifndef NULL #define NULL ((void *) 0) #endif typedef unsigned long my_u_int32_t; typedef unsigned char my_u_char_t; /* Re-entrantify me -- all this junk needs to be in * struct crypt_data to make this really reentrant... */ static my_u_char_t inv_key_perm[64]; static my_u_char_t inv_comp_perm[56]; static my_u_char_t u_sbox[8][64]; static my_u_char_t un_pbox[32]; static my_u_int32_t en_keysl[16], en_keysr[16]; static my_u_int32_t de_keysl[16], de_keysr[16]; #ifndef LOWSPACE static my_u_int32_t ip_maskl[8][256], ip_maskr[8][256]; static my_u_int32_t fp_maskl[8][256], fp_maskr[8][256]; static my_u_int32_t key_perm_maskl[8][128], key_perm_maskr[8][128]; static my_u_int32_t comp_maskl[8][128], comp_maskr[8][128]; #endif static my_u_int32_t saltbits; static my_u_int32_t old_salt; static my_u_int32_t old_rawkey0, old_rawkey1; #ifdef LOWSPACE static my_u_int32_t common[8][256]; #endif /* Static stuff that stays resident and doesn't change after * being initialized, and therefore doesn't need to be made * reentrant. */ static my_u_char_t init_perm[64], final_perm[64]; static my_u_char_t m_sbox[4][4096]; #ifndef LOWSPACE static my_u_int32_t psbox[4][256]; #endif /* A pile of data */ static const my_u_char_t ascii64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static const my_u_char_t IP[64] = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; static const my_u_char_t key_perm[56] = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; static const my_u_char_t key_shifts[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; static const my_u_char_t comp_perm[48] = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; /* * No E box is used, as it's replaced by some ANDs, shifts, and ORs. */ static const my_u_char_t sbox[8][64] = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} }; static const my_u_char_t pbox[32] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; static const my_u_int32_t bits32[32] = { 0x80000000, 0x40000000, 0x20000000, 0x10000000, 0x08000000, 0x04000000, 0x02000000, 0x01000000, 0x00800000, 0x00400000, 0x00200000, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001 }; static const my_u_int32_t bits28[28] = { 0x08000000, 0x04000000, 0x02000000, 0x01000000, 0x00800000, 0x00400000, 0x00200000, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001 }; static const my_u_int32_t bits24[24] = { 0x00800000, 0x00400000, 0x00200000, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001 }; static const my_u_char_t bits8[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; // static const my_u_int32_t *bits28, *bits24; static int ascii_to_bin(char ch) { if (ch > 'z') return (0); if (ch >= 'a') return (ch - 'a' + 38); if (ch > 'Z') return (0); if (ch >= 'A') return (ch - 'A' + 12); if (ch > '9') return (0); if (ch >= '.') return (ch - '.'); return (0); } static void des_init(void) { #ifdef LOWSPACE int i, j, b; #else int i, j, b, k, inbit, obit; my_u_int32_t *p, *il, *ir, *fl, *fr; #endif static int des_initialised = 0; if (des_initialised == 1) return; old_rawkey0 = old_rawkey1 = 0L; saltbits = 0L; old_salt = 0L; // bits24 = (bits28 = bits32 + 4) + 4; /* * Invert the S-boxes, reordering the input bits. */ for (i = 0; i < 8; i++) for (j = 0; j < 64; j++) { b = (j & 0x20) | ((j & 1) << 4) | ((j >> 1) & 0xf); u_sbox[i][j] = sbox[i][b]; } /* * Convert the inverted S-boxes into 4 arrays of 8 bits. * Each will handle 12 bits of the S-box input. */ for (b = 0; b < 4; b++) for (i = 0; i < 64; i++) for (j = 0; j < 64; j++) m_sbox[b][(i << 6) | j] = (my_u_char_t) ((u_sbox[(b << 1)][i] << 4) | u_sbox[(b << 1) + 1][j]); /* * Set up the initial & final permutations into a useful form, and * initialise the inverted key permutation. */ for (i = 0; i < 64; i++) { init_perm[final_perm[i] = IP[i] - 1] = (my_u_char_t) i; inv_key_perm[i] = 255; } /* * Invert the key permutation and initialise the inverted key * compression permutation. */ for (i = 0; i < 56; i++) { inv_key_perm[key_perm[i] - 1] = (my_u_char_t) i; inv_comp_perm[i] = 255; } /* * Invert the key compression permutation. */ for (i = 0; i < 48; i++) { inv_comp_perm[comp_perm[i] - 1] = (my_u_char_t) i; } /* * Set up the OR-mask arrays for the initial and final permutations, * and for the key initial and compression permutations. */ #ifndef LOWSPACE for (k = 0; k < 8; k++) { for (i = 0; i < 256; i++) { *(il = &ip_maskl[k][i]) = 0L; *(ir = &ip_maskr[k][i]) = 0L; *(fl = &fp_maskl[k][i]) = 0L; *(fr = &fp_maskr[k][i]) = 0L; for (j = 0; j < 8; j++) { inbit = 8 * k + j; if (i & bits8[j]) { if ((obit = init_perm[inbit]) < 32) *il |= bits32[obit]; else *ir |= bits32[obit - 32]; if ((obit = final_perm[inbit]) < 32) *fl |= bits32[obit]; else *fr |= bits32[obit - 32]; } } } for (i = 0; i < 128; i++) { *(il = &key_perm_maskl[k][i]) = 0L; *(ir = &key_perm_maskr[k][i]) = 0L; for (j = 0; j < 7; j++) { inbit = 8 * k + j; if (i & bits8[j + 1]) { if ((obit = inv_key_perm[inbit]) == 255) continue; if (obit < 28) *il |= bits28[obit]; else *ir |= bits28[obit - 28]; } } *(il = &comp_maskl[k][i]) = 0L; *(ir = &comp_maskr[k][i]) = 0L; for (j = 0; j < 7; j++) { inbit = 7 * k + j; if (i & bits8[j + 1]) { if ((obit = inv_comp_perm[inbit]) == 255) continue; if (obit < 24) *il |= bits24[obit]; else *ir |= bits24[obit - 24]; } } } } #endif /* * Invert the P-box permutation, and convert into OR-masks for * handling the output of the S-box arrays setup above. */ for (i = 0; i < 32; i++) un_pbox[pbox[i] - 1] = (my_u_char_t) i; #ifndef LOWSPACE for (b = 0; b < 4; b++) for (i = 0; i < 256; i++) { *(p = &psbox[b][i]) = 0L; for (j = 0; j < 8; j++) { if (i & bits8[j]) *p |= bits32[un_pbox[8 * b + j]]; } } #endif des_initialised = 1; } #ifdef LOWSPACE static void setup_ip_maskl(void) { int i, j, k, inbit, obit; my_u_int32_t *il; for (k = 0; k < 8; k++) { for (i = 0; i < 256; i++) { *(il = &common[k][i]) = 0L; for (j = 0; j < 8; j++) { inbit = 8 * k + j; if (i & bits8[j]) { if ((obit = init_perm[inbit]) < 32) *il |= bits32[obit]; } } } } } static void setup_ip_maskr(void) { int i, j, k, inbit, obit; my_u_int32_t *ir; for (k = 0; k < 8; k++) { for (i = 0; i < 256; i++) { *(ir = &common[k][i]) = 0L; for (j = 0; j < 8; j++) { inbit = 8 * k + j; if (i & bits8[j]) { if ((obit = init_perm[inbit]) >= 32) *ir |= bits32[obit - 32]; } } } } } static void setup_fp_maskl(void) { int i, j, k, inbit, obit; my_u_int32_t *fl; for (k = 0; k < 8; k++) { for (i = 0; i < 256; i++) { *(fl = &common[k][i]) = 0L; for (j = 0; j < 8; j++) { inbit = 8 * k + j; if (i & bits8[j]) { if ((obit = final_perm[inbit]) < 32) *fl |= bits32[obit]; } } } } } static void setup_fp_maskr(void) { int i, j, k, inbit, obit; my_u_int32_t *fr; for (k = 0; k < 8; k++) { for (i = 0; i < 256; i++) { *(fr = &common[k][i]) = 0L; for (j = 0; j < 8; j++) { inbit = 8 * k + j; if (i & bits8[j]) { if ((obit = final_perm[inbit]) >= 32) *fr |= bits32[obit - 32]; } } } } } static void setup_key_perm_maskl(void) { int i, j, k, inbit, obit; my_u_int32_t *il; for (k = 0; k < 8; k++) { for (i = 0; i < 128; i++) { *(il = &common[k][i]) = 0L; for (j = 0; j < 7; j++) { inbit = 8 * k + j; if (i & bits8[j + 1]) { if ((obit = inv_key_perm[inbit]) == 255) continue; if (obit < 28) *il |= bits28[obit]; } } } } } static void setup_key_perm_maskr(void) { int i, j, k, inbit, obit; my_u_int32_t *ir; for (k = 0; k < 8; k++) { for (i = 0; i < 128; i++) { *(ir = &common[k][i]) = 0L; for (j = 0; j < 7; j++) { inbit = 8 * k + j; if (i & bits8[j + 1]) { if ((obit = inv_key_perm[inbit]) == 255) continue; if (obit >= 28) *ir |= bits28[obit - 28]; } } } } } static void setup_comp_maskl(void) { int i, j, k, inbit, obit; my_u_int32_t *il; for (k = 0; k < 8; k++) { for (i = 0; i < 128; i++) { *(il = &common[k][i]) = 0L; for (j = 0; j < 7; j++) { inbit = 7 * k + j; if (i & bits8[j + 1]) { if ((obit = inv_comp_perm[inbit]) == 255) continue; if (obit < 24) *il |= bits24[obit]; } } } } } static void setup_comp_maskr(void) { int i, j, k, inbit, obit; my_u_int32_t *ir; for (k = 0; k < 8; k++) { for (i = 0; i < 128; i++) { *(ir = &common[k][i]) = 0L; for (j = 0; j < 7; j++) { inbit = 7 * k + j; if (i & bits8[j + 1]) { if ((obit = inv_comp_perm[inbit]) == 255) continue; if (obit >= 24) *ir |= bits24[obit - 24]; } } } } } static void setup_psbox(void) { int i, j, b; my_u_int32_t *p; for (b = 0; b < 4; b++) for (i = 0; i < 256; i++) { *(p = &common[b][i]) = 0L; for (j = 0; j < 8; j++) { if (i & bits8[j]) *p |= bits32[un_pbox[8 * b + j]]; } } } #endif static void setup_salt(my_u_int32_t salt) { my_u_int32_t obit, saltbit; int i; if (salt == old_salt) return; old_salt = salt; saltbits = 0L; saltbit = 1; obit = 0x800000; for (i = 0; i < 24; i++) { if (salt & saltbit) saltbits |= obit; saltbit <<= 1; obit >>= 1; } } static my_u_int32_t char_to_int(const char *key) { my_u_int32_t byte0, byte1, byte2, byte3; byte0 = (my_u_int32_t) (my_u_char_t) key[0]; byte1 = (my_u_int32_t) (my_u_char_t) key[1]; byte2 = (my_u_int32_t) (my_u_char_t) key[2]; byte3 = (my_u_int32_t) (my_u_char_t) key[3]; return byte0 << 24 | byte1 << 16 | byte2 << 8 | byte3; } static int des_setkey(const char *key) { my_u_int32_t k0, k1, rawkey0, rawkey1; int shifts, round; des_init(); /* rawkey0 = ntohl(*(const my_u_int32_t *) key); * rawkey1 = ntohl(*(const my_u_int32_t *) (key + 4)); */ rawkey0 = char_to_int(key); rawkey1 = char_to_int(key + 4); if ((rawkey0 | rawkey1) && rawkey0 == old_rawkey0 && rawkey1 == old_rawkey1) { /* * Already setup for this key. * This optimisation fails on a zero key (which is weak and * has bad parity anyway) in order to simplify the starting * conditions. */ return (0); } old_rawkey0 = rawkey0; old_rawkey1 = rawkey1; /* * Do key permutation and split into two 28-bit subkeys. */ #ifdef LOWSPACE setup_key_perm_maskl(); k0 = common[0][rawkey0 >> 25] | common[1][(rawkey0 >> 17) & 0x7f] | common[2][(rawkey0 >> 9) & 0x7f] | common[3][(rawkey0 >> 1) & 0x7f] | common[4][rawkey1 >> 25] | common[5][(rawkey1 >> 17) & 0x7f] | common[6][(rawkey1 >> 9) & 0x7f] | common[7][(rawkey1 >> 1) & 0x7f]; setup_key_perm_maskr(); k1 = common[0][rawkey0 >> 25] | common[1][(rawkey0 >> 17) & 0x7f] | common[2][(rawkey0 >> 9) & 0x7f] | common[3][(rawkey0 >> 1) & 0x7f] | common[4][rawkey1 >> 25] | common[5][(rawkey1 >> 17) & 0x7f] | common[6][(rawkey1 >> 9) & 0x7f] | common[7][(rawkey1 >> 1) & 0x7f]; #else k0 = key_perm_maskl[0][rawkey0 >> 25] | key_perm_maskl[1][(rawkey0 >> 17) & 0x7f] | key_perm_maskl[2][(rawkey0 >> 9) & 0x7f] | key_perm_maskl[3][(rawkey0 >> 1) & 0x7f] | key_perm_maskl[4][rawkey1 >> 25] | key_perm_maskl[5][(rawkey1 >> 17) & 0x7f] | key_perm_maskl[6][(rawkey1 >> 9) & 0x7f] | key_perm_maskl[7][(rawkey1 >> 1) & 0x7f]; k1 = key_perm_maskr[0][rawkey0 >> 25] | key_perm_maskr[1][(rawkey0 >> 17) & 0x7f] | key_perm_maskr[2][(rawkey0 >> 9) & 0x7f] | key_perm_maskr[3][(rawkey0 >> 1) & 0x7f] | key_perm_maskr[4][rawkey1 >> 25] | key_perm_maskr[5][(rawkey1 >> 17) & 0x7f] | key_perm_maskr[6][(rawkey1 >> 9) & 0x7f] | key_perm_maskr[7][(rawkey1 >> 1) & 0x7f]; #endif /* * Rotate subkeys and do compression permutation. */ shifts = 0; for (round = 0; round < 16; round++) { my_u_int32_t t0, t1; shifts += key_shifts[round]; t0 = (k0 << shifts) | (k0 >> (28 - shifts)); t1 = (k1 << shifts) | (k1 >> (28 - shifts)); #ifdef LOWSPACE setup_comp_maskl(); de_keysl[15 - round] = en_keysl[round] = common[0][(t0 >> 21) & 0x7f] | common[1][(t0 >> 14) & 0x7f] | common[2][(t0 >> 7) & 0x7f] | common[3][t0 & 0x7f] | common[4][(t1 >> 21) & 0x7f] | common[5][(t1 >> 14) & 0x7f] | common[6][(t1 >> 7) & 0x7f] | common[7][t1 & 0x7f]; setup_comp_maskr(); de_keysr[15 - round] = en_keysr[round] = common[0][(t0 >> 21) & 0x7f] | common[1][(t0 >> 14) & 0x7f] | common[2][(t0 >> 7) & 0x7f] | common[3][t0 & 0x7f] | common[4][(t1 >> 21) & 0x7f] | common[5][(t1 >> 14) & 0x7f] | common[6][(t1 >> 7) & 0x7f] | common[7][t1 & 0x7f]; #else de_keysl[15 - round] = en_keysl[round] = comp_maskl[0][(t0 >> 21) & 0x7f] | comp_maskl[1][(t0 >> 14) & 0x7f] | comp_maskl[2][(t0 >> 7) & 0x7f] | comp_maskl[3][t0 & 0x7f] | comp_maskl[4][(t1 >> 21) & 0x7f] | comp_maskl[5][(t1 >> 14) & 0x7f] | comp_maskl[6][(t1 >> 7) & 0x7f] | comp_maskl[7][t1 & 0x7f]; de_keysr[15 - round] = en_keysr[round] = comp_maskr[0][(t0 >> 21) & 0x7f] | comp_maskr[1][(t0 >> 14) & 0x7f] | comp_maskr[2][(t0 >> 7) & 0x7f] | comp_maskr[3][t0 & 0x7f] | comp_maskr[4][(t1 >> 21) & 0x7f] | comp_maskr[5][(t1 >> 14) & 0x7f] | comp_maskr[6][(t1 >> 7) & 0x7f] | comp_maskr[7][t1 & 0x7f]; #endif } return (0); } static int do_des(my_u_int32_t l_in, my_u_int32_t r_in, my_u_int32_t * l_out, my_u_int32_t * r_out, int count) { /* * l_in, r_in, l_out, and r_out are in pseudo-"big-endian" format. */ my_u_int32_t l, r, *kl, *kr, *kl1, *kr1; my_u_int32_t f, r48l, r48r; int round; if (count == 0) { return (1); } else if (count > 0) { /* * Encrypting */ kl1 = en_keysl; kr1 = en_keysr; } else { /* * Decrypting */ count = -count; kl1 = de_keysl; kr1 = de_keysr; } /* * Do initial permutation (IP). */ #ifdef LOWSPACE setup_ip_maskl(); l = common[0][l_in >> 24] | common[1][(l_in >> 16) & 0xff] | common[2][(l_in >> 8) & 0xff] | common[3][l_in & 0xff] | common[4][r_in >> 24] | common[5][(r_in >> 16) & 0xff] | common[6][(r_in >> 8) & 0xff] | common[7][r_in & 0xff]; setup_ip_maskr(); r = common[0][l_in >> 24] | common[1][(l_in >> 16) & 0xff] | common[2][(l_in >> 8) & 0xff] | common[3][l_in & 0xff] | common[4][r_in >> 24] | common[5][(r_in >> 16) & 0xff] | common[6][(r_in >> 8) & 0xff] | common[7][r_in & 0xff]; #else l = ip_maskl[0][l_in >> 24] | ip_maskl[1][(l_in >> 16) & 0xff] | ip_maskl[2][(l_in >> 8) & 0xff] | ip_maskl[3][l_in & 0xff] | ip_maskl[4][r_in >> 24] | ip_maskl[5][(r_in >> 16) & 0xff] | ip_maskl[6][(r_in >> 8) & 0xff] | ip_maskl[7][r_in & 0xff]; r = ip_maskr[0][l_in >> 24] | ip_maskr[1][(l_in >> 16) & 0xff] | ip_maskr[2][(l_in >> 8) & 0xff] | ip_maskr[3][l_in & 0xff] | ip_maskr[4][r_in >> 24] | ip_maskr[5][(r_in >> 16) & 0xff] | ip_maskr[6][(r_in >> 8) & 0xff] | ip_maskr[7][r_in & 0xff]; #endif while (count--) { /* * Do each round. */ kl = kl1; kr = kr1; round = 16; while (round--) { /* * Expand R to 48 bits (simulate the E-box). */ r48l = ((r & 0x00000001) << 23) | ((r & 0xf8000000) >> 9) | ((r & 0x1f800000) >> 11) | ((r & 0x01f80000) >> 13) | ((r & 0x001f8000) >> 15); r48r = ((r & 0x0001f800) << 7) | ((r & 0x00001f80) << 5) | ((r & 0x000001f8) << 3) | ((r & 0x0000001f) << 1) | ((r & 0x80000000) >> 31); /* * Do salting for crypt() and friends, and * XOR with the permuted key. */ f = (r48l ^ r48r) & saltbits; r48l ^= f ^ *kl++; r48r ^= f ^ *kr++; /* * Do sbox lookups (which shrink it back to 32 bits) * and do the pbox permutation at the same time. */ #ifdef LOWSPACE setup_psbox(); f = common[0][m_sbox[0][r48l >> 12]] | common[1][m_sbox[1][r48l & 0xfff]] | common[2][m_sbox[2][r48r >> 12]] | common[3][m_sbox[3][r48r & 0xfff]]; #else f = psbox[0][m_sbox[0][r48l >> 12]] | psbox[1][m_sbox[1][r48l & 0xfff]] | psbox[2][m_sbox[2][r48r >> 12]] | psbox[3][m_sbox[3][r48r & 0xfff]]; #endif /* * Now that we've permuted things, complete f(). */ f ^= l; l = r; r = f; } r = l; l = f; } /* * Do final permutation (inverse of IP). */ #ifdef LOWSPACE setup_fp_maskl(); *l_out = common[0][l >> 24] | common[1][(l >> 16) & 0xff] | common[2][(l >> 8) & 0xff] | common[3][l & 0xff] | common[4][r >> 24] | common[5][(r >> 16) & 0xff] | common[6][(r >> 8) & 0xff] | common[7][r & 0xff]; setup_fp_maskr(); *r_out = common[0][l >> 24] | common[1][(l >> 16) & 0xff] | common[2][(l >> 8) & 0xff] | common[3][l & 0xff] | common[4][r >> 24] | common[5][(r >> 16) & 0xff] | common[6][(r >> 8) & 0xff] | common[7][r & 0xff]; #else *l_out = fp_maskl[0][l >> 24] | fp_maskl[1][(l >> 16) & 0xff] | fp_maskl[2][(l >> 8) & 0xff] | fp_maskl[3][l & 0xff] | fp_maskl[4][r >> 24] | fp_maskl[5][(r >> 16) & 0xff] | fp_maskl[6][(r >> 8) & 0xff] | fp_maskl[7][r & 0xff]; *r_out = fp_maskr[0][l >> 24] | fp_maskr[1][(l >> 16) & 0xff] | fp_maskr[2][(l >> 8) & 0xff] | fp_maskr[3][l & 0xff] | fp_maskr[4][r >> 24] | fp_maskr[5][(r >> 16) & 0xff] | fp_maskr[6][(r >> 8) & 0xff] | fp_maskr[7][r & 0xff]; #endif return (0); } #if 0 static int des_cipher(const char *in, char *out, my_u_int32_t salt, int count) { my_u_int32_t l_out, r_out, rawl, rawr; int retval; union { my_u_int32_t *ui32; const char *c; } trans; des_init(); setup_salt(salt); trans.c = in; rawl = ntohl(*trans.ui32++); rawr = ntohl(*trans.ui32); retval = do_des(rawl, rawr, &l_out, &r_out, count); trans.c = out; *trans.ui32++ = htonl(l_out); *trans.ui32 = htonl(r_out); return (retval); } #endif void setkey(const char *key) { int i, j; my_u_int32_t packed_keys[2]; my_u_char_t *p; p = (my_u_char_t *) packed_keys; for (i = 0; i < 8; i++) { p[i] = 0; for (j = 0; j < 8; j++) if (*key++ & 1) p[i] |= bits8[j]; } des_setkey(p); } void encrypt(char *block, int flag) { my_u_int32_t io[2]; my_u_char_t *p; int i, j; des_init(); setup_salt(0L); p = block; for (i = 0; i < 2; i++) { io[i] = 0L; for (j = 0; j < 32; j++) if (*p++ & 1) io[i] |= bits32[j]; } do_des(io[0], io[1], io, io + 1, flag ? -1 : 1); for (i = 0; i < 2; i++) for (j = 0; j < 32; j++) block[(i << 5) | j] = (io[i] & bits32[j]) ? 1 : 0; } char *crypt(const char *key, const char *setting) { my_u_int32_t count, salt, l, r0, r1, keybuf[2]; my_u_char_t *p, *q; static char output[21]; des_init(); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (my_u_char_t *) keybuf; while (q - (my_u_char_t *) keybuf - 8) { *q++ = *key << 1; if (*(q - 1)) key++; } if (des_setkey((char *)keybuf)) return (NULL); #if 0 if (*setting == _PASSWORD_EFMT1) { int i; /* * "new"-style: * setting - underscore, 4 bytes of count, 4 bytes of salt * key - unlimited characters */ for (i = 1, count = 0L; i < 5; i++) count |= ascii_to_bin(setting[i]) << ((i - 1) * 6); for (i = 5, salt = 0L; i < 9; i++) salt |= ascii_to_bin(setting[i]) << ((i - 5) * 6); while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((char *)keybuf, (char *)keybuf, 0L, 1)) return (NULL); /* * And XOR with the next 8 characters of the key. */ q = (my_u_char_t *) keybuf; while (q - (my_u_char_t *) keybuf - 8 && *key) *q++ ^= *key++ << 1; if (des_setkey((char *)keybuf)) return (NULL); } strncpy(output, setting, 9); /* * Double check that we weren't given a short setting. * If we were, the above code will probably have created * wierd values for count and salt, but we don't really care. * Just make sure the output string doesn't have an extra * NUL in it. */ output[9] = '\0'; p = (my_u_char_t *) output + strlen(output); } else #endif { /* * "old"-style: * setting - 2 bytes of salt * key - up to 8 characters */ count = 25; salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); output[0] = setting[0]; /* * If the encrypted password that the salt was extracted from * is only 1 character long, the salt will be corrupted. We * need to ensure that the output string doesn't have an extra * NUL in it! */ output[1] = setting[1] ? setting[1] : output[0]; p = (my_u_char_t *) output + 2; } setup_salt(salt); /* * Do it. */ if (do_des(0L, 0L, &r0, &r1, (int)count)) return (NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return (output); }
zeha/syslinux
com32/cmenu/libmenu/des.c
C
gpl-2.0
28,016
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Code Igniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../scripts/nav.js"></script> <script type="text/javascript" src="../scripts/prototype.lite.js"></script> <script type="text/javascript" src="../scripts/moo.fx.js"></script> <script type="text/javascript"> window.onload = function() { myHeight = new fx.Height('nav', {duration: 400}); myHeight.hide(); } </script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='Rick Ellis' /> <meta name='description' content='Code Igniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle.jpg" width="153" height="44" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>Code Igniter User Guide Version 1.3.2</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Full Table of Contents</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://www.codeigniter.com/">Code Igniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; Input and Security Class </td> <td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="www.codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td> </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <h1>Input Class</h1> <p>The Input Class serves two purposes:</p> <ol> <li>It pre-processes global input data for security.</li> <li>It provides some helper functions for fetching input data and pre-processing it.</li> </ol> <p class="important"><strong>Note:</strong> This class is initialized automatically by the system so there is no need to do it manually.</p> <h2>Security Filtering</h2> <p>The security filtering function is called automatically when a new <a href="../general/controllers.html">controller</a> is invoked. It does the following:</p> <ul> <li>Destroys the global GET array. Since Code Igniter does not utilize GET strings, there is no reason to allow it.</li> <li>Destroys all global variables in the event register_globals is turned on.</li> <li>Filters the POST/COOKIE array keys, permitting only alpha-numeric (and a few other) characters.</li> <li>Provides XSS (Cross-site Scripting Hacks) filtering. This can be enabled globally, or upon request.</li> <li>Standardizes newline characters to \n</li> </ul> <h2>XSS Filtering</h2> <p>Code Igniter comes with a Cross Site Scripting Hack prevention filter which can either run automatically to filter all POST and COOKIE data that is encountered, or you can run it on a per item basis. By default it does <strong>not</strong> run globally since it requires a bit of processing overhead, and since you may not need it in all cases.</p> <p>The XSS filter looks for commonly used techniques to trigger Javascript or other types of code that attempt to hijack cookies or do other malicious things. If anything disallowed is encountered it is rendered safe by converting the data to character entities.</p> <p> Note: This function should only be used to deal with data upon submission. It's not something that should be used for general runtime processing since it requires a fair amount of processing overhead.</p> <p>To filter data through the XSS filter use this function:</p> <h2>$this->input->xss_clean()</h2> <p>Here is an usage example:</p> <code>$data = $this->input->xss_clean($data);</code> <p>If you want the filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening your <kbd>application/config/config.php</kbd> file and setting this: <code>$config['global_xss_filtering'] = TRUE;</code> <p>Note: If you use the form validation class, it gives you the option of XSS filtering as well.</p> <h2>Using POST or COOKIE Data</h2> <p>Code Igniter comes with two helper functions that let you fetch POST or COOKIE items. The main advantage of using the provided functions rather then fetching an item directly ($_POST['something']) is that the functions will check to see if the item is set and return false (boolean) if not. This lets you conveniently use data without having to test whether an item exists first. In other words, normally you might do something like this: <code> if ( ! isset($_POST['something']))<br /> {<br /> &nbsp;&nbsp;&nbsp;&nbsp;$something = FALSE;<br /> }<br /> else<br /> {<br /> &nbsp;&nbsp;&nbsp;&nbsp;$something = $_POST['something'];<br /> }</code> <p>With Code Igniter's built in functions you can simply do this:</p> <code>$something = $this->input->post('something');</code> <p>The two functions are:</p> <h2>$this->input->post()</h2> <p>The first parameter will contain the name of the POST item you are looking for:</p> <code>$this->input->post('some_data');</code> <p>The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist.</p> <p>The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE;</p> <code>$this->input->post('some_data', TRUE);</code> <h2>$this->input->cookie()</h2> <p>This function is identical to the post function, only it fetches cookie data:</p> <code>$this->input->cookie('some_data', TRUE);</code> <h2>$this->input->ip_address()</h2> <p>Returns the IP address for the current user. If the IP address is not valid, the function will return an IP of: 0.0.0.0</p> <code>echo $this->input->ip_address();</code> <h2>$this->input->valid_ip(<var>$ip</var>)</h2> <p>Takes an IP address as input and returns TRUE or FALSE (boolean) if it is valid or not. Note: The $this->input->ip_address() function above validates the IP automatically.</p> <code>if ( ! valid_id($ip))<br /> {<br /> &nbsp;&nbsp;&nbsp;&nbsp; echo 'Not Valid';<br /> }<br /> else<br /> {<br /> &nbsp;&nbsp;&nbsp;&nbsp; echo 'Valid';<br /> }</code> <h2>$this->input->user_agent()</h2> <p>Returns the user agent (web browser) being used by the current user. Returns FALSE if it's not available.</p> <code>echo $this->input->user_agent();</code> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="image_lib.html">Image Manipulation Class</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="loader.html">Loader Class</a> <p> <p><a href="http://www.codeigniter.com">Code Igniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 &nbsp;&middot;&nbsp; <a href="http://www.pmachine.com">pMachine, Inc.</a></p> </div> </body> </html>
Calico90/codeigniter-version-scanner
CodeIgniter_1.3.2/CodeIgniter_1.3.2/user_guide/libraries/input.html
HTML
gpl-2.0
7,793
-- This profile gets rid of exploitable doors. hook.Add("InitPostEntityMap", "Adding", function() for _, door in pairs(ents.FindByClass("func_door_rotating")) do door:Fire("open", "", 0) door:Fire("kill", "", 1) end end)
JarnoVgr/ZombieSurvival
gamemodes/zombiesurvival/gamemode/maps/zm_portal.lua
Lua
gpl-2.0
241
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed 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. # # Copyright Buildbot Team Members from __future__ import absolute_import from __future__ import print_function from future.utils import lrange ALL_RESULTS = lrange(7) SUCCESS, WARNINGS, FAILURE, SKIPPED, EXCEPTION, RETRY, CANCELLED = ALL_RESULTS Results = ["success", "warnings", "failure", "skipped", "exception", "retry", "cancelled"] def statusToString(status): if status is None: return "not finished" if status < 0 or status >= len(Results): return "Invalid status" else: return Results[status] def worst_status(a, b): # SKIPPED > SUCCESS > WARNINGS > FAILURE > EXCEPTION > RETRY > CANCELLED # CANCELLED needs to be considered the worst. for s in (CANCELLED, RETRY, EXCEPTION, FAILURE, WARNINGS, SUCCESS, SKIPPED): if s in (a, b): return s def computeResultAndTermination(obj, result, previousResult): possible_overall_result = result terminate = False if result == FAILURE: if not obj.flunkOnFailure: possible_overall_result = SUCCESS if obj.warnOnFailure: possible_overall_result = WARNINGS if obj.flunkOnFailure: possible_overall_result = FAILURE if obj.haltOnFailure: terminate = True elif result == WARNINGS: if not obj.warnOnWarnings: possible_overall_result = SUCCESS else: possible_overall_result = WARNINGS if obj.flunkOnWarnings: possible_overall_result = FAILURE elif result in (EXCEPTION, RETRY, CANCELLED): terminate = True result = worst_status(previousResult, possible_overall_result) return result, terminate class ResultComputingConfigMixin(object): haltOnFailure = False flunkOnWarnings = False flunkOnFailure = True warnOnWarnings = False warnOnFailure = False resultConfig = [ "haltOnFailure", "flunkOnWarnings", "flunkOnFailure", "warnOnWarnings", "warnOnFailure", ]
Lekensteyn/buildbot
master/buildbot/process/results.py
Python
gpl-2.0
2,689
/* * Copyright (c) 2012, 2013 Intel Corporation. All rights reserved. * Copyright (c) 2006 - 2012 QLogic Corporation. All rights reserved. * Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/vmalloc.h> #include <linux/delay.h> #include <linux/idr.h> #include <linux/module.h> #include <linux/printk.h> #ifdef CONFIG_INFINIBAND_QIB_DCA #include <linux/dca.h> #endif #include "qib.h" #include "qib_common.h" #include "qib_mad.h" #ifdef CONFIG_DEBUG_FS #include "qib_debugfs.h" #include "qib_verbs.h" #endif #undef pr_fmt #define pr_fmt(fmt) QIB_DRV_NAME ": " fmt /* * min buffers we want to have per context, after driver */ #define QIB_MIN_USER_CTXT_BUFCNT 7 #define QLOGIC_IB_R_SOFTWARE_MASK 0xFF #define QLOGIC_IB_R_SOFTWARE_SHIFT 24 #define QLOGIC_IB_R_EMULATOR_MASK (1ULL<<62) /* * Number of ctxts we are configured to use (to allow for more pio * buffers per ctxt, etc.) Zero means use chip value. */ ushort qib_cfgctxts; module_param_named(cfgctxts, qib_cfgctxts, ushort, S_IRUGO); MODULE_PARM_DESC(cfgctxts, "Set max number of contexts to use"); unsigned qib_numa_aware; module_param_named(numa_aware, qib_numa_aware, uint, S_IRUGO); MODULE_PARM_DESC(numa_aware, "0 -> PSM allocation close to HCA, 1 -> PSM allocation local to process"); /* * If set, do not write to any regs if avoidable, hack to allow * check for deranged default register values. */ ushort qib_mini_init; module_param_named(mini_init, qib_mini_init, ushort, S_IRUGO); MODULE_PARM_DESC(mini_init, "If set, do minimal diag init"); unsigned qib_n_krcv_queues; module_param_named(krcvqs, qib_n_krcv_queues, uint, S_IRUGO); MODULE_PARM_DESC(krcvqs, "number of kernel receive queues per IB port"); unsigned qib_cc_table_size; module_param_named(cc_table_size, qib_cc_table_size, uint, S_IRUGO); MODULE_PARM_DESC(cc_table_size, "Congestion control table entries 0 (CCA disabled - default), min = 128, max = 1984"); /* * qib_wc_pat parameter: * 0 is WC via MTRR * 1 is WC via PAT * If PAT initialization fails, code reverts back to MTRR */ unsigned qib_wc_pat = 1; /* default (1) is to use PAT, not MTRR */ module_param_named(wc_pat, qib_wc_pat, uint, S_IRUGO); MODULE_PARM_DESC(wc_pat, "enable write-combining via PAT mechanism"); static void verify_interrupt(unsigned long); static struct idr qib_unit_table; u32 qib_cpulist_count; unsigned long *qib_cpulist; /* set number of contexts we'll actually use */ void qib_set_ctxtcnt(struct qib_devdata *dd) { if (!qib_cfgctxts) { dd->cfgctxts = dd->first_user_ctxt + num_online_cpus(); if (dd->cfgctxts > dd->ctxtcnt) dd->cfgctxts = dd->ctxtcnt; } else if (qib_cfgctxts < dd->num_pports) dd->cfgctxts = dd->ctxtcnt; else if (qib_cfgctxts <= dd->ctxtcnt) dd->cfgctxts = qib_cfgctxts; else dd->cfgctxts = dd->ctxtcnt; dd->freectxts = (dd->first_user_ctxt > dd->cfgctxts) ? 0 : dd->cfgctxts - dd->first_user_ctxt; } /* * Common code for creating the receive context array. */ int qib_create_ctxts(struct qib_devdata *dd) { unsigned i; int ret; int local_node_id = pcibus_to_node(dd->pcidev->bus); if (local_node_id < 0) local_node_id = numa_node_id(); dd->assigned_node_id = local_node_id; /* * Allocate full ctxtcnt array, rather than just cfgctxts, because * cleanup iterates across all possible ctxts. */ dd->rcd = kzalloc(sizeof(*dd->rcd) * dd->ctxtcnt, GFP_KERNEL); if (!dd->rcd) { qib_dev_err(dd, "Unable to allocate ctxtdata array, failing\n"); ret = -ENOMEM; goto done; } /* create (one or more) kctxt */ for (i = 0; i < dd->first_user_ctxt; ++i) { struct qib_pportdata *ppd; struct qib_ctxtdata *rcd; if (dd->skip_kctxt_mask & (1 << i)) continue; ppd = dd->pport + (i % dd->num_pports); rcd = qib_create_ctxtdata(ppd, i, dd->assigned_node_id); if (!rcd) { qib_dev_err(dd, "Unable to allocate ctxtdata for Kernel ctxt, failing\n"); ret = -ENOMEM; goto done; } rcd->pkeys[0] = QIB_DEFAULT_P_KEY; rcd->seq_cnt = 1; } ret = 0; done: return ret; } /* * Common code for user and kernel context setup. */ struct qib_ctxtdata *qib_create_ctxtdata(struct qib_pportdata *ppd, u32 ctxt, int node_id) { struct qib_devdata *dd = ppd->dd; struct qib_ctxtdata *rcd; rcd = kzalloc_node(sizeof(*rcd), GFP_KERNEL, node_id); if (rcd) { INIT_LIST_HEAD(&rcd->qp_wait_list); rcd->node_id = node_id; rcd->ppd = ppd; rcd->dd = dd; rcd->cnt = 1; rcd->ctxt = ctxt; dd->rcd[ctxt] = rcd; #ifdef CONFIG_DEBUG_FS if (ctxt < dd->first_user_ctxt) { /* N/A for PSM contexts */ rcd->opstats = kzalloc_node(sizeof(*rcd->opstats), GFP_KERNEL, node_id); if (!rcd->opstats) { kfree(rcd); qib_dev_err(dd, "Unable to allocate per ctxt stats buffer\n"); return NULL; } } #endif dd->f_init_ctxt(rcd); /* * To avoid wasting a lot of memory, we allocate 32KB chunks * of physically contiguous memory, advance through it until * used up and then allocate more. Of course, we need * memory to store those extra pointers, now. 32KB seems to * be the most that is "safe" under memory pressure * (creating large files and then copying them over * NFS while doing lots of MPI jobs). The OOM killer can * get invoked, even though we say we can sleep and this can * cause significant system problems.... */ rcd->rcvegrbuf_size = 0x8000; rcd->rcvegrbufs_perchunk = rcd->rcvegrbuf_size / dd->rcvegrbufsize; rcd->rcvegrbuf_chunks = (rcd->rcvegrcnt + rcd->rcvegrbufs_perchunk - 1) / rcd->rcvegrbufs_perchunk; BUG_ON(!is_power_of_2(rcd->rcvegrbufs_perchunk)); rcd->rcvegrbufs_perchunk_shift = ilog2(rcd->rcvegrbufs_perchunk); } return rcd; } /* * Common code for initializing the physical port structure. */ void qib_init_pportdata(struct qib_pportdata *ppd, struct qib_devdata *dd, u8 hw_pidx, u8 port) { int size; ppd->dd = dd; ppd->hw_pidx = hw_pidx; ppd->port = port; /* IB port number, not index */ spin_lock_init(&ppd->sdma_lock); spin_lock_init(&ppd->lflags_lock); init_waitqueue_head(&ppd->state_wait); init_timer(&ppd->symerr_clear_timer); ppd->symerr_clear_timer.function = qib_clear_symerror_on_linkup; ppd->symerr_clear_timer.data = (unsigned long)ppd; ppd->qib_wq = NULL; spin_lock_init(&ppd->cc_shadow_lock); if (qib_cc_table_size < IB_CCT_MIN_ENTRIES) goto bail; ppd->cc_supported_table_entries = min(max_t(int, qib_cc_table_size, IB_CCT_MIN_ENTRIES), IB_CCT_ENTRIES*IB_CC_TABLE_CAP_DEFAULT); ppd->cc_max_table_entries = ppd->cc_supported_table_entries/IB_CCT_ENTRIES; size = IB_CC_TABLE_CAP_DEFAULT * sizeof(struct ib_cc_table_entry) * IB_CCT_ENTRIES; ppd->ccti_entries = kzalloc(size, GFP_KERNEL); if (!ppd->ccti_entries) { qib_dev_err(dd, "failed to allocate congestion control table for port %d!\n", port); goto bail; } size = IB_CC_CCS_ENTRIES * sizeof(struct ib_cc_congestion_entry); ppd->congestion_entries = kzalloc(size, GFP_KERNEL); if (!ppd->congestion_entries) { qib_dev_err(dd, "failed to allocate congestion setting list for port %d!\n", port); goto bail_1; } size = sizeof(struct cc_table_shadow); ppd->ccti_entries_shadow = kzalloc(size, GFP_KERNEL); if (!ppd->ccti_entries_shadow) { qib_dev_err(dd, "failed to allocate shadow ccti list for port %d!\n", port); goto bail_2; } size = sizeof(struct ib_cc_congestion_setting_attr); ppd->congestion_entries_shadow = kzalloc(size, GFP_KERNEL); if (!ppd->congestion_entries_shadow) { qib_dev_err(dd, "failed to allocate shadow congestion setting list for port %d!\n", port); goto bail_3; } return; bail_3: kfree(ppd->ccti_entries_shadow); ppd->ccti_entries_shadow = NULL; bail_2: kfree(ppd->congestion_entries); ppd->congestion_entries = NULL; bail_1: kfree(ppd->ccti_entries); ppd->ccti_entries = NULL; bail: /* User is intentionally disabling the congestion control agent */ if (!qib_cc_table_size) return; if (qib_cc_table_size < IB_CCT_MIN_ENTRIES) { qib_cc_table_size = 0; qib_dev_err(dd, "Congestion Control table size %d less than minimum %d for port %d\n", qib_cc_table_size, IB_CCT_MIN_ENTRIES, port); } qib_dev_err(dd, "Congestion Control Agent disabled for port %d\n", port); return; } static int init_pioavailregs(struct qib_devdata *dd) { int ret, pidx; u64 *status_page; dd->pioavailregs_dma = dma_alloc_coherent( &dd->pcidev->dev, PAGE_SIZE, &dd->pioavailregs_phys, GFP_KERNEL); if (!dd->pioavailregs_dma) { qib_dev_err(dd, "failed to allocate PIOavail reg area in memory\n"); ret = -ENOMEM; goto done; } /* * We really want L2 cache aligned, but for current CPUs of * interest, they are the same. */ status_page = (u64 *) ((char *) dd->pioavailregs_dma + ((2 * L1_CACHE_BYTES + dd->pioavregs * sizeof(u64)) & ~L1_CACHE_BYTES)); /* device status comes first, for backwards compatibility */ dd->devstatusp = status_page; *status_page++ = 0; for (pidx = 0; pidx < dd->num_pports; ++pidx) { dd->pport[pidx].statusp = status_page; *status_page++ = 0; } /* * Setup buffer to hold freeze and other messages, accessible to * apps, following statusp. This is per-unit, not per port. */ dd->freezemsg = (char *) status_page; *dd->freezemsg = 0; /* length of msg buffer is "whatever is left" */ ret = (char *) status_page - (char *) dd->pioavailregs_dma; dd->freezelen = PAGE_SIZE - ret; ret = 0; done: return ret; } /** * init_shadow_tids - allocate the shadow TID array * @dd: the qlogic_ib device * * allocate the shadow TID array, so we can qib_munlock previous * entries. It may make more sense to move the pageshadow to the * ctxt data structure, so we only allocate memory for ctxts actually * in use, since we at 8k per ctxt, now. * We don't want failures here to prevent use of the driver/chip, * so no return value. */ static void init_shadow_tids(struct qib_devdata *dd) { struct page **pages; dma_addr_t *addrs; pages = vzalloc(dd->cfgctxts * dd->rcvtidcnt * sizeof(struct page *)); if (!pages) { qib_dev_err(dd, "failed to allocate shadow page * array, no expected sends!\n"); goto bail; } addrs = vzalloc(dd->cfgctxts * dd->rcvtidcnt * sizeof(dma_addr_t)); if (!addrs) { qib_dev_err(dd, "failed to allocate shadow dma handle array, no expected sends!\n"); goto bail_free; } dd->pageshadow = pages; dd->physshadow = addrs; return; bail_free: vfree(pages); bail: dd->pageshadow = NULL; } /* * Do initialization for device that is only needed on * first detect, not on resets. */ static int loadtime_init(struct qib_devdata *dd) { int ret = 0; if (((dd->revision >> QLOGIC_IB_R_SOFTWARE_SHIFT) & QLOGIC_IB_R_SOFTWARE_MASK) != QIB_CHIP_SWVERSION) { qib_dev_err(dd, "Driver only handles version %d, chip swversion is %d (%llx), failng\n", QIB_CHIP_SWVERSION, (int)(dd->revision >> QLOGIC_IB_R_SOFTWARE_SHIFT) & QLOGIC_IB_R_SOFTWARE_MASK, (unsigned long long) dd->revision); ret = -ENOSYS; goto done; } if (dd->revision & QLOGIC_IB_R_EMULATOR_MASK) qib_devinfo(dd->pcidev, "%s", dd->boardversion); spin_lock_init(&dd->pioavail_lock); spin_lock_init(&dd->sendctrl_lock); spin_lock_init(&dd->uctxt_lock); spin_lock_init(&dd->qib_diag_trans_lock); spin_lock_init(&dd->eep_st_lock); mutex_init(&dd->eep_lock); if (qib_mini_init) goto done; ret = init_pioavailregs(dd); init_shadow_tids(dd); qib_get_eeprom_info(dd); /* setup time (don't start yet) to verify we got interrupt */ init_timer(&dd->intrchk_timer); dd->intrchk_timer.function = verify_interrupt; dd->intrchk_timer.data = (unsigned long) dd; ret = qib_cq_init(dd); done: return ret; } /** * init_after_reset - re-initialize after a reset * @dd: the qlogic_ib device * * sanity check at least some of the values after reset, and * ensure no receive or transmit (explicitly, in case reset * failed */ static int init_after_reset(struct qib_devdata *dd) { int i; /* * Ensure chip does no sends or receives, tail updates, or * pioavail updates while we re-initialize. This is mostly * for the driver data structures, not chip registers. */ for (i = 0; i < dd->num_pports; ++i) { /* * ctxt == -1 means "all contexts". Only really safe for * _dis_abling things, as here. */ dd->f_rcvctrl(dd->pport + i, QIB_RCVCTRL_CTXT_DIS | QIB_RCVCTRL_INTRAVAIL_DIS | QIB_RCVCTRL_TAILUPD_DIS, -1); /* Redundant across ports for some, but no big deal. */ dd->f_sendctrl(dd->pport + i, QIB_SENDCTRL_SEND_DIS | QIB_SENDCTRL_AVAIL_DIS); } return 0; } static void enable_chip(struct qib_devdata *dd) { u64 rcvmask; int i; /* * Enable PIO send, and update of PIOavail regs to memory. */ for (i = 0; i < dd->num_pports; ++i) dd->f_sendctrl(dd->pport + i, QIB_SENDCTRL_SEND_ENB | QIB_SENDCTRL_AVAIL_ENB); /* * Enable kernel ctxts' receive and receive interrupt. * Other ctxts done as user opens and inits them. */ rcvmask = QIB_RCVCTRL_CTXT_ENB | QIB_RCVCTRL_INTRAVAIL_ENB; rcvmask |= (dd->flags & QIB_NODMA_RTAIL) ? QIB_RCVCTRL_TAILUPD_DIS : QIB_RCVCTRL_TAILUPD_ENB; for (i = 0; dd->rcd && i < dd->first_user_ctxt; ++i) { struct qib_ctxtdata *rcd = dd->rcd[i]; if (rcd) dd->f_rcvctrl(rcd->ppd, rcvmask, i); } } static void verify_interrupt(unsigned long opaque) { struct qib_devdata *dd = (struct qib_devdata *) opaque; if (!dd) return; /* being torn down */ /* * If we don't have a lid or any interrupts, let the user know and * don't bother checking again. */ if (dd->int_counter == 0) { if (!dd->f_intr_fallback(dd)) dev_err(&dd->pcidev->dev, "No interrupts detected, not usable.\n"); else /* re-arm the timer to see if fallback works */ mod_timer(&dd->intrchk_timer, jiffies + HZ/2); } } static void init_piobuf_state(struct qib_devdata *dd) { int i, pidx; u32 uctxts; /* * Ensure all buffers are free, and fifos empty. Buffers * are common, so only do once for port 0. * * After enable and qib_chg_pioavailkernel so we can safely * enable pioavail updates and PIOENABLE. After this, packets * are ready and able to go out. */ dd->f_sendctrl(dd->pport, QIB_SENDCTRL_DISARM_ALL); for (pidx = 0; pidx < dd->num_pports; ++pidx) dd->f_sendctrl(dd->pport + pidx, QIB_SENDCTRL_FLUSH); /* * If not all sendbufs are used, add the one to each of the lower * numbered contexts. pbufsctxt and lastctxt_piobuf are * calculated in chip-specific code because it may cause some * chip-specific adjustments to be made. */ uctxts = dd->cfgctxts - dd->first_user_ctxt; dd->ctxts_extrabuf = dd->pbufsctxt ? dd->lastctxt_piobuf - (dd->pbufsctxt * uctxts) : 0; /* * Set up the shadow copies of the piobufavail registers, * which we compare against the chip registers for now, and * the in memory DMA'ed copies of the registers. * By now pioavail updates to memory should have occurred, so * copy them into our working/shadow registers; this is in * case something went wrong with abort, but mostly to get the * initial values of the generation bit correct. */ for (i = 0; i < dd->pioavregs; i++) { __le64 tmp; tmp = dd->pioavailregs_dma[i]; /* * Don't need to worry about pioavailkernel here * because we will call qib_chg_pioavailkernel() later * in initialization, to busy out buffers as needed. */ dd->pioavailshadow[i] = le64_to_cpu(tmp); } while (i < ARRAY_SIZE(dd->pioavailshadow)) dd->pioavailshadow[i++] = 0; /* for debugging sanity */ /* after pioavailshadow is setup */ qib_chg_pioavailkernel(dd, 0, dd->piobcnt2k + dd->piobcnt4k, TXCHK_CHG_TYPE_KERN, NULL); dd->f_initvl15_bufs(dd); } /** * qib_create_workqueues - create per port workqueues * @dd: the qlogic_ib device */ static int qib_create_workqueues(struct qib_devdata *dd) { int pidx; struct qib_pportdata *ppd; for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; if (!ppd->qib_wq) { char wq_name[8]; /* 3 + 2 + 1 + 1 + 1 */ snprintf(wq_name, sizeof(wq_name), "qib%d_%d", dd->unit, pidx); ppd->qib_wq = create_singlethread_workqueue(wq_name); if (!ppd->qib_wq) goto wq_error; } } return 0; wq_error: pr_err("create_singlethread_workqueue failed for port %d\n", pidx + 1); for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; if (ppd->qib_wq) { destroy_workqueue(ppd->qib_wq); ppd->qib_wq = NULL; } } return -ENOMEM; } /** * qib_init - do the actual initialization sequence on the chip * @dd: the qlogic_ib device * @reinit: reinitializing, so don't allocate new memory * * Do the actual initialization sequence on the chip. This is done * both from the init routine called from the PCI infrastructure, and * when we reset the chip, or detect that it was reset internally, * or it's administratively re-enabled. * * Memory allocation here and in called routines is only done in * the first case (reinit == 0). We have to be careful, because even * without memory allocation, we need to re-write all the chip registers * TIDs, etc. after the reset or enable has completed. */ int qib_init(struct qib_devdata *dd, int reinit) { int ret = 0, pidx, lastfail = 0; u32 portok = 0; unsigned i; struct qib_ctxtdata *rcd; struct qib_pportdata *ppd; unsigned long flags; /* Set linkstate to unknown, so we can watch for a transition. */ for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; spin_lock_irqsave(&ppd->lflags_lock, flags); ppd->lflags &= ~(QIBL_LINKACTIVE | QIBL_LINKARMED | QIBL_LINKDOWN | QIBL_LINKINIT | QIBL_LINKV); spin_unlock_irqrestore(&ppd->lflags_lock, flags); } if (reinit) ret = init_after_reset(dd); else ret = loadtime_init(dd); if (ret) goto done; /* Bypass most chip-init, to get to device creation */ if (qib_mini_init) return 0; ret = dd->f_late_initreg(dd); if (ret) goto done; /* dd->rcd can be NULL if early init failed */ for (i = 0; dd->rcd && i < dd->first_user_ctxt; ++i) { /* * Set up the (kernel) rcvhdr queue and egr TIDs. If doing * re-init, the simplest way to handle this is to free * existing, and re-allocate. * Need to re-create rest of ctxt 0 ctxtdata as well. */ rcd = dd->rcd[i]; if (!rcd) continue; lastfail = qib_create_rcvhdrq(dd, rcd); if (!lastfail) lastfail = qib_setup_eagerbufs(rcd); if (lastfail) { qib_dev_err(dd, "failed to allocate kernel ctxt's rcvhdrq and/or egr bufs\n"); continue; } } for (pidx = 0; pidx < dd->num_pports; ++pidx) { int mtu; if (lastfail) ret = lastfail; ppd = dd->pport + pidx; mtu = ib_mtu_enum_to_int(qib_ibmtu); if (mtu == -1) { mtu = QIB_DEFAULT_MTU; qib_ibmtu = 0; /* don't leave invalid value */ } /* set max we can ever have for this driver load */ ppd->init_ibmaxlen = min(mtu > 2048 ? dd->piosize4k : dd->piosize2k, dd->rcvegrbufsize + (dd->rcvhdrentsize << 2)); /* * Have to initialize ibmaxlen, but this will normally * change immediately in qib_set_mtu(). */ ppd->ibmaxlen = ppd->init_ibmaxlen; qib_set_mtu(ppd, mtu); spin_lock_irqsave(&ppd->lflags_lock, flags); ppd->lflags |= QIBL_IB_LINK_DISABLED; spin_unlock_irqrestore(&ppd->lflags_lock, flags); lastfail = dd->f_bringup_serdes(ppd); if (lastfail) { qib_devinfo(dd->pcidev, "Failed to bringup IB port %u\n", ppd->port); lastfail = -ENETDOWN; continue; } portok++; } if (!portok) { /* none of the ports initialized */ if (!ret && lastfail) ret = lastfail; else if (!ret) ret = -ENETDOWN; /* but continue on, so we can debug cause */ } enable_chip(dd); init_piobuf_state(dd); done: if (!ret) { /* chip is OK for user apps; mark it as initialized */ for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; /* * Set status even if port serdes is not initialized * so that diags will work. */ *ppd->statusp |= QIB_STATUS_CHIP_PRESENT | QIB_STATUS_INITTED; if (!ppd->link_speed_enabled) continue; if (dd->flags & QIB_HAS_SEND_DMA) ret = qib_setup_sdma(ppd); init_timer(&ppd->hol_timer); ppd->hol_timer.function = qib_hol_event; ppd->hol_timer.data = (unsigned long)ppd; ppd->hol_state = QIB_HOL_UP; } /* now we can enable all interrupts from the chip */ dd->f_set_intr_state(dd, 1); /* * Setup to verify we get an interrupt, and fallback * to an alternate if necessary and possible. */ mod_timer(&dd->intrchk_timer, jiffies + HZ/2); /* start stats retrieval timer */ mod_timer(&dd->stats_timer, jiffies + HZ * ACTIVITY_TIMER); } /* if ret is non-zero, we probably should do some cleanup here... */ return ret; } /* * These next two routines are placeholders in case we don't have per-arch * code for controlling write combining. If explicit control of write * combining is not available, performance will probably be awful. */ int __attribute__((weak)) qib_enable_wc(struct qib_devdata *dd) { return -EOPNOTSUPP; } void __attribute__((weak)) qib_disable_wc(struct qib_devdata *dd) { } static inline struct qib_devdata *__qib_lookup(int unit) { return idr_find(&qib_unit_table, unit); } struct qib_devdata *qib_lookup(int unit) { struct qib_devdata *dd; unsigned long flags; spin_lock_irqsave(&qib_devs_lock, flags); dd = __qib_lookup(unit); spin_unlock_irqrestore(&qib_devs_lock, flags); return dd; } /* * Stop the timers during unit shutdown, or after an error late * in initialization. */ static void qib_stop_timers(struct qib_devdata *dd) { struct qib_pportdata *ppd; int pidx; if (dd->stats_timer.data) { del_timer_sync(&dd->stats_timer); dd->stats_timer.data = 0; } if (dd->intrchk_timer.data) { del_timer_sync(&dd->intrchk_timer); dd->intrchk_timer.data = 0; } for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; if (ppd->hol_timer.data) del_timer_sync(&ppd->hol_timer); if (ppd->led_override_timer.data) { del_timer_sync(&ppd->led_override_timer); atomic_set(&ppd->led_override_timer_active, 0); } if (ppd->symerr_clear_timer.data) del_timer_sync(&ppd->symerr_clear_timer); } } /** * qib_shutdown_device - shut down a device * @dd: the qlogic_ib device * * This is called to make the device quiet when we are about to * unload the driver, and also when the device is administratively * disabled. It does not free any data structures. * Everything it does has to be setup again by qib_init(dd, 1) */ static void qib_shutdown_device(struct qib_devdata *dd) { struct qib_pportdata *ppd; unsigned pidx; for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; spin_lock_irq(&ppd->lflags_lock); ppd->lflags &= ~(QIBL_LINKDOWN | QIBL_LINKINIT | QIBL_LINKARMED | QIBL_LINKACTIVE | QIBL_LINKV); spin_unlock_irq(&ppd->lflags_lock); *ppd->statusp &= ~(QIB_STATUS_IB_CONF | QIB_STATUS_IB_READY); } dd->flags &= ~QIB_INITTED; /* mask interrupts, but not errors */ dd->f_set_intr_state(dd, 0); for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; dd->f_rcvctrl(ppd, QIB_RCVCTRL_TAILUPD_DIS | QIB_RCVCTRL_CTXT_DIS | QIB_RCVCTRL_INTRAVAIL_DIS | QIB_RCVCTRL_PKEY_ENB, -1); /* * Gracefully stop all sends allowing any in progress to * trickle out first. */ dd->f_sendctrl(ppd, QIB_SENDCTRL_CLEAR); } /* * Enough for anything that's going to trickle out to have actually * done so. */ udelay(20); for (pidx = 0; pidx < dd->num_pports; ++pidx) { ppd = dd->pport + pidx; dd->f_setextled(ppd, 0); /* make sure LEDs are off */ if (dd->flags & QIB_HAS_SEND_DMA) qib_teardown_sdma(ppd); dd->f_sendctrl(ppd, QIB_SENDCTRL_AVAIL_DIS | QIB_SENDCTRL_SEND_DIS); /* * Clear SerdesEnable. * We can't count on interrupts since we are stopping. */ dd->f_quiet_serdes(ppd); if (ppd->qib_wq) { destroy_workqueue(ppd->qib_wq); ppd->qib_wq = NULL; } } qib_update_eeprom_log(dd); } /** * qib_free_ctxtdata - free a context's allocated data * @dd: the qlogic_ib device * @rcd: the ctxtdata structure * * free up any allocated data for a context * This should not touch anything that would affect a simultaneous * re-allocation of context data, because it is called after qib_mutex * is released (and can be called from reinit as well). * It should never change any chip state, or global driver state. */ void qib_free_ctxtdata(struct qib_devdata *dd, struct qib_ctxtdata *rcd) { if (!rcd) return; if (rcd->rcvhdrq) { dma_free_coherent(&dd->pcidev->dev, rcd->rcvhdrq_size, rcd->rcvhdrq, rcd->rcvhdrq_phys); rcd->rcvhdrq = NULL; if (rcd->rcvhdrtail_kvaddr) { dma_free_coherent(&dd->pcidev->dev, PAGE_SIZE, rcd->rcvhdrtail_kvaddr, rcd->rcvhdrqtailaddr_phys); rcd->rcvhdrtail_kvaddr = NULL; } } if (rcd->rcvegrbuf) { unsigned e; for (e = 0; e < rcd->rcvegrbuf_chunks; e++) { void *base = rcd->rcvegrbuf[e]; size_t size = rcd->rcvegrbuf_size; dma_free_coherent(&dd->pcidev->dev, size, base, rcd->rcvegrbuf_phys[e]); } kfree(rcd->rcvegrbuf); rcd->rcvegrbuf = NULL; kfree(rcd->rcvegrbuf_phys); rcd->rcvegrbuf_phys = NULL; rcd->rcvegrbuf_chunks = 0; } kfree(rcd->tid_pg_list); vfree(rcd->user_event_mask); vfree(rcd->subctxt_uregbase); vfree(rcd->subctxt_rcvegrbuf); vfree(rcd->subctxt_rcvhdr_base); #ifdef CONFIG_DEBUG_FS kfree(rcd->opstats); rcd->opstats = NULL; #endif kfree(rcd); } /* * Perform a PIO buffer bandwidth write test, to verify proper system * configuration. Even when all the setup calls work, occasionally * BIOS or other issues can prevent write combining from working, or * can cause other bandwidth problems to the chip. * * This test simply writes the same buffer over and over again, and * measures close to the peak bandwidth to the chip (not testing * data bandwidth to the wire). On chips that use an address-based * trigger to send packets to the wire, this is easy. On chips that * use a count to trigger, we want to make sure that the packet doesn't * go out on the wire, or trigger flow control checks. */ static void qib_verify_pioperf(struct qib_devdata *dd) { u32 pbnum, cnt, lcnt; u32 __iomem *piobuf; u32 *addr; u64 msecs, emsecs; piobuf = dd->f_getsendbuf(dd->pport, 0ULL, &pbnum); if (!piobuf) { qib_devinfo(dd->pcidev, "No PIObufs for checking perf, skipping\n"); return; } /* * Enough to give us a reasonable test, less than piobuf size, and * likely multiple of store buffer length. */ cnt = 1024; addr = vmalloc(cnt); if (!addr) { qib_devinfo(dd->pcidev, "Couldn't get memory for checking PIO perf," " skipping\n"); goto done; } preempt_disable(); /* we want reasonably accurate elapsed time */ msecs = 1 + jiffies_to_msecs(jiffies); for (lcnt = 0; lcnt < 10000U; lcnt++) { /* wait until we cross msec boundary */ if (jiffies_to_msecs(jiffies) >= msecs) break; udelay(1); } dd->f_set_armlaunch(dd, 0); /* * length 0, no dwords actually sent */ writeq(0, piobuf); qib_flush_wc(); /* * This is only roughly accurate, since even with preempt we * still take interrupts that could take a while. Running for * >= 5 msec seems to get us "close enough" to accurate values. */ msecs = jiffies_to_msecs(jiffies); for (emsecs = lcnt = 0; emsecs <= 5UL; lcnt++) { qib_pio_copy(piobuf + 64, addr, cnt >> 2); emsecs = jiffies_to_msecs(jiffies) - msecs; } /* 1 GiB/sec, slightly over IB SDR line rate */ if (lcnt < (emsecs * 1024U)) qib_dev_err(dd, "Performance problem: bandwidth to PIO buffers is only %u MiB/sec\n", lcnt / (u32) emsecs); preempt_enable(); vfree(addr); done: /* disarm piobuf, so it's available again */ dd->f_sendctrl(dd->pport, QIB_SENDCTRL_DISARM_BUF(pbnum)); qib_sendbuf_done(dd, pbnum); dd->f_set_armlaunch(dd, 1); } void qib_free_devdata(struct qib_devdata *dd) { unsigned long flags; spin_lock_irqsave(&qib_devs_lock, flags); idr_remove(&qib_unit_table, dd->unit); list_del(&dd->list); spin_unlock_irqrestore(&qib_devs_lock, flags); #ifdef CONFIG_DEBUG_FS qib_dbg_ibdev_exit(&dd->verbs_dev); #endif ib_dealloc_device(&dd->verbs_dev.ibdev); } /* * Allocate our primary per-unit data structure. Must be done via verbs * allocator, because the verbs cleanup process both does cleanup and * free of the data structure. * "extra" is for chip-specific data. * * Use the idr mechanism to get a unit number for this unit. */ struct qib_devdata *qib_alloc_devdata(struct pci_dev *pdev, size_t extra) { unsigned long flags; struct qib_devdata *dd; int ret; dd = (struct qib_devdata *) ib_alloc_device(sizeof(*dd) + extra); if (!dd) return ERR_PTR(-ENOMEM); INIT_LIST_HEAD(&dd->list); idr_preload(GFP_KERNEL); spin_lock_irqsave(&qib_devs_lock, flags); ret = idr_alloc(&qib_unit_table, dd, 0, 0, GFP_NOWAIT); if (ret >= 0) { dd->unit = ret; list_add(&dd->list, &qib_dev_list); } spin_unlock_irqrestore(&qib_devs_lock, flags); idr_preload_end(); if (ret < 0) { qib_early_err(&pdev->dev, "Could not allocate unit ID: error %d\n", -ret); goto bail; } if (!qib_cpulist_count) { u32 count = num_online_cpus(); qib_cpulist = kzalloc(BITS_TO_LONGS(count) * sizeof(long), GFP_KERNEL); if (qib_cpulist) qib_cpulist_count = count; else qib_early_err(&pdev->dev, "Could not alloc cpulist info, cpu affinity might be wrong\n"); } #ifdef CONFIG_DEBUG_FS qib_dbg_ibdev_init(&dd->verbs_dev); #endif return dd; bail: if (!list_empty(&dd->list)) list_del_init(&dd->list); ib_dealloc_device(&dd->verbs_dev.ibdev); return ERR_PTR(ret);; } /* * Called from freeze mode handlers, and from PCI error * reporting code. Should be paranoid about state of * system and data structures. */ void qib_disable_after_error(struct qib_devdata *dd) { if (dd->flags & QIB_INITTED) { u32 pidx; dd->flags &= ~QIB_INITTED; if (dd->pport) for (pidx = 0; pidx < dd->num_pports; ++pidx) { struct qib_pportdata *ppd; ppd = dd->pport + pidx; if (dd->flags & QIB_PRESENT) { qib_set_linkstate(ppd, QIB_IB_LINKDOWN_DISABLE); dd->f_setextled(ppd, 0); } *ppd->statusp &= ~QIB_STATUS_IB_READY; } } /* * Mark as having had an error for driver, and also * for /sys and status word mapped to user programs. * This marks unit as not usable, until reset. */ if (dd->devstatusp) *dd->devstatusp |= QIB_STATUS_HWERROR; } static void qib_remove_one(struct pci_dev *); static int qib_init_one(struct pci_dev *, const struct pci_device_id *); #define DRIVER_LOAD_MSG "Intel " QIB_DRV_NAME " loaded: " #define PFX QIB_DRV_NAME ": " static DEFINE_PCI_DEVICE_TABLE(qib_pci_tbl) = { { PCI_DEVICE(PCI_VENDOR_ID_PATHSCALE, PCI_DEVICE_ID_QLOGIC_IB_6120) }, { PCI_DEVICE(PCI_VENDOR_ID_QLOGIC, PCI_DEVICE_ID_QLOGIC_IB_7220) }, { PCI_DEVICE(PCI_VENDOR_ID_QLOGIC, PCI_DEVICE_ID_QLOGIC_IB_7322) }, { 0, } }; MODULE_DEVICE_TABLE(pci, qib_pci_tbl); struct pci_driver qib_driver = { .name = QIB_DRV_NAME, .probe = qib_init_one, .remove = qib_remove_one, .id_table = qib_pci_tbl, .err_handler = &qib_pci_err_handler, }; #ifdef CONFIG_INFINIBAND_QIB_DCA static int qib_notify_dca(struct notifier_block *, unsigned long, void *); static struct notifier_block dca_notifier = { .notifier_call = qib_notify_dca, .next = NULL, .priority = 0 }; static int qib_notify_dca_device(struct device *device, void *data) { struct qib_devdata *dd = dev_get_drvdata(device); unsigned long event = *(unsigned long *)data; return dd->f_notify_dca(dd, event); } static int qib_notify_dca(struct notifier_block *nb, unsigned long event, void *p) { int rval; rval = driver_for_each_device(&qib_driver.driver, NULL, &event, qib_notify_dca_device); return rval ? NOTIFY_BAD : NOTIFY_DONE; } #endif /* * Do all the generic driver unit- and chip-independent memory * allocation and initialization. */ static int __init qlogic_ib_init(void) { int ret; ret = qib_dev_init(); if (ret) goto bail; /* * These must be called before the driver is registered with * the PCI subsystem. */ idr_init(&qib_unit_table); #ifdef CONFIG_INFINIBAND_QIB_DCA dca_register_notify(&dca_notifier); #endif #ifdef CONFIG_DEBUG_FS qib_dbg_init(); #endif ret = pci_register_driver(&qib_driver); if (ret < 0) { pr_err("Unable to register driver: error %d\n", -ret); goto bail_dev; } /* not fatal if it doesn't work */ if (qib_init_qibfs()) pr_err("Unable to register ipathfs\n"); goto bail; /* all OK */ bail_dev: #ifdef CONFIG_INFINIBAND_QIB_DCA dca_unregister_notify(&dca_notifier); #endif #ifdef CONFIG_DEBUG_FS qib_dbg_exit(); #endif idr_destroy(&qib_unit_table); qib_dev_cleanup(); bail: return ret; } module_init(qlogic_ib_init); /* * Do the non-unit driver cleanup, memory free, etc. at unload. */ static void __exit qlogic_ib_cleanup(void) { int ret; ret = qib_exit_qibfs(); if (ret) pr_err( "Unable to cleanup counter filesystem: error %d\n", -ret); #ifdef CONFIG_INFINIBAND_QIB_DCA dca_unregister_notify(&dca_notifier); #endif pci_unregister_driver(&qib_driver); #ifdef CONFIG_DEBUG_FS qib_dbg_exit(); #endif qib_cpulist_count = 0; kfree(qib_cpulist); idr_destroy(&qib_unit_table); qib_dev_cleanup(); } module_exit(qlogic_ib_cleanup); /* this can only be called after a successful initialization */ static void cleanup_device_data(struct qib_devdata *dd) { int ctxt; int pidx; struct qib_ctxtdata **tmp; unsigned long flags; /* users can't do anything more with chip */ for (pidx = 0; pidx < dd->num_pports; ++pidx) { if (dd->pport[pidx].statusp) *dd->pport[pidx].statusp &= ~QIB_STATUS_CHIP_PRESENT; spin_lock(&dd->pport[pidx].cc_shadow_lock); kfree(dd->pport[pidx].congestion_entries); dd->pport[pidx].congestion_entries = NULL; kfree(dd->pport[pidx].ccti_entries); dd->pport[pidx].ccti_entries = NULL; kfree(dd->pport[pidx].ccti_entries_shadow); dd->pport[pidx].ccti_entries_shadow = NULL; kfree(dd->pport[pidx].congestion_entries_shadow); dd->pport[pidx].congestion_entries_shadow = NULL; spin_unlock(&dd->pport[pidx].cc_shadow_lock); } if (!qib_wc_pat) qib_disable_wc(dd); if (dd->pioavailregs_dma) { dma_free_coherent(&dd->pcidev->dev, PAGE_SIZE, (void *) dd->pioavailregs_dma, dd->pioavailregs_phys); dd->pioavailregs_dma = NULL; } if (dd->pageshadow) { struct page **tmpp = dd->pageshadow; dma_addr_t *tmpd = dd->physshadow; int i; for (ctxt = 0; ctxt < dd->cfgctxts; ctxt++) { int ctxt_tidbase = ctxt * dd->rcvtidcnt; int maxtid = ctxt_tidbase + dd->rcvtidcnt; for (i = ctxt_tidbase; i < maxtid; i++) { if (!tmpp[i]) continue; pci_unmap_page(dd->pcidev, tmpd[i], PAGE_SIZE, PCI_DMA_FROMDEVICE); qib_release_user_pages(&tmpp[i], 1); tmpp[i] = NULL; } } dd->pageshadow = NULL; vfree(tmpp); dd->physshadow = NULL; vfree(tmpd); } /* * Free any resources still in use (usually just kernel contexts) * at unload; we do for ctxtcnt, because that's what we allocate. * We acquire lock to be really paranoid that rcd isn't being * accessed from some interrupt-related code (that should not happen, * but best to be sure). */ spin_lock_irqsave(&dd->uctxt_lock, flags); tmp = dd->rcd; dd->rcd = NULL; spin_unlock_irqrestore(&dd->uctxt_lock, flags); for (ctxt = 0; tmp && ctxt < dd->ctxtcnt; ctxt++) { struct qib_ctxtdata *rcd = tmp[ctxt]; tmp[ctxt] = NULL; /* debugging paranoia */ qib_free_ctxtdata(dd, rcd); } kfree(tmp); kfree(dd->boardname); qib_cq_exit(dd); } /* * Clean up on unit shutdown, or error during unit load after * successful initialization. */ static void qib_postinit_cleanup(struct qib_devdata *dd) { /* * Clean up chip-specific stuff. * We check for NULL here, because it's outside * the kregbase check, and we need to call it * after the free_irq. Thus it's possible that * the function pointers were never initialized. */ if (dd->f_cleanup) dd->f_cleanup(dd); qib_pcie_ddcleanup(dd); cleanup_device_data(dd); qib_free_devdata(dd); } static int qib_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { int ret, j, pidx, initfail; struct qib_devdata *dd = NULL; ret = qib_pcie_init(pdev, ent); if (ret) goto bail; /* * Do device-specific initialiation, function table setup, dd * allocation, etc. */ switch (ent->device) { case PCI_DEVICE_ID_QLOGIC_IB_6120: #ifdef CONFIG_PCI_MSI dd = qib_init_iba6120_funcs(pdev, ent); #else qib_early_err(&pdev->dev, "Intel PCIE device 0x%x cannot work if CONFIG_PCI_MSI is not enabled\n", ent->device); dd = ERR_PTR(-ENODEV); #endif break; case PCI_DEVICE_ID_QLOGIC_IB_7220: dd = qib_init_iba7220_funcs(pdev, ent); break; case PCI_DEVICE_ID_QLOGIC_IB_7322: dd = qib_init_iba7322_funcs(pdev, ent); break; default: qib_early_err(&pdev->dev, "Failing on unknown Intel deviceid 0x%x\n", ent->device); ret = -ENODEV; } if (IS_ERR(dd)) ret = PTR_ERR(dd); if (ret) goto bail; /* error already printed */ ret = qib_create_workqueues(dd); if (ret) goto bail; /* do the generic initialization */ initfail = qib_init(dd, 0); ret = qib_register_ib_device(dd); /* * Now ready for use. this should be cleared whenever we * detect a reset, or initiate one. If earlier failure, * we still create devices, so diags, etc. can be used * to determine cause of problem. */ if (!qib_mini_init && !initfail && !ret) dd->flags |= QIB_INITTED; j = qib_device_create(dd); if (j) qib_dev_err(dd, "Failed to create /dev devices: %d\n", -j); j = qibfs_add(dd); if (j) qib_dev_err(dd, "Failed filesystem setup for counters: %d\n", -j); if (qib_mini_init || initfail || ret) { qib_stop_timers(dd); flush_workqueue(ib_wq); for (pidx = 0; pidx < dd->num_pports; ++pidx) dd->f_quiet_serdes(dd->pport + pidx); if (qib_mini_init) goto bail; if (!j) { (void) qibfs_remove(dd); qib_device_remove(dd); } if (!ret) qib_unregister_ib_device(dd); qib_postinit_cleanup(dd); if (initfail) ret = initfail; goto bail; } if (!qib_wc_pat) { ret = qib_enable_wc(dd); if (ret) { qib_dev_err(dd, "Write combining not enabled (err %d): performance may be poor\n", -ret); ret = 0; } } qib_verify_pioperf(dd); bail: return ret; } static void qib_remove_one(struct pci_dev *pdev) { struct qib_devdata *dd = pci_get_drvdata(pdev); int ret; /* unregister from IB core */ qib_unregister_ib_device(dd); /* * Disable the IB link, disable interrupts on the device, * clear dma engines, etc. */ if (!qib_mini_init) qib_shutdown_device(dd); qib_stop_timers(dd); /* wait until all of our (qsfp) queue_work() calls complete */ flush_workqueue(ib_wq); ret = qibfs_remove(dd); if (ret) qib_dev_err(dd, "Failed counters filesystem cleanup: %d\n", -ret); qib_device_remove(dd); qib_postinit_cleanup(dd); } /** * qib_create_rcvhdrq - create a receive header queue * @dd: the qlogic_ib device * @rcd: the context data * * This must be contiguous memory (from an i/o perspective), and must be * DMA'able (which means for some systems, it will go through an IOMMU, * or be forced into a low address range). */ int qib_create_rcvhdrq(struct qib_devdata *dd, struct qib_ctxtdata *rcd) { unsigned amt; int old_node_id; if (!rcd->rcvhdrq) { dma_addr_t phys_hdrqtail; gfp_t gfp_flags; amt = ALIGN(dd->rcvhdrcnt * dd->rcvhdrentsize * sizeof(u32), PAGE_SIZE); gfp_flags = (rcd->ctxt >= dd->first_user_ctxt) ? GFP_USER : GFP_KERNEL; old_node_id = dev_to_node(&dd->pcidev->dev); set_dev_node(&dd->pcidev->dev, rcd->node_id); rcd->rcvhdrq = dma_alloc_coherent( &dd->pcidev->dev, amt, &rcd->rcvhdrq_phys, gfp_flags | __GFP_COMP); set_dev_node(&dd->pcidev->dev, old_node_id); if (!rcd->rcvhdrq) { qib_dev_err(dd, "attempt to allocate %d bytes for ctxt %u rcvhdrq failed\n", amt, rcd->ctxt); goto bail; } if (rcd->ctxt >= dd->first_user_ctxt) { rcd->user_event_mask = vmalloc_user(PAGE_SIZE); if (!rcd->user_event_mask) goto bail_free_hdrq; } if (!(dd->flags & QIB_NODMA_RTAIL)) { set_dev_node(&dd->pcidev->dev, rcd->node_id); rcd->rcvhdrtail_kvaddr = dma_alloc_coherent( &dd->pcidev->dev, PAGE_SIZE, &phys_hdrqtail, gfp_flags); set_dev_node(&dd->pcidev->dev, old_node_id); if (!rcd->rcvhdrtail_kvaddr) goto bail_free; rcd->rcvhdrqtailaddr_phys = phys_hdrqtail; } rcd->rcvhdrq_size = amt; } /* clear for security and sanity on each use */ memset(rcd->rcvhdrq, 0, rcd->rcvhdrq_size); if (rcd->rcvhdrtail_kvaddr) memset(rcd->rcvhdrtail_kvaddr, 0, PAGE_SIZE); return 0; bail_free: qib_dev_err(dd, "attempt to allocate 1 page for ctxt %u rcvhdrqtailaddr failed\n", rcd->ctxt); vfree(rcd->user_event_mask); rcd->user_event_mask = NULL; bail_free_hdrq: dma_free_coherent(&dd->pcidev->dev, amt, rcd->rcvhdrq, rcd->rcvhdrq_phys); rcd->rcvhdrq = NULL; bail: return -ENOMEM; } /** * allocate eager buffers, both kernel and user contexts. * @rcd: the context we are setting up. * * Allocate the eager TID buffers and program them into hip. * They are no longer completely contiguous, we do multiple allocation * calls. Otherwise we get the OOM code involved, by asking for too * much per call, with disastrous results on some kernels. */ int qib_setup_eagerbufs(struct qib_ctxtdata *rcd) { struct qib_devdata *dd = rcd->dd; unsigned e, egrcnt, egrperchunk, chunk, egrsize, egroff; size_t size; gfp_t gfp_flags; int old_node_id; /* * GFP_USER, but without GFP_FS, so buffer cache can be * coalesced (we hope); otherwise, even at order 4, * heavy filesystem activity makes these fail, and we can * use compound pages. */ gfp_flags = __GFP_WAIT | __GFP_IO | __GFP_COMP; egrcnt = rcd->rcvegrcnt; egroff = rcd->rcvegr_tid_base; egrsize = dd->rcvegrbufsize; chunk = rcd->rcvegrbuf_chunks; egrperchunk = rcd->rcvegrbufs_perchunk; size = rcd->rcvegrbuf_size; if (!rcd->rcvegrbuf) { rcd->rcvegrbuf = kzalloc_node(chunk * sizeof(rcd->rcvegrbuf[0]), GFP_KERNEL, rcd->node_id); if (!rcd->rcvegrbuf) goto bail; } if (!rcd->rcvegrbuf_phys) { rcd->rcvegrbuf_phys = kmalloc_node(chunk * sizeof(rcd->rcvegrbuf_phys[0]), GFP_KERNEL, rcd->node_id); if (!rcd->rcvegrbuf_phys) goto bail_rcvegrbuf; } for (e = 0; e < rcd->rcvegrbuf_chunks; e++) { if (rcd->rcvegrbuf[e]) continue; old_node_id = dev_to_node(&dd->pcidev->dev); set_dev_node(&dd->pcidev->dev, rcd->node_id); rcd->rcvegrbuf[e] = dma_alloc_coherent(&dd->pcidev->dev, size, &rcd->rcvegrbuf_phys[e], gfp_flags); set_dev_node(&dd->pcidev->dev, old_node_id); if (!rcd->rcvegrbuf[e]) goto bail_rcvegrbuf_phys; } rcd->rcvegr_phys = rcd->rcvegrbuf_phys[0]; for (e = chunk = 0; chunk < rcd->rcvegrbuf_chunks; chunk++) { dma_addr_t pa = rcd->rcvegrbuf_phys[chunk]; unsigned i; /* clear for security and sanity on each use */ memset(rcd->rcvegrbuf[chunk], 0, size); for (i = 0; e < egrcnt && i < egrperchunk; e++, i++) { dd->f_put_tid(dd, e + egroff + (u64 __iomem *) ((char __iomem *) dd->kregbase + dd->rcvegrbase), RCVHQ_RCV_TYPE_EAGER, pa); pa += egrsize; } cond_resched(); /* don't hog the cpu */ } return 0; bail_rcvegrbuf_phys: for (e = 0; e < rcd->rcvegrbuf_chunks && rcd->rcvegrbuf[e]; e++) dma_free_coherent(&dd->pcidev->dev, size, rcd->rcvegrbuf[e], rcd->rcvegrbuf_phys[e]); kfree(rcd->rcvegrbuf_phys); rcd->rcvegrbuf_phys = NULL; bail_rcvegrbuf: kfree(rcd->rcvegrbuf); rcd->rcvegrbuf = NULL; bail: return -ENOMEM; } /* * Note: Changes to this routine should be mirrored * for the diagnostics routine qib_remap_ioaddr32(). * There is also related code for VL15 buffers in qib_init_7322_variables(). * The teardown code that unmaps is in qib_pcie_ddcleanup() */ int init_chip_wc_pat(struct qib_devdata *dd, u32 vl15buflen) { u64 __iomem *qib_kregbase = NULL; void __iomem *qib_piobase = NULL; u64 __iomem *qib_userbase = NULL; u64 qib_kreglen; u64 qib_pio2koffset = dd->piobufbase & 0xffffffff; u64 qib_pio4koffset = dd->piobufbase >> 32; u64 qib_pio2klen = dd->piobcnt2k * dd->palign; u64 qib_pio4klen = dd->piobcnt4k * dd->align4k; u64 qib_physaddr = dd->physaddr; u64 qib_piolen; u64 qib_userlen = 0; /* * Free the old mapping because the kernel will try to reuse the * old mapping and not create a new mapping with the * write combining attribute. */ iounmap(dd->kregbase); dd->kregbase = NULL; /* * Assumes chip address space looks like: * - kregs + sregs + cregs + uregs (in any order) * - piobufs (2K and 4K bufs in either order) * or: * - kregs + sregs + cregs (in any order) * - piobufs (2K and 4K bufs in either order) * - uregs */ if (dd->piobcnt4k == 0) { qib_kreglen = qib_pio2koffset; qib_piolen = qib_pio2klen; } else if (qib_pio2koffset < qib_pio4koffset) { qib_kreglen = qib_pio2koffset; qib_piolen = qib_pio4koffset + qib_pio4klen - qib_kreglen; } else { qib_kreglen = qib_pio4koffset; qib_piolen = qib_pio2koffset + qib_pio2klen - qib_kreglen; } qib_piolen += vl15buflen; /* Map just the configured ports (not all hw ports) */ if (dd->uregbase > qib_kreglen) qib_userlen = dd->ureg_align * dd->cfgctxts; /* Sanity checks passed, now create the new mappings */ qib_kregbase = ioremap_nocache(qib_physaddr, qib_kreglen); if (!qib_kregbase) goto bail; qib_piobase = ioremap_wc(qib_physaddr + qib_kreglen, qib_piolen); if (!qib_piobase) goto bail_kregbase; if (qib_userlen) { qib_userbase = ioremap_nocache(qib_physaddr + dd->uregbase, qib_userlen); if (!qib_userbase) goto bail_piobase; } dd->kregbase = qib_kregbase; dd->kregend = (u64 __iomem *) ((char __iomem *) qib_kregbase + qib_kreglen); dd->piobase = qib_piobase; dd->pio2kbase = (void __iomem *) (((char __iomem *) dd->piobase) + qib_pio2koffset - qib_kreglen); if (dd->piobcnt4k) dd->pio4kbase = (void __iomem *) (((char __iomem *) dd->piobase) + qib_pio4koffset - qib_kreglen); if (qib_userlen) /* ureg will now be accessed relative to dd->userbase */ dd->userbase = qib_userbase; return 0; bail_piobase: iounmap(qib_piobase); bail_kregbase: iounmap(qib_kregbase); bail: return -ENOMEM; }
Supervenom/linux-mod_sys_call
drivers/infiniband/hw/qib/qib_init.c
C
gpl-2.0
47,962
.threecol-split-row-12--4-8 .hr--2-3 .l-r, .threecol-split-row-12--4-8 .arc--3 .l-r:nth-child(2) { width: 32.20339%; float: left; margin-right: 1.69492%; } .threecol-split-row-12--4-8 .hr--2-3 .l-r:last-child, .threecol-split-row-12--4-8 .arc--3 .l-r:last-child { width: 66.10169%; float: right; margin-right: 0; }
raghavdev/project6
modules/contrib/at_tools/at_theme_generator/starterkits/starterkit/layout/site-builder/css/threecol/threecol-split-row-12--4-8.css
CSS
gpl-2.0
328
<div class="homepage-section main section align-items-center" data-anchor="main" > <div class="ui container container-main"> <div class="cod-banner row"> <h2> <span> Explore more than <span><strong>two petabytes</strong></span> <br /> <span class="scnd-line" >of open data from particle physics!</span ></span > </h2> </div> <div class="cod-search row"> <form class="search-form container" action="{{config.THEME_SEARCH_ENDPOINT}}" role="search" > <input autofocus type="text" class="form-control search" name="q" /> <div> <button type="submit">Search</button> <div class="cod-home-image"> <img src="{{url_for('static', filename='assets/img/header-image.svg')}}" alt="" /> </div> </div> </form> <div class="search-examples row"> <span class="example-title">search examples:</span> <a href="/search?subtype=Collision&type=Dataset">collision datasets</a>, <a href="/search?keywords=education">keywords:education</a>, <a href="/search?collision_energy=7TeV">energy:7TeV</a> </div> </div> <div class="cod-collections row"> <div class="collections-col"> <header><span>Explore</span></header> <ul> <li><a href="/search?type=Dataset">datasets</a></li> <li><a href="/search?type=Software">software</a></li> <li><a href="/search?type=Environment">environments</a></li> <li><a href="/search?type=Documentation">documentation</a></li> </ul> </div> <div class="collections-col"> <header><span>Focus on</span></header> <ul> <li><a href="/search?experiment=ATLAS">ATLAS</a></li> <li><a href="/search?experiment=ALICE">ALICE</a></li> <li><a href="/search?experiment=CMS">CMS</a></li> <li><a href="/search?experiment=LHCb">LHCb</a></li> <li><a href="/search?experiment=OPERA">OPERA</a></li> <li><a href="/search?experiment=PHENIX">PHENIX</a></li> <li><a href="/search?keywords=datascience">Data Science</a></li> </ul> </div> </div> <div class="cod-scroll row"> <div class="icon"> <a href="#lva"> <img src="{{url_for('static', filename='assets/img/mouse-scrolling.png')}}" alt="" /> <span>Get started</span> <img src="{{url_for('static', filename='assets/img/mouse-scrolling.png')}}" alt="" /> </a> </div> </div> </div> </div>
tiborsimko/opendata.cern.ch
cernopendata/templates/cernopendata_pages/front/main.html
HTML
gpl-2.0
2,770
/*************************************************************************** selectgame.h Copyright (C) 2002,2003 Walter van Niftrik This program may be modified and copied freely according to the terms of the GNU general public license (GPL), as long as the above copyright notice and the licensing information contained herein are preserved. Please refer to www.gnu.org for licensing details. This work is provided AS IS, without warranty of any kind, expressed or implied, including but not limited to the warranties of merchantibility, noninfringement, and fitness for a specific purpose. The author will not be held liable for any damage caused by this work or derivatives of it. By using this source code, you agree to the licensing terms as stated above. Please contact the maintainer for bug reports or inquiries. Current Maintainer: Walter van Niftrik <w.f.b.w.v.niftrik@stud.tue.nl> ***************************************************************************/ #ifndef __SELECTGAME_H #define __SELECTGAME_H /* This function changes to the directory of the game that the user wants to ** run. Currently implemented by a Dreamcast-specific graphical interface based ** on Daniel Potter's GhettoPlay interface. It also creates a config file on ** the ram disk, based on options the user has set in the interface. ** Parameters: void. ** Returns : void. */ void choose_game(void); #endif /* __SELECTGAME_H */
wjp/freesci-archive
src/dc/selectgame.h
C
gpl-2.0
1,445
<?php /** Erzya (Эрзянь) * * See MessagesQqq.php for message documentation incl. usage of parameters * To improve a translation please visit http://translatewiki.net * * @ingroup Language * @file * * @author Amdf * @author Botuzhaleny-sodamo * @author Erzianj jurnalist * @author MF-Warburg * @author Spacebirdy * @author Sura * @author Tupikovs * @author Urhixidur */ $fallback = 'ru'; $namespaceNames = array( NS_MEDIA => 'Медия', NS_SPECIAL => 'Башка тевень', NS_TALK => 'Кортамо', NS_USER => 'Теиця', NS_USER_TALK => 'Теицянь кортамось', NS_PROJECT_TALK => '$1 кортамось', NS_FILE => 'Артовкс', NS_FILE_TALK => 'Артовксто кортамось', NS_MEDIAWIKI => 'MediaWiki', NS_MEDIAWIKI_TALK => 'MediaWiki-нь кортамось', NS_TEMPLATE => 'ЛопаПарцун', NS_TEMPLATE_TALK => 'ЛопаПарцундо кортамось', NS_HELP => 'Лезкс', NS_HELP_TALK => 'Лезкстэ кортамось', NS_CATEGORY => 'Категория', NS_CATEGORY_TALK => 'Категориядо кортамось', ); $specialPageAliases = array( 'DoubleRedirects' => array( 'КавтоньКирданьЛиявНевтемат' ), 'BrokenRedirects' => array( 'СинденьЛиявНевтемат' ), 'Userlogin' => array( 'ТеицяСовамо' ), 'Userlogout' => array( 'ТеицяЛисема' ), 'CreateAccount' => array( 'ТеемсШкамсСовамоТарка' ), 'Watchlist' => array( 'ВанстнемаКерькс' ), 'Recentchanges' => array( 'ЧыяконьПолавтомат' ), 'Upload' => array( 'Ёвкстамо' ), 'Listfiles' => array( 'АртовксКерькс' ), 'Newimages' => array( 'ОдАртовкст' ), 'Statistics' => array( 'Статистика' ), 'Randompage' => array( 'КодамоПонгсьЛопа' ), 'Lonelypages' => array( 'СькамнестЛопат', 'УрозЛопат' ), 'Uncategorizedpages' => array( 'КатегориявтомоЛопат' ), 'Uncategorizedcategories' => array( 'КатегориясАпакСовавтоСатегорият' ), 'Uncategorizedimages' => array( 'КатегориявтомоАртовкст' ), 'Uncategorizedtemplates' => array( 'КатегориявтомоЛопаПарцунт' ), 'Unusedcategories' => array( 'ТевсАНолдавицяКатегорият' ), 'Unusedimages' => array( 'ТевсАНолдавицяАртовкст' ), 'Wantedpages' => array( 'ВешемаЛопат' ), 'Wantedcategories' => array( 'ВешемаКатегорият' ), 'Mostlinked' => array( 'СехтеЛамоСюлмавомаПеМартот' ), 'Mostlinkedcategories' => array( 'СехтеЛамоСюлмавомаПеМартоКатегорият' ), 'Mostlinkedtemplates' => array( 'СехтеЛамоСюлмавомаПеМартоЛопаПарцунт' ), 'Mostimages' => array( 'ВесемедеЛамоАртовксМарто' ), 'Mostcategories' => array( 'ВесемедеЛамоКатегорияМарто' ), 'Mostrevisions' => array( 'ВесемедеЛамокстьЛиякстомтозь' ), 'Fewestrevisions' => array( 'ВесемедеАламокстьЛиякстомтозь' ), 'Shortpages' => array( 'НурькинеЛопат' ), 'Longpages' => array( 'КувакаЛопат' ), 'Newpages' => array( 'ОдЛопат' ), 'Ancientpages' => array( 'ТюштяПингеньЛопат' ), 'Deadendpages' => array( 'ЛисемаСюлмавомаПевтемеЛопат' ), 'Protectedpages' => array( 'ВанстоньЛопат' ), 'Protectedtitles' => array( 'ВанстоньКонякст' ), 'Allpages' => array( 'ВесеЛопат' ), 'Specialpages' => array( 'БашкаТевеньЛопат' ), 'Contributions' => array( 'Поладкст' ), 'Whatlinkshere' => array( 'ТезэньКодамтСюлмавомаПеть' ), 'Recentchangeslinked' => array( 'МалавиксПолавтомат' ), 'Movepage' => array( 'ПечтевтемсЛопа' ), 'Blockme' => array( 'СаймасСаемизь' ), 'Booksources' => array( 'КнигаЛисьмапрят' ), 'Categories' => array( 'Категорият' ), 'Export' => array( 'Экспортировамс' ), 'Version' => array( 'Версия' ), 'Allmessages' => array( 'ВесеПачтямнэть' ), 'Blockip' => array( 'СаймасСаемсIP' ), 'Undelete' => array( 'Вельмевтемс' ), 'Import' => array( 'Импортировамс' ), 'Lockdb' => array( 'СёлгомсДБ' ), 'Unlockdb' => array( 'ПанжомсДБ' ), 'Userrights' => array( 'ТеицяньВидечыть' ), 'MIMEsearch' => array( 'MIMEВешнема' ), 'Unwatchedpages' => array( 'ВанстнемавтомоЛопат' ), 'Revisiondelete' => array( 'ЛиякстомтоманьНардамо' ), 'Unusedtemplates' => array( 'ТевсАпакНолдаЛопаПарцунт' ), 'Mypage' => array( 'МоньЛопам' ), 'Mytalk' => array( 'МоньКортамом' ), 'Mycontributions' => array( 'МонМезеТеинь' ), 'Popularpages' => array( 'ЛисийСовийМартоЛопат' ), 'Search' => array( 'Вешнемс' ), 'Resetpass' => array( 'СовамоВалоньПолавтома' ), 'Filepath' => array( 'ФайланьКи' ), 'Blankpage' => array( 'ЧавоЛопа' ), ); $magicWords = array( 'currentmonth' => array( '1', 'МОЛИЦЯКОВ', 'ТЕКУЩИЙ_МЕСЯЦ', 'ТЕКУЩИЙ_МЕСЯЦ_2', 'CURRENTMONTH', 'CURRENTMONTH2' ), 'currentmonthname' => array( '1', 'МОЛИЦЯКОВЛЕМ', 'НАЗВАНИЕ_ТЕКУЩЕГО_МЕСЯЦА', 'CURRENTMONTHNAME' ), 'currentmonthnamegen' => array( '1', 'МОЛИЦЯКОВЛЕМГЕН', 'НАЗВАНИЕ_ТЕКУЩЕГО_МЕСЯЦА_РОД', 'CURRENTMONTHNAMEGEN' ), 'currentmonthabbrev' => array( '1', 'МОЛИЦЯКОВКИРЬТЯНЬХВОРМА', 'НАЗВАНИЕ_ТЕКУЩЕГО_МЕСЯЦА_АБР', 'CURRENTMONTHABBREV' ), 'currentday' => array( '1', 'МОЛИЦЯЧЫ', 'ТЕКУЩИЙ_ДЕНЬ', 'CURRENTDAY' ), 'currentday2' => array( '1', 'МОЛИЦЯЧЫ2', 'ТЕКУЩИЙ_ДЕНЬ_2', 'CURRENTDAY2' ), 'currentdayname' => array( '1', 'МОЛИЦЯЧЫЛЕМ', 'НАЗВАНИЕ_ТЕКУЩЕГО_ДНЯ', 'CURRENTDAYNAME' ), 'currentyear' => array( '1', 'МОЛИЦЯИЕ', 'ТЕКУЩИЙ_ГОД', 'CURRENTYEAR' ), 'currenttime' => array( '1', 'МОЛИЦЯШКА', 'ТЕКУЩЕЕ_ВРЕМЯ', 'CURRENTTIME' ), 'currenthour' => array( '1', 'МОЛИЦЯЦЯС', 'ТЕКУЩИЙ_ЧАС', 'CURRENTHOUR' ), 'localmonth' => array( '1', 'ТЕСКЭНЬКОВ', 'МЕСТНЫЙ_МЕСЯЦ', 'МЕСТНЫЙ_МЕСЯЦ_2', 'LOCALMONTH', 'LOCALMONTH2' ), 'localmonthname' => array( '1', 'ТЕСКЭНЬКОВЛЕМ', 'НАЗВАНИЕ_МЕСТНОГО_МЕСЯЦА', 'LOCALMONTHNAME' ), 'localmonthnamegen' => array( '1', 'ТЕСКЭНЬКОВЛЕМГЕН', 'НАЗВАНИЕ_МЕСТНОГО_МЕСЯЦА_РОД', 'LOCALMONTHNAMEGEN' ), 'localmonthabbrev' => array( '1', 'ТЕСКЭНЬКОВКИРЬТЯНЬХВОРМА', 'НАЗВАНИЕ_МЕСТНОГО_МЕСЯЦА_АБР', 'LOCALMONTHABBREV' ), 'localday' => array( '1', 'ТЕСКЭНЬЧЫ', 'МЕСТНЫЙ_ДЕНЬ', 'LOCALDAY' ), 'localday2' => array( '1', 'ТЕСКЭНЬЧЫ2', 'МЕСТНЫЙ_ДЕНЬ_2', 'LOCALDAY2' ), 'localdayname' => array( '1', 'ТЕСКЭНЬЧЫЛЕМ', 'НАЗВАНИЕ_МЕСТНОГО_ДНЯ', 'LOCALDAYNAME' ), 'localyear' => array( '1', 'ТЕСКЭНЬИЕ', 'МЕСТНЫЙ_ГОД', 'LOCALYEAR' ), 'localtime' => array( '1', 'ТЕСКЭНЬШКА', 'МЕСТНОЕ_ВРЕМЯ', 'LOCALTIME' ), 'localhour' => array( '1', 'ТЕСКЭНЬЦЯС', 'МЕСТНЫЙ_ЧАС', 'LOCALHOUR' ), 'numberofpages' => array( '1', 'ЗЯРОЛОПАТ', 'КОЛИЧЕСТВО_СТРАНИЦ', 'NUMBEROFPAGES' ), 'numberofarticles' => array( '1', 'ЗЯРОСЁРМАДОВКСТ', 'КОЛИЧЕСТВО_СТАТЕЙ', 'NUMBEROFARTICLES' ), 'numberoffiles' => array( '1', 'ЗЯРОФАЙЛАТ', 'КОЛИЧЕСТВО_ФАЙЛОВ', 'NUMBEROFFILES' ), 'numberofusers' => array( '1', 'ЗЯРОТЕИЦЯТ', 'КОЛИЧЕСТВО_УЧАСТНИКОВ', 'NUMBEROFUSERS' ), 'numberofedits' => array( '1', 'ЗЯРОВИТНЕМАТПЕТНЕМАТ', 'КОЛИЧЕСТВО_ПРАВОК', 'NUMBEROFEDITS' ), 'pagename' => array( '1', 'ЛОПАЛЕМ', 'НАЗВАНИЕ_СТРАНИЦЫ', 'PAGENAME' ), 'namespace' => array( '1', 'ЛЕМПОТМО', 'ПРОСТРАНСТВО_ИМЁН', 'NAMESPACE' ), 'talkspace' => array( '1', 'КОРТАМОПОТМО', 'ПРОСТРАНСТВО_ОБСУЖДЕНИЙ', 'TALKSPACE' ), 'fullpagename' => array( '1', 'ЛОПАЛЕМКУВАКАСТО', 'ПОЛНОЕ_НАЗВАНИЕ_СТРАНИЦЫ', 'FULLPAGENAME' ), 'talkpagename' => array( '1', 'КОРТАМОЛОПАЛЕМ', 'НАЗВАНИЕ_СТРАНИЦЫ_ОБСУЖДЕНИЯ', 'TALKPAGENAME' ), 'img_right' => array( '1', 'вить кедь', 'справа', 'right' ), 'img_left' => array( '1', 'керш кедь', 'слева', 'left' ), 'img_none' => array( '1', 'вейкеяк арась', 'без', 'none' ), 'img_center' => array( '1', 'куншкасо', 'центр', 'center', 'centre' ), 'img_framed' => array( '1', 'кундсо', 'обрамить', 'framed', 'enframed', 'frame' ), 'img_frameless' => array( '1', 'кундовтомо', 'безрамки', 'frameless' ), 'img_page' => array( '1', 'лопа=$1', 'лопа $1', 'страница=$1', 'страница $1', 'page=$1', 'page $1' ), 'img_top' => array( '1', 'верькс', 'сверху', 'top' ), 'img_text_top' => array( '1', 'текст-верькс', 'текст-сверху', 'text-top' ), 'img_middle' => array( '1', 'куншка', 'посередине', 'middle' ), 'img_bottom' => array( '1', 'алкс', 'снизу', 'bottom' ), 'img_text_bottom' => array( '1', 'текст-алкс', 'текст-снизу', 'text-bottom' ), 'localweek' => array( '1', 'ТЕСКЭНЬТАРГО', 'МЕСТНАЯ_НЕДЕЛЯ', 'LOCALWEEK' ), 'revisionid' => array( '1', 'ЛИЯКСТОМТОМАID', 'ИД_ВЕРСИИ', 'REVISIONID' ), 'revisionday' => array( '1', 'ЛИЯКСТОМТОМАЧЫ', 'ДЕНЬ_ВЕРСИИ', 'REVISIONDAY' ), 'revisionday2' => array( '1', 'ЛИЯКСТОМТОМАЧЫ2', 'ДЕНЬ_ВЕРСИИ_2', 'REVISIONDAY2' ), 'revisionmonth' => array( '1', 'ЛИЯКСТОМТОМАКОВ', 'МЕСЯЦ_ВЕРСИИ', 'REVISIONMONTH' ), 'revisionyear' => array( '1', 'ЛИЯКСТОМТОМАИЕ', 'ГОД_ВЕРСИИ', 'REVISIONYEAR' ), 'plural' => array( '0', 'ЛАМОНЬЧИСЛА', 'МНОЖЕСТВЕННОЕ_ЧИСЛО:', 'PLURAL:' ), 'raw' => array( '0', 'ВЕРЕКСТЭ', 'НЕОБРАБ:', 'RAW:' ), 'currentversion' => array( '1', 'ТЕВАТЕВЕРСИЯ', 'ТЕКУЩАЯ_ВЕРСИЯ', 'CURRENTVERSION' ), 'language' => array( '0', '#КЕЛЬ', '#ЯЗЫК:', '#LANGUAGE:' ), 'numberofadmins' => array( '1', 'ЗЯРОАДМИНТНЭДЕ', 'КОЛИЧЕСТВО_АДМИНИСТРАТОРОВ', 'NUMBEROFADMINS' ), 'special' => array( '0', 'башка тевень', 'служебная', 'special' ), 'filepath' => array( '0', 'ФАЙЛАНЬКИ', 'ПУТЬ_К_ФАЙЛУ:', 'FILEPATH:' ), 'pagesize' => array( '1', 'ЛОПАКУВАЛМО', 'РАЗМЕР_СТРАНИЦЫ', 'PAGESIZE' ), ); $messages = array( # User preference toggles 'tog-underline' => 'Сюлмавома петнень алга черькстамс:', 'tog-highlightbroken' => 'Петемс синдтрень сюлмавома петнень <a href="" class="new">вана истя</a>(лиякс вана истя<a href="" class="internal">?</a>).', 'tog-justify' => 'Вейкетстявтомс сёрмадовкс ушодоманть лопанть кувалмга', 'tog-hideminor' => 'Од полавтоматнесэ кекшемс вишинькине витевкстнэнь', 'tog-extendwatchlist' => 'Келейгавтомс сёрмадовксонь мельга ваномань сёрмалевксэнть невтевест весе полавтнематне, аволь ансяк чыеньсетне.', 'tog-usenewrc' => 'Нолдак тевс вадрялгавтозь од лиякстомат (веши JavaScript)', 'tog-numberheadings' => 'Сёрмадовкс коняксос кадык сынсь ловома валтнэ путовить', 'tog-showtoolbar' => 'Кедьёнкс лазнэнть невтемс сёрмадома шкасто (JavaScript)', 'tog-editondblclick' => 'Кавксть лепштязь совамс сёрмадовксонь витнеме-петнеме (JavaScript)', 'tog-editsection' => 'Невтемс сюлмавома пенть «витемс» эрьва секциянтень-пельксэнтень', 'tog-editsectiononrightclick' => 'Витнемс секциятнень-пелькстнэнь, лепштямс сёрмадовксонть лемензэ лангс чэерень витьёнсе повнэсэ (JavaScript)', 'tog-showtoc' => 'Невтемс сёрмадовкс потмокс (лопатненень, конатнесэ 3-до ламо сёрмадовкст)', 'tog-rememberpassword' => 'Ванстомс совамо валом те арсиймашинасонть', 'tog-editwidth' => 'Келейгавтомс витнема-петнема паксясь весе браузер вальманть келес', 'tog-watchcreations' => 'Совавтомс монь теевть лопатнень ванома лем рисьмезэнь', 'tog-watchdefault' => 'Совавтомс монь витевть лопатнень ванома лем рисьмезэнь', 'tog-watchmoves' => 'Лопанть лиякстомтса, совавтык ванома лем рисьмезэнь', 'tog-watchdeletion' => 'Лопанть нардаса, совавтык сонзэ ванома лем рисьмезэнь', 'tog-minordefault' => 'Тешкстамс витевкстнэнь апокшкэкс, бути лиякс апак ёвта', 'tog-previewontop' => 'Невтемс сёрмадовксонть васнянь невтевксэнь вальманть витеманьседенть икеле', 'tog-previewonfirst' => 'Васнянь невтевкс васенцеде витнемстэ-петнемстэ', 'tog-nocache' => 'А мерема лопатнень кешировамс', 'tog-enotifwatchlistpages' => 'Пачтямс е-сёрма, зярдо ванстнема лопазон теевить лиякстомтомат', 'tog-enotifusertalkpages' => 'Пачтямс е-сёрма теицянь ванома лемрисьмесэнь теезь лиякстомтоматнеде', 'tog-enotifminoredits' => 'Пачтямс е-сёрмасо лиякстомтоматнеде, сестэяк зярдо апокшкынеть', 'tog-enotifrevealaddr' => 'Штавтомс е-сёрмань адресэм яволявтомань сёрмадовкстнэсэ', 'tog-shownumberswatching' => 'Невтемс зяро теицятнеде, конат аравтызь лопанть эсест ванома лемрисьментень', 'tog-fancysig' => 'Лемпутовксось прок викитекст (сонсь теевиця сюлмавома певтеме)', 'tog-externaleditor' => 'Нолдамс тевс ушоёнонь витнемканть, зярс лиякс апак аравто (ансяк тевень содыйтненень, арсий машинасот эрявить башка ёнкст-аравтомат)', 'tog-externaldiff' => 'Нолдамс тевс ушоёнонь diff, зярс лиякс апак аравто', 'tog-showjumplinks' => 'Меремс "тёкадемс" маласпонгомань сюлмавомапетнес', 'tog-uselivepreview' => 'Максомс эряй васнянь невтевкс (JavaScript) (Варчамонь)', 'tog-forceeditsummary' => 'Невтик монень, мезе сёрмадомс витнемадо-петнемадо ёвтамонь вальминентень', 'tog-watchlisthideown' => 'Кекшить монь теевть витневкстнэнь ванома лемрисьменть эйстэ', 'tog-watchlisthidebots' => 'Кекшить бот витневкстнэнь-петневкстнэнь ванома лемрисьсенть эйстэ', 'tog-watchlisthideminor' => 'Кекшить апокшкыне витневкстнэнь ванома лемрисьменть эйстэ', 'tog-watchlisthideliu' => 'Кекшемс совазь теицянь витнематнень-петнематнень, иляст неяво ванома лемрисьмесэ', 'tog-watchlisthideanons' => 'Кекшемс апак сова теицянь витнематнень-петнематнень, иляст неяво ванома лемрисьмесэ', 'tog-nolangconversion' => 'А меремс вариантонь полавтома лия лангс', 'tog-ccmeonemails' => 'Кучт монень копия е-сёрматнеде, конатнень кучан лия теицянень', 'tog-diffonly' => 'Иляк невтне лопапотмоксонть diffs ало', 'tog-showhiddencats' => 'Невтемс кекшень категориятнень', 'underline-always' => 'Свал', 'underline-never' => 'Зярдояк', 'underline-default' => 'Васнянь браузер', # Font style option in Special:Preferences 'editfont-style' => 'Витнема-петнема уминенть фонт стилезэ', 'editfont-serif' => 'Сериф шрифтэсь', # Dates 'sunday' => 'Таргочи', 'monday' => 'Атяньчи', 'tuesday' => 'Вастаньчи', 'wednesday' => 'Куншкачи', 'thursday' => 'Калоньчи', 'friday' => 'Сюконьчи', 'saturday' => 'Шлямочи', 'sun' => 'Тар', 'mon' => 'Атя', 'tue' => 'Вас', 'wed' => 'Кун', 'thu' => 'Кал', 'fri' => 'Сюк', 'sat' => 'Шля', 'january' => 'Якшамков', 'february' => 'Даволков', 'march' => 'Эйзюрков', 'april' => 'Чадыков', 'may_long' => 'Панжиков', 'june' => 'Аштемков', 'july' => 'Медьков', 'august' => 'Умарьков', 'september' => 'Таштамков', 'october' => 'Ожоков', 'november' => 'Сундерьков', 'december' => 'Ацамков', 'january-gen' => 'Якшамковонь', 'february-gen' => 'Даволковонь', 'march-gen' => 'Эйзюрковонь', 'april-gen' => 'Чадыковонь', 'may-gen' => 'Панжиковонь', 'june-gen' => 'Аштемковонь', 'july-gen' => 'Медьковонь', 'august-gen' => 'Умарьковонь', 'september-gen' => 'Таштамковонь', 'october-gen' => 'Ожоковонь', 'november-gen' => 'Сундерьковонь', 'december-gen' => 'Ацамковонь', 'jan' => 'Якш', 'feb' => 'Дав', 'mar' => 'Эйз', 'apr' => 'Чад', 'may' => 'Пан', 'jun' => 'Ашт', 'jul' => 'Мед', 'aug' => 'Ума', 'sep' => 'Таш', 'oct' => 'Ожо', 'nov' => 'Сун', 'dec' => 'Аца', # Categories related messages 'pagecategories' => '{{PLURAL:$1|Категория|Категорият}}', 'category_header' => '"$1" категориясонть лопатне', 'subcategories' => 'Алкскатегорият', 'category-media-header' => '"$1" категориясонть медиясь', 'category-empty' => "''Те категориясонть арасть лопат-медият.''", 'hidden-categories' => '{{PLURAL:$1|Кекшень категория|Кекшень категорият}}', 'hidden-category-category' => 'Кекшень категорият', 'category-subcat-count' => '{{PLURAL:$2|Те категориясонть вейкине явкс категория.|Те категориясонть {{PLURAL:$1|явкс категория|$1 явкс категорият}}, $2 -тнень эйстэ.}}', 'category-subcat-count-limited' => 'Те категориясонть {{PLURAL:$1|алкс категория|$1 алкс категорият}}.', 'category-article-count' => '{{PLURAL:$2|Те категориясонть вейкине лопась вана косо.|{{PLURAL:$1|Те лопась кандови|$1 Не лопатне кандовить}} те категориянтень, категориясонть лопатнеде весемезэ $2.}}', 'category-article-count-limited' => '{{PLURAL:$1|Те лопась|$1 Не лопатне}} те категориясонть.', 'category-file-count' => '{{PLURAL:$2|Те категориясонть вейкине файлась вана косо.|{{PLURAL:$1|Те файлась кандови|$1 Не файлатне кандовить}} те категориянтень, категориясонть файлатнеде весемезэ $2.}}', 'category-file-count-limited' => '{{PLURAL:$1|Те файлась|$1 Не файлатне}} вановиця категориянтень кандови.', 'listingcontinuesabbrev' => 'поладксозо моли', 'index-category' => 'Индекс марто лопатне', 'noindex-category' => 'Индекстэме лопатне', 'mainpagetext' => "'''МедияВикинь тевс аравтомазо парсте лиссь.'''", 'about' => 'Эстедензэ', 'article' => 'Потмокслопа', 'newwindow' => '(панжови од вальмасо)', 'cancel' => 'Саемс мекев', 'moredotdotdot' => 'Седе ламо...', 'mypage' => 'Монь лопам', 'mytalk' => 'Монь кортамом', 'anontalk' => 'Кортамс те IP-нть марто', 'navigation' => 'Навигация', 'and' => '&#32;ды', # Cologne Blue skin 'qbfind' => 'Мук', 'qbbrowse' => 'Ваномо-тееме', 'qbedit' => 'Витнеме-петнеме', 'qbpageoptions' => 'Те лопась', 'qbpageinfo' => 'Косо-зярдо', 'qbmyoptions' => 'Монь лопан', 'qbspecialpages' => 'Башка тевень лопат', 'faq' => 'Сеедьстэ кепедень кевкстемат', 'faqpage' => 'Project:Сеедьстэ кепедень кевкстемат', # Vector skin 'vector-action-addsection' => 'Поладомс мезде кортамс', 'vector-action-delete' => 'Нардамс', 'vector-action-move' => 'Печтевтемс', 'vector-action-protect' => 'Аравтомс ванстомас', 'vector-action-undelete' => 'Вельмевтемс нардазенть', 'vector-action-unprotect' => 'Ванстомасто саемс', 'vector-namespace-category' => 'Категория', 'vector-namespace-help' => 'Лезкс лопа', 'vector-namespace-image' => 'Файла', 'vector-namespace-main' => 'Лопа', 'vector-namespace-media' => 'Медиа лопа', 'vector-namespace-mediawiki' => 'Пачтямнэ', 'vector-namespace-project' => 'Проекттэ лопа', 'vector-namespace-special' => 'Башка тевень лопа', 'vector-namespace-talk' => 'Кортнема', 'vector-namespace-template' => 'Лопа парцун', 'vector-namespace-user' => 'Теицянь лопа', 'vector-view-create' => 'Теемс-Шкамс', 'vector-view-edit' => 'Витнемс-петнемс', 'vector-view-history' => 'Ваномс юронзо-путовксонзо', 'vector-view-view' => 'Ловномс', 'vector-view-viewsource' => 'Ваномс косто саезь', 'actions' => 'Тев теемат', 'namespaces' => 'Лемпотмот', 'variants' => 'Вариантт', 'errorpagetitle' => 'Ильведькс', 'returnto' => 'Велявтомс $1 лопантень.', 'tagline' => '{{SITENAME}} -нь пельде', 'help' => 'Лезкс', 'search' => 'Вешнэмс', 'searchbutton' => 'Вешнэк', 'go' => 'Адя', 'searcharticle' => 'Адя', 'history' => 'Лопань полавтнемат - витнемат', 'history_short' => 'Путовксонзо-йуронзо', 'updatedmarker' => 'меельседе сакшномадот мейле полавтовсь', 'info_short' => 'Мезе содамс', 'printableversion' => 'Ливтевиця версия', 'permalink' => 'Свалшкас сюлмавомапе', 'print' => 'Нолдамс', 'edit' => 'Витнеме-петнеме', 'create' => 'Тейть-шкак', 'editthispage' => 'Витнемс-петнемс те лопанть', 'create-this-page' => 'Теик-шкик те лопанть', 'delete' => 'Нардамс', 'deletethispage' => 'Нардамс те лопанть', 'undelete_short' => 'Велявтомс нардазенть {{PLURAL:$1|вейке витнема-петнема|$1 витнемат-петнемат}}', 'protect' => 'Аравтомс прянь ванстомас', 'protect_change' => 'полавтомс', 'protectthispage' => 'Аравтомс те лопанть ванстомас', 'unprotect' => 'Саемс прянь ванстомасто', 'unprotectthispage' => 'Саемс те лопанть ванстомасто', 'newpage' => 'Од лопа', 'talkpage' => 'Кортнемс те лопадонть', 'talkpagelinktext' => 'Кортнеме', 'specialpage' => 'Башка тевень лопа', 'personaltools' => 'Эсень кедьёнкст', 'postcomment' => 'Од явкс', 'articlepage' => 'Ваномс потмокслопанть', 'talk' => 'Кортнеме', 'views' => 'Ваномкат', 'toolbox' => 'Кедьёнкс парго', 'userpage' => 'Ваномонзо кирдицянть лопанзо', 'projectpage' => 'Ваномонзо проектенть лопанть', 'imagepage' => 'Ваномс файлань лопанть', 'mediawikipage' => 'Невтемензе сёрма паргонть лопанть', 'templatepage' => 'Ванномс лопапарцунонь лопанть', 'viewhelppage' => 'Ванномс лезкслопанть', 'categorypage' => 'Ванномс категориянь лопанть', 'viewtalkpage' => 'Ванномс мезде молить кортнемат', 'otherlanguages' => 'Лия кельсэ', 'redirectedfrom' => '(Ютавтозь $1 вельде)', 'redirectpagesub' => 'Лиясто ютавтозь лопа', 'lastmodifiedat' => 'Те лопанть меельседе витнезь-петнезь $2, $1.', 'viewcount' => 'Те лопантень совасть {{PLURAL:$1|весть|$1-ксть}}.', 'protectedpage' => 'Те лопась ванстомасо', 'jumpto' => 'Тёкадемс тей:', 'jumptonavigation' => 'Новигациясь-лездамось', 'jumptosearch' => 'вешнэме', # All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage) and the disambiguation template definition (see disambiguations). 'aboutsite' => '{{SITENAME}} ланга', 'aboutpage' => 'Project:Эстэдензэ', 'copyright' => '$1-сто муят мезе тесэ.', 'copyrightpage' => '{{ns:project}}:Ломанень видечинзэ', 'currentevents' => 'Мезе ней моли', 'currentevents-url' => 'Project:Мезе ней моли', 'disclaimers' => 'Видечинь кортамотне', 'disclaimerpage' => 'Project:Видечинь прякс кортнема', 'edithelp' => 'Витнемань-петнемань лезкс', 'edithelppage' => 'Help:Витнема-петнема', 'helppage' => 'Help:Лопась мезе кирди', 'mainpage' => 'Прякслопа', 'mainpage-description' => 'Прякслопа', 'policy-url' => 'Project:Политика', 'portal' => 'Велень-сядонь вальма', 'portal-url' => 'Project:Вейтьсэнь вальма', 'privacy' => 'Салавачинь политикась', 'privacypage' => 'Project:Салавачинь политикась', 'badaccess' => 'Меревемань асатыкс', 'badaccess-group0' => 'Тонеть а мерить теемс мезе вешить.', 'versionrequired' => 'МедияВикинь $1 версиясь эряви', 'versionrequiredtext' => 'МедияВикинь $1 версиясь эряви те лопанть тевс нолдамга. Вант [[Special:Version|версиянь лопанть]].', 'ok' => 'Маштови', 'retrievedfrom' => 'Лисмапрясь "$1"-сто', 'youhavenewmessages' => 'Тонеть сась $1 ($2).', 'newmessageslink' => 'Од пачтямнэть', 'newmessagesdifflink' => 'меельсе полавтома', 'youhavenewmessagesmulti' => 'Од сёрминеть учить эйсэть $1-со', 'editsection' => 'витнеме-петнеме', 'editold' => 'витнеме-петнеме', 'viewsourceold' => 'ваномс лисьмапрянть', 'editlink' => 'витнеме-петнеме', 'viewsourcelink' => 'ваномс лисьмапрянзо', 'editsectionhint' => '$1 секциянть-пельксэнть витнеме-петнеме', 'toc' => 'Потмокс', 'showtoc' => 'невтемс', 'hidetoc' => 'кекшемс', 'thisisdeleted' => '$1-нть ваномс эли велявтомс мекев?', 'viewdeleted' => 'Ванномс $1?', 'restorelink' => '{{PLURAL:$1|нардазь вейке витнема-петнема|нардазь $1 витнемат-петнемат}}', 'feedlinks' => 'Максовкс:', 'feed-invalid' => 'А маштови сёрмадстома каналонть сортозо.', 'site-rss-feed' => 'RSS-нть максовкс $1 -нть кисэ', 'site-atom-feed' => 'Atom-нть максовкс $1-нть кисэ', 'page-rss-feed' => '«$1» RSS максовкс', 'page-atom-feed' => '«$1» Atom максовкс', 'red-link-title' => '$1 (истямо лопа арась)', # Short words for each namespace, by default used in the namespace tab in monobook 'nstab-main' => 'Лопа', 'nstab-user' => 'Теицянь лопась', 'nstab-media' => 'Кулянь пачтямо керькстнэнь лопась', 'nstab-special' => 'Башка лопа', 'nstab-project' => 'Проектэнь лопа', 'nstab-image' => 'Файла', 'nstab-mediawiki' => 'Сёрмине', 'nstab-template' => 'Лопа парцун', 'nstab-help' => 'Лезкс лопа', 'nstab-category' => 'Категория', # Main script and global functions 'nosuchaction' => 'Истямо тев арась', 'nosuchspecialpage' => 'Истямо башка лопа арась', # General errors 'error' => 'Ильведькс', 'databaseerror' => 'Датабазань ильведькс', 'laggedslavemode' => 'Ванок: Кизды, лопасонть материалось таштомсь.', 'readonly' => 'Датабазась панжома экшсэ', 'enterlockreason' => 'Сёрмадт мейс сёлгамс эряви, ды ёвтак, зярдо таго арьсят панжови', 'missing-article' => 'Дата йуртсто а муеви эрявикс текстэсь, сонзэ лемезэ "$1" $2. Седе сеедьстэ истя лиси, зярдо таштомозь diff эли историянь сюлмавома песь вети нардань лопас. Лисиндерясь аволь истя, можок муить программа керьксстэнть (тапавкс тарка) сийне. Пачтта сёрмине теде [[Special:ListUsers/sysop|системань ветийнень]] URL адресэнть тештязь.', 'missingarticle-rev' => '(лиякстомтома#: $1)', 'missingarticle-diff' => '(Мейсэ явовить: $1, $2)', 'internalerror' => 'Потмонь ильведькс', 'internalerror_info' => 'Потмонь ильведькс: $1', 'filecopyerror' => '"$1" файлась эзь ванстово од "$2" файлакс.', 'filerenameerror' => 'Файлантень а маштови "$1" максомс од лем "$2".', 'filedeleteerror' => '"$1" файлась шукшпряв эзь ливтеве.', 'directorycreateerror' => '"$1" директориясь а тееви.', 'filenotfound' => '"$1" файлась а муеви.', 'fileexistserror' => 'Файлась "$1" а сёрмадови: ули уш истямо', 'unexpected' => 'Апак учонь вейкетстямо: "$1"="$2".', 'formerror' => 'Ильведевкс: Формась а кучови', 'badarticleerror' => 'Те лопасонть вешезь тевесь а тееви.', 'badtitle' => 'Амаштовикс конякс', 'badtitletext' => 'Вешезь лопанть лемезэ аволь виде, чаво, эли аволь видестэ сюлмазь келеньйутковань эли интервикинь лем. Паряк, лемсэнть тевс нолдазь анолдавикс тешкст.', 'viewsource' => 'Ванномс лисьмапрянть', 'viewsourcefor' => ' $1 -нь юртозо', 'actionthrottled' => 'Тев тееманть курокксчизэ киртязь', 'protectedpagetext' => 'Те лопась панжома экшсэ, илязо понго витнемс - петнемс киненьгак.', 'viewsourcetext' => 'Те лопанть лисьмапрясь маштови ваномскак, лангстонзо саемс копияяк:', 'sqlhidden' => '(SQL вешнемась кекшезь)', 'ns-specialprotected' => '{{ns:special}} лем марто лопатне а витневить-петневить.', 'titleprotected' => "Те коняксонть ванстызе [[Теиця:$1|$1]], кияк иляссо тее. Тувталось вана ''$2''.", # Virus scanner 'virus-scanfailed' => 'сканнось эзь лисе (код $1)', 'virus-unknownscanner' => 'апак содань антивирус:', # Login and logout pages 'welcomecreation' => '== Совак, инеськеть, $1! == Совамотаркат теезь. Иля стувто полавтнемс эсеть [[Special:Preferences|{{SITENAME}} ладсематнень]].', 'yourname' => 'Теицянь лем:', 'yourpassword' => 'Совамо валот:', 'yourpasswordagain' => 'Омбоцеде сёрмадык кирдицянь леметь:', 'remembermypassword' => 'Ледстемс монь совамо валонть те арсемашинасонть', 'yourdomainname' => 'Эсеть доменэть:', 'login' => 'Совамо', 'nav-login-createaccount' => 'Совамо / тейть совамотарка', 'loginprompt' => '{{SITENAME}} сайтэнтень совамга эряви нолдамс тевс cookies.', 'userlogin' => 'Совамо / тейть совамотарка', 'userloginnocreate' => 'Совамо', 'logout' => 'Лисеме', 'userlogout' => 'Лисеме', 'notloggedin' => 'Апак соваво', 'nologin' => "Совамотаркат арась? '''$1'''.", 'nologinlink' => 'Тейть совамотарка', 'createaccount' => 'Теемс теицянь од лопа', 'gotaccount' => "Совамотаркат ули? '''$1'''.", 'gotaccountlink' => 'Совамс', 'createaccountmail' => 'е-сёрмасо', 'badretype' => 'Сёрмадыть совамо валот кавксть, сынь аволь вейкеть.', 'userexists' => 'Те лемесь уш саезь. Арсека эсеть лия, инеськеть.', 'loginerror' => 'Совамсто ильведькс', 'createaccounterror' => 'Совамо тарка эзь теевть: $1', 'nocookiesnew' => 'Совамо таркась шкавсь, ансяк зярс эзить сова. {{SITENAME}} сайтэв совават cookies функция вельде. Содымашинасот cookies функциятне тевс апак нолда. Васня нолдытя функциятнень тевс, мейле совак: сёрмадыть од теицянь леметь ды совамо валот.', 'noname' => 'Зярс эзить максо кемекстазь теицянь лем.', 'loginsuccesstitle' => 'Совавить', 'loginsuccess' => "'''Тон совить {{SITENAME}}-с кода \"\$1\".'''", 'nosuchuser' => '$1 лем марто теиця арась. Теиця лемтне явозь тень корясь вишка эли покш тештинесэ сёрмадозь. Ваннык видестэ - а видестэ сёрмадык, эли [[Special:UserLogin/signup|тейть-шкак од совамо тарка]].', 'nosuchusershort' => '"<nowiki>$1</nowiki>" лемсэ теиця арась. Варштака, кизды, аволь истя сёрмадозь.', 'nouserspecified' => 'Теицянь лем эряви.', 'wrongpassword' => 'Аволь истя сёрмадык совамо валот. Варчыка одов.', 'wrongpasswordempty' => 'Салавань валот кадовсь апак сёрмадо. Сёрмадыка одов.', 'passwordtooshort' => 'Совамо валонть кувалмозо {{PLURAL:$1|улезэ 1 тешкс| улезт $1 тешкст}}, аволь седе аламо.', 'mailmypassword' => 'Кучт е-сёрмасо од совамо вал', 'passwordremindertitle' => '{{SITENAME}} туртов акуватень од совамо вал', 'passwordremindertext' => 'Кие-бути (кода неяви тон IP-тешксстэнть $1) вешсь,<br /> кедьстэнек кучомс теицянь од совамо вал {{SITENAME}} ($4) сайтс совамга.<br /> Теицянтень "$2" кучозь нурькине шкань совамо вал, конась ней "$3".<br /> Бути те тон ульнить, сави ней совамс ды кочкамс од совамо вал эстеть.<br /> Нурькине шкань совамо валот нолдави тевс {{PLURAL:$5|вейке чи|$5 чить}}. Бути аволь тон вешицясь, эли мелезэть ледстик совамо валонть, иля яво мель те пачтямнэнтень. Нолдык тевс мельсэ аштицянть - мельс ледстязенть.', 'noemail' => '"$1" теицянть арась е-сёрмапаргозо.', 'passwordsent' => '$1 -нь е-сёрмань адресэнтень кучозь од совамо вал.<br /> Инеськеть, кодак валось пачкоди, совака одов.', 'eauthentsent' => 'Электрононь адресэзэть кучозь кемекстамонь е-сёрмине.<br /> Сонзэ эйсэ сёрмадозь мезе кода теемс. Ансяк седе мейле, зярдо невтик, адресэсь алкукс эсеть, карматано кучомо лия сёрмат.', 'mailerror' => 'Е-сёрма кучомсто ильведькс: $1', 'acct_creation_throttle_hit' => 'Те викисэ тонь IP адресстэть совасть теицят, конат теисть {{PLURAL:$1|1 сёрмадовкс|$1 сёрмадовкст}} меельсе чынть перть, седе ламо полавтомат а мерить теемс истя зняронь шкань перть. Тень кисэ, те IP адресэнть коряс седе тов а маштови теемс-шкамс од сёрмадовкст, зярс.', 'emailauthenticated' => 'Е-сёрма паргот кемекстазель $2 чыстэ $3 цяссто.', 'emailconfirmlink' => 'Кемекстык е-сёрмапаргот', 'accountcreated' => 'Совамо таркась теезь', 'accountcreatedtext' => '$1-нь совицянь таркась теевсь-шкавсь.', 'loginlanguagelabel' => 'Кель: $1', # Password reset dialog 'resetpass' => 'Полавтомс совамо валот', 'resetpass_header' => 'Полавтомс совамо валот', 'oldpassword' => 'Ташто совамо валот:', 'newpassword' => 'Од совамо валот:', 'retypenew' => 'Сёрмадык омбоцеде совамо валот:', 'resetpass_submit' => 'Тештик совамо валот ды совак', 'resetpass_success' => 'Совамо валот полавтовсь теть! Совавтыть эйсэть системас...', 'resetpass_forbidden' => 'Совамо валтнэ а полавтовить', 'resetpass-submit-loggedin' => 'Полавтомс совамо валот', 'resetpass-temp-password' => 'А куватень совамо валось:', # Edit page toolbar 'bold_sample' => 'Эчке текст', 'bold_tip' => 'Эчке текст', 'italic_sample' => 'Комавтонь текст', 'italic_tip' => 'Комавтонь текст', 'link_sample' => 'Сюлмавомапень конякс', 'link_tip' => 'Потмоёндонь сюлмавомапе', 'extlink_sample' => 'http://www.example.com налткенть лемезе', 'extlink_tip' => 'Ушо ёнксонь сюлмавкс / налтке (мельсэ кирдить http:// путовксонть)', 'headline_sample' => 'Конякссонть текстэсь', 'headline_tip' => 'Омбоце эскельксэнь конякс', 'math_sample' => 'Совавтомс тезэнь хвормула', 'math_tip' => 'Математикань хвормула (LaTeX)', 'nowiki_sample' => 'Совавтомс хворматтомо текст тезэнь', 'nowiki_tip' => 'Wiki -нь поладомантень-витнемантень мель апак яво', 'image_sample' => 'Саемга.jpg', 'image_tip' => 'Путонь медия файла', 'media_sample' => 'Саемга.ogg', 'media_tip' => 'Медия файлантень сюлмавома пе (налтке)', 'sig_tip' => 'Шка марто кедь путовксот', 'hr_tip' => 'Менель кирьксэнь кикс (тевс нолдыть ванстозь)', # Edit pages 'summary' => 'Вейсэндязь:', 'subject' => 'Сёрмадовксонть лемезэ:', 'minoredit' => 'Те апокшкэ витнема-петнема', 'watchthis' => 'Ваномс те лопанть мельга', 'savearticle' => 'Ванстомс лопанть', 'preview' => 'Васнянь неевтезэ', 'showpreview' => 'Максомс васнянь невтевкс', 'showlivepreview' => 'Эряй васнянь невтевкс', 'showdiff' => 'Невтемс мезе полавтовсь', 'anoneditwarning' => "'''Ванок:''' Зярс эзить сова. IP адресэть совавтови те лопанть витнема-петнема икелькс умантень.", 'missingcommenttext' => 'Инеськеть мелеть-арьсемат путта тезэнь алов.', 'summary-preview' => 'Цётомань седеикелев вановкс:', 'subject-preview' => 'Темань/коняксонь васнянь невтема:', 'blockedtitle' => 'Совицясь кардазь', 'blockedtext' => "'''Тонть теицянь леметь эли IP-тешкстэть совавтозь саймас.''' Саймас совавтынзеть $1 прявт кирдицясь. Максозь истямо тувталось: ''«$2»''. * Саймас совавтозят: $8 * Саймасто нолдамсат: $6 * Саймас совавтозесь: $7 Ули мелеть пачтт сёрма теицянтень $1 эли лиятненень [[{{MediaWiki:Grouppage-sysop}}|прявт кирдицятненень]], сынст марто маштови кортамс саймас совавтомадонть. Мель явт, эзик максо е-почта сёрмапаргот (адресэть) [[Special:Preferences|эсеть аравтоматнесэ]], а нолдави тевс 'сёрмадт те теицянтень' функциясь. Истяжо функциясь а нолдави сестэяк, зярдо тосояк саймас совавтозят. IP-тешкстэть — $3, саймас совавтоманть ID-сь — #$5. Инескеть, кевкстемат улить, невттяя нетнень лангс.", 'blockednoreason' => 'тувтал апак максо', 'blockedoriginalsource' => "'''$1''' -нть лисьмапрясь ало неяви:", 'whitelistedittitle' => 'Витнемань-петнемань теемга эряви совамо лем', 'whitelistedittext' => 'Лопанть витнемс - петнемс эряви $1.', 'nosuchsectiontitle' => 'Явксось а муеви', 'loginreqtitle' => 'Совамс эряви', 'loginreqlink' => 'совамс', 'loginreqpagetext' => 'Лия лопань ванномга, эряви $1.', 'accmailtitle' => 'Салавань вал кучозь.', 'accmailtext' => "Кода понгсь теезь совамо вал [[User talk:$1|$1]]-нь туртов кучозь $2 адресэнтень. Те од совамо таркас совамо валось полавтови ''[[Special:ChangePassword|совамо валонь полавтома]]'' лопас совамодо мейле.", 'newarticle' => '(Од)', 'newarticletext' => "Молить налтке мельга сёрмадовксос, конась апак тее. Ули мелеть теемс сёрмадовкс, сёрмадт валт ало паргос (вант [[{{MediaWiki:Helppage}}|help page]] тесэ лездамо информация). Лисиндеряй тесэ ильведькс, лепштик браузерсэ '''back''' повнэнть.", 'noarticletext' => 'Неень шкасто те лопасонть сёрмадовкс арась. Мусак [[Special:Search/{{PAGENAME}}|вешнемс файлань те конякс]] лия сёрмадовкстнэстэ <span class="plainlinks"> [{{fullurl:{{#Special:Log}}|page={{FULLPAGENAMEE}}}} вешнемс малавикс журналтнэстэ], эли [{{fullurl: {{FULLPAGENAME}}|action=edit}} витнемс-петнемс те лопанть]</span>.', 'updated' => '(Одолгавтозь)', 'note' => "'''Явт мель:'''", 'previewnote' => "'''Те - ансяк васнянь невтевкс; полавтоматне зярс апак вансто!'''", 'editing' => 'Витнят-петнят $1', 'editingsection' => 'Витнеме-петнеме $1 (секциянть)', 'editingcomment' => 'Витнят-петнят $1 (од явкс)', 'editconflict' => 'Витнемадо-петнемадо аладямо: $1', 'yourtext' => 'Мезе сёрмадыть', 'storedversion' => 'Ванстозь версия', 'yourdiff' => 'Мейсэ явовить', 'copyrightwarning' => "Инескеть кирдть мельсэ {{SITENAME}}-сэ весе путовкстнэнь, лововить нолдазекс ало $2 конёвонть коряс (вант $1 педе пес). Арась мелеть витневтемс-петневтемс сёрмадовксот педе пес, иляк сестэ путо сонзэ тезэнь.<br /> Истяжо тезэнь материалонь максомсот, кемекстат тон тонсь сёрмадык сонзэ, али саик сонзэ вейсэнь ёнксто али олячинь порталсто. '''ИЛЯ МАКСО ВАНСТОНЬ ВИДЕЧИСЭ ЛОМАНЕНЬ ВАЖОДЕМАНТЬ АПАК КЕВКСТНЕ!'''", 'longpagewarning' => "'''ВАНОК: Те лопанть сталмозо $1 килобайтт; конат-конат интерчаматнесэ-браузертнэсэ стакасто витнемс-петнемс сёрмадовкс 32-во kб сталмосо али седе стака. Инеськеть, паро улевель лопанть явомс вишка пельксекс.'''", 'titleprotectedwarning' => "'''ВАНОК: Те лопась сёлгозь, сонзэ шкамга-теемга [[Special:ListGroupRights|башка видечыть]] эрявить.''' Журналонь меельсе сёрмадовксось максозь ало, эрявиндеряй сонзэ ваномс.", 'templatesused' => 'Те лопасонть тевс нолдазь {{PLURAL:$1|лопа парцун|лопа парцунт}}:', 'templatesusedpreview' => 'Те икелькс вановкссонть тевс нолдазь {{PLURAL:$1|лопа парцун|лопа парцунт}}:', 'templatesusedsection' => 'Те пелькссэнть тевс нолдазь {{PLURAL:$1|лопа парцунось|лопа парцунтнэ}}:', 'template-protected' => '(ванстозь)', 'template-semiprotected' => '(пельс ванстозь)', 'hiddencategories' => 'Те лопась совавтови {{PLURAL:$1|кекшень 1 категорияс|кекшень $1 категорияс}}:', 'nocreatetitle' => 'Лопань теемась аволь певтеме', 'nocreatetext' => 'Те {{SITENAME}} лопасонть пирязь од лопань теемась. Тонь ули мелеть велявтомс удалов ды питнемензе-витнемензе улиця лопанть, али [[Special:UserLogin|совамс али теемс од совама]].', 'nocreate-loggedin' => 'Тонеть а мерить теемс-шкамс од лопат.', 'permissionserrorstext' => 'Тонеть а мерить теемс тень, вана {{PLURAL:$1|тувталось|тувталтнэ}}:', 'permissionserrorstext-withaction' => 'Тонеть а мерить теемс $2, {{PLURAL:$1|тувталось|тувталтнэ}} вана:', 'recreate-moveddeleted-warn' => "'''Ванок: Вельмевтят лопа, кона нардазель.''' Васня арьсек, эряви - а эряви полалемс ды витнемс-петнемс те лопанть. Те лопанть нардамодо ды печтевтемадо путовкстнэ одов максозь тесэ, улезт шожда ванстнемс:", 'moveddeleted-notice' => 'Те лопась нардазь. Лопанть нардамодо сёрмадовксось максозь вана ало.', 'edit-conflict' => 'Витнемань-петнемань аладямо.', 'edit-already-exists' => 'Од лопась кодаяк эзь тееве; сон уш ули.', # Parser/template warnings 'post-expand-template-argument-category' => 'Лопатнесэ улить лопа парцунонь нардань аргументт', 'parser-template-loop-warning' => 'Лопа парцунсто "чары реве" муевсь: [[$1]]', # Account creation failure 'cantcreateaccounttitle' => 'Сёрмадома таркынесь а тееви', # History pages 'viewpagelogs' => 'Ванномс те лопас совамодо-лисемадо тевть', 'nohistory' => 'Те лопанть витнемадо-петнемадо икелькс умазо арась.', 'currentrev' => 'Тевате лиякстомтома', 'currentrev-asof' => 'Неень верзиясь истямо шкань $1', 'revisionasof' => '$1-це версиясь', 'revision-info' => '$1 -нь лиякстомтома, конань теизе $2', 'previousrevision' => '←Седе икелень лиякстомтома', 'nextrevision' => 'Седе од вановкс→', 'currentrevisionlink' => 'Тевате лиякстомтома', 'cur' => 'неень', 'next' => 'сыця', 'last' => 'меельсе', 'page_first' => 'васенце', 'page_last' => 'меельсе', 'histlegend' => "Версиняь кочкамось: тешксты невтезь верисятнень, али лепштик Enter повнэнть.<br /> Чарькодевтемат: (молиц.) = редямось молиця версиястонть; (и. молиц.) = редямось икеле молиця версиястонть; '''а''' = аволь седе ламо лиякстомтома.", 'history-fieldset-title' => 'Ваномс лопанть юронзо-путовксонзо', 'history-show-deleted' => 'Ансяк нардазь', 'histfirst' => 'Васенце', 'histlast' => 'Меельсе', 'historysize' => '({{PLURAL:$1|1 байт|$1 байтт}})', 'historyempty' => '(чаво)', # Revision feed 'history-feed-title' => 'Лиякстомтомань тевде', 'history-feed-description' => 'Викинь тевате лопанть лиякстомтомань тевдензэ', 'history-feed-item-nocomment' => '$1 $2-зэ', # Revision deletion 'rev-deleted-comment' => '(арсемась-мелесь нардазь)', 'rev-deleted-user' => '(теицянь лемесь нардазь)', 'rev-deleted-event' => '(сёрмадсткэсь нардазь)', 'rev-delundel' => 'невтемс/кекшемс', 'rev-showdeleted' => 'невтемс', 'revisiondelete' => 'Нардамс/вельмевтемс лиякстомтоматнень', 'revdelete-nologtype-title' => 'Журнал типесь апак максо', 'revdelete-selected' => "'''[[:$1]]-нь {{PLURAL:$2|Кочкань лиякстомтомась|Кочкань лиякстомтоматне}}:'''", 'revdelete-legend' => 'Аравтомс неявомачынь петне', 'revdelete-hide-text' => 'Кекшемс лиякстомтомань текстэнть', 'revdelete-hide-image' => 'Кекшемс мезе файлатнесэ', 'revdelete-hide-name' => 'Кекшемс тев тееманть ды норовамо тарканзо', 'revdelete-hide-comment' => 'Кекшемс витнемадо-петнемадо арсематнень', 'revdelete-hide-user' => 'Кекшемс витницянть-петницянть теиця лемензэ/IP-нзэ', 'revdelete-log' => 'Тувталось:', 'revdelete-submit' => 'Аравтомс кочказь {{PLURAL:$1|лиякстомтомантень|лиякстомтоматненень}}', 'revdelete-logentry' => '[[$1]]-нть лиякстомтоманть неявомазо полавтовсь', 'revdel-restore' => 'Полавтомс неявомачынзэ', 'pagehist' => 'Лопанть икелькс умазо', 'deletedhist' => 'Нардань икелькс умазо', 'revdelete-content' => 'потмозо', 'revdelete-summary' => 'витнемадо-петнемадо нурькине йовтавкс', 'revdelete-uname' => 'Совицянь леметь', 'revdelete-hid' => '$1 кекшезь', 'revdelete-unhid' => '$1 ливтезь лангс', 'revdelete-log-message' => '$1 $2 {{PLURAL:$2|лиякстомтомань туртов|лиякстомтоматнень туртов}}', 'revdelete-reasonotherlist' => 'Лия тувтал', 'revdelete-edit-reasonlist' => 'Витнемс-петнемс нардамонь тувталтнэсэ', 'revdelete-offender' => 'Версиянть теицязо:', # History merging 'mergehistory' => 'Совавтомс лопатнень лиякстомтомадо сёрмадовкстнэнь ве лувс', 'mergehistory-box' => 'Совавтомс кавто лопатнень лиякстомтомадо сёрмадовкстнэнь ве лувс:', 'mergehistory-from' => 'Лисьмапря лопа:', 'mergehistory-into' => 'Совавтома лопа:', 'mergehistory-list' => 'Вейтьсэндявиця юронзо-путовксонзо', 'mergehistory-go' => 'Невтемс вейтьс совавтомкс витнемат-петнемат', 'mergehistory-submit' => 'Совавтомс лиякстомтоматнень вейтьс', 'mergehistory-empty' => 'Вейкеяк лиякстомтома а совавтови вейтьс лия марто.', 'mergehistory-no-source' => 'Лисьмапрянь $1 лопась арась.', 'mergehistory-no-destination' => 'Норовазь $1 лопась арась.', 'mergehistory-invalid-source' => 'Ливтемкс лопанть улезэ маштовикс лем.', 'mergehistory-invalid-destination' => 'Совавтомкс лопанть улезэ маштовикс лем.', 'mergehistory-autocomment' => 'Совавтомс [[:$1]] [[:$2]]-с', 'mergehistory-reason' => 'Тувталось:', # Merge log 'mergelog' => 'Вейтьсэндямс логонть', 'revertmerge' => 'Явомс логонть мекев, кода ульнесь вейтьсэндямодо икеле', # Diffs 'history-title' => 'Историясь ламо вановксонть "$1"', 'difference' => '(Явовкс ванокснень юткова)', 'lineno' => 'Киксэсь $1:', 'compareselectedversions' => 'Кочказь версиятнень аравтомс карадо-каршо', 'editundo' => 'Велявтомс мекев мезе витнинь-петнинь', 'diff-multi' => '({{PLURAL:$1|$1 юткине версиясь апак невте|$1 юткине версиятне апак невте|$1 юткине версиятнеде апак невте.}})', # Search results 'searchresults' => 'Мезе муевсь', 'searchresults-title' => 'Мезе муевсь "$1" вешнемасо', 'searchresulttext' => '{{SITENAME}} сайтсэ вешнэмадо седе ламо содамга вант [[{{MediaWiki:Helppage}}|кевкстемань пельксэнть]].', 'searchsubtitle' => 'Вешнить \'\'\'[[:$1]]\'\'\' ([[Special:Prefixindex/$1|весе лопатне "$1" лопасто саезь]]{{int:pipe-separator}}[[Special:WhatLinksHere/$1|"$1" лопа марто сюлмазь весе лопатне]])', 'searchsubtitleinvalid' => "Вешнить '''$1'''", 'titlematches' => 'Лопанть коняксонзо марто вейтьс прась', 'notitlematches' => 'Лопанть коняксонзо марто вейтьс прамот арасть', 'textmatches' => 'Лопанть сёрмадсткэнзэ марто вейтьс прамот', 'notextmatches' => 'Лопанть сёрмадсткэнзэ марто вейтьс прамот арасть', 'prevn' => 'седе икелень {{PLURAL:$1|$1}}', 'nextn' => 'сы {{PLURAL:$1|$1}}', 'viewprevnext' => 'Ванномс ($1 {{int:pipe-separator}} $2) ($3)', 'searchmenu-legend' => 'Вешнемань аравтомкат', 'searchmenu-exists' => "'''Те викисэнть ули \"[[\$1]]\" лем марто лопа'''", 'searchhelp-url' => 'Help:Лопась мезе кирди', 'searchprofile-articles' => 'Потмокс лопат', 'searchprofile-project' => 'Лезкс ды проекттэ лопат', 'searchprofile-images' => 'Мультимедия', 'searchprofile-everything' => 'Весе', 'searchprofile-articles-tooltip' => 'Вешнемс вана тестэ $1', 'searchprofile-project-tooltip' => 'Вешнемс вана тестэ $1', 'searchprofile-images-tooltip' => 'Вешнемс файлат', 'search-result-size' => '$1 ({{PLURAL:$2|1 вал|$2 валт}})', 'search-redirect' => '(йутавтт $1-с)', 'search-section' => '(пелькс $1)', 'search-suggest' => 'Истя мерикскелить: $1', 'search-interwiki-caption' => 'Дугакс проектт', 'search-interwiki-default' => '$1 савкс:', 'search-interwiki-more' => '(седе ламо)', 'search-mwsuggest-enabled' => 'ушодкс марто', 'search-mwsuggest-disabled' => 'ушодкстомо', 'search-relatedarticle' => 'Малавикс', 'searchrelated' => 'малавикс', 'searchall' => 'весе', 'nonefound' => "'''Ванта''': Башка лем потмонь апак аравто ансяк кона-кона лем потмот понгить вешнэма таркакс. Аравтта вешнэма икельксэкс ''all:'', зярдо мель саят вешнэмс эрьва кодамо таркасто (сайсынек: кортнема лопатнень, лопа парцунтнэнь, ды седе тов), лиякс аравтыка эрявикс лем потмонть вешнэма икельксэкс.", 'powersearch' => 'Седеяк вешнемс', 'powersearch-legend' => 'Седе келейстэ вешнема', 'powersearch-ns' => 'Вешнемс не лем потмотнестэ:', 'powersearch-redir' => 'Лия таркав йутавтоматнень сёрмалема', 'powersearch-field' => 'Вешнемс', 'powersearch-toggleall' => 'Весе', 'search-external' => 'Ушо йондонь вешнема', # Quickbar 'qbsettings' => 'Навигациянь лазнэ', 'qbsettings-none' => 'Арась мезе невтемс', 'qbsettings-fixedleft' => 'Керш ёндо кирдезь', 'qbsettings-fixedright' => 'Вить ёндо кирдезь', 'qbsettings-floatingleft' => 'Керш ёнга уи', 'qbsettings-floatingright' => 'Вить ёнга уи', # Preferences page 'preferences' => 'Лия ютксто явома', 'mypreferences' => 'Мейсэ явован лиятнень эйстэ', 'prefs-edits' => 'Зяроксть витнезь-петнезь:', 'prefsnologin' => 'Эзить сова', 'changepassword' => 'Салавань валонь полавтома', 'prefs-skin' => 'Неемань ладсема', 'skin-preview' => 'Васнянь неевтезэ', 'prefs-math' => 'Математика', 'datedefault' => 'Икелькс вешема арась', 'prefs-datetime' => 'Чи ды шка', 'prefs-personal' => 'Теицядо', 'prefs-rc' => 'Чиень полавтнемат', 'prefs-watchlist' => 'Ванома лемрисьме', 'prefs-watchlist-days-max' => '(сех ламо 7 чить)', 'prefs-misc' => 'Минеть-сюнот', 'prefs-resetpass' => 'Совамо валонь полавтомо', 'saveprefs' => 'Ванстомс', 'resetprefs' => 'Нардамс апак вансто полавтнемат', 'prefs-editing' => 'Витнема-петнема', 'prefs-edit-boxsize' => 'Витнема-петнема вальманть сэрензэ-келензэ.', 'rows' => 'Вал чилькстнэ (строкатне):', 'columns' => 'Палманть:', 'searchresultshead' => 'Вешнэма', 'resultsperpage' => 'Зяроксть вастневи ве лопасо:', 'contextlines' => 'Зяро рисьметь эрьва муевкссэ:', 'recentchangesdays-max' => '(максимумось $1 {{PLURAL:$1|чи|чить}})', 'timezonelegend' => 'Шкань зонась:', 'localtime' => 'Теицянь шкась:', 'servertime' => 'Серверэнь шкась:', 'guesstimezone' => 'Пештемс интернет икельксстэть', 'timezoneregion-africa' => 'Африка', 'timezoneregion-america' => 'Америка', 'timezoneregion-antarctica' => 'Антарктика', 'timezoneregion-arctic' => 'Арктика', 'timezoneregion-asia' => 'Азия', 'timezoneregion-atlantic' => 'Атлантикань иневедь', 'timezoneregion-australia' => 'Австралия', 'timezoneregion-europe' => 'Эвропа', 'timezoneregion-indian' => 'Индиянь иневедь', 'timezoneregion-pacific' => 'Сэтьме иневедь', 'prefs-namespaces' => 'Лем потмот', 'default' => 'зярдо лиякс апак йовта', 'prefs-files' => 'Файлат', 'youremail' => 'Е-сёрма:', 'username' => 'Теицянь леметь:', 'uid' => 'Теицянь ID:', 'yourrealname' => 'Алкуксонь леметь:', 'yourlanguage' => 'Келесь:', 'yournick' => 'Кедень путома:', 'badsiglength' => 'Кедень путомат пек кувака. Эйсэнзэ иляст уле $1 -до ламо {{PLURAL:$1|тешкст|тешкст}}.', 'yourgender' => 'Сыметь (цёрань-тейтерень):', 'gender-unknown' => 'апак невте', 'gender-male' => 'цёрань сыме', 'gender-female' => 'Авань сыме', 'email' => 'Е-сёрма', 'prefs-help-realname' => 'Алкуксонь леметь (арась мелеть, иляк путо): путсак, ды сон карми неявомо не таркатнесэ, косо тон тев теят.', 'prefs-help-email-required' => 'Е-сёрмань адресэть эряви.', 'prefs-signature' => 'Кедь путовкс', 'prefs-dateformat' => 'Ков чинь форматозо', 'prefs-diffs' => 'Мейсэ явовить верзиятне', # User rights 'userrights-lookup-user' => 'Сови куротнень ветямось', 'userrights-user-editname' => 'Сёрмадт теицянь лем:', 'editusergroup' => 'Витнемс-петнемс сови куротнень', 'saveusergroups' => 'Ванстомс сови куротнень', 'userrights-reason' => 'Тувталось:', 'userrights-changeable-col' => 'Курот, конат тонеть полавтовить', 'userrights-unchangeable-col' => 'Курот, конат тонеть а полавтовить', # Groups 'group' => 'Группа:', 'group-user' => 'Совицятне', 'group-autoconfirmed' => 'Сынсь кемекстазь сёрмадыцят', 'group-bot' => 'Ботт', 'group-sysop' => 'Администраторт', 'group-bureaucrat' => 'Бюрократт', 'group-all' => '(весе)', 'group-user-member' => 'Совицясь', 'group-autoconfirmed-member' => 'Сонсь кемекстазь сёрмадыця', 'group-bot-member' => 'Бот', 'group-sysop-member' => 'Администратор', 'group-bureaucrat-member' => 'Бюрократ', 'grouppage-user' => '{{ns:project}}:Совицятне', 'grouppage-bot' => '{{ns:project}}:Ботт', 'grouppage-sysop' => '{{ns:project}}:Администраторт', 'grouppage-bureaucrat' => '{{ns:project}}:Бюрократт', # Rights 'right-read' => 'Лопатнень ловномо', 'right-edit' => 'Лопатнень витнеме-петнеме', 'right-createpage' => 'Теемс-шкамс лопат (аволь кортнема лопат)', 'right-createtalk' => 'Теемс-шкамс кортнема лопат', 'right-createaccount' => 'Теемс-шкамс совицянь од таркат', 'right-minoredit' => 'Тешкстамс витнематнень-петнематнень а покшкынекс', 'right-move' => 'Ютавтомс лопат лияв', 'right-move-subpages' => 'Печтевтемс лопатнень алкс лопанек', 'right-movefile' => 'Печтевтемс файлат', 'right-upload' => 'Ёвкстамс файлат', 'right-reupload' => 'Одонь сёрмадомга уликс файланть нардамс', 'right-upload_by_url' => 'Ёвкстамс файлат URL адресстэ', 'right-delete' => 'Нардамс лопатнень', 'right-bigdelete' => 'Нардамс кувака икелькс ума марто лопатнень', 'right-browsearchive' => 'Вешнемс нардань файлатнесэ', 'right-undelete' => 'Вельмевтемс нардань лопа', 'right-block' => 'Кардамс лия совийтнень-лисийтнень витнемадо-петнемадо', 'right-blockemail' => 'Кардамс лия лисийтнень-совийтнень е-сёрмань кучомадо', 'right-editinterface' => 'Витнемс-петнемс теицянь интерчаманть (васодема йожонть)', 'right-editusercssjs' => 'Витнемс-петнемс лия теицятнень CSS ды JS файласт', 'right-editusercss' => 'Витнемс-петнемс лия теицятнень CSS файласт', 'right-edituserjs' => 'Витнемс-петнемс лия теицятнень JS файласт', 'right-import' => 'Ёвкстамс лия Викистэ лопат', 'right-mergehistory' => 'Вейтьсэндямс лопатнень юрост-путовксост', 'right-userrights' => 'Витнемс-петнемс совицянь весе видечитнень', 'right-siteadmin' => 'Датабазань сёлгомо ды панжомо', # User rights log 'rightslog' => 'Уськетеицянть видечинть кемекстома', 'rightsnone' => '(арасть)', # Associated actions - in the sentence "You do not have permission to X" 'action-read' => 'те лопань ловномо', 'action-edit' => 'те лопанть витнеме-петнеме', 'action-createpage' => 'лопань тееме-шкамо', 'action-createtalk' => 'кортнема лопань тееме-шкамо', 'action-minoredit' => 'Тешкстамс те витнеманть-петнеманть а покшкынекс', 'action-move' => 'печтевтемс те лопанть', 'action-move-subpages' => 'печтевтемс те лопанть, ды алонзо весе лопатнень', 'action-move-rootuserpages' => 'печтевтемс теицянь юрт лопатнень', 'action-movefile' => 'печтевтемс те файланть', 'action-upload' => 'йовкстамс те файланть', 'action-reupload' => 'уликс файланть полавтомс одонть марто', 'action-delete' => 'нардамс те лопанть', 'action-deleterevision' => 'нардамс те лиякстомтоманть', 'action-browsearchive' => 'вешнемс нардань лопатнестэ', 'action-undelete' => 'вельмевтемс мекев те лопанть', 'action-import' => 'совавтомс те лопанть лия Викистэ', 'action-importupload' => 'совавтомс те лопанть файлань йовкстамо юртсто', # Recent changes 'nchanges' => '$1 {{PLURAL:$1|полавтнема|полавтнемат}}', 'recentchanges' => 'Чыяконь полавтнемат-лиякстомтомат', 'recentchanges-legend' => 'Улконь полавтнематнень аравтнемаст', 'recentchanges-feed-description' => 'Мельга ваннынк кода ульнесть витьнемат-петнемат wiki-сэ те максовксонть.', 'recentchanges-legend-newpage' => '$1, те - од лопа', 'recentchanges-label-newpage' => 'Те витнемась-петнемась од лопа тейсь', 'recentchanges-legend-minor' => '$1, те - а покшкэ витнема-петнема', 'recentchanges-label-minor' => 'Те а покшкэ витнемась-петнемась', 'recentchanges-legend-bot' => '$1, те - ботонь витнемазо-петнемазо', 'recentchanges-label-bot' => 'Те витнеманть-петнеманть теизе кона-кона бот', 'recentchanges-legend-unpatrolled' => '$1, те витнеманть-петнеманть мельга а ванстнить', 'rcnote' => "$5, $4 шканть коряс муят алдо {{PLURAL:$1|Меельсе '''1''' лиякстомтоманть|Меельсе '''$1''' лиякстомтоматнень}} меельсе {{PLURAL:$2|чинть|'''$2''' читнень}} шкасто.", 'rcnotefrom' => "Ало невтезь '''$2''' лиякстомтомасто саезь ('''$1''' видс).", 'rclistfrom' => 'Невтемс од витьнематнень $1-нть эйстэ саезь.', 'rcshowhideminor' => '$1 апокшкэ витнемат-петнемат', 'rcshowhidebots' => '$1 ботт', 'rcshowhideliu' => '$1 совазь уськекирдийтне', 'rcshowhideanons' => '$1 лемтеме теицят', 'rcshowhidepatr' => '$1 кона патрульсэ витьни-петни', 'rcshowhidemine' => '$1 мезе мон витнинь-петнинь', 'rclinks' => 'Невтемс меельсе $1 полавтнемат меельсе $2 чинь перть<br />$3', 'diff' => 'кадовикс', 'hist' => 'ист', 'hide' => 'Кекшемс', 'show' => 'Невтемс', 'minoreditletter' => 'а', 'newpageletter' => 'О', 'boteditletter' => 'б', 'rc_categories_any' => 'Кодамо илязо уле', 'newsectionsummary' => '/* $1 */ од пелькс', 'rc-enhanced-expand' => 'Невтемс седе ламо тень ланга (JavaScript эряви)', 'rc-enhanced-hide' => 'Кекшемс келейстэ ёвтазенть', # Recent changes linked 'recentchangeslinked' => 'Сюлмавозь лиякстоматне', 'recentchangeslinked-feed' => 'Сюлмавозь лиякстоматне', 'recentchangeslinked-toolbox' => 'Сюлмавозь лиякстоматне', 'recentchangeslinked-title' => 'Полавтнемат-лиякстомтомат конат кандовить теватезэнь "$1"', 'recentchangeslinked-noresult' => 'Максозь шкастонть кодаткак полавтовомат сюлмавозь лопатнесэ арасельть.', 'recentchangeslinked-summary' => "Тесэ максозь меельсе шкань витнемат-петнемат, конат теезельть башка максозь лопа вельде (эли категорияс совавтовиця тевнес). Ванома лопасот лопатне максозь '''эчкстэ тештезь'''", 'recentchangeslinked-page' => 'Лопанть лемезэ:', 'recentchangeslinked-to' => 'Тень таркас невтить те лопанть марто сюлмазь лопатнесэ полавтнематнень', # Upload 'upload' => 'Ёкстамс файла', 'uploadbtn' => 'Йовксамс файланть', 'uploadnologin' => 'Эзить сова', 'uploaderror' => 'Тонгомсто ильведькс', 'upload-permitted' => 'Файлань форматт, конат меревить: $1.', 'uploadlog' => 'Файлань йовкстамодо журнал', 'uploadlogpage' => 'Файлань йовкстамодо журнал', 'filename' => 'Файлонь лем', 'filedesc' => 'Нурькинестэ', 'fileuploadsummary' => 'Нурькинестэ:', 'filereuploadsummary' => 'Файласонть полавтнематне:', 'filesource' => 'Лисьмапрязо:', 'uploadedfiles' => 'Ёвкстань файлат', 'minlength1' => 'Файлалемесь аштезэ вейке эли седе ламо тешксттнэстэ.', 'badfilename' => 'Файланть лемесь полавтозь "$1"-кс.', 'filetype-missing' => 'Файланть арась поладкс пезэ (саемга «.jpg»).', 'file-thumbnail-no' => "Файланть лемезэ ушодови '''<tt>$1</tt>'''. Сонсь маряви вишкалгавтозь фотокуво, покшолмазо ''(кенжешка)''. Улиндеряй файланть покш верзиязо, йовкстыка сонзэ - арась, полавтыка тетень лемензэ.", 'file-exists-duplicate' => 'Те кавонзавкс файла вана {{PLURAL:$1|те файланть|неть файлатнень}} эйстэ:', 'successfulupload' => 'Совавтовсь кода эряви', 'uploadwarning' => 'Совавтомадо кардамонь пачтямо', 'savefile' => 'Ванстомс файланть', 'uploadedimage' => 'йовкстазь "[[$1]]"', 'overwroteimage' => 'Ёвкстамс "[[$1]]" файлань од версия', 'uploaddisabled' => 'Совавтомась лоткавтозь', 'uploadvirus' => 'Те файласонть вирус програм! Информация: $1', 'upload-source' => 'Лисьмапрякс файла', 'sourcefilename' => 'Лисьмапря файланть лемезэ', 'sourceurl' => 'Лисьмапрянть "URL" адресэзэ:', 'destfilename' => 'Теевиця файланть лемезэ', 'upload-maxfilesize' => 'Файлань покшолмазо иляссо юта: $1', 'upload-description' => 'Файланть йовтамозо', 'upload-options' => 'Йовкстамонь параметрат', 'watchthisupload' => 'Ваномс те лопанть мельга', 'upload-proto-error' => 'Аволь истямо протокол', 'upload-file-error' => 'Потмонь ильведькс', 'upload-misc-error' => 'Файлань ёвкстамонь апак содань ильведевкс', 'upload-too-many-redirects' => 'URL адрессэнть пек ламо печтевтемат', 'upload-unknown-size' => 'Апак содань покшолмазо', # img_auth script messages 'img-auth-accessdenied' => 'Совамось кардазь', # Some likely curl errors. More could be added from <http://curl.haxx.se/libcurl/c/libcurl-errors.html> 'upload-curl-error6' => 'URL-эсь а кундави', 'upload-curl-error28' => 'Ёвкстамо шкась весиясь', 'license' => 'Лицензиянь теема:', 'license-header' => 'Лицензиянь теема:', 'nolicense' => 'Лицензия арась', 'license-nopreview' => '(Васнянь невтевкс арась)', 'upload_source_file' => ' (арси машинасот файла)', # Special:ListFiles 'listfiles_search_for' => 'Вешнемс медиа лементь:', 'imgfile' => 'файл', 'listfiles' => 'Файлат-мезть', 'listfiles_date' => 'Чи', 'listfiles_name' => 'Лемезэ', 'listfiles_user' => 'Теиця', 'listfiles_size' => 'Покшолма', 'listfiles_description' => 'Чарькодевтемгакс', 'listfiles_count' => 'Верзият', # File description page 'file-anchor-link' => 'Файла', 'filehist' => 'Файланть эрямопингезэ', 'filehist-help' => 'Лепштинк чиннть/шканть ланкс, сестэ вансынк коли файлось ульнесь теезь.', 'filehist-deleteall' => 'нардамс весе', 'filehist-deleteone' => 'нардамс', 'filehist-revert' => 'велявтомс мекев', 'filehist-current' => 'неень шкань', 'filehist-datetime' => 'Чи/Шка', 'filehist-thumb' => 'Нуркинестэ', 'filehist-thumbtext' => '$1-стэ саезь верзиядо нуркинестэ ёвтазь', 'filehist-nothumb' => 'Нуркинестэ ёвтазесь арась', 'filehist-user' => 'Теиця', 'filehist-dimensions' => 'Онкставкс', 'filehist-filesize' => 'Файланть покшолмазо', 'filehist-comment' => 'Мельполадкс', 'filehist-missing' => 'Файлась арась', 'imagelinks' => 'Файлань сюлмавомапеть', 'linkstoimage' => 'Те файланть марто сюлмавозь вана {{PLURAL:$1|истямо сюлмавома пене|$1 истят сюлмавома пенеть}}:', 'nolinkstoimage' => 'Арась вейкеяк лопа, кона сюлмавови те файланть марто.', 'sharedupload' => 'Те файлась саезь "$1" файлань пусмосто, сон нолдави тевс лия проектсэяк.', 'uploadnewversion-linktext' => 'Тонгодо од версия те файланть', 'shared-repo-from' => 'вана теньстэ $1', 'shared-repo' => 'вейтьсэнь ванстома тарка', # File reversion 'filerevert' => 'Велявтомс $1 мекев', 'filerevert-legend' => 'Велявтомс файланть', 'filerevert-comment' => 'Арсемат-мельть:', 'filerevert-submit' => 'Велявтомс мекев', # File deletion 'filedelete' => 'Нардамс $1', 'filedelete-legend' => 'Нардамс файланть', 'filedelete-intro' => "Пурнат нардамо '''[[Media:$1|$1]]''' файланть путовкснэк-йурнэк.", 'filedelete-comment' => 'Тувталось:', 'filedelete-submit' => 'Нардамс', 'filedelete-success' => "'''$1'''-сь нардазь.", 'filedelete-nofile' => "'''$1''' арась.", 'filedelete-otherreason' => 'Лия тувтал:', 'filedelete-reason-otherlist' => 'Лия тувтал', 'filedelete-edit-reasonlist' => 'Витнемс-петнемс нардамонь тувталтнэсэ', # MIME search 'mimesearch' => 'MIME вешнема', 'mimetype' => 'MIME тип:', 'download' => 'таргамс', # Unwatched pages 'unwatchedpages' => 'лопат, кона мельга апак вано', # List redirects 'listredirects' => 'Лияв адрессев кучома потмо', # Unused templates 'unusedtemplates' => 'Тевс апак нолда лопа парцунт', 'unusedtemplateswlh' => 'лия сюлмавома пенеть', # Random page 'randompage' => 'Кодамо понгсь лопа', 'randompage-nopages' => '{{PLURAL:$2|Те лем потмосо|Не лем потмотнесэ}}: $1 лопат арасть.', # Random redirect 'randomredirect' => 'Апак фатя ёнксось', 'randomredirect-nopages' => '"$1" лем потмосонть лияв ютавтомат арасть.', # Statistics 'statistics' => 'Статистикат', 'statistics-header-pages' => 'Лопань статистикат', 'statistics-header-edits' => 'Статистикань витнеме-петнеме', 'statistics-header-views' => 'Статистикань ваномо', 'statistics-header-users' => 'Теицянь статистика', 'statistics-articles' => 'Потмо марто лопат', 'statistics-pages' => 'Лопат', 'statistics-files' => 'Йовкстань файлат', 'statistics-views-total' => 'Ваннома потмотнеде весемезэ', 'statistics-users-active' => 'Чистэ лисийть-совийть', 'statistics-mostpopular' => 'Весемеде сеедьстэ ванозь лопат', 'disambiguations' => 'Лопат, конат сёрмадстовтовить ламосмустев терминтт', 'disambiguationspage' => 'Template:смустень коряс явома', 'doubleredirects' => 'Кавксть ютавтозь', 'double-redirect-fixer' => 'Печтевтемс витнема-петнема пель', 'brokenredirects' => 'Сезезь ёнксось', 'brokenredirects-edit' => 'витнеме-петнеме', 'brokenredirects-delete' => 'нардамс', 'withoutinterwiki' => 'Лопат келеньютковань невтевкснень теме', 'withoutinterwiki-summary' => 'Вана неть лопатне апак сюлма лия келень верзия марто:', 'withoutinterwiki-legend' => 'Икелькс пене', 'withoutinterwiki-submit' => 'Невтемс', 'fewestrevisions' => 'Лопат, конатнесэ весемеде аламо лиякстомтомат', # Miscellaneous special pages 'nbytes' => '$1 {{PLURAL:$1|байт|байтт}}', 'ncategories' => '$1 {{PLURAL:$1|категория|категорият}}', 'nlinks' => '$1 {{PLURAL:$1|невтевкс|невтевкст|невтевкснедэ}}', 'nmembers' => '$1 {{PLURAL:$1|теиця|теицятне}}', 'nrevisions' => '$1 {{PLURAL:$1|лиякстомтома|лиякстомтомат}}', 'nviews' => '$1 {{PLURAL:$1|ванома потмо|ванома потмот}}', 'lonelypages' => 'Лопаурозкэть', 'uncategorizedpages' => 'Категориявтомо лопат', 'uncategorizedcategories' => 'Категориявтомо категорият', 'uncategorizedimages' => 'Категориявтомо файлат', 'uncategorizedtemplates' => 'Категориявтомо лопа парцунт', 'unusedcategories' => 'Тевс апак нолда категорият', 'unusedimages' => 'Тевс апак нолда файлат', 'popularpages' => 'Раське ютксо вечкевикс лопат', 'wantedcategories' => 'Вешень категорият', 'wantedpages' => 'Вешень лопат', 'wantedfiles' => 'Вешезь файлат', 'wantedtemplates' => 'Вешезь лопа парцунт', 'mostlinked' => 'Лопат конатнес сехте ламо сюлмавома пенеть невтить', 'mostlinkedcategories' => 'Сехте сюлмавозь категориятнень марто', 'mostlinkedtemplates' => 'Сехте ламо сюлмавома пе марто лопа парцунт', 'mostcategories' => 'Весемеде ламо категория марто лопат', 'mostimages' => 'Весемеде ламо сюлмавкс марто файлат', 'mostrevisions' => 'Лопат конатнесэ теезь сехте ламо лиякстомтомат', 'prefixindex' => 'Весе лопатне, конат саевить истямо икелькс пене марто', 'shortpages' => 'Нурькине лопат', 'longpages' => 'Кувака лопат', 'deadendpages' => 'Поладкстомо-лисемавтомо лопат', 'deadendpagestext' => 'Не вана лопатне апак сюлмаво {{SITENAME}} сайтсэ лия лопа марто.', 'protectedpages' => 'Ванстонь лопат', 'protectedpagestext' => 'Не вана лопатне ванстозь, иляст понго печтевтемс эли витнемс-петнемс', 'protectedtitles' => 'Ванстонь конякст', 'listusers' => 'Теицят-кить', 'listusers-editsonly' => 'Невтемс ансяк витнема-петнема марто совийтнень-лисийтнень', 'listusers-creationsort' => 'Аравтомс мельга мельцек шкамо чинь коряс', 'usereditcount' => '$1 {{PLURAL:$1|витнема-петнема|витнемат-петнемат}}', 'usercreated' => 'Шказь $1 чистэ $2 шкасто', 'newpages' => 'Од лопат', 'newpages-username' => 'Теицянь лем:', 'ancientpages' => 'Весемеде умонь лопат', 'move' => 'Печтевтть', 'movethispage' => 'Ютавтомс те лопанть лияв', 'notargettitle' => 'Совавтома лопа арась', 'nopagetitle' => 'Истямо вешема лопа арась', 'nopagetext' => 'Истямо лопа, конань вешить, арась.', 'pager-newer-n' => '{{PLURAL:$1|седе од 1|седе одт $1}}', 'pager-older-n' => '{{PLURAL:$1|седе ташто 1|седе таштт $1}}', 'suppress' => 'А ванома', # Book sources 'booksources' => 'Кинигань лисьмапрят', 'booksources-search-legend' => 'Вешнемс кинигань лисьмапрят', 'booksources-go' => 'Адя', # Special:Log 'specialloguserlabel' => 'Теицясь:', 'speciallogtitlelabel' => 'Коняксозо:', 'log' => 'Совамо-лисема тевть (регистрациясь)', 'all-logs-page' => 'Весемень туртов весе совамодо-кемекстамодо журналт', 'logempty' => 'Сови-лиси журналсто а муевить тень марто вейкеть тевть', # Special:AllPages 'allpages' => 'Весе лопат', 'alphaindexline' => '$1-сто $2-нтень', 'nextpage' => 'Седе тов лопась ($1)', 'prevpage' => 'Седе икелень лопа ($1)', 'allpagesfrom' => 'Невтемс лопатнень тестэ ушодозь:', 'allpagesto' => 'Невтемс лопатнень, конатне прядовить:', 'allarticles' => 'Весе сёрмадовкст', 'allinnamespace' => 'Весе лопат ($1 сёрмадовксонть лемезе)', 'allnotinnamespace' => 'Весе лопатне («$1» лемпотмонь томбалеть)', 'allpagesprev' => 'Икеле', 'allpagesnext' => 'Сыця', 'allpagessubmit' => 'Молемс', 'allpagesprefix' => 'Невтевкс лопась полаткс марто:', 'allpages-bad-ns' => '{{SITENAME}} сайтсэнть арась лем потмо "$1".', # Special:Categories 'categories' => 'Категорият', 'categoriespagetext' => '{{PLURAL:$1|Те категориясонть|Не категориятнесэ}} улить лопат эли медият. [[Special:UnusedCategories|тевс апак нолда категориятне]] тесэ а невтевить. Истяжо ванытя [[Special:WantedCategories|вешень категориятнень]].', 'special-categories-sort-count' => 'аравтомс цётонь коряс', 'special-categories-sort-abc' => 'аравтомс альфавитэнь коряс', # Special:DeletedContributions 'sp-deletedcontributions-contribs' => 'путовксонзо', # Special:LinkSearch 'linksearch' => 'Ушонь сюлмавомапенеть', 'linksearch-pat' => 'Вешнемкс парцун:', 'linksearch-ns' => 'Лем потмозо:', 'linksearch-ok' => 'Вешнэмс', # Special:ListUsers 'listusers-submit' => 'Невтемс', 'listusers-noresult' => 'Совицязо а муеви', 'listusers-blocked' => '(саймас саезь)', # Special:ActiveUsers 'activeusers-hidebots' => 'Кекшемс ботатнень', 'activeusers-hidesysops' => 'Кекшемс администратортнэнь', 'activeusers-noresult' => 'Якинзэ-пакинзэ арасть', # Special:Log/newusers 'newuserlogpage' => 'Теицянь шкамодо-теемадо конёв', 'newuserlogpagetext' => 'Те теицянь шкавксто журнал', 'newuserlog-byemail' => 'совамо вал кучозь е-сёрмасо', 'newuserlog-create-entry' => 'Од совиця', 'newuserlog-create2-entry' => 'шкизе од совамо тарканть $1', # Special:ListGroupRights 'listgrouprights' => 'Теиця куронть видечинзэ', 'listgrouprights-group' => 'Куро', 'listgrouprights-rights' => 'Видечытне', 'listgrouprights-members' => '(куронь ломанть)', 'listgrouprights-addgroup-all' => 'Поладомс весе куротнень', 'listgrouprights-removegroup-all' => 'Весе куротнень нардамс', # E-mail user 'mailnologin' => 'Кучомс сёрма парго арась', 'emailuser' => 'Кучомс е-сёрма те теицянтень', 'emailpage' => 'Кучт э-сёрма теицянтень', 'defemailsubject' => '{{SITENAME}} е-сёрма', 'noemailtitle' => 'Е-сёрма парго арась', 'emailfrom' => 'Кинь пельде:', 'emailto' => 'Кинень:', 'emailsubject' => 'Мезде:', 'emailmessage' => 'Пачтямнэ:', 'emailsend' => 'Кучомс', 'emailccme' => 'Кучок монень е-сёрмам копиянзо.', 'emailsent' => 'Е-сёрма кучозь', 'emailsenttext' => 'Е-сёрмасо пачтямнэть кучовсь.', # Watchlist 'watchlist' => 'Мезе мельга мон ванстнян', 'mywatchlist' => 'Мезе мельга мон ванстнян', 'watchlistfor' => "('''$1'''-те)", 'watchnologin' => 'Апак сова', 'addedwatch' => 'Топавтозь ванома потмоксоньте', 'addedwatchtext' => 'Лопась «[[:$1]]» совавтозь [[Special:Watchlist|ванома потмозот]]. Седе тов те лопасонть ды мартонзо сюлмавозь кортнема лопасонть теезь витьнематне тешкставтовить те потмонтень, истяжо кармить кикстазь те лопасонть[[Special:RecentChanges|потмо од витнематне]], истя седе шождасто сынь неявить.', 'removedwatch' => 'Нардазь ванома потмокстонть', 'removedwatchtext' => '«[[:$1]]» лопась нардавсь [[Special:Watchlist|ванома потмоксстот]].', 'watch' => 'Ванстнемс', 'watchthispage' => 'Ванстнемс те лопа мельга', 'unwatch' => 'А ванстнемс тень мельга', 'unwatchthispage' => 'Лоткамс ванстомадонзо', 'notvisiblerev' => 'Лиякстомтомась нардазь', 'watchlist-details' => 'Ванома лемрисьмесэть {{PLURAL:$1|$1 лопа|$1 лопат}}, апак лово кортнема лопатнень.', 'wlshowlast' => 'Невтемс мельсе $1 цяст $2 чить $3', 'watchlist-options' => 'Ванома потмонь аравтнемат', # Displayed when you click the "watch" button and it is in the process of watching 'watching' => 'Ванома...', 'unwatching' => 'Аванома...', 'enotif_newpagetext' => 'Те од лопа.', 'enotif_impersonal_salutation' => '{{SITENAME}} теицясь', 'changed' => 'полавтозь', 'created' => 'теезь-шказь', 'enotif_lastdiff' => 'Те полавтоманть ваномга вант $1.', 'enotif_anon_editor' => 'лемтеме теиця $1', # Delete 'deletepage' => 'Нардамс лопанть', 'confirm' => 'Кемекстамс', 'excontent' => "потсонзоль: '$1'", 'exbeforeblank' => "чамдомадо икеле эйсэнзэ ульнесь: '$1'", 'exblank' => 'лопась чаволь', 'delete-confirm' => 'Нардамс "$1"', 'delete-legend' => 'Нардамс', 'historywarning' => 'Ванок: Лопанть, конань нардамонзо пурнат, лиякстомтомань икелькс $1 {{PLURAL:$1|умазо|уманзо}}:', 'confirmdeletetext' => 'Кундыть нардамо лопа (эли невтевкс-артовкс) вейтьсэ лиякстомтоматнеде икелькс уманзо марто.<br /> Инеськеть, кемекстык, эсеть мелеть коряс тень тейсак, алкукс содат, мезе лияды теде мейле, ды алкукс теят тень видечинть (правилатьнень) коряс, конат сёрмадозь [[{{MediaWiki:Policy-url}}]].', 'actioncomplete' => 'Тевень теемась топавтовсь', 'actionfailed' => 'Тев теемась эзь лисе', 'deletedtext' => '"<nowiki>$1</nowiki>"-сь ульнесь нардазь. Вант $2 тосо веси уаль умоконь нардавксне.', 'deletedarticle' => 'нардазь "[[$1]]"', 'dellogpage' => 'Нардомань совама-кемекстома', 'deletionlog' => 'нардамонь сёрмалема', 'reverted' => 'Вельмевтезь лопань седе икелень лиякстомтома', 'deletecomment' => 'Тувталось:', 'deleteotherreason' => 'Лия/топавтозь тувтал:', 'deletereasonotherlist' => 'Лия тувтал', 'delete-edit-reasonlist' => 'Витнемс-петнемс нардамонь тувталтнэнь', # Rollback 'rollback' => 'Кевердемс витнематнень-петнематнень мекев', 'rollback_short' => 'Мекев кевердема', 'rollbacklink' => 'кевердемс', 'rollbackfailed' => 'Мекев кевердемась эзь лисе', # Protect 'protectlogpage' => 'Ванстомань совамо-кемекстамо', 'protectedarticle' => 'ванстозь "[[$1]]"', 'modifiedarticleprotection' => '«[[$1]]»-нь ванстомань виезэ полавтовсь', 'unprotectedarticle' => '«[[$1]]» лопась аволь ванстома экшсэ', 'prot_1movedto2' => '[[$1]] печтевтезь тей [[$2]]', 'protect-legend' => 'Кемекстынк аравтоманть лопанть ванстоманзо', 'protectcomment' => 'Тувталось:', 'protectexpiry' => 'Прядови:', 'protect_expiry_invalid' => 'Прядома шкась ашти ютань шкасо.', 'protect_expiry_old' => 'Прядома шкась амаштовикс.', 'protect-text' => "Тесэ тынь вансынк ды лиякстомсынк ванстоманть покшолманзо лопаньте '''<nowiki>$1</nowiki>'''.", 'protect-locked-access' => "Кирдицянь совамо таркат а максы видечи лиякстомтомс лопанть ванстома лувонзо. Тесэ вана лопанть уликс путовксонзо-аравтоманзо '''$1''':", 'protect-cascadeon' => 'Те лопась ванстозь, сон путозь {{PLURAL:$1|невтезезь ало лопаньте, конаньте|невтезезь ало лопатьнене конатьнене}}-те путозь каскадонь ванстомась. Тынь лиякставсынк те ванстома сэренть, ансяк те кодаяк а полавсы каскадонь ванстоманть.', 'protect-default' => 'Весе теицятненень маштови', 'protect-fallback' => 'Вешеви ве мельс прамось «$1»-нть', 'protect-level-autoconfirmed' => 'Саймас аравтомс од ды апак сёрмадстово теицятнень', 'protect-level-sysop' => 'Ансяк администраторт', 'protect-summary-cascade' => 'каскадонь ладсо', 'protect-expiring' => 'прядови $1 (UTC)', 'protect-expiry-indefinite' => 'певтема', 'protect-cascade' => 'Ванстомс лопатьнень, конат совавтозь те лопаньте(каскадонь ванстома)', 'protect-cantedit' => 'Тынь алиякставсынк ванстомань уровнянть те лопанть, тынк арасть видечинк сонзэ лиякстоманьте.', 'protect-othertime' => 'Лия шкась:', 'protect-othertime-op' => 'лия шка', 'protect-otherreason' => 'Лия/поладкс тувталось:', 'protect-otherreason-op' => 'лия/поладкс тувтал', 'protect-expiry-options' => '1 час:1 hour,1 чи:1 day,1 тарго:1 week,2 таргот:2 weeks,1 ков:1 month,3 ковт:3 months,6 ковт:6 months,1 ие:1 year,певтеме:infinite', 'restriction-type' => 'Нолдамо:', 'restriction-level' => 'Нолдавксонь покшизэ:', 'minimum-size' => 'Минимум кувалмозо', 'maximum-size' => 'Покшолмань тёкш:', 'pagesize' => '(байтт)', # Restrictions (nouns) 'restriction-edit' => 'Витнеме-петнеме', 'restriction-move' => 'Ютавтомс лия таркас', 'restriction-create' => 'Шкамс-теемс', 'restriction-upload' => 'Ёвкстамс', # Restriction levels 'restriction-level-sysop' => 'ванстозь теицядо', 'restriction-level-autoconfirmed' => 'пельс ванстозь теицядо', 'restriction-level-all' => 'кода мелеть виезэ', # Undelete 'undelete' => 'Ваномс нардазь лопатнень', 'viewdeletedpage' => 'Ваномс нардазь лопатнень', 'undeletebtn' => 'Велявтомс мекев сенень, мезе ульнесь витнемадо-петнемадо икеле', 'undeletelink' => 'неемс/вельмевтемс', 'undeleteviewlink' => 'ваномс', 'undeleteinvert' => 'Кочказень таркас апаконь кочкамо', 'undeletecomment' => 'Арсемат - мельть:', 'undeletedarticle' => 'вельмевтезь "[[$1]]"', 'undeletedrevisions' => '{{PLURAL:$1|1 лиякстомтома|$1 лиякстомтомат}} вельмевтезь', 'undeletedrevisions-files' => '{{PLURAL:$1|1 лиякстомтома|$1 лиякстомтомат}} ды {{PLURAL:$2|1 файла|$2 файлат}} вельмевтезь', 'undeletedfiles' => '{{PLURAL:$1|1 файла|$1 файлат}} вельмевтезь', 'undelete-search-box' => 'Вешнемс нардань лопатнень йутксто', 'undelete-search-prefix' => 'Невтемс лопат тестэ саезь:', 'undelete-search-submit' => 'Вешнэмс', 'undelete-error-short' => '"$1" файлань вельмевтемстэ лиссь ильведевкс', 'undelete-show-file-submit' => 'Истя', # Namespace form on various pages 'namespace' => 'Лем потмозо:', 'invert' => 'Кочказень таркас апаконь кочкамо', 'blanknamespace' => '(Прявкс)', # Contributions 'contributions' => 'Теицянть-кирдицянть путовксозо', 'contributions-title' => 'Теицянть путовксонзо $1 таркантень', 'mycontris' => 'Монь путовкст', 'contribsub2' => '$1 ($2) туртов', 'uctop' => '(меельцесь)', 'month' => 'Ковстонть (ды седе икеле):', 'year' => 'Иестэнть (ды седе икеле):', 'sp-contributions-newbies' => 'Невтемс ансяк од теицятнень путовксост', 'sp-contributions-newbies-sub' => 'Од акаунтс', 'sp-contributions-blocklog' => 'Пекстамонь журналось', 'sp-contributions-logs' => 'журналт', 'sp-contributions-talk' => 'кортнеме', 'sp-contributions-search' => 'Путовксонь вешнеме', 'sp-contributions-username' => 'IP адрес эли теицянь лем:', 'sp-contributions-submit' => 'Вешнэмс', # What links here 'whatlinkshere' => 'Мезе тезэнь сюлмави', 'whatlinkshere-title' => '$1 марто сюлмазь лопатне', 'whatlinkshere-page' => 'Лопась:', 'linkshere' => "Сыця лопатьне сюлмававить '''[[:$1]]''' марто:", 'nolinkshere' => "Кодаткак лопат асульмавить '''[[:$1]]''' марто.", 'isredirect' => 'Лиякс витнинк-петнинк лопанть', 'istemplate' => 'совавтомс', 'isimage' => 'артовксонь сюлмавома пене', 'whatlinkshere-prev' => '{{PLURAL:$1|икеле|седе икелень $1}}', 'whatlinkshere-next' => '{{PLURAL:$1|сыця|сы $1}}', 'whatlinkshere-links' => '← сюлмавомапеть', 'whatlinkshere-hideredirs' => '$1 {{PLURAL:$1|тарка йутавты|таркат йутавтыть}} тей', 'whatlinkshere-hidetrans' => '$1 сюлмавозь пелькстнэнь', 'whatlinkshere-hidelinks' => '$1 сюлмавома петь', 'whatlinkshere-filters' => 'Фильтрат', # Block/unblock 'blockip' => 'Пекстамондо теицянть', 'blockip-title' => 'Совицянть саймас саемс', 'blockip-legend' => 'Аравтомс теицянть саймас', 'ipaddress' => 'IP адрес:', 'ipadressorusername' => 'IP адрес эли теицянь лем:', 'ipbexpiry' => 'Таштомома шказо:', 'ipbreason' => 'Тувталось:', 'ipbreasonotherlist' => 'Лия тувтал', 'ipbsubmit' => 'Озавтомс те теицянть саймес', 'ipbother' => 'Лия шка:', 'ipboptions' => '2 част:2 hours,1 чи:1 day,3 чить:3 days,1 тарго:1 week,2 таргот:2 weeks,1 ков:1 month,3 ковт:3 months,6 ковт:6 months,1 ие:1 year,певтеме:infinite', 'ipbotheroption' => 'лия', 'ipbotherreason' => 'Лия/поладкс тувтал:', 'badipaddress' => 'Амаштовикс IP адрес', 'blockipsuccesssub' => 'Саймес озавтовсь', 'ipb-edit-dropdown' => 'Витнемс-петнемс саймес озавтомань тувталтнэнь', 'ipb-unblock-addr' => 'Нолдамс $1-нть сайместэ', 'ipb-blocklist-addr' => 'Теицянть $1 саймес озавтоманзо', 'ipb-blocklist' => 'Ваномс саймес озавтозетнень', 'ipb-blocklist-contribs' => '$1 лопас путовкст', 'unblockip' => 'Нолдамс теицянть сайместэ', 'ipusubmit' => 'Нардамс те саймас аравтоманть', 'ipblocklist' => 'Саймес саень IP адресст ды теицят', 'ipblocklist-legend' => 'Вешнемс саймас саезь теиця', 'ipblocklist-username' => 'Совицянть лемезэ эли IP адресэзэ:', 'ipblocklist-submit' => 'Вешнэме', 'infiniteblock' => 'певтеме', 'expiringblock' => 'саймас саемась прядови $1 $2 цяссто', 'anononlyblock' => 'ансяк лемтеме', 'blocklink' => 'блокось', 'unblocklink' => 'панжомс', 'change-blocklink' => 'полавтомадо сайма', 'contribslink' => 'лездыцят кить', 'blocklogpage' => 'Пекстамонь журналось', 'blocklogentry' => 'пектстамонзо [[$1]] ютазь шканть марто $2 $3', 'unblocklogentry' => 'сайместэ нолдазь $1', 'block-log-flags-anononly' => 'ансяк лемтеме теицятненень', 'block-log-flags-nocreate' => 'од теицянь тарканть шкамось-теемась лоткавтозь', 'block-log-flags-noemail' => 'е-сёрма озавтозь саймес', 'block-log-flags-hiddenname' => 'лисиенть-совиенть лемезэ кекшезь', 'ipb_already_blocked' => '"$1" уш саймас саезь', 'blockme' => 'Озавтомак саймес', 'proxyblocksuccess' => 'Озавтовсь.', # Developer tools 'lockdb' => 'Сёлгомс датабазанть', 'unlockdb' => 'Панжомс датабазанть', 'lockconfirm' => 'Истя, ули мелем сёлгамс датабазанть.', 'lockbtn' => 'Сёлгамс датабазанть', 'unlockbtn' => 'Панжомс датабазанть', 'lockdbsuccesssub' => 'Теветь лиссь, датабазась сёлговсь', 'unlockdbsuccesssub' => 'Датабазась сёлгозель, ней таго панжадо', 'databasenotlocked' => 'Датабазась апак сёлго.', # Move page 'move-page' => 'Печтевтемс $1 лия таркав', 'move-page-legend' => 'Печтевтемс лопанть', 'movepagetext' => "Ало максозь лувонть тевс нолдазь, одс лемдят лопа, ве шкасто печтевтят од таркас сонзэ лиякстомтома юронзо-журналонзо. Икелень лемезэ тееви печтевтема лопакс, кона ютавты лисийть-совийть од лементень. Невтевкстнэ икелень лементь лангс а кармить лиякстомтовомо (инеськеть, вант улить - арасть [[Special:DoubleRedirects|кавтонь кирдань]] ды [[Special:BrokenRedirects|сезень печтевтемат]]). Эсеть лангсо вана невтевкстнэ невтест сев, ков эряви. Мель явт, улиндеряй анок лопа од лементь таркасо, лопась '''а печтевтеви'''. Печтевтеви ансяк сестэ, зярдо лопась чаво эли ашти певтевтема лопакс, конань арась витнемань-петнемань икелькс умазо. Лиякс меремга, маштови одов лемдемс лопа икелень лемсэнзэ, зярдо теят ильведевкс; уликс лия лопа а нардави. '''ВАНОК!''' Одс лемдямось тусы покш ды пек апак учонь полавтовомат лопатненень, конатнес ''весеменень пек содавикст''. Инеськеть, поладомадо икеле васня вант, чарькодят - чарькодят козонь те тевесь вети.", 'movepagetalktext' => "Поладозь кортавтома лопась, кодак истямось ули ютавтови автоматика вельде одс лемдязенть марто, '''а ютавтови, зярдо:'''<br /> *Истямо лем марто кортавтома лопа, конась аволь чаво муеви *Эзить путо тешкст паксясонть ало.<br /> Зярдо истят тевтне, сави тонстеть лопатнень кучомс-сюлмамс, кедьсэ.", 'movearticle' => 'Одов лемдемс лопанть:', 'movenologin' => 'Апак сова', 'movenotallowed' => 'Арась меремат печтевтемс лопатнесэ.', 'newtitle' => 'Од леменьтэ:', 'move-watch' => 'Ваномс лопанть', 'movepagebtn' => 'Печтевтемс лопанть', 'pagemovedsub' => 'Лопась печтевтевсь', 'movepage-moved' => "'''«$1»-сь печтевтезь «$2»-с'''", 'articleexists' => 'Лопась истямо лем марто ули али невтезь тынк эйсэ лемесь анолдавиксев.<br />Инескеть, кочкадо лия лем.', 'talkexists' => "'''Сонсь лопась печтевтевсь, ансяк кортамонь лопась кодаяк эзь печтевтеве, вана мекс, истямо лем марто лопась ули. Инеськеть, пурныть сынст вейтьс кедьсэ.'''", 'movedto' => 'печтевтезь', 'movetalk' => 'Печтевтемань кортамо лопа', 'movepage-page-moved' => '"$1" лопась печтевтезь "$2"-с.', 'movepage-page-unmoved' => 'Лопа $1 эзь печтевтеве $2 лопас.', '1movedto2' => '[[$1]] печтевтезь тей [[$2]]', '1movedto2_redir' => '«[[$1]]» таркась печтевтезь «[[$2]]» таркантень седе тов ютавтомканть вельде', 'movelogpage' => 'Печтевтемань журнал', 'movesubpage' => '{{PLURAL:$1|Алкслопа|Алкслопа}}', 'movesubpagetext' => 'Те лопасонть ало невтеви $1 {{PLURAL:$1|алкслопа|алкслопа}}.', 'movereason' => 'Тувталось:', 'revertmove' => 'велявтодо', 'delete_and_move' => 'Нардык ды печтевтик', 'delete_and_move_confirm' => 'Нардыка те лопанть', 'delete_and_move_reason' => 'Печтевтемга нардазь', 'immobile-source-namespace' => '"$1" лемпотмосонть лопатне а печтевтевить', 'immobile-target-namespace' => '"$1" лемпотмонтень лопатне а печтевтевить', # Export 'export' => 'Экспортировамс лопат', 'export-submit' => 'Ливтемс', 'export-addcattext' => 'Поладомс лопат, конань категорияст:', 'export-addcat' => 'Поладомс', 'export-addnstext' => 'Поладомс лопат лем потмостонть:', 'export-addns' => 'Поладомс', 'export-download' => 'Таргамс файлакс', 'export-templates' => 'Поладомс лопа парцунонтень', # Namespace 8 related 'allmessages' => 'Систэмань вишка сёрмадовкс', 'allmessagesname' => 'Лемезэ', 'allmessagescurrent' => 'Тевате текстэсь', 'allmessages-filter-legend' => 'Сувтеме', 'allmessages-filter-unmodified' => 'Апак одкстомто', 'allmessages-filter-all' => 'Весе', 'allmessages-filter-modified' => 'Одолгавтозь', 'allmessages-prefix' => 'Икелькс валпень коряс сувтеме', 'allmessages-language' => 'Келесь:', 'allmessages-filter-submit' => 'Ютак', # Thumbnails 'thumbnail-more' => 'Покшолгавтомс', 'filemissing' => 'Файлась а муеви', 'thumbnail_error' => 'Миниатюрань тееманть ильветькс: $1', # Special:Import 'import' => 'Таргамс лопатнень', 'import-interwiki-source' => 'Вики лисьмапрякс/лопась:', 'import-interwiki-templates' => 'Совавтомс весе лопа парцунтнэнь', 'import-interwiki-submit' => 'Таргамс', 'import-interwiki-namespace' => 'Норовазь лемпотмось:', 'import-upload-filename' => 'Файла лемесь:', 'import-comment' => 'Арсемат-мельть:', 'importstart' => 'Лопатне совавтовить...', 'import-revision-count' => '$1 {{PLURAL:$1|лиякстомтома|лиякстомтомат}}', 'importnopages' => 'Ёвкстамс лопат арасть', 'importfailed' => 'Совавтома тевесь эзь лисе: <nowiki>$1</nowiki>', 'importcantopen' => 'Совавтозь файлась эзь панжово', 'importbadinterwiki' => 'Амаштовикс интервики сюлмавома пе', 'importnotext' => 'Чаво эли текст арась', 'importsuccess' => 'Совавтомась прядовсь!', 'importnofile' => 'Кодамояк совавтома файла эзь йовкставо.', 'import-noarticle' => 'Совавтомс лопат арасть!', 'import-upload' => 'Ёвкстамс XML датанть', # Import log 'importlogpage' => 'Импортонть журналось', 'import-logentry-upload-detail' => '$1 {{PLURAL:$1|лиякстомтома|лиякстомтомат}}', # Tooltip help for the actions 'tooltip-pt-userpage' => 'Теицянь лопат', 'tooltip-pt-mytalk' => 'Кортнемалопам', 'tooltip-pt-preferences' => 'Мейсэ явован лиятнень эйстэ', 'tooltip-pt-watchlist' => 'Лопатне, конатнень мельга ванстнят: лиякстомтовить а лиякстомтовить', 'tooltip-pt-mycontris' => 'Мезесэ лездынь мезе путынь', 'tooltip-pt-login' => 'Совавтовлить эсь прят тезэнь, арась мелеть, иля.', 'tooltip-pt-logout' => 'Лисемс', 'tooltip-ca-talk' => 'Кортавтома пек паро лопадонть', 'tooltip-ca-edit' => 'Те лопаськак витневи-петневи. Ансяк, ванстомадо икеле яла васнянь невтевкс повнэнть лепштика.', 'tooltip-ca-addsection' => 'Ушодомс од явкс.', 'tooltip-ca-viewsource' => 'Те лопась ванстозь. Ули меленк ваномонзо сонзе лисмапрянть.', 'tooltip-ca-history' => 'Те лопанть йутазь версиянзо.', 'tooltip-ca-protect' => 'Аравтомс те лопанть прянь ванстомас', 'tooltip-ca-delete' => 'Нардамс те лопанть, илязо улеяк', 'tooltip-ca-move' => 'Ютавтык те лопанть лияв', 'tooltip-ca-watch' => 'Топавтомс те лопанть тынк ваномалопаньте', 'tooltip-ca-unwatch' => 'Панемензе (нардамонзо) те лопанть тынк ваномалопастонть', 'tooltip-search' => 'Вешнемс вана тестэ {{SITENAME}}', 'tooltip-search-go' => 'Истямо лем марто лопа улиндеряй, молемс сезэнь', 'tooltip-search-fulltext' => 'Лопатнестэ вешнемс истямо текст', 'tooltip-p-logo' => 'Прякс лопа', 'tooltip-n-mainpage' => 'Совака прякслопантень', 'tooltip-n-mainpage-description' => 'Совамс прякс лопав', 'tooltip-n-portal' => 'Проектэнть эйстэ, мейсэ лездамс, косто мезе муемс', 'tooltip-n-currentevents' => 'Муинк совавикс информациянть неень событиятнесэ', 'tooltip-n-recentchanges' => 'Викисэ мезе чияк полавтовсь-лиякстомтовсь.', 'tooltip-n-randompage' => 'Макста ловномс кодамо понгсь лопа', 'tooltip-n-help' => 'Превс путыть косо.', 'tooltip-t-whatlinkshere' => 'Викинь весе лопатне, конат тезэнь сюлмазь', 'tooltip-t-recentchangeslinked' => 'Чыяконь полавтнемат сеть лопатнесэ, конат сюлмазь те лопанть марто', 'tooltip-feed-rss' => '"RSS" чидикерькске те лопантень', 'tooltip-feed-atom' => 'Атом лезкс те лопантень', 'tooltip-t-contributions' => 'Варштык путовкс потмонть те теицянть', 'tooltip-t-emailuser' => 'Те теицянтень кучомс е-сёрма', 'tooltip-t-upload' => 'Йовкстамс файлат', 'tooltip-t-specialpages' => 'Башка тевень лопатне мельга-мельцек', 'tooltip-t-print' => 'Лопанть конёв лангс нолдавома версиязо', 'tooltip-t-permalink' => 'Свал шкань сюлмавома пе лопань те верзиянтень', 'tooltip-ca-nstab-main' => 'Ваномс потмо лопанзо', 'tooltip-ca-nstab-user' => 'Ваномс теицянь лопанть', 'tooltip-ca-nstab-media' => 'Ваномс медиа лопанть', 'tooltip-ca-nstab-special' => 'Те башка тевень лопась, сонсь лопась а витневи-петневи', 'tooltip-ca-nstab-project' => 'Ваннынк проетной лопанть', 'tooltip-ca-nstab-image' => 'Ванык файлань лопанть', 'tooltip-ca-nstab-mediawiki' => 'Ваномс системань пачтямнэнть', 'tooltip-ca-nstab-template' => 'Ванномс лопа парцунонть', 'tooltip-ca-nstab-help' => 'Ванномс лездамонь лопанть', 'tooltip-ca-nstab-category' => 'Варштынк категориянь лопатьнень', 'tooltip-minoredit' => 'Тешкстынк тень, сон вишкинесте витнезь-петнезь', 'tooltip-save' => 'Ванстомс мезе лиякстомтыть', 'tooltip-preview' => 'Ванодо тынк лиякстоматнень, инескеть тевс нолдадо тень ванстоманть икеле!', 'tooltip-diff' => 'Невтемс мейсэ лиякстомтыть текстэнть.', 'tooltip-compareselectedversions' => 'Вант явовкст кавто саезь версиятнень те лопанть.', 'tooltip-watch' => 'Топавтомс те лопанть тынк ваномалопаньте', 'tooltip-upload' => 'Ушодомс йовкстамонть', 'tooltip-rollback' => '"Мекев кевердема" повнэнть весть лепштямось велявтсынзе те лопасонть меельсекс теезь витнематнень-петнематнень', 'tooltip-undo' => '"Велявтомс мекев" велявтсы витнемань-петнемань тевенть ды панжсы васнянь невтемань формасо. Сонзэ вельде маштови поладомс полавтомадо тувтал.', # Attribution 'anonymous' => '{{SITENAME}} сайтэнть лемтеме {{PLURAL:$1|теицязо|теицянзо}}', 'siteuser' => '{{SITENAME}}-нь теиця $1', 'lastmodifiedatby' => 'Меельседе те лопанть полавтызе $3 $2, $1.', 'othercontribs' => '$1-нь важодеманзо лангс нежедезь.', 'others' => 'лият', 'siteusers' => '{{SITENAME}} сайтэнть {{PLURAL:$2|теицязо|теицянзо}} $1', 'creditspage' => 'Лопасонть кинь путовксонзо', # Spam protection 'spamprotectiontitle' => 'Шукшто ванстома филтра', 'spambot_username' => 'MediaWiki-нь шукшто ванькскавтома', # Info page 'infosubtitle' => 'Лопанть информациянзо', 'numedits' => 'Зяроксть витнезь-петнезь (лопа): $1', 'numtalkedits' => 'Зяроксть витнезь-петнезь (кортнема лопа): $1', 'numwatchers' => 'Зяро ванстнить тень мельга: $1', # Skin names 'skinname-standard' => 'Классикань', 'skinname-nostalgia' => 'ОдПингеньМазы', 'skinname-myskin' => 'ЭсьМелемКоряс', 'skinname-simple' => 'Шожда', 'skinname-modern' => 'НееньШкань', # Math options 'mw_math_simple' => 'HTML зярдо вельть шожда, лиякс PNG', 'mw_math_html' => 'HTML, те тееви, теик, лиякс PNG', 'mw_math_source' => 'Кадык TeX хорматсо (текст вальмас)', 'mw_math_modern' => 'Арьсезь неень шкань содый машинань вальмас', 'mw_math_mathml' => 'MathML косо ули кода (варчамонь)', # Math errors 'math_failure' => 'А ловнови', 'math_unknown_error' => 'апак содань ильведькс', 'math_unknown_function' => 'апак содань функция', 'math_lexing_error' => 'лексиконь манявкс', 'math_syntax_error' => 'синтаксонь ильведевкс', # Patrolling 'markaspatrolleddiff' => 'Тешкстамс ванстнемань ютазекс', 'markaspatrolledtext' => 'Тешкстамс те лопанть ванстнемань ютазекс', 'markedaspatrolled' => 'Тешкстазь ванстнемань ютазекс', # Patrol log 'patrol-log-page' => 'Ванстнемадо конёв', 'patrol-log-auto' => '(сонсь теи)', 'patrol-log-diff' => 'версия $1', # Image deletion 'deletedrevision' => 'Нардань ташто лиякстомтома $1', # Browsing diffs 'previousdiff' => '← Седе икелень верзиязо', 'nextdiff' => 'Од верзиязо →', # Media information 'thumbsize' => 'Кенжешканть покшолмазо:', 'widthheightpage' => '$1×$2, {{PLURAL:$3|лопа|$3 лопат}}', 'file-info' => '(файлонть-путовксонть сталмозо: $1, MIME типезе: $2)', 'file-info-size' => '($1 × $2 пиксельть, файлонть-путовксонть сталмозо: $3, MIME типезе: $4)', 'file-nohires' => '<small>Арась версия покш разрешения марто.</small>', 'svg-long-desc' => '(SVG файла, $1 × $2 пиксельть, файланть покшолмазо: $3)', 'show-big-image' => 'Пешксе теевксесь', 'show-big-image-thumb' => '<small>Васнянь невтевксэнть покшолмазо: $1 × $2 пиксэлт</small>', # Special:NewFiles 'newimages' => 'Од файлатьнень галлереясь', 'newimages-legend' => 'Сувтеме', 'newimages-label' => 'Файлалем (эли пельксэзэ):', 'showhidebots' => '($1 ботт)', 'noimages' => 'Арась мезе ваномс.', 'ilsubmit' => 'Вешнэмс', 'bydate' => 'чинь коряс', # Bad image list 'bad_image_list' => 'Лувось-форматось вана истямо: Тесэ ансяк потмонть пакшкетне (рисьметне, конат ушодовить * тешкстсэ) лововить. Рисьмень васень сюлмавома пентень эряви невтемс амаштовикс файла лангс. Секе рисьминентень понгиндеряйть лия сюлмавома петь, сынь лововить башка, лиякс меремс сынь лопат, косо файлат маштовить невтемс.', # Metadata 'metadata' => 'Meta-нь даннойтне', 'metadata-help' => 'Те файласонть поладкс информация, кона, паряк, саевсь цифровой камерастонть эли сулеймашинастонть (скенерстэнть), зядро файлась теезель цифровой лувс. Бути сон оригиналонть эйстэ лиякстомтозь, паряк аволь весе ёнкстнэ ванстовсть; фото-артовкстнэсэ редявить асатыкст.', 'metadata-expand' => 'Невтемс топавтозь даннойтнень', 'metadata-collapse' => 'Пекстынк келейкстазь детальтнень.', 'metadata-fields' => 'Матадань паксятьне, конататьне ловозь те потмосонть, кармить невтезь артома лопасонть а сёпазь, лиятне кармить кекшезезь. * make * model * datetimeoriginal * exposuretime * fnumber * isospeedratings * focallength', # EXIF tags 'exif-imagewidth' => 'Келе', 'exif-imagelength' => 'Сэрь', 'exif-orientation' => 'Ориентация', 'exif-planarconfiguration' => 'Максовксонь аравтнема', 'exif-xresolution' => 'Горизонтальсэ сеедезэ', 'exif-yresolution' => 'Вертикальсэ сеедезэ', 'exif-transferfunction' => 'Печтевтемань функция', 'exif-referenceblackwhite' => 'Раужот-ашот кавто корямо точкат', 'exif-imagedescription' => 'Артовксонть коняксозо', 'exif-software' => 'Тевс нолдазь программатне', 'exif-artist' => 'Теицязо', 'exif-copyright' => 'Копия теемань видечинь кирдицясь', 'exif-colorspace' => 'Тюс ютко', 'exif-pixelydimension' => 'Артовксонть эрявикс келезэ', 'exif-pixelxdimension' => 'Артовксонть эрявикс сэрезэ', 'exif-usercomment' => 'Теицянь мельть-арьсемат', 'exif-exposuretime' => 'Валдомтомань (Экспозициянь) шка', 'exif-fnumber' => 'Диафрагмань числась', 'exif-brightnessvalue' => 'Валдоксчи', 'exif-lightsource' => 'Валдонь лисьмапрязо', 'exif-flash' => 'Кивчкадема', 'exif-subjectarea' => 'Субъектонть саема тарказо', 'exif-filesource' => 'Файланть саемазо', 'exif-cfapattern' => 'CFA парцун', 'exif-contrast' => 'Контрастось', 'exif-saturation' => 'Тустолмазо', 'exif-sharpness' => 'Пштиксчизэ', 'exif-gpslatituderef' => 'Йакшамо йононь эли лембе мастор йононь келезэ', 'exif-gpslatitude' => 'Келезэ', 'exif-gpslongituderef' => 'Чилисемань эли чивалгомань кувалмо', 'exif-gpslongitude' => 'Кувалмозо', 'exif-gpsaltituderef' => 'Сэрень корямо', 'exif-gpsaltitude' => 'Сэрь', 'exif-gpsspeedref' => 'Курокксчинь единица', 'exif-gpstrackref' => 'Ютамонь нерь йонксонь корямо тарка', 'exif-gpstrack' => 'Ютамонь нерь йонкс', 'exif-gpsdestlatituderef' => 'Норовамо таркань келелмань корямо тарка', 'exif-gpsdestlatitude' => 'Норовамо тарканть келелмазо', 'exif-gpsdestlongitude' => 'Норовамо тарканть кувалмозо', 'exif-gpsdatestamp' => 'GPS чи', # EXIF attributes 'exif-compression-1' => 'Апак сювордо', 'exif-unknowndate' => 'Апак содань чи', 'exif-orientation-1' => 'Свалшкань', 'exif-orientation-3' => 'Велявтомс 180°', 'exif-orientation-5' => 'Чаравтозь 90° чинь каршо, мейле велявтозь прянзо лангс', 'exif-orientation-6' => 'Чаравтозь 90° чи мельга', 'exif-orientation-8' => 'Чаравтозь 90° чинь каршо', 'exif-componentsconfiguration-0' => 'арась', 'exif-exposureprogram-0' => 'Апак чарькодевте', 'exif-exposureprogram-1' => 'Кедьсёрмадовкс', 'exif-exposureprogram-2' => 'Эрьва чинь программа', 'exif-subjectdistance-value' => '$1 метрат', 'exif-meteringmode-0' => 'Апак содань', 'exif-meteringmode-1' => 'Куншка видэнь', 'exif-meteringmode-5' => 'Парцун', 'exif-meteringmode-6' => 'Пельксэнь-пельксэнь', 'exif-meteringmode-255' => 'Лия', 'exif-lightsource-0' => 'А содави', 'exif-lightsource-1' => 'Чи валдо', 'exif-lightsource-2' => 'Флуоресцент', 'exif-lightsource-4' => 'Кивчкадема', 'exif-lightsource-9' => 'Маней', 'exif-lightsource-10' => 'Пелензазь', 'exif-lightsource-11' => 'Сулей', 'exif-lightsource-17' => 'Стандарт валдо A', 'exif-lightsource-18' => 'Стандарт валдо B', 'exif-lightsource-19' => 'Стандарт валдо C', 'exif-lightsource-255' => 'Валдонь лия лисьмапря', # Flash modes 'exif-flash-fired-0' => 'Кивчкадемкась эзь нолдаво', 'exif-flash-fired-1' => 'Кивчкадемкась нолдавсь', 'exif-focalplaneresolutionunit-2' => 'дуймат', 'exif-sensingmethod-1' => 'Апак путо', 'exif-customrendered-0' => 'Эрьва чинь процесс', 'exif-customrendered-1' => 'Башка ёнкс марто процесс', 'exif-exposuremode-0' => 'Сонсь тееви экспозициясь', 'exif-scenecapturetype-0' => 'Стандарт', 'exif-scenecapturetype-1' => 'Ландшафт', 'exif-scenecapturetype-2' => 'Портрет', 'exif-scenecapturetype-3' => 'Вень картина', 'exif-gaincontrol-0' => 'Вейкеяк арась', 'exif-gaincontrol-1' => 'Аламошка ламолгавтома', 'exif-gaincontrol-2' => 'Пек ламолгавтома', 'exif-gaincontrol-3' => 'Аламошка вишкалгавтома', 'exif-gaincontrol-4' => 'Пек вишкалгавтома', 'exif-contrast-0' => 'Эрьва чинь', 'exif-contrast-1' => 'Чэвте', 'exif-contrast-2' => 'Калгодо', 'exif-saturation-0' => 'Эрьва чынь', 'exif-saturation-1' => 'Лавшо тустолма', 'exif-saturation-2' => 'Кеме тустолма', 'exif-sharpness-0' => 'Свал шкань', 'exif-sharpness-1' => 'Чэвте', 'exif-sharpness-2' => 'Калгодо', 'exif-subjectdistancerange-0' => 'Апак содань', 'exif-subjectdistancerange-1' => 'Макро кодось', 'exif-subjectdistancerange-2' => 'Маласто неевть', 'exif-subjectdistancerange-3' => 'Васолдонь неевть', # Pseudotags used for GPSLatitudeRef and GPSDestLatitudeRef 'exif-gpslatitude-n' => 'Йакшамо йононь келезэ', 'exif-gpslatitude-s' => 'Лембе масторонь келесь', # Pseudotags used for GPSLongitudeRef and GPSDestLongitudeRef 'exif-gpslongitude-e' => 'Чилисемань кувалмо', 'exif-gpslongitude-w' => 'Чивалгомань кувалмо', 'exif-gpsstatus-a' => 'Онкстамозо моли', 'exif-gpsmeasuremode-2' => 'келес-кувалмс онкстамо', 'exif-gpsmeasuremode-3' => 'келес-кувалмс-сэрьс онкстамо', # Pseudotags used for GPSSpeedRef 'exif-gpsspeed-k' => 'Вайгельпеть цясозонзо', 'exif-gpsspeed-m' => 'Милат цясозонзо', 'exif-gpsspeed-n' => 'Сюлмот цясозонзо', # Pseudotags used for GPSTrackRef, GPSImgDirectionRef and GPSDestBearingRef 'exif-gpsdirection-t' => 'Алкуксонь йонкс', 'exif-gpsdirection-m' => 'Магнитэнь йонкс', # External editor support 'edit-externally' => 'Витнемс-петнемс те файланть, тевс нолдазь ушо ёнксонь программанть', 'edit-externally-help' => '(Вант [http://www.mediawiki.org/wiki/Manual:External_editors аравтома инструкциятнень] седе ламо информациянть кис.)', # 'all' in various places, this might be different for inflected languages 'recentchangesall' => 'весе', 'imagelistall' => 'весе', 'watchlistall2' => 'весе', 'namespacesall' => 'весе', 'monthsall' => 'весе', 'limitall' => 'весе', # E-mail address confirmation 'confirmemail' => 'Кемекстамс е-почтань сёрмапаргот', 'confirmemail_send' => 'Кучомс е-сёрмасо кемекстамонь код', 'confirmemail_loggedin' => 'Е-сёрма паргот апак кемекста.', 'confirmemail_error' => 'Кемекстамот ванстомсто мезе-бути лиссь.', # Scary transclusion 'scarytranscludetoolong' => '[URL пек кувака]', # Trackbacks 'trackbackremove' => '([$1 Нардамс])', 'trackbacklink' => 'Мекев потамо эскельксэнь-эскельксэнь', # Delete conflict 'recreate' => 'Шкак-тейть одов', # action=purge 'confirm_purge_button' => 'ОК', # Multipage image navigation 'imgmultipageprev' => '← седикелень лопась', 'imgmultipagenext' => 'седе мейлень лопась →', 'imgmultigo' => 'Адя!', 'imgmultigoto' => 'Молемс $1 лопантень', # Table pager 'table_pager_next' => 'Седе тов ве лопа', 'table_pager_prev' => 'Седе икелень лопа', 'table_pager_first' => 'Васень лопась', 'table_pager_last' => 'Меельсе лопась', 'table_pager_limit' => 'Невтемс ве лопас $1 тевть', 'table_pager_limit_submit' => 'Адя', 'table_pager_empty' => 'Ресултатт арасть', # Auto-summaries 'autosumm-replace' => "Лопась полавтови '$1' марто", 'autosumm-new' => 'Шкавсь-теевсь од лопа $1 марто', # Live preview 'livepreview-loading' => 'Йоракшны…', 'livepreview-ready' => 'Йоракшны… Йоразь!', # Watchlist editor 'watchlistedit-normal-title' => 'Витнемс-петнемс ванстома лопанть', 'watchlistedit-normal-submit' => 'Нардамс конякстнэнь', 'watchlistedit-normal-done' => '{{PLURAL:$1|1 конякс|$1 конякст}} нардазь ваномань лопастот:', 'watchlistedit-raw-title' => 'Витнеме-петнеме верек ваномалопанть', 'watchlistedit-raw-legend' => 'Витнеме-петнеме верек ваномалопанть', 'watchlistedit-raw-titles' => 'Конякст:', 'watchlistedit-raw-submit' => 'Мезе мельга ванстнят, спискаст одкстомтомс', 'watchlistedit-raw-added' => 'Поладозь {{PLURAL:$1|1 конякс|$1 конякст}}:', 'watchlistedit-raw-removed' => '{{PLURAL:$1|1 конякс нардазь|$1 конякст нардазь}}:', # Watchlist editing tools 'watchlisttools-view' => 'Лиякстоматьне лопатнесэ потмоксстонть', 'watchlisttools-edit' => 'Ваномс ды витнемс-петнемс мезе мельга ванстнят', 'watchlisttools-raw' => 'Витнеме-петнеме верек ваномалопанть', # Special:Version 'version' => 'Версия', 'version-specialpages' => 'Башка тевень лопат', 'version-variables' => 'Полавтневикс тевть', 'version-other' => 'Лия', 'version-hooks' => 'Кечказт', 'version-hook-name' => 'Кечказонть лемезэ', 'version-hook-subscribedby' => 'Сёрмадстызе', 'version-version' => '(Версия $1)', 'version-license' => 'Лицензия', 'version-software' => 'Нолдань программат', 'version-software-product' => 'Шкавкс-нолдавкс', 'version-software-version' => 'Верзия', # Special:FilePath 'filepath' => 'Файлас яннэ', 'filepath-page' => 'Файл:', 'filepath-submit' => 'Ютак', # Special:FileDuplicateSearch 'fileduplicatesearch' => 'Вешнэмс кавтаське файлат', 'fileduplicatesearch-legend' => 'Вешнэмс кавтаське', 'fileduplicatesearch-filename' => 'Файла лем:', 'fileduplicatesearch-submit' => 'Вешнэмс', # Special:SpecialPages 'specialpages' => 'Башка тевень лопат', 'specialpages-group-other' => 'Лия башка тевень лопат', 'specialpages-group-login' => 'Совамо / прянь сёрмадстомо', 'specialpages-group-users' => 'Теицятне ды видечыст', 'specialpages-group-highuse' => 'Пек тевс нолдазь лопат', 'specialpages-group-pages' => 'Лопа керькст', 'specialpages-group-pagetools' => 'Лопань кедьёнкст', 'specialpages-group-wiki' => 'Викинь дата ды кедьйонкст', 'specialpages-group-redirects' => 'Башка тевень лопатнень ютавтома лия таркас', 'specialpages-group-spam' => 'Шукш пачтнематнеде кедьёнкст', # Special:BlankPage 'blankpage' => 'Чаво лопа', 'intentionallyblankpage' => 'Те лопась арьсезь-содазь чавосто кадозь', # Special:Tags 'tag-filter-submit' => 'Сувтемень пачк нолдамс', 'tags-edit' => 'витнемс-петнемс', # Database error messages 'dberr-header' => 'Те викисэнть проблема', # HTML forms 'htmlform-selectorother-other' => 'Лия', );
thewebmind/docs
languages/messages/MessagesMyv.php
PHP
gpl-2.0
150,122
/* Copyright (C) 1991-2015 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <unistd.h> #include <sys/types.h> /* Set the user ID of the calling process to UID. If the calling process is the super-user, the real and effective user IDs, and the saved set-user-ID to UID; if not, the effective user ID is set to UID. */ int __setuid (uid_t uid) { __set_errno (ENOSYS); return -1; } stub_warning (setuid) weak_alias (__setuid, setuid)
gbenson/glibc
posix/setuid.c
C
gpl-2.0
1,188
<?php foreach ($items as $file) : ?> <li id="file-id-<?php echo $file->id?>"><a title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('files/files','Delete file')?>" onclick="return lhinst.deleteChatfile('<?php echo $file->id?>')" class="button tiny round icon-trash"></a> <a href="<?php echo erLhcoreClassDesign::baseurl('file/downloadfile')?>/<?php echo $file->id?>/<?php echo $file->security_hash?>" class="link" target="_blank"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('files/files','Download file')?> - <?php echo htmlspecialchars($file->upload_name).' ['.$file->extension.']'?> </a></li> <?php endforeach; ?>
euqip/glpi-smartcities
plugins/chat/front/design/defaulttheme/tpl/lhfile/chatfileslist.tpl.php
PHP
gpl-2.0
674
/* Copyright (C) 1991-2015 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <sys/socket.h> /* Send N bytes of BUF to socket FD. Returns the number sent or -1. */ ssize_t __send (int fd, const __ptr_t buf, size_t n, int flags) { __set_errno (ENOSYS); return -1; } libc_hidden_def (__send) weak_alias (__send, send) stub_warning (send)
gbenson/glibc
socket/send.c
C
gpl-2.0
1,083
/* $Id: uaccess.h,v 1.24 2001/10/30 04:32:24 davem Exp $ * uaccess.h: User space memore access functions. * * Copyright (C) 1996 David S. Miller (davem@caip.rutgers.edu) * Copyright (C) 1996,1997 Jakub Jelinek (jj@sunsite.mff.cuni.cz) */ #ifndef _ASM_UACCESS_H #define _ASM_UACCESS_H #ifdef __KERNEL__ #include <linux/compiler.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/errno.h> #include <asm/vac-ops.h> #include <asm/a.out.h> #endif #ifndef __ASSEMBLY__ /* Sparc is not segmented, however we need to be able to fool verify_area() * when doing system calls from kernel mode legitimately. * * "For historical reasons, these macros are grossly misnamed." -Linus */ #define KERNEL_DS ((mm_segment_t) { 0 }) #define USER_DS ((mm_segment_t) { -1 }) #define VERIFY_READ 0 #define VERIFY_WRITE 1 #define get_ds() (KERNEL_DS) #define get_fs() (current->thread.current_ds) #define set_fs(val) ((current->thread.current_ds) = (val)) #define segment_eq(a,b) ((a).seg == (b).seg) /* We have there a nice not-mapped page at PAGE_OFFSET - PAGE_SIZE, so that this test * can be fairly lightweight. * No one can read/write anything from userland in the kernel space by setting * large size and address near to PAGE_OFFSET - a fault will break his intentions. */ #define __user_ok(addr,size) ((addr) < STACK_TOP) #define __kernel_ok (segment_eq(get_fs(), KERNEL_DS)) #define __access_ok(addr,size) (__user_ok((addr) & get_fs().seg,(size))) #define access_ok(type,addr,size) __access_ok((unsigned long)(addr),(size)) static inline int verify_area(int type, const void __user * addr, unsigned long size) { return access_ok(type,addr,size)?0:-EFAULT; } /* * The exception table consists of pairs of addresses: the first is the * address of an instruction that is allowed to fault, and the second is * the address at which the program should continue. No registers are * modified, so it is entirely up to the continuation code to figure out * what to do. * * All the routines below use bits of fixup code that are out of line * with the main instruction path. This means when everything is well, * we don't even have to jump over them. Further, they do not intrude * on our cache or tlb entries. * * There is a special way how to put a range of potentially faulting * insns (like twenty ldd/std's with now intervening other instructions) * You specify address of first in insn and 0 in fixup and in the next * exception_table_entry you specify last potentially faulting insn + 1 * and in fixup the routine which should handle the fault. * That fixup code will get * (faulting_insn_address - first_insn_in_the_range_address)/4 * in %g2 (ie. index of the faulting instruction in the range). */ struct exception_table_entry { unsigned long insn, fixup; }; /* Returns 0 if exception not found and fixup otherwise. */ extern unsigned long search_extables_range(unsigned long addr, unsigned long *g2); extern void __ret_efault(void); /* Uh, these should become the main single-value transfer routines.. * They automatically use the right size if we just have the right * pointer type.. * * This gets kind of ugly. We want to return _two_ values in "get_user()" * and yet we don't want to do any pointers, because that is too much * of a performance impact. Thus we have a few rather ugly macros here, * and hide all the ugliness from the user. */ #define put_user(x,ptr) ({ \ unsigned long __pu_addr = (unsigned long)(ptr); \ __chk_user_ptr(ptr); \ __put_user_check((__typeof__(*(ptr)))(x),__pu_addr,sizeof(*(ptr))); }) #define get_user(x,ptr) ({ \ unsigned long __gu_addr = (unsigned long)(ptr); \ __chk_user_ptr(ptr); \ __get_user_check((x),__gu_addr,sizeof(*(ptr)),__typeof__(*(ptr))); }) /* * The "__xxx" versions do not do address space checking, useful when * doing multiple accesses to the same area (the user has to do the * checks by hand with "access_ok()") */ #define __put_user(x,ptr) __put_user_nocheck((__typeof__(*(ptr)))(x),(ptr),sizeof(*(ptr))) #define __get_user(x,ptr) __get_user_nocheck((x),(ptr),sizeof(*(ptr)),__typeof__(*(ptr))) struct __large_struct { unsigned long buf[100]; }; #define __m(x) ((struct __large_struct *)(x)) #define __put_user_check(x,addr,size) ({ \ register int __pu_ret; \ if (__access_ok(addr,size)) { \ switch (size) { \ case 1: __put_user_asm(x,b,addr,__pu_ret); break; \ case 2: __put_user_asm(x,h,addr,__pu_ret); break; \ case 4: __put_user_asm(x,,addr,__pu_ret); break; \ case 8: __put_user_asm(x,d,addr,__pu_ret); break; \ default: __pu_ret = __put_user_bad(); break; \ } } else { __pu_ret = -EFAULT; } __pu_ret; }) #define __put_user_check_ret(x,addr,size,retval) ({ \ register int __foo __asm__ ("l1"); \ if (__access_ok(addr,size)) { \ switch (size) { \ case 1: __put_user_asm_ret(x,b,addr,retval,__foo); break; \ case 2: __put_user_asm_ret(x,h,addr,retval,__foo); break; \ case 4: __put_user_asm_ret(x,,addr,retval,__foo); break; \ case 8: __put_user_asm_ret(x,d,addr,retval,__foo); break; \ default: if (__put_user_bad()) return retval; break; \ } } else return retval; }) #define __put_user_nocheck(x,addr,size) ({ \ register int __pu_ret; \ switch (size) { \ case 1: __put_user_asm(x,b,addr,__pu_ret); break; \ case 2: __put_user_asm(x,h,addr,__pu_ret); break; \ case 4: __put_user_asm(x,,addr,__pu_ret); break; \ case 8: __put_user_asm(x,d,addr,__pu_ret); break; \ default: __pu_ret = __put_user_bad(); break; \ } __pu_ret; }) #define __put_user_nocheck_ret(x,addr,size,retval) ({ \ register int __foo __asm__ ("l1"); \ switch (size) { \ case 1: __put_user_asm_ret(x,b,addr,retval,__foo); break; \ case 2: __put_user_asm_ret(x,h,addr,retval,__foo); break; \ case 4: __put_user_asm_ret(x,,addr,retval,__foo); break; \ case 8: __put_user_asm_ret(x,d,addr,retval,__foo); break; \ default: if (__put_user_bad()) return retval; break; \ } }) #define __put_user_asm(x,size,addr,ret) \ __asm__ __volatile__( \ "/* Put user asm, inline. */\n" \ "1:\t" "st"#size " %1, %2\n\t" \ "clr %0\n" \ "2:\n\n\t" \ ".section .fixup,#alloc,#execinstr\n\t" \ ".align 4\n" \ "3:\n\t" \ "b 2b\n\t" \ " mov %3, %0\n\t" \ ".previous\n\n\t" \ ".section __ex_table,#alloc\n\t" \ ".align 4\n\t" \ ".word 1b, 3b\n\t" \ ".previous\n\n\t" \ : "=&r" (ret) : "r" (x), "m" (*__m(addr)), \ "i" (-EFAULT)) #define __put_user_asm_ret(x,size,addr,ret,foo) \ if (__builtin_constant_p(ret) && ret == -EFAULT) \ __asm__ __volatile__( \ "/* Put user asm ret, inline. */\n" \ "1:\t" "st"#size " %1, %2\n\n\t" \ ".section __ex_table,#alloc\n\t" \ ".align 4\n\t" \ ".word 1b, __ret_efault\n\n\t" \ ".previous\n\n\t" \ : "=r" (foo) : "r" (x), "m" (*__m(addr))); \ else \ __asm__ __volatile( \ "/* Put user asm ret, inline. */\n" \ "1:\t" "st"#size " %1, %2\n\n\t" \ ".section .fixup,#alloc,#execinstr\n\t" \ ".align 4\n" \ "3:\n\t" \ "ret\n\t" \ " restore %%g0, %3, %%o0\n\t" \ ".previous\n\n\t" \ ".section __ex_table,#alloc\n\t" \ ".align 4\n\t" \ ".word 1b, 3b\n\n\t" \ ".previous\n\n\t" \ : "=r" (foo) : "r" (x), "m" (*__m(addr)), "i" (ret)) extern int __put_user_bad(void); #define __get_user_check(x,addr,size,type) ({ \ register int __gu_ret; \ register unsigned long __gu_val; \ if (__access_ok(addr,size)) { \ switch (size) { \ case 1: __get_user_asm(__gu_val,ub,addr,__gu_ret); break; \ case 2: __get_user_asm(__gu_val,uh,addr,__gu_ret); break; \ case 4: __get_user_asm(__gu_val,,addr,__gu_ret); break; \ case 8: __get_user_asm(__gu_val,d,addr,__gu_ret); break; \ default: __gu_val = 0; __gu_ret = __get_user_bad(); break; \ } } else { __gu_val = 0; __gu_ret = -EFAULT; } x = (type) __gu_val; __gu_ret; }) #define __get_user_check_ret(x,addr,size,type,retval) ({ \ register unsigned long __gu_val __asm__ ("l1"); \ if (__access_ok(addr,size)) { \ switch (size) { \ case 1: __get_user_asm_ret(__gu_val,ub,addr,retval); break; \ case 2: __get_user_asm_ret(__gu_val,uh,addr,retval); break; \ case 4: __get_user_asm_ret(__gu_val,,addr,retval); break; \ case 8: __get_user_asm_ret(__gu_val,d,addr,retval); break; \ default: if (__get_user_bad()) return retval; \ } x = (type) __gu_val; } else return retval; }) #define __get_user_nocheck(x,addr,size,type) ({ \ register int __gu_ret; \ register unsigned long __gu_val; \ switch (size) { \ case 1: __get_user_asm(__gu_val,ub,addr,__gu_ret); break; \ case 2: __get_user_asm(__gu_val,uh,addr,__gu_ret); break; \ case 4: __get_user_asm(__gu_val,,addr,__gu_ret); break; \ case 8: __get_user_asm(__gu_val,d,addr,__gu_ret); break; \ default: __gu_val = 0; __gu_ret = __get_user_bad(); break; \ } x = (type) __gu_val; __gu_ret; }) #define __get_user_nocheck_ret(x,addr,size,type,retval) ({ \ register unsigned long __gu_val __asm__ ("l1"); \ switch (size) { \ case 1: __get_user_asm_ret(__gu_val,ub,addr,retval); break; \ case 2: __get_user_asm_ret(__gu_val,uh,addr,retval); break; \ case 4: __get_user_asm_ret(__gu_val,,addr,retval); break; \ case 8: __get_user_asm_ret(__gu_val,d,addr,retval); break; \ default: if (__get_user_bad()) return retval; \ } x = (type) __gu_val; }) #define __get_user_asm(x,size,addr,ret) \ __asm__ __volatile__( \ "/* Get user asm, inline. */\n" \ "1:\t" "ld"#size " %2, %1\n\t" \ "clr %0\n" \ "2:\n\n\t" \ ".section .fixup,#alloc,#execinstr\n\t" \ ".align 4\n" \ "3:\n\t" \ "clr %1\n\t" \ "b 2b\n\t" \ " mov %3, %0\n\n\t" \ ".previous\n\t" \ ".section __ex_table,#alloc\n\t" \ ".align 4\n\t" \ ".word 1b, 3b\n\n\t" \ ".previous\n\t" \ : "=&r" (ret), "=&r" (x) : "m" (*__m(addr)), \ "i" (-EFAULT)) #define __get_user_asm_ret(x,size,addr,retval) \ if (__builtin_constant_p(retval) && retval == -EFAULT) \ __asm__ __volatile__( \ "/* Get user asm ret, inline. */\n" \ "1:\t" "ld"#size " %1, %0\n\n\t" \ ".section __ex_table,#alloc\n\t" \ ".align 4\n\t" \ ".word 1b,__ret_efault\n\n\t" \ ".previous\n\t" \ : "=&r" (x) : "m" (*__m(addr))); \ else \ __asm__ __volatile__( \ "/* Get user asm ret, inline. */\n" \ "1:\t" "ld"#size " %1, %0\n\n\t" \ ".section .fixup,#alloc,#execinstr\n\t" \ ".align 4\n" \ "3:\n\t" \ "ret\n\t" \ " restore %%g0, %2, %%o0\n\n\t" \ ".previous\n\t" \ ".section __ex_table,#alloc\n\t" \ ".align 4\n\t" \ ".word 1b, 3b\n\n\t" \ ".previous\n\t" \ : "=&r" (x) : "m" (*__m(addr)), "i" (retval)) extern int __get_user_bad(void); extern unsigned long __copy_user(void __user *to, const void __user *from, unsigned long size); static inline unsigned long copy_to_user(void __user *to, const void *from, unsigned long n) { if (n && __access_ok((unsigned long) to, n)) return __copy_user(to, (void __user *) from, n); else return n; } static inline unsigned long __copy_to_user(void __user *to, const void *from, unsigned long n) { return __copy_user(to, (void __user *) from, n); } static inline unsigned long copy_from_user(void *to, const void __user *from, unsigned long n) { if (n && __access_ok((unsigned long) from, n)) return __copy_user((void __user *) to, from, n); else return n; } static inline unsigned long __copy_from_user(void *to, const void __user *from, unsigned long n) { return __copy_user((void __user *) to, from, n); } static inline unsigned long __clear_user(void __user *addr, unsigned long size) { unsigned long ret; __asm__ __volatile__ ( ".section __ex_table,#alloc\n\t" ".align 4\n\t" ".word 1f,3\n\t" ".previous\n\t" "mov %2, %%o1\n" "1:\n\t" "call __bzero\n\t" " mov %1, %%o0\n\t" "mov %%o0, %0\n" : "=r" (ret) : "r" (addr), "r" (size) : "o0", "o1", "o2", "o3", "o4", "o5", "o7", "g1", "g2", "g3", "g4", "g5", "g7", "cc"); return ret; } static inline unsigned long clear_user(void __user *addr, unsigned long n) { if (n && __access_ok((unsigned long) addr, n)) return __clear_user(addr, n); else return n; } extern long __strncpy_from_user(char *dest, const char __user *src, long count); static inline long strncpy_from_user(char *dest, const char __user *src, long count) { if (__access_ok((unsigned long) src, count)) return __strncpy_from_user(dest, src, count); else return -EFAULT; } extern long __strlen_user(const char __user *); extern long __strnlen_user(const char __user *, long len); static inline long strlen_user(const char __user *str) { if (!access_ok(VERIFY_READ, str, 0)) return 0; else return __strlen_user(str); } static inline long strnlen_user(const char __user *str, long len) { if (!access_ok(VERIFY_READ, str, 0)) return 0; else return __strnlen_user(str, len); } #endif /* __ASSEMBLY__ */ #endif /* _ASM_UACCESS_H */
z3bu/AH4222
kernel/linux/include/asm-sparc/uaccess.h
C
gpl-2.0
12,964
/* * report.h * * Copyright(c) 1998 - 2010 Texas Instruments. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name Texas Instruments nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /***************************************************************************/ /* */ /* MODULE: report.h */ /* PURPOSE: Report module internal header API */ /* */ /***************************************************************************/ #ifndef __REPORT_H__ #define __REPORT_H__ /** \file report.h * \brief Report module API \n * APIs which are used for reporting messages to the User while running. \n\n * * The report mechanism: Messages are reported per file and severity Level \n * Therefore, each file has a report flag which indicate if reporting for that file is enabled, \n * and each severity has a severity flag which indicate if reporting for that severity is enabled. \n * Only if both flags are enabled, the message is printed. \n * The report flags of all file are indicated in a bit map Table which is contained in the report module handle \n * The report flags of all severities are indicated in a bit map Table which is contained in the report module handle \n */ /* in order to work without the driver logger use that definition here * #define PRINTF_ROLLBACK */ #include "osApi.h" #include "commonTypes.h" #define MAX_STRING_LEN 32 /*******************************/ /* Report Files IDs */ /*******************************/ typedef enum { FILE_ID_0, /* timer */ FILE_ID_1, /* measurementMgr */ FILE_ID_2, /* measurementMgrSM */ FILE_ID_3, /* regulatoryDomain */ FILE_ID_4, /* requestHandler */ FILE_ID_5, /* SoftGemini */ FILE_ID_6, /* spectrumMngmntMgr */ FILE_ID_7, /* SwitchChannel */ FILE_ID_8, /* roamingMngr */ FILE_ID_9, /* scanMngr */ FILE_ID_10, /* admCtrlXCC */ FILE_ID_11, /* XCCMngr */ FILE_ID_12, /* XCCRMMngr */ FILE_ID_13, /* XCCTSMngr */ FILE_ID_14, /* rogueAp */ FILE_ID_15, /* TransmitPowerXCC */ FILE_ID_16, /* admCtrl */ FILE_ID_17, /* admCtrlNone */ FILE_ID_18, /* admCtrlWep */ FILE_ID_19, /* admCtrlWpa */ FILE_ID_20, /* admCtrlWpa2 */ FILE_ID_21, /* apConn */ FILE_ID_22, /* broadcastKey802_1x */ FILE_ID_23, /* broadcastKeyNone */ FILE_ID_24, /* broadcastKeySM */ FILE_ID_25, /* conn */ FILE_ID_26, /* connIbss */ FILE_ID_27, /* connInfra */ FILE_ID_28, /* keyDerive */ FILE_ID_29, /* keyDeriveAes */ FILE_ID_30, /* keyDeriveCkip */ FILE_ID_31, /* keyDeriveTkip */ FILE_ID_32, /* keyDeriveWep */ FILE_ID_33, /* keyParser */ FILE_ID_34, /* keyParserExternal */ FILE_ID_35, /* keyParserWep */ FILE_ID_36, /* mainKeysSm */ FILE_ID_37, /* mainSecKeysOnly */ FILE_ID_38, /* mainSecNull */ FILE_ID_39, /* mainSecSm */ FILE_ID_40, /* rsn */ FILE_ID_41, /* sme */ FILE_ID_42, /* smeSelect */ FILE_ID_43, /* smeSm */ FILE_ID_44, /* unicastKey802_1x */ FILE_ID_45, /* unicastKeyNone */ FILE_ID_46, /* unicastKeySM */ FILE_ID_47, /* CmdDispatcher */ FILE_ID_48, /* CmdHndlr */ FILE_ID_49, /* DrvMain */ FILE_ID_50, /* EvHandler */ FILE_ID_51, /* Ctrl */ FILE_ID_52, /* GeneralUtil */ FILE_ID_53, /* RateAdaptation */ FILE_ID_54, /* rx */ FILE_ID_55, /* TrafficMonitor */ FILE_ID_56, /* txCtrl */ FILE_ID_57, /* txCtrlParams */ FILE_ID_58, /* txCtrlServ */ FILE_ID_59, /* TxDataClsfr */ FILE_ID_60, /* txDataQueue */ FILE_ID_61, /* txMgmtQueue */ FILE_ID_62, /* txPort */ FILE_ID_63, /* assocSM */ FILE_ID_64, /* authSm */ FILE_ID_65, /* currBss */ FILE_ID_66, /* healthMonitor */ FILE_ID_67, /* mlmeBuilder */ FILE_ID_68, /* mlmeParser */ FILE_ID_69, /* mlmeSm */ FILE_ID_70, /* openAuthSm */ FILE_ID_71, /* PowerMgr */ FILE_ID_72, /* PowerMgrDbgPrint */ FILE_ID_73, /* PowerMgrKeepAlive */ FILE_ID_74, /* qosMngr */ FILE_ID_75, /* roamingInt */ FILE_ID_76, /* ScanCncn */ FILE_ID_77, /* ScanCncnApp */ FILE_ID_78, /* ScanCncnOsSm */ FILE_ID_79, /* ScanCncnSm */ FILE_ID_80, /* ScanCncnSmSpecific */ FILE_ID_81, /* scanResultTable */ FILE_ID_82, /* scr */ FILE_ID_83, /* sharedKeyAuthSm */ FILE_ID_84, /* siteHash */ FILE_ID_85, /* siteMgr */ FILE_ID_86, /* StaCap */ FILE_ID_87, /* systemConfig */ FILE_ID_88, /* templates */ FILE_ID_89, /* trafficAdmControl */ FILE_ID_90, /* CmdBld */ FILE_ID_91, /* CmdBldCfg */ FILE_ID_92, /* CmdBldCfgIE */ FILE_ID_93, /* CmdBldCmd */ FILE_ID_94, /* CmdBldCmdIE */ FILE_ID_95, /* CmdBldItr */ FILE_ID_96, /* CmdBldItrIE */ FILE_ID_97, /* CmdQueue */ FILE_ID_98, /* RxQueue */ FILE_ID_99, /* txCtrlBlk */ FILE_ID_100, /* txHwQueue */ FILE_ID_101, /* CmdMBox */ FILE_ID_102, /* eventMbox */ FILE_ID_103, /* fwDebug */ FILE_ID_104, /* FwEvent */ FILE_ID_105, /* HwInit */ FILE_ID_106, /* RxXfer */ FILE_ID_107, /* txResult */ FILE_ID_108, /* txXfer */ FILE_ID_109, /* MacServices */ FILE_ID_110, /* MeasurementSrv */ FILE_ID_111, /* measurementSrvDbgPrint */ FILE_ID_112, /* MeasurementSrvSM */ FILE_ID_113, /* PowerSrv */ FILE_ID_114, /* PowerSrvSM */ FILE_ID_115, /* ScanSrv */ FILE_ID_116, /* ScanSrvSM */ FILE_ID_117, /* TWDriver */ FILE_ID_118, /* TWDriverCtrl */ FILE_ID_119, /* TWDriverRadio */ FILE_ID_120, /* TWDriverTx */ FILE_ID_121, /* TwIf */ FILE_ID_122, /* SdioBusDrv */ FILE_ID_123, /* TxnQueue */ FILE_ID_124, /* WspiBusDrv */ FILE_ID_125, /* context */ FILE_ID_126, /* freq */ FILE_ID_127, /* fsm */ FILE_ID_128, /* GenSM */ FILE_ID_129, /* mem */ FILE_ID_130, /* queue */ FILE_ID_131, /* rate */ FILE_ID_132, /* report */ FILE_ID_133, /* stack */ FILE_ID_134, /* externalSec */ FILE_ID_135, /* roamingMngr_autoSM */ FILE_ID_136, /* roamingMngr_manualSM */ FILE_ID_137, /* cmdinterpretoid */ FILE_ID_138, /* wlandrvif */ REPORT_FILES_NUM /* Number of files with trace reports */ } EReportFiles; /************************************/ /* Report Severity values */ /************************************/ /** \enum EReportSeverity * \brief Report Severity Types * * \par Description * All available severity Levels of the events which are reported to user.\n * * \sa */ typedef enum { REPORT_SEVERITY_INIT = 1, /**< Init Level (event happened during initialization) */ REPORT_SEVERITY_INFORMATION = 2, /**< Information Level */ REPORT_SEVERITY_WARNING = 3, /**< Warning Level */ REPORT_SEVERITY_ERROR = 4, /**< Error Level (error accored) */ REPORT_SEVERITY_FATAL_ERROR = 5, /**< Fatal-Error Level (fatal-error accored) */ REPORT_SEVERITY_SM = 6, /**< State-Machine Level (event happened in State-Machine) */ REPORT_SEVERITY_CONSOLE = 7, /**< Consol Level (event happened in Consol) */ REPORT_SEVERITY_MAX = REPORT_SEVERITY_CONSOLE + 1 /**< Maximum number of report severity levels */ } EReportSeverity; /** \enum EProblemType * \brief used to handle SW problems according to their types. * * \par Description * All available SW problem types checked in run time.\n * * \sa */ typedef enum { PROBLEM_BUF_SIZE_VIOLATION = 1, PROBLEM_NULL_VALUE_PTR = 2, PROBLEM_MAX_VALUE } EProblemType; /** \struct TReport * \brief Report Module Object * * \par Description * All the Databases and other parameters which are needed for reporting messages to user * * \sa */ typedef struct { TI_HANDLE hOs; /**< Handle to Operating System Object */ TI_UINT8 aSeverityTable[REPORT_SEVERITY_MAX]; /**< Severities Table: Table which holds for each severity level a flag which indicates whether the severity is enabled for reporting */ char aSeverityDesc[REPORT_SEVERITY_MAX][MAX_STRING_LEN]; /**< Severities Descriptors Table: Table which holds for each severity a string of its name, which is used in severity's reported messages */ TI_UINT8 aFileEnable[REPORT_FILES_NUM]; /**< Files table indicating per file if it is enabled for reporting */ #ifdef PRINTF_ROLLBACK char aFileName[REPORT_FILES_NUM][MAX_STRING_LEN]; /**< Files names table inserted in the file's reported messages */ #endif } TReport; /** \struct TReportParamInfo * \brief Report Parameter Information * * \par Description * Struct which defines all the Databases and other parameters which are needed * for reporting messages to user. * The actual Content of the Report Parameter Could be one of the followed (held in union): * Severety Table | Module Table | Enable/Disable indication of debug module usage * * \sa EExternalParam, ETwdParam */ typedef struct { TI_UINT32 paramType; /**< The reported parameter type - one of External Parameters (which includes Set,Get, Module, internal number etc.) * of Report Module. Used by user for Setting or Getting Report Module Paramters, for exaple Set/Get severety table * to/from Report Module */ TI_UINT32 paramLength; /**< Length of reported parameter */ union { TI_UINT8 aSeverityTable[REPORT_SEVERITY_MAX]; /**< Table which holds severity flag for every available LOG severity level. * This flag indicates for each severity - whether it is enabled for Logging or not. * User can Set/Get this Tabel */ TI_UINT8 aFileEnable[REPORT_FILES_NUM]; /**< Table which holds file flag for every available LOG file. * This flag indicates for each file - whether it is enabled for Logging or not. * User can Set/Get this Tabel */ TI_UINT32 uReportPPMode; /**< Used by user for Indicating if Debug Module should be enabled/disabled */ } content; } TReportParamInfo; /** \struct TReportInitParams * \brief Report Init Parameters * * \par Description * Struct which defines all the Databases needed for init and set the defualts of the Report Module. * */ typedef struct { /* Note: The arrays sizes are aligned to 4 byte to avoid padding added by the compiler! */ TI_UINT8 aSeverityTable[(REPORT_SEVERITY_MAX + 3) & ~3]; /**< Table in the size of all available LOG severity levels which indicates for each severity - whether it is enabled for Logging or not. */ TI_UINT8 aFileEnable[(REPORT_FILES_NUM + 3) & ~3]; /**< Table in the size of all available LOG files which indicates for each file - whether it is enabled for Logging or not */ } TReportInitParams; /****************************/ /* report module Macros */ /****************************/ /* The report mechanism is like that: Each file has a report flag. Each severity has a severity flag. Only if bits are enabled, the message is printed */ /* The modules which have their report flag enable are indicated by a bit map in the reportModule variable contained in the report handle*/ /* The severities which have are enabled are indicated by a bit map in the reportSeverity variable contained in the report handle*/ /* general trace messages */ #ifndef PRINTF_ROLLBACK #define TRACE0(hReport, level, str) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 0); } } while(0) #define TRACE1(hReport, level, str, p1) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 1, (TI_UINT32)p1); } } while(0) #define TRACE2(hReport, level, str, p1, p2) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 2, (TI_UINT32)p1, (TI_UINT32)p2); } } while(0) #define TRACE3(hReport, level, str, p1, p2, p3) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 3, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3); } } while(0) #define TRACE4(hReport, level, str, p1, p2, p3, p4) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 4, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4); } } while(0) #define TRACE5(hReport, level, str, p1, p2, p3, p4, p5) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 5, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5); } } while(0) #define TRACE6(hReport, level, str, p1, p2, p3, p4, p5, p6) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 6, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6); } } while(0) #define TRACE7(hReport, level, str, p1, p2, p3, p4, p5, p6, p7) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 7, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7); } } while(0) #define TRACE8(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 8, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8); } } while(0) #define TRACE9(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 9, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9); } } while(0) #define TRACE10(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 10, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10); } } while(0) #define TRACE11(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 11, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11); } } while(0) #define TRACE12(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 12, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12); } } while(0) #define TRACE13(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 13, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13); } } while(0) #define TRACE14(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 14, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14); } } while(0) #define TRACE15(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 15, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15); } } while(0) #define TRACE16(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 16, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16); } } while(0) #define TRACE17(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 17, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17); } } while(0) #define TRACE18(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 18, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17, (TI_UINT32)p18); } } while(0) #define TRACE19(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 19, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17, (TI_UINT32)p18, (TI_UINT32)p19); } } while(0) #define TRACE20(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 20, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17, (TI_UINT32)p18, (TI_UINT32)p19, (TI_UINT32)p20); } } while(0) #define TRACE21(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 21, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17, (TI_UINT32)p18, (TI_UINT32)p19, (TI_UINT32)p20, (TI_UINT32)p21); } } while(0) #define TRACE22(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 22, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17, (TI_UINT32)p18, (TI_UINT32)p19, (TI_UINT32)p20, (TI_UINT32)p21, (TI_UINT32)p22); } } while(0) #define TRACE25(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 22, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17, (TI_UINT32)p18, (TI_UINT32)p19, (TI_UINT32)p20, (TI_UINT32)p21, (TI_UINT32)p22, (TI_UINT32)p23, (TI_UINT32)p24, (TI_UINT32)p25); } } while(0) #define TRACE31(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_Trace((((TReport *)hReport)->hOs), level, __FILE_ID__, __LINE__, 22, (TI_UINT32)p1, (TI_UINT32)p2, (TI_UINT32)p3, (TI_UINT32)p4, (TI_UINT32)p5, (TI_UINT32)p6, (TI_UINT32)p7, (TI_UINT32)p8, (TI_UINT32)p9, (TI_UINT32)p10, (TI_UINT32)p11, (TI_UINT32)p12, (TI_UINT32)p13, (TI_UINT32)p14, (TI_UINT32)p15, (TI_UINT32)p16, (TI_UINT32)p17, (TI_UINT32)p18, (TI_UINT32)p19, (TI_UINT32)p20, (TI_UINT32)p21, (TI_UINT32)p22, (TI_UINT32)p23, (TI_UINT32)p24, (TI_UINT32)p25, (TI_UINT32)p26, (TI_UINT32)p27, (TI_UINT32)p28, (TI_UINT32)p29, (TI_UINT32)p30, (TI_UINT32)p31); } } while(0) #else /* PRINTF_ROLLBACK */ #define TRACE0(hReport, level, str) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str); } } while(0) #define TRACE1(hReport, level, str, p1) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1); } } while(0) #define TRACE2(hReport, level, str, p1, p2) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2); } } while(0) #define TRACE3(hReport, level, str, p1, p2, p3) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3); } } while(0) #define TRACE4(hReport, level, str, p1, p2, p3, p4) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4); } } while(0) #define TRACE5(hReport, level, str, p1, p2, p3, p4, p5) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5); } } while(0) #define TRACE6(hReport, level, str, p1, p2, p3, p4, p5, p6) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6); } } while(0) #define TRACE7(hReport, level, str, p1, p2, p3, p4, p5, p6, p7) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7); } } while(0) #define TRACE8(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8); } } while(0) #define TRACE9(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9); } } while(0) #define TRACE10(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } } while(0) #define TRACE11(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); } } while(0) #define TRACE12(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); } } while(0) #define TRACE13(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } } while(0) #define TRACE14(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14); } } while(0) #define TRACE15(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15); } } while(0) #define TRACE16(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16); } } while(0) #define TRACE17(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17); } } while(0) #define TRACE18(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18); } } while(0) #define TRACE19(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19); } } while(0) #define TRACE20(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20); } } while(0) #define TRACE21(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21); } } while(0) #define TRACE22(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22); } } while(0) #define TRACE25(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25); } } while(0) #define TRACE31(hReport, level, str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[level]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { os_printf ("%s, %s:", ((TReport *)hReport)->aFileName[__FILE_ID__], ((TReport *)hReport)->aSeverityDesc[level]); os_printf (str, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p27, p27, p28, p29, p30, p31); } } while(0) #endif /* #ifdef PRINTF_ROLLBACK */ /****************************/ /* report module Macros */ /****************************/ /* The report mechanism is like that: Each file has a report flag. Each severity has a severity flag. Only if bits are enabled, the message is printed */ /* The modules which have their report flag enable are indicated by a bit map in the reportModule variable contained in the report handle*/ /* The severities which have are enabled are indicated by a bit map in the reportSeverity variable contained in the report handle*/ #ifdef REPORT_LOG /** \def WLAN_OS_REPORT * \brief Macro which writes a message to user via specific Operating System printf. * E.g. print is done using the relevant used OS printf method. */ #define WLAN_OS_REPORT(msg) \ do { os_printf msg;} while(0) #ifdef INIT_MESSAGES /** \def WLAN_INIT_REPORT * \brief Macro which writes a message to user via specific Operating System printf. * E.g. print is done using the relevant used OS printf method. */ #define WLAN_INIT_REPORT(msg) \ do { os_printf msg;} while(0) #else /** \def WLAN_INIT_REPORT * \brief Macro which writes a message to user via specific Operating System printf. * E.g. print is done using the relevant used OS printf method. */ #define WLAN_INIT_REPORT(msg) #endif #define TRACE_INFO_HEX(hReport, data, datalen) \ do { if (hReport && (((TReport *)hReport)->aSeverityTable[REPORT_SEVERITY_INFORMATION]) && (((TReport *)hReport)->aFileEnable[__FILE_ID__])) \ { report_PrintDump (data, datalen); } } while(0) #else /* REPORT_LOG */ /* NOTE: Keep a dummy report function call to treat compilation warnings */ /** \def WLAN_OS_REPORT * \brief Dummy macro: Nothing is done */ #define WLAN_OS_REPORT(msg) \ do { } while (0) /** \def WLAN_INIT_REPORT * \brief Dummy macro: Nothing is done */ #define WLAN_INIT_REPORT(msg) \ do { } while (0) #define TRACE_INFO_HEX(hReport, data, datalen) \ do { } while (0) #endif /* REPORT_LOG */ /****************************/ /* report module prototypes */ /****************************/ /** \brief Create Report Module Object * \param hOs - OS module object handle * \return Handle to the report module on success, NULL otherwise * * \par Description * Report module creation function, called by the config mgr in creation phase \n * performs the following: \n * - Allocate the report handle */ TI_HANDLE report_Create(TI_HANDLE hOs); /** \brief Set Report Module Defaults * \param hReport - Report module object handle * \param pInitParams - Pointer to Input Init Parameters * \return TI_OK on success or TI_NOK on failure * * \par Description * Report module configuration function, called by the config mgr in configuration phase \n * performs the following: \n * - Reset & init local variables * - Resets all report modules bits * - Resets all severities bits * - Init the description strings * */ TI_STATUS report_SetDefaults(TI_HANDLE hReport, TReportInitParams * pInitParams); /** \brief Unload Report Module * \param hReport - Report module object handle * \return TI_OK on success or TI_NOK on failure * * \par Description * Report Module unload function, called by the config mgr in the unload phase \n * performs the following: \n * - Free all memory allocated by the module */ TI_STATUS report_Unload(TI_HANDLE hReport); /** \brief Set Report Module * \param hReport - Report module object handle * \return TI_OK on success or TI_NOK on failure * * \par Description * Enables the relevant module for reporting - according to the received module index */ TI_STATUS report_SetReportModule(TI_HANDLE hReport, TI_UINT8 module_index); /** \brief Clear Report Module * \param hReport - Report module object handle * \param module_index - Index of file to be disable for reporting * \return TI_OK on success or TI_NOK on failure * * \par Description * Disables the relevant module for reporting - according to the received module index */ TI_STATUS report_ClearReportModule(TI_HANDLE hReport, TI_UINT8 module_index); /** \brief Get Report files Table * \param hReport - Report module object handle * \param pFiles - Pointer to output files Table * \return TI_OK on success or TI_NOK on failure * * \par Description * Returns the Modules Table (the table which holds Modules reporting indication) held in Report Module Object */ TI_STATUS report_GetReportFilesTable(TI_HANDLE hReport, TI_UINT8 * pFiles); /** \brief Set Report Files Table * \param hReport - Report module object handle * \param pFiles - Pointer to input files Table * \return TI_OK on success or TI_NOK on failure * * \par Description * Updates the Modules Table: copies the input Modules Table (the table which holds Modules reporting indication) * to the Modules Table which is held in Report Module Object */ TI_STATUS report_SetReportFilesTable(TI_HANDLE hReport, TI_UINT8 * pFiles); /** \brief Get Report Severity Table * \param hReport - Report module object handle * \param pSeverities - Pointer to input Severity Table * \return TI_OK on success or TI_NOK on failure * * \par Description * Returns the Severities Table (the table which holds Severities reporting indication) held in Report Module Object */ TI_STATUS report_GetReportSeverityTable(TI_HANDLE hReport, TI_UINT8 * pSeverities); /** \brief Set Report Severity Table * \param hReport - Report module object handle * \param pSeverities - Pointer to input Severity Table * \return TI_OK on success or TI_NOK on failure * * \par Description * Updates the Severities Table: copies the input Severities Table (the table which holds Severities reporting indication) * to the Severities Table which is held in Report Module Object */ TI_STATUS report_SetReportSeverityTable(TI_HANDLE hReport, TI_UINT8 * pSeverities); /** \brief Set Report Parameters * \param hReport - Report module object handle * \param pParam - Pointer to input Report Parameters Information * \return TI_OK on success or TI_NOK on failure * * \par Description * Report set param function sets parameter/s to Report Module Object. * Called by the following: * - configuration Manager in order to set a parameter/s from the OS abstraction layer * - Form inside the driver */ TI_STATUS report_SetParam(TI_HANDLE hReport, TReportParamInfo * pParam); /** \brief Get Report Parameters * \param hReport - Report module object handle * \param pParam - Pointer to output Report Parameters Information * \return TI_OK on success or TI_NOK on failure * * \par Description * Report get param function gets parameter/s from Report Module Object. * Called by the following: * - configuration Manager in order to get a parameter/s from the OS abstraction layer * - from inside the driver */ TI_STATUS report_GetParam(TI_HANDLE hReport, TReportParamInfo * pParam); /** \brief Report Dump * \param pBuffer - Pointer to input HEX buffer * \param pString - Pointer to output string * \param size - size of output string * \return TI_OK on success or TI_NOK on failure * * \par Description * Converts hex buffer to string buffer * NOTE: 1. The caller has to make sure that the string size is at lease: ((Size * 2) + 1) * 2. A string terminator is inserted into lase char of the string */ TI_STATUS report_Dump(TI_UINT8 * pBuffer, char *pString, TI_UINT32 size); /** \brief Report Print Dump * \param pData - Pointer to input data buffer * \param datalen - size of input data buffer * \return TI_OK on success or TI_NOK on failure * * \par Description * Performs HEX dump of input Data buffer. Used for debug only! */ TI_STATUS report_PrintDump(TI_UINT8 * pData, TI_UINT32 datalen); /** \brief Sets bRedirectOutputToLogger * \param value - True if to direct output to remote PC * \param hEvHandler - Event handler */ void os_setDebugOutputToLogger(TI_BOOL value); /** \brief Sets handles a SW running problem * \param problemType - used for different problem handling depending on problem type */ void handleRunProblem(EProblemType prType); #endif /* __REPORT_H__ */
nimengyu2/dm37x-cus-mini8510d-linux-2.6.32-sbc8100_plus
drivers/net/wireless/wilink/utils/report.h
C
gpl-2.0
46,546
MODULE deri23_I INTERFACE !...Generated by Pacific-Sierra Research 77to90 4.4G 10:47:07 03/09/06 SUBROUTINE deri23 (F, FD, E, FCI, CMO, EMO) USE vast_kind_param,ONLY: DOUBLE REAL(DOUBLE), DIMENSION(*), INTENT(IN) :: F REAL(DOUBLE), DIMENSION(*), INTENT(IN) :: FD REAL(DOUBLE), DIMENSION(*), INTENT(IN) :: E REAL(DOUBLE), DIMENSION(*), INTENT(IN) :: FCI REAL(DOUBLE), DIMENSION(*), INTENT(OUT) :: CMO REAL(DOUBLE), DIMENSION(*) :: EMO END SUBROUTINE END INTERFACE END MODULE
alinelena/aten
src/plugins/method_mopac71/mopac7.1/deri23_I.f90
FORTRAN
gpl-2.0
572
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ /** * */ package org.opennms.netmgt.asterisk.agi.scripts; import java.net.InetAddress; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.BaseAgiScript; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.ThreadCategory; /** * <p>Abstract BaseOnmsAgiScript class.</p> * * @author jeffg * @version $Id: $ */ public abstract class BaseOnmsAgiScript extends BaseAgiScript { /** Constant <code>VAR_INTERRUPT_DIGITS="INTERRUPT_DIGITS"</code> */ protected static final String VAR_INTERRUPT_DIGITS = "INTERRUPT_DIGITS"; /** Constant <code>VAR_OPENNMS_INTERFACE="OPENNMS_INTERFACE"</code> */ public static final String VAR_OPENNMS_INTERFACE = "OPENNMS_INTERFACE"; /** Constant <code>VAR_OPENNMS_SERVICE="OPENNMS_SERVICE"</code> */ public static final String VAR_OPENNMS_SERVICE = "OPENNMS_SERVICE"; /** Constant <code>VAR_OPENNMS_NODEID="OPENNMS_NODEID"</code> */ public static final String VAR_OPENNMS_NODEID = "OPENNMS_NODEID"; /** Constant <code>VAR_OPENNMS_NODELABEL="OPENNMS_NODELABEL"</code> */ public static final String VAR_OPENNMS_NODELABEL = "OPENNMS_NODELABEL"; /** Constant <code>VAR_OPENNMS_NOTIFY_SUBJECT="OPENNMS_NOTIFY_SUBJECT"</code> */ public static final String VAR_OPENNMS_NOTIFY_SUBJECT = "OPENNMS_NOTIFY_SUBJECT"; /** Constant <code>VAR_OPENNMS_NOTIFY_BODY="OPENNMS_NOTIFY_BODY"</code> */ public static final String VAR_OPENNMS_NOTIFY_BODY = "OPENNMS_NOTIFY_BODY"; /** Constant <code>VAR_OPENNMS_USER_PIN="OPENNMS_USER_PIN"</code> */ public static final String VAR_OPENNMS_USER_PIN = "OPENNMS_USER_PIN"; /** Constant <code>VAR_OPENNMS_USERNAME="OPENNMS_USERNAME"</code> */ public static final String VAR_OPENNMS_USERNAME = "OPENNMS_USERNAME"; /** * <p>sayAlphaInterruptible</p> * * @param text a {@link java.lang.String} object. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayAlphaInterruptible(String text) throws AgiException { if (! "".equals(getVariable(VAR_INTERRUPT_DIGITS))) { return sayAlpha(text, getVariable(VAR_INTERRUPT_DIGITS)); } else { sayAlpha(text); return 0x0; } } /** * <p>sayDateTimeInterruptible</p> * * @param time a long. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayDateTimeInterruptible(long time) throws AgiException { if (! "".equals(getVariable(VAR_INTERRUPT_DIGITS))) { return sayDateTime(time, getVariable(VAR_INTERRUPT_DIGITS)); } else { sayDateTime(time); return 0x0; } } /** * <p>sayDigitsInterruptible</p> * * @param digits a {@link java.lang.String} object. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayDigitsInterruptible(String digits) throws AgiException { if (! "".equals(getVariable(VAR_INTERRUPT_DIGITS))) { return sayDigits(digits, getVariable(VAR_INTERRUPT_DIGITS)); } else { sayDigits(digits); return 0x0; } } /** * <p>sayNumberInterruptible</p> * * @param number a {@link java.lang.String} object. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayNumberInterruptible(String number) throws AgiException { if (! "".equals(getVariable(VAR_INTERRUPT_DIGITS))) { return sayNumber(number, getVariable(VAR_INTERRUPT_DIGITS)); } else { sayNumber(number); return 0x0; } } /** * <p>sayPhoneticInterruptible</p> * * @param text a {@link java.lang.String} object. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayPhoneticInterruptible(String text) throws AgiException { if (! "".equals(getVariable(VAR_INTERRUPT_DIGITS))) { return sayPhonetic(text, getVariable(VAR_INTERRUPT_DIGITS)); } else { sayPhonetic(text); return 0x0; } } /** * <p>sayTimeInterruptible</p> * * @param time a long. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayTimeInterruptible(long time) throws AgiException { if (! "".equals(getVariable(VAR_INTERRUPT_DIGITS))) { return sayTime(time, getVariable(VAR_INTERRUPT_DIGITS)); } else { sayTime(time); return 0x0; } } /** * <p>sayIpAddressInterruptible</p> * * @param addr a {@link java.net.InetAddress} object. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayIpAddressInterruptible(InetAddress addr) throws AgiException { char pressed; // FIXME: this needs to be IPv6-compatible for (String octet : addr.getHostAddress().split("\\.")) { pressed = sayDigitsInterruptible(octet); if (pressed != 0x0) return pressed; pressed = sayAlphaInterruptible("."); if (pressed != 0x0) return pressed; } return 0x0; } /** * <p>sayIpAddressInterruptible</p> * * @param addrString a {@link java.lang.String} object. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char sayIpAddressInterruptible(String addrString) throws AgiException { final InetAddress addr = InetAddressUtils.addr(addrString); if (addr == null) { return 0x0; } return sayIpAddressInterruptible(addr); } /** * <p>streamFileInterruptible</p> * * @param file a {@link java.lang.String} object. * @return a char. * @throws org.asteriskjava.fastagi.AgiException if any. */ protected char streamFileInterruptible(String file) throws AgiException { if (! "".equals(getVariable(VAR_INTERRUPT_DIGITS))) { return streamFile(file, getVariable(VAR_INTERRUPT_DIGITS)); } else { streamFile(file); return 0x0; } } /** * <p>log</p> * * @return a {@link org.opennms.core.utils.ThreadCategory} object. */ protected ThreadCategory log() { return ThreadCategory.getInstance(getClass()); } }
bugcy013/opennms-tmp-tools
opennms-asterisk/src/main/java/org/opennms/netmgt/asterisk/agi/scripts/BaseOnmsAgiScript.java
Java
gpl-2.0
7,825
<?php namespace Drupal\search_api_solr\Plugin\SolrConnector; use Drupal\Core\Annotation\Translation; use Drupal\search_api_solr\Annotation\SolrConnector; use Drupal\search_api_solr\SolrConnector\SolrConnectorPluginBase; /** * Standard Solr connector. * * @SolrConnector( * id = "standard", * label = @Translation("Standard"), * description = @Translation("A standard connector usable for local installations of the standard Solr distribution.") * ) */ class StandardSolrConnector extends SolrConnectorPluginBase { }
Deepali-AddWeb/csv-import-d8
modules/search_api_solr/src/Plugin/SolrConnector/StandardSolrConnector.php
PHP
gpl-2.0
534
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.alarmd.api.support; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.opennms.netmgt.alarmd.api.Preservable; /** * Based on Matt's queue implementation of event forwarding in opennmsd (OVAPI daemon) * When in forwarding state, uses Nagle's algorithm to batch up alarms for forwarding by the NBI. * * FIXME: Need to make sure the are reasonable defaults in the configuration just-in-case * the NBI implementations don't set the batch size, etc. * * @auther <a mailto:brozow@opennms.org>Matt Brozowski</a> * @author <a mailto:david@opennms.org>David Hustace</a> */ class AlarmQueue<T extends Preservable> { private static final Logger LOG = LoggerFactory.getLogger(AlarmQueue.class); public abstract class State { abstract List<T> getAlarmsToForward() throws InterruptedException; abstract void forwardSuccessful(List<T> alarms); abstract void forwardFailed(List<T> alarms); protected void addToPreservedQueue(T a) { if (m_preservedQueue.size() >= m_maxPreservedAlarms) { m_nextBatch.clear(); m_preservedQueue.clear(); m_preservedQueue.offer(m_statusFactory.createSyncLostMessage()); } m_preservedQueue.offer(a); } protected void discardNonPreservedAlarms() { List<T> alarms = new ArrayList<T>(m_queue.size()); m_queue.drainTo(alarms); addPreservedToPreservedQueue(alarms); } protected void addPreservedToPreservedQueue(List<T> alarms) { for(Iterator<T> it = alarms.iterator(); it.hasNext(); ) { T a = it.next(); if (a.isPreserved()) { addToPreservedQueue(a); } } } protected void loadNextBatch() { m_preservedQueue.drainTo(m_nextBatch, m_maxBatchSize - m_nextBatch.size()); } } private final State FORWARDING = new State() { @Override public List<T> getAlarmsToForward() throws InterruptedException { List<T> alarms = new ArrayList<T>(m_maxBatchSize); T a = m_queue.take(); alarms.add(a); m_queue.drainTo(alarms, m_maxBatchSize - alarms.size()); if (m_naglesDelay <= 0) { return alarms; } long now = System.currentTimeMillis(); long expirationTime = now + m_naglesDelay; while (alarms.size() < m_maxBatchSize && now < expirationTime) { T alarm = m_queue.poll(expirationTime - now, TimeUnit.MILLISECONDS); if (alarm != null) { alarms.add(alarm); m_queue.drainTo(alarms, m_maxBatchSize - alarms.size()); } now = System.currentTimeMillis(); } return alarms; } @Override public void forwardSuccessful(List<T> alarms) { // no need to do anything here } @Override public void forwardFailed(List<T> alarms) { addPreservedToPreservedQueue(alarms); if (!m_preservedQueue.isEmpty()) { setState(FAILING); } } @Override public String toString() { return "FORWARDING"; } }; private final State FAILING = new State() { @Override public List<T> getAlarmsToForward() { discardNonPreservedAlarms(); loadNextBatch(); //Matt, why are we returning a field? return m_nextBatch; } @Override public void forwardFailed(List<T> alarms) { // do nothing we are already failing } @Override public void forwardSuccessful(List<T> alarms) { m_nextBatch.clear(); if (m_preservedQueue.isEmpty()) { setState(FORWARDING); } else { setState(RECOVERING); } } @Override public String toString() { return "FAILING"; } }; private final State RECOVERING = new State() { @Override public List<T> getAlarmsToForward() { loadNextBatch(); return m_nextBatch; } @Override public void forwardFailed(List<T> alarms) { setState(FAILING); } @Override public void forwardSuccessful(List<T> alarms) { m_nextBatch.clear(); if (m_preservedQueue.isEmpty()) { setState(FORWARDING); } } @Override public String toString() { return "RECOVERING"; } }; // operational parameters private int m_maxPreservedAlarms = 300000; private int m_maxBatchSize = 100; private long m_naglesDelay = 1000; // queue for all alarms to be forwarded private BlockingQueue<T> m_queue = new LinkedBlockingQueue<T>(); // queue for preserving alarms that are being saved during a forwarding failure private BlockingQueue<T> m_preservedQueue = new LinkedBlockingQueue<T>(); // a list of alarms that are pending due to a forwarding failure private List<T> m_nextBatch; // used to define the behavior of the getNext and forwardSuccessful and forwardFailed private State m_state = FORWARDING; // creates messages use to indicate that a connection failure has // occurred or queue has overflowed private StatusFactory<T> m_statusFactory; public AlarmQueue(StatusFactory<T> statusFactory) { m_statusFactory = statusFactory; } private void setState(State state) { m_state = state; LOG.debug("Setting state of AlarmQueue to {}", m_state); } public long getNaglesDelay() { return m_naglesDelay; } public void setNaglesDelay(long delay) { m_naglesDelay = delay; } public int getMaxPreservedAlarms() { return m_maxPreservedAlarms; } public void setMaxPreservedAlarms(int maxPreservedAlarms) { m_maxPreservedAlarms = maxPreservedAlarms; } public int getMaxBatchSize() { return m_maxBatchSize; } public void setMaxBatchSize(int maxBatchSize) { m_maxBatchSize = maxBatchSize; } public void init() { m_nextBatch = new ArrayList<T>(m_maxBatchSize); } public void discard(T a) { // do nothing } public void accept(T a) { m_queue.offer(a); } public void preserve(T a) { a.setPreserved(true); m_queue.offer(a); } public List<T> getAlarmsToForward() throws InterruptedException { return m_state.getAlarmsToForward(); } public void forwardSuccessful(List<T> alarms) { m_state.forwardSuccessful(alarms); } public void forwardFailed(List<T> alarms) { m_state.forwardFailed(alarms); } }
rfdrake/opennms
opennms-alarms/api/src/main/java/org/opennms/netmgt/alarmd/api/support/AlarmQueue.java
Java
gpl-2.0
8,674
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2007 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This 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 program; if not, write to the Free Software ## Foundation, Inc., or visit: http://www.gnu.org/. ## ## Author(s): Stoq Team <stoq-devel@async.com.br> ## """ Product transfer management """ # pylint: enable=E1101 from decimal import Decimal from kiwi.currency import currency from storm.expr import Join, LeftJoin, Sum, Cast, Coalesce, And from storm.info import ClassAlias from storm.references import Reference from zope.interface import implementer from stoqlib.database.expr import NullIf from stoqlib.database.properties import (DateTimeCol, IdCol, IdentifierCol, IntCol, PriceCol, QuantityCol, UnicodeCol, EnumCol) from stoqlib.database.viewable import Viewable from stoqlib.domain.base import Domain from stoqlib.domain.fiscal import Invoice from stoqlib.domain.product import ProductHistory, StockTransactionHistory from stoqlib.domain.person import Person, Branch, Company from stoqlib.domain.interfaces import IContainer, IInvoice, IInvoiceItem from stoqlib.domain.sellable import Sellable from stoqlib.domain.taxes import InvoiceItemIcms, InvoiceItemIpi from stoqlib.lib.dateutils import localnow from stoqlib.lib.translation import stoqlib_gettext _ = stoqlib_gettext @implementer(IInvoiceItem) class TransferOrderItem(Domain): """Transfer order item """ __storm_table__ = 'transfer_order_item' sellable_id = IdCol() # FIXME: This should be a product, since it does not make sense to transfer # serviçes #: The |sellable| to transfer sellable = Reference(sellable_id, 'Sellable.id') batch_id = IdCol() #: If the sellable is a storable, the |batch| that was transfered batch = Reference(batch_id, 'StorableBatch.id') transfer_order_id = IdCol() #: The |transfer| this item belongs to transfer_order = Reference(transfer_order_id, 'TransferOrder.id') #: The quantity to transfer quantity = QuantityCol() #: Average cost of the item in the source branch at the time of transfer. stock_cost = PriceCol(default=0) icms_info_id = IdCol() #: the :class:`stoqlib.domain.taxes.InvoiceItemIcms` tax for *self* icms_info = Reference(icms_info_id, 'InvoiceItemIcms.id') ipi_info_id = IdCol() #: the :class:`stoqlib.domain.taxes.InvoiceItemIpi` tax for *self* ipi_info = Reference(ipi_info_id, 'InvoiceItemIpi.id') item_discount = Decimal('0') def __init__(self, store=None, **kwargs): if not 'sellable' in kwargs: raise TypeError('You must provide a sellable argument') kwargs['ipi_info'] = InvoiceItemIpi(store=store) kwargs['icms_info'] = InvoiceItemIcms(store=store) super(TransferOrderItem, self).__init__(store=store, **kwargs) product = self.sellable.product if product: self.ipi_info.set_item_tax(self) self.icms_info.set_item_tax(self) # # IInvoiceItem implementation # @property def parent(self): return self.transfer_order @property def base_price(self): return self.stock_cost @property def price(self): return self.stock_cost @property def nfe_cfop_code(self): source_branch = self.transfer_order.source_branch source_address = source_branch.person.get_main_address() destination_branch = self.transfer_order.destination_branch destination_address = destination_branch.person.get_main_address() same_state = True if (source_address.city_location.state != destination_address.city_location.state): same_state = False if same_state: return u'5152' else: return u'6152' # # Public API # def get_total(self): """Returns the total cost of a transfer item eg quantity * cost""" return self.quantity * self.sellable.cost def send(self): """Sends this item to it's destination |branch|. This method should never be used directly, and to send a transfer you should use TransferOrder.send(). """ product = self.sellable.product if product.manage_stock: storable = product.storable storable.decrease_stock(self.quantity, self.transfer_order.source_branch, StockTransactionHistory.TYPE_TRANSFER_TO, self.id, batch=self.batch) ProductHistory.add_transfered_item(self.store, self.transfer_order.source_branch, self) def receive(self): """Receives this item, increasing the quantity in the stock. This method should never be used directly, and to receive a transfer you should use TransferOrder.receive(). """ product = self.sellable.product if product.manage_stock: storable = product.storable storable.increase_stock(self.quantity, self.transfer_order.destination_branch, StockTransactionHistory.TYPE_TRANSFER_FROM, self.id, unit_cost=self.stock_cost, batch=self.batch) @implementer(IContainer) @implementer(IInvoice) class TransferOrder(Domain): """ Transfer Order class """ __storm_table__ = 'transfer_order' STATUS_PENDING = u'pending' STATUS_SENT = u'sent' STATUS_RECEIVED = u'received' statuses = {STATUS_PENDING: _(u'Pending'), STATUS_SENT: _(u'Sent'), STATUS_RECEIVED: _(u'Received')} status = EnumCol(default=STATUS_PENDING) #: A numeric identifier for this object. This value should be used instead #: of :obj:`Domain.id` when displaying a numerical representation of this #: object to the user, in dialogs, lists, reports and such. identifier = IdentifierCol() #: The date the order was created open_date = DateTimeCol(default_factory=localnow) #: The date the order was received receival_date = DateTimeCol() #: The invoice number of the transfer invoice_number = IntCol() #: Comments of a transfer comments = UnicodeCol() source_branch_id = IdCol() #: The |branch| sending the stock source_branch = Reference(source_branch_id, 'Branch.id') destination_branch_id = IdCol() #: The |branch| receiving the stock destination_branch = Reference(destination_branch_id, 'Branch.id') source_responsible_id = IdCol() #: The |employee| responsible for the |transfer| at source |branch| source_responsible = Reference(source_responsible_id, 'Employee.id') destination_responsible_id = IdCol() #: The |employee| responsible for the |transfer| at destination |branch| destination_responsible = Reference(destination_responsible_id, 'Employee.id') #: |payments| generated by this transfer payments = None #: |transporter| used in transfer transporter = None invoice_id = IdCol() #: The |invoice| generated by the transfer invoice = Reference(invoice_id, 'Invoice.id') def __init__(self, store=None, **kwargs): kwargs['invoice'] = Invoice(store=store, invoice_type=Invoice.TYPE_OUT) super(TransferOrder, self).__init__(store=store, **kwargs) # # IContainer implementation # def get_items(self): return self.store.find(TransferOrderItem, transfer_order=self) def add_item(self, item): assert self.status == self.STATUS_PENDING item.transfer_order = self def remove_item(self, item): if item.transfer_order is not self: raise ValueError(_('The item does not belong to this ' 'transfer order')) item.transfer_order = None self.store.maybe_remove(item) # # IInvoice implementation # @property def discount_value(self): return currency(0) @property def invoice_subtotal(self): subtotal = self.get_items().sum(TransferOrderItem.quantity * TransferOrderItem.stock_cost) return currency(subtotal) @property def invoice_total(self): return self.invoice_subtotal @property def recipient(self): return self.destination_branch.person @property def operation_nature(self): # TODO: Save the operation nature in new transfer_order table field return _(u"Transfer") # # Public API # @property def branch(self): return self.source_branch @property def status_str(self): return(self.statuses[self.status]) def add_sellable(self, sellable, batch, quantity=1, cost=None): """Add the given |sellable| to this |transfer|. :param sellable: The |sellable| we are transfering :param batch: What |batch| of the storable (represented by sellable) we are transfering. :param quantity: The quantity of this product that is being transfered. """ assert self.status == self.STATUS_PENDING self.validate_batch(batch, sellable=sellable) product = sellable.product if product.manage_stock: stock_item = product.storable.get_stock_item( self.source_branch, batch) stock_cost = stock_item.stock_cost else: stock_cost = sellable.cost return TransferOrderItem(store=self.store, transfer_order=self, sellable=sellable, batch=batch, quantity=quantity, stock_cost=cost or stock_cost) def can_send(self): return (self.status == self.STATUS_PENDING and self.get_items().count() > 0) def can_receive(self): return self.status == self.STATUS_SENT def send(self): """Sends a transfer order to the destination branch. """ assert self.can_send() for item in self.get_items(): item.send() # Save invoice number, operation_nature and branch in Invoice table. self.invoice.invoice_number = self.invoice_number self.invoice.operation_nature = self.operation_nature self.invoice.branch = self.branch self.status = self.STATUS_SENT def receive(self, responsible, receival_date=None): """Confirms the receiving of the transfer order. """ assert self.can_receive() for item in self.get_items(): item.receive() self.receival_date = receival_date or localnow() self.destination_responsible = responsible self.status = self.STATUS_RECEIVED @classmethod def get_pending_transfers(cls, store, branch): """Get all the transfers that need to be recieved Get all transfers that have STATUS_SENT and the current branch as the destination This is useful if you want to list all the items that need to be recieved in a certain branch """ return store.find(cls, And(cls.status == cls.STATUS_SENT, cls.destination_branch == branch)) def get_source_branch_name(self): """Returns the source |branch| name""" return self.source_branch.get_description() def get_destination_branch_name(self): """Returns the destination |branch| name""" return self.destination_branch.get_description() def get_source_responsible_name(self): """Returns the name of the |employee| responsible for the transfer at source |branch| """ return self.source_responsible.person.name def get_destination_responsible_name(self): """Returns the name of the |employee| responsible for the transfer at destination |branch| """ if not self.destination_responsible: return u'' return self.destination_responsible.person.name def get_total_items_transfer(self): """Retuns the |transferitems| quantity """ return sum([item.quantity for item in self.get_items()], 0) class BaseTransferView(Viewable): BranchDest = ClassAlias(Branch, 'branch_dest') PersonDest = ClassAlias(Person, 'person_dest') CompanyDest = ClassAlias(Company, 'company_dest') transfer_order = TransferOrder identifier = TransferOrder.identifier identifier_str = Cast(TransferOrder.identifier, 'text') status = TransferOrder.status open_date = TransferOrder.open_date receival_date = TransferOrder.receival_date source_branch_id = TransferOrder.source_branch_id destination_branch_id = TransferOrder.destination_branch_id source_branch_name = Coalesce(NullIf(Company.fancy_name, u''), Person.name) destination_branch_name = Coalesce(NullIf(CompanyDest.fancy_name, u''), PersonDest.name) group_by = [TransferOrder, source_branch_name, destination_branch_name] tables = [ TransferOrder, Join(TransferOrderItem, TransferOrder.id == TransferOrderItem.transfer_order_id), # Source LeftJoin(Branch, TransferOrder.source_branch_id == Branch.id), LeftJoin(Person, Branch.person_id == Person.id), LeftJoin(Company, Company.person_id == Person.id), # Destination LeftJoin(BranchDest, TransferOrder.destination_branch_id == BranchDest.id), LeftJoin(PersonDest, BranchDest.person_id == PersonDest.id), LeftJoin(CompanyDest, CompanyDest.person_id == PersonDest.id), ] @property def branch(self): # We need this property for the acronym to appear in the identifier return self.store.get(Branch, self.source_branch_id) class TransferOrderView(BaseTransferView): id = TransferOrder.id # Aggregates total_items = Sum(TransferOrderItem.quantity) class TransferItemView(BaseTransferView): id = TransferOrderItem.id item_quantity = TransferOrderItem.quantity item_description = Sellable.description group_by = BaseTransferView.group_by[:] group_by.extend([TransferOrderItem, Sellable]) tables = BaseTransferView.tables[:] tables.append(Join(Sellable, Sellable.id == TransferOrderItem.sellable_id))
andrebellafronte/stoq
stoqlib/domain/transfer.py
Python
gpl-2.0
15,361
#pragma once #include "Emu/Cell/PPCDisAsm.h" class RSXDisAsm final : public CPUDisAsm { public: RSXDisAsm(cpu_disasm_mode mode, const u8* offset, const cpu_thread* cpu) : CPUDisAsm(mode, offset, cpu) { } private: void Write(const std::string& str, s32 count, bool is_non_inc = false, u32 id = 0); public: u32 disasm(u32 pc) override; };
Megamouse/rpcs3
rpcs3/Emu/RSX/RSXDisAsm.h
C
gpl-2.0
346
<?php /* * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * * 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. */ /** * @copyright XOOPS Project (https://xoops.org) * @license GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html) * @author XOOPS Development Team */ use Xmf\Module\Admin; require_once __DIR__ . '/admin_header.php'; xoops_cp_header(); $adminObject = Admin::getInstance(); $adminObject->displayNavigation(basename(__FILE__)); lx_importMenu(9); $adminObject->addItemButton(_AM_LEXIKON_IMPORT_WORDBOOK, 'importwordbook.php', 'add'); $adminObject->addItemButton(_AM_LEXIKON_IMPORT_DICTIONARY, 'importdictionary.php', 'add'); $adminObject->addItemButton(_AM_LEXIKON_IMPORT_GLOSSAIRE, 'importglossaire.php', 'add'); $adminObject->addItemButton(_AM_LEXIKON_IMPORT_WIWIMOD, 'importwiwimod.php', 'add'); $adminObject->addItemButton(_AM_LEXIKON_IMPORT_XWORDS, 'importxwords.php', 'add'); $adminObject->displayButton('left'); require_once __DIR__ . '/admin_footer.php';
XoopsModules25x/lexikon
admin/import.php
PHP
gpl-2.0
1,339
<li role="menuitem"><a target="_blank" href="<?php echo erLhcoreClassDesign::baseurl('chat/printchat')?>/<?php echo $chat->id?>/<?php echo $chat->hash?>" class="material-icons mat-100 mr-0" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Print')?>">print</a></li>
giahuy10/mokarafashion
livechat/design/defaulttheme/tpl/lhchat/customer_user_settings/option_print.tpl.php
PHP
gpl-2.0
318
/* png.c - location for general purpose libpng functions * * libpng 1.0.2 - June 14, 1998 * For conditions of distribution and use, see copyright notice in png.h * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. * Copyright (c) 1996, 1997 Andreas Dilger * Copyright (c) 1998, Glenn Randers-Pehrson */ #define PNG_INTERNAL #define PNG_NO_EXTERN #include "png.h" /* Version information for C files. This had better match the version * string defined in png.h. */ char png_libpng_ver[12] = "1.0.2"; /* Place to hold the signature string for a PNG file. */ png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; /* Constant strings for known chunk types. If you need to add a chunk, * add a string holding the name here. If you want to make the code * portable to EBCDIC machines, use ASCII numbers, not characters. */ png_byte FARDATA png_IHDR[5] = { 73, 72, 68, 82, '\0'}; png_byte FARDATA png_IDAT[5] = { 73, 68, 65, 84, '\0'}; png_byte FARDATA png_IEND[5] = { 73, 69, 78, 68, '\0'}; png_byte FARDATA png_PLTE[5] = { 80, 76, 84, 69, '\0'}; png_byte FARDATA png_bKGD[5] = { 98, 75, 71, 68, '\0'}; png_byte FARDATA png_cHRM[5] = { 99, 72, 82, 77, '\0'}; png_byte FARDATA png_gAMA[5] = {103, 65, 77, 65, '\0'}; png_byte FARDATA png_hIST[5] = {104, 73, 83, 84, '\0'}; png_byte FARDATA png_oFFs[5] = {111, 70, 70, 115, '\0'}; png_byte FARDATA png_pCAL[5] = {112, 67, 65, 76, '\0'}; png_byte FARDATA png_pHYs[5] = {112, 72, 89, 115, '\0'}; png_byte FARDATA png_sBIT[5] = {115, 66, 73, 84, '\0'}; png_byte FARDATA png_sRGB[5] = {115, 82, 71, 66, '\0'}; png_byte FARDATA png_tEXt[5] = {116, 69, 88, 116, '\0'}; png_byte FARDATA png_tIME[5] = {116, 73, 77, 69, '\0'}; png_byte FARDATA png_tRNS[5] = {116, 82, 78, 83, '\0'}; png_byte FARDATA png_zTXt[5] = {122, 84, 88, 116, '\0'}; /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* start of interlace block */ int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; /* offset to next interlace block */ int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; /* start of interlace block in the y direction */ int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1}; /* offset to next interlace block in the y direction */ int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2}; /* Width of interlace block. This is not currently used - if you need * it, uncomment it here and in png.h int FARDATA png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; */ /* Height of interlace block. This is not currently used - if you need * it, uncomment it here and in png.h int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1}; */ /* Mask to determine which pixels are valid in a pass */ int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff}; /* Mask to determine which pixels to overwrite while displaying */ int FARDATA png_pass_dsp_mask[] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff}; /* Tells libpng that we have already handled the first "num_bytes" bytes * of the PNG file signature. If the PNG data is embedded into another * stream we can set num_bytes = 8 so that libpng will not attempt to read * or write any of the magic bytes before it starts on the IHDR. */ void png_set_sig_bytes(png_structp png_ptr, int num_bytes) { png_debug(1, "in png_set_sig_bytes\n"); if (num_bytes > 8) png_error(png_ptr, "Too many bytes for PNG signature."); png_ptr->sig_bytes = num_bytes < 0 ? 0 : num_bytes; } /* Checks whether the supplied bytes match the PNG signature. We allow * checking less than the full 8-byte signature so that those apps that * already read the first few bytes of a file to determine the file type * can simply check the remaining bytes for extra assurance. Returns * an integer less than, equal to, or greater than zero if sig is found, * respectively, to be less than, to match, or be greater than the correct * PNG signature (this is the same behaviour as strcmp, memcmp, etc). */ int png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check) { if (num_to_check > 8) num_to_check = 8; else if (num_to_check < 1) return (0); if (start > 7) return (0); if (start + num_to_check > 8) num_to_check = 8 - start; return ((int)(png_memcmp(&sig[start], &png_sig[start], num_to_check))); } /* (Obsolete) function to check signature bytes. It does not allow one * to check a partial signature. This function will be removed in the * future - use png_sig_cmp(). */ int png_check_sig(png_bytep sig, int num) { return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num)); } /* Function to allocate memory for zlib. */ voidpf png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_uint_32 num_bytes = (png_uint_32)items * size; png_voidp ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } return ((voidpf)ptr); } /* function to free memory for zlib */ void png_zfree(voidpf png_ptr, voidpf ptr) { png_free((png_structp)png_ptr, (png_voidp)ptr); } /* Reset the CRC variable to 32 bits of 1's. Care must be taken * in case CRC is > 32 bits to leave the top bits 0. */ void png_reset_crc(png_structp png_ptr) { png_ptr->crc = crc32(0, Z_NULL, 0); } /* Calculate the CRC over a section of data. We can only pass as * much data to this routine as the largest single buffer size. We * also check that this data will actually be used before going to the * trouble of calculating it. */ void png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length) { int need_crc = 1; if (png_ptr->chunk_name[0] & 0x20) /* ancillary */ { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) == (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN)) need_crc = 0; } else /* critical */ { if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) need_crc = 0; } if (need_crc) png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length); } /* Allocate the memory for an info_struct for the application. We don't * really need the png_ptr, but it could potentially be useful in the * future. This should be used in favour of malloc(sizeof(png_info)) * and png_info_init() so that applications that want to use a shared * libpng don't have to be recompiled if png_info changes size. */ png_infop png_create_info_struct(png_structp png_ptr) { png_infop info_ptr; png_debug(1, "in png_create_info_struct\n"); if(png_ptr == NULL) return (NULL); #ifdef PNG_USER_MEM_SUPPORTED if ((info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO, png_ptr->malloc_fn)) != NULL) #else if ((info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO)) != NULL) #endif { png_info_init(info_ptr); } return (info_ptr); } /* Initialize the info structure. This is now an internal function (0.89) * and applications using it are urged to use png_create_info_struct() * instead. */ void png_info_init(png_infop info_ptr) { png_debug(1, "in png_info_init\n"); /* set everything to 0 */ png_memset(info_ptr, 0, sizeof (png_info)); } /* This is an internal routine to free any memory that the info struct is * pointing to before re-using it or freeing the struct itself. Recall * that png_free() checks for NULL pointers for us. */ void png_info_destroy(png_structp png_ptr, png_infop info_ptr) { #if defined(PNG_READ_tEXt_SUPPORTED) || defined(PNG_READ_zTXt_SUPPORTED) png_debug(1, "in png_info_destroy\n"); if (info_ptr->text != NULL) { int i; for (i = 0; i < info_ptr->num_text; i++) { png_free(png_ptr, info_ptr->text[i].key); } png_free(png_ptr, info_ptr->text); } #endif #if defined(PNG_READ_pCAL_SUPPORTED) png_free(png_ptr, info_ptr->pcal_purpose); png_free(png_ptr, info_ptr->pcal_units); if (info_ptr->pcal_params != NULL) { int i; for (i = 0; i < (int)info_ptr->pcal_nparams; i++) { png_free(png_ptr, info_ptr->pcal_params[i]); } png_free(png_ptr, info_ptr->pcal_params); } #endif png_info_init(info_ptr); } /* Initialize the default input/output functions for the PNG file. If you * use your own read or write routines, you can call either png_set_read_fn() * or png_set_write_fn() instead of png_init_io(). */ void png_init_io(png_structp png_ptr, FILE *fp) { png_debug(1, "in png_init_io\n"); png_ptr->io_ptr = (png_voidp)fp; } #if defined(PNG_TIME_RFC1123_SUPPORTED) /* Convert the supplied time into an RFC 1123 string suitable for use in * a "Creation Time" or other text-based time string. */ png_charp png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) { static PNG_CONST char short_months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (png_ptr->time_buffer == NULL) { png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* sizeof(char))); } #ifdef USE_FAR_KEYWORD { char near_time_buf[29]; sprintf(near_time_buf, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); png_memcpy(png_ptr->time_buffer, near_time_buf, 29*sizeof(char)); } #else sprintf(png_ptr->time_buffer, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); #endif return ((png_charp)png_ptr->time_buffer); } #endif /* PNG_TIME_RFC1123_SUPPORTED */
fgenesis/Aquaria_experimental
ExternalLibs/glpng/png/png.c
C
gpl-2.0
10,052
#! /usr/bin/env python # # Copyright (C) 2015 Open Information Security Foundation # # You can copy, redistribute or modify this Program 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 # version 2 along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # This script generates DNP3 related source code based on definitions # of DNP3 objects (currently the object structs). from __future__ import print_function import sys import re from cStringIO import StringIO import yaml import types import jinja2 IN_PLACE_START = "/* START GENERATED CODE */" IN_PLACE_END = "/* END GENERATED CODE */" util_lua_dnp3_objects_c_template = """/* Copyright (C) 2015 Open Information Security Foundation * * You can copy, redistribute or modify this Program 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * DO NOT EDIT. THIS FILE IS AUTO-GENERATED. * * Generated by command: * {{command_line}} */ #include "suricata-common.h" #include "app-layer-dnp3.h" #include "app-layer-dnp3-objects.h" #ifdef HAVE_LUA #include <lua.h> #include <lualib.h> #include <lauxlib.h> #include "util-lua.h" #include "util-lua-dnp3-objects.h" /** * \\brief Push an object point item onto the stack. */ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, DNP3Point *point) { switch (DNP3_OBJECT_CODE(object->group, object->variation)) { {% for object in objects %} case DNP3_OBJECT_CODE({{object.group}}, {{object.variation}}): { DNP3ObjectG{{object.group}}V{{object.variation}} *data = point->data; {% for field in object.fields %} {% if is_integer_type(field.type) %} lua_pushliteral(luastate, "{{field.name}}"); lua_pushinteger(luastate, data->{{field.name}}); lua_settable(luastate, -3); {% elif field["type"] in ["flt32", "flt64"] %} lua_pushliteral(luastate, "{{field.name}}"); lua_pushnumber(luastate, data->{{field.name}}); lua_settable(luastate, -3); {% elif field["type"] == "chararray" %} lua_pushliteral(luastate, "{{field.name}}"); LuaPushStringBuffer(luastate, (uint8_t *)data->{{field.name}}, strlen(data->{{field.name}})); lua_settable(luastate, -3); {% elif field["type"] == "vstr4" %} lua_pushliteral(luastate, "{{field.name}}"); LuaPushStringBuffer(luastate, (uint8_t *)data->{{field.name}}, strlen(data->{{field.name}})); lua_settable(luastate, -3); {% elif field.type == "bytearray" %} lua_pushliteral(luastate, "{{field.name}}"); lua_pushlstring(luastate, (const char *)data->{{field.name}}, data->{{field.len_field}}); lua_settable(luastate, -3); {% elif field.type == "bstr8" %} {% for field in field.fields %} lua_pushliteral(luastate, "{{field.name}}"); lua_pushinteger(luastate, data->{{field.name}}); lua_settable(luastate, -3); {% endfor %} {% else %} {{ raise("Unhandled datatype: %s" % (field.type)) }} {% endif %} {% endfor %} break; } {% endfor %} default: break; } } #endif /* HAVE_LUA */ """ output_json_dnp3_objects_template = """/* Copyright (C) 2015 Open Information Security Foundation * * You can copy, redistribute or modify this Program 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * DO NOT EDIT. THIS FILE IS AUTO-GENERATED. * * Generated by command: * {{command_line}} */ #include "suricata-common.h" #include "util-crypt.h" #include "app-layer-dnp3.h" #include "app-layer-dnp3-objects.h" #include "output-json-dnp3-objects.h" #ifdef HAVE_LIBJANSSON void OutputJsonDNP3SetItem(json_t *js, DNP3Object *object, DNP3Point *point) { switch (DNP3_OBJECT_CODE(object->group, object->variation)) { {% for object in objects %} case DNP3_OBJECT_CODE({{object.group}}, {{object.variation}}): { DNP3ObjectG{{object.group}}V{{object.variation}} *data = point->data; {% for field in object.fields %} {% if is_integer_type(field.type) %} json_object_set_new(js, "{{field.name}}", json_integer(data->{{field.name}})); {% elif field.type in ["flt32", "flt64"] %} json_object_set_new(js, "{{field.name}}", json_real(data->{{field.name}})); {% elif field.type == "bytearray" %} unsigned long {{field.name}}_b64_len = data->{{field.len_field}} * 2; uint8_t {{field.name}}_b64[{{field.name}}_b64_len]; Base64Encode(data->{{field.name}}, data->{{field.len_field}}, {{field.name}}_b64, &{{field.name}}_b64_len); json_object_set_new(js, "data->{{field.name}}", json_string((char *){{field.name}}_b64)); {% elif field.type == "vstr4" %} json_object_set_new(js, "data->{{field.name}}", json_string(data->{{field.name}})); {% elif field.type == "chararray" %} if (data->{{field.len_field}} > 0) { /* First create a null terminated string as not all versions * of jansson have json_stringn. */ char tmpbuf[data->{{field.len_field}} + 1]; memcpy(tmpbuf, data->{{field.name}}, data->{{field.len_field}}); tmpbuf[data->{{field.len_field}}] = '\\0'; json_object_set_new(js, "{{field.name}}", json_string(tmpbuf)); } else { json_object_set_new(js, "{{field.name}}", json_string("")); } {% elif field.type == "bstr8" %} {% for field in field.fields %} json_object_set_new(js, "{{field.name}}", json_integer(data->{{field.name}})); {% endfor %} {% else %} {{ raise("Unhandled datatype: %s" % (field.type)) }} {% endif %} {% endfor %} break; } {% endfor %} default: SCLogDebug("Unknown object: %d:%d", object->group, object->variation); break; } } #endif /* HAVE_LIBJANSSON */ """ def has_freeable_types(fields): freeable_types = [ "bytearray", ] for field in fields: if field["type"] in freeable_types: return True return False def is_integer_type(datatype): integer_types = [ "uint64", "uint32", "uint24", "uint16", "uint8", "int64", "int32", "int16", "int8", "dnp3time", ] return datatype in integer_types def to_type(datatype): type_map = { "uint8": "uint8_t", } if datatype in type_map: return type_map[datatype] else: raise Exception("Unknown datatype: %s" % (datatype)) def generate(template, filename, context): print("Generating %s." % (filename)) try: env = jinja2.Environment(trim_blocks=True) output = env.from_string(template).render(context) with open(filename, "w") as fileobj: fileobj.write(output) except Exception as err: print("Failed to generate %s: %s" % (filename, err)) sys.exit(1) def raise_helper(msg): raise Exception(msg) def gen_object_structs(context): """ Generate structs for all the define DNP3 objects. """ template = """ /* Code generated by: * {{command_line}} */ {% for object in objects %} typedef struct DNP3ObjectG{{object.group}}V{{object.variation}}_ { {% for field in object.fields %} {% if field.type == "bstr8" %} {% for field in field.fields %} uint8_t {{field.name}}:{{field.width}}; {% endfor %} {% else %} {% if field.type == "int16" %} int16_t {{field.name}}; {% elif field.type == "int32" %} int32_t {{field.name}}; {% elif field.type == "uint8" %} uint8_t {{field.name}}; {% elif field.type == "uint16" %} uint16_t {{field.name}}; {% elif field.type == "uint24" %} uint32_t {{field.name}}; {% elif field.type == "uint32" %} uint32_t {{field.name}}; {% elif field.type == "uint64" %} uint64_t {{field.name}}; {% elif field.type == "flt32" %} float {{field.name}}; {% elif field.type == "flt64" %} double {{field.name}}; {% elif field.type == "dnp3time" %} uint64_t {{field.name}}; {% elif field.type == "bytearray" %} uint8_t *{{field.name}}; {% elif field.type == "vstr4" %} char {{field.name}}[5]; {% elif field.type == "chararray" %} char {{field.name}}[{{field.size}}]; {% else %} {{ raise("Unknown datatype type '%s' for object %d:%d" % ( field.type, object.group, object.variation)) }} {% endif %} {% endif %} {% endfor %} {% if object.extra_fields %} {% for field in object.extra_fields %} {% if field.type == "uint8" %} uint8_t {{field.name}}; {% elif field.type == "uint16" %} uint16_t {{field.name}}; {% elif field.type == "uint32" %} uint32_t {{field.name}}; {% else %} {{ raise("Unknown datatype: %s" % (field.type)) }} {% endif %} {% endfor %} {% endif %} } DNP3ObjectG{{object.group}}V{{object.variation}}; {% endfor %} """ filename = "src/app-layer-dnp3-objects.h" try: env = jinja2.Environment(trim_blocks=True) code = env.from_string(template).render(context) content = open(filename).read() content = re.sub( "(%s).*(%s)" % (re.escape(IN_PLACE_START), re.escape(IN_PLACE_END)), r"\1%s\2" % (code), content, 1, re.M | re.DOTALL) open(filename, "w").write(content) print("Updated %s." % (filename)) except Exception as err: print("Failed to update %s: %s" % (filename, err), file=sys.stderr) sys.exit(1) def gen_object_decoders(context): """ Generate decoders for all defined DNP3 objects. """ template = """ /* Code generated by: * {{command_line}} */ {% for object in objects %} {% if object.packed %} static int DNP3DecodeObjectG{{object.group}}V{{object.variation}}(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG{{object.group}}V{{object.variation}} *object = NULL; int bytes = (count / 8) + 1; uint32_t prefix = 0; int point_index = start; if (!DNP3ReadPrefix(buf, len, prefix_code, &prefix)) { goto error; } for (int i = 0; i < bytes; i++) { uint8_t octet; if (!DNP3ReadUint8(buf, len, &octet)) { goto error; } for (int j = 0; j < 8 && count; j = j + {{object.fields[0].width}}) { object = SCCalloc(1, sizeof(*object)); if (unlikely(object == NULL)) { goto error; } {% if object.fields[0].width == 1 %} object->{{object.fields[0].name}} = (octet >> j) & 0x1; {% elif object.fields[0].width == 2 %} object->{{object.fields[0].name}} = (octet >> j) & 0x3; {% else %} #error "Unhandled field width: {{object.fields[0].width}}" {% endif %} if (!DNP3AddPoint(points, object, point_index, prefix_code, prefix)) { goto error; } object = NULL; count--; point_index++; } } return 1; error: if (object != NULL) { SCFree(object); } return 0; } {% else %} static int DNP3DecodeObjectG{{object.group}}V{{object.variation}}(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG{{object.group}}V{{object.variation}} *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; {% if object._track_offset %} uint32_t offset; {% endif %} {% if object.constraints %} {% for (key, val) in object.constraints.items() %} {% if key == "require_size_prefix" %} if (!DNP3PrefixIsSize(prefix_code)) { goto error; } {% elif key == "require_prefix_code" %} if (prefix_code != {{val}}) { goto error; } {% else %} {{ raise("Unhandled constraint: %s" % (key)) }} {% endif %} {% endfor %} {% endif %} while (count--) { object = SCCalloc(1, sizeof(*object)); if (unlikely(object == NULL)) { goto error; } if (!DNP3ReadPrefix(buf, len, prefix_code, &prefix)) { goto error; } {% if object._track_offset %} offset = *len; {% endif %} {% for field in object.fields %} {% if field.type == "int16" %} if (!DNP3ReadUint16(buf, len, (uint16_t *)&object->{{field.name}})) { goto error; } {% elif field.type == "int32" %} if (!DNP3ReadUint32(buf, len, (uint32_t *)&object->{{field.name}})) { goto error; } {% elif field.type == "uint8" %} if (!DNP3ReadUint8(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "uint16" %} if (!DNP3ReadUint16(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "uint24" %} if (!DNP3ReadUint24(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "uint32" %} if (!DNP3ReadUint32(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "uint64" %} if (!DNP3ReadUint64(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "flt32" %} if (!DNP3ReadFloat32(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "flt64" %} if (!DNP3ReadFloat64(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "dnp3time" %} if (!DNP3ReadUint48(buf, len, &object->{{field.name}})) { goto error; } {% elif field.type == "vstr4" %} if (*len < 4) { goto error; } memcpy(object->{{field.name}}, *buf, 4); object->{{field.name}}[4] = '\\\\0'; *buf += 4; *len -= 4; {% elif field.type == "bytearray" %} {% if field.len_from_prefix %} object->{{field.len_field}} = prefix - (offset - *len); {% endif %} if (object->{{field.len_field}} > 0) { if (*len < object->{{field.len_field}}) { /* Not enough data. */ goto error; } object->{{field.name}} = SCCalloc(1, object->{{field.len_field}}); if (unlikely(object->{{field.name}} == NULL)) { goto error; } memcpy(object->{{field.name}}, *buf, object->{{field.len_field}}); *buf += object->{{field.len_field}}; *len -= object->{{field.len_field}}; } {% elif field.type == "chararray" %} {% if field.len_from_prefix %} object->{{field.len_field}} = prefix - (offset - *len); {% endif %} if (object->{{field.len_field}} > 0) { if (*len < object->{{field.len_field}}) { /* Not enough data. */ goto error; } memcpy(object->{{field.name}}, *buf, object->{{field.len_field}}); *buf += object->{{field.len_field}}; *len -= object->{{field.len_field}}; } object->{{field.name}}[object->{{field.len_field}}] = '\\\\0'; {% elif field.type == "bstr8" %} { uint8_t octet; if (!DNP3ReadUint8(buf, len, &octet)) { goto error; } {% set ns = namespace(shift=0) %} {% for field in field.fields %} {% if field.width == 1 %} object->{{field.name}} = (octet >> {{ns.shift}}) & 0x1; {% elif field.width == 2 %} object->{{field.name}} = (octet >> {{ns.shift}}) & 0x3; {% elif field.width == 4 %} object->{{field.name}} = (octet >> {{ns.shift}}) & 0xf; {% elif field.width == 7 %} object->{{field.name}} = (octet >> {{ns.shift}}) & 0x7f; {% else %} {{ raise("Unhandled width of %d." % (field.width)) }} {% endif %} {% set ns.shift = ns.shift + field.width %} {% endfor %} } {% else %} {{ raise("Unhandled datatype '%s' for object %d:%d." % (field.type, object.group, object.variation)) }} {% endif %} {% endfor %} if (!DNP3AddPoint(points, object, point_index, prefix_code, prefix)) { goto error; } object = NULL; point_index++; } return 1; error: if (object != NULL) { SCFree(object); } return 0; } {% endif %} {% endfor %} void DNP3FreeObjectPoint(int group, int variation, void *point) { switch(DNP3_OBJECT_CODE(group, variation)) { {% for object in objects %} {% if f_has_freeable_types(object.fields) %} case DNP3_OBJECT_CODE({{object.group}}, {{object.variation}}): { DNP3ObjectG{{object.group}}V{{object.variation}} *object = (DNP3ObjectG{{object.group}}V{{object.variation}} *) point; {% for field in object.fields %} {% if field.type == "bytearray" %} if (object->{{field.name}} != NULL) { SCFree(object->{{field.name}}); } {% endif %} {% endfor %} break; } {% endif %} {% endfor %} default: break; } SCFree(point); } /** * \\\\brief Decode a DNP3 object. * * \\\\retval 0 on success. On failure a positive integer corresponding * to a DNP3 application layer event will be returned. */ int DNP3DecodeObject(int group, int variation, const uint8_t **buf, uint32_t *len, uint8_t prefix_code, uint32_t start, uint32_t count, DNP3PointList *points) { int rc = 0; switch (DNP3_OBJECT_CODE(group, variation)) { {% for object in objects %} case DNP3_OBJECT_CODE({{object.group}}, {{object.variation}}): rc = DNP3DecodeObjectG{{object.group}}V{{object.variation}}(buf, len, prefix_code, start, count, points); break; {% endfor %} default: return DNP3_DECODER_EVENT_UNKNOWN_OBJECT; } return rc ? 0 : DNP3_DECODER_EVENT_MALFORMED; } """ try: filename = "src/app-layer-dnp3-objects.c" env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) code = env.from_string(template).render(context) content = open(filename).read() content = re.sub( "(%s).*(%s)" % (re.escape(IN_PLACE_START), re.escape(IN_PLACE_END)), r"\1%s\n\2" % (code), content, 1, re.M | re.DOTALL) open(filename, "w").write(content) print("Updated %s." % (filename)) except Exception as err: print("Failed to update %s: %s" % (filename, err), file=sys.stderr) sys.exit(1) def preprocess_object(obj): valid_keys = [ "group", "variation", "constraints", "extra_fields", "fields", "packed", ] valid_field_keys = [ "type", "name", "width", "len_from_prefix", "len_field", "fields", "size", ] if "unimplemented" in obj: print("Object not implemented: %s:%s: %s" % ( str(obj["group"]), str(obj["variation"]), obj["unimplemented"])) return None for key, val in obj.items(): if key not in valid_keys: print("Invalid key '%s' in object %d:%d" % ( key, obj["group"], obj["variation"]), file=sys.stderr) sys.exit(1) for field in obj["fields"]: for key in field.keys(): if key not in valid_field_keys: print("Invalid key '%s' in object %d:%d" % ( key, obj["group"], obj["variation"]), file=sys.stderr) sys.exit(1) if "len_from_prefix" in field and field["len_from_prefix"]: obj["_track_offset"] = True break if field["type"] == "bstr8": width = 0 for subfield in field["fields"]: width += int(subfield["width"]) assert(width == 8) return obj def main(): # Require Jinja2 2.10 or greater. jv = jinja2.__version__.split(".") if int(jv[0]) < 2 or (int(jv[0]) == 2 and int(jv[1]) < 10): print("error: jinja2 v2.10 or great required") return 1 definitions = yaml.load(open("scripts/dnp3-gen/dnp3-objects.yaml")) print("Loaded %s objects." % (len(definitions["objects"]))) definitions["objects"] = map(preprocess_object, definitions["objects"]) # Filter out unimplemented objects. definitions["objects"] = [ obj for obj in definitions["objects"] if obj != None] context = { "raise": raise_helper, "objects": definitions["objects"], "is_integer_type": is_integer_type, "f_to_type": to_type, "f_has_freeable_types": has_freeable_types, "command_line": " ".join(sys.argv), } gen_object_structs(context) gen_object_decoders(context) generate(util_lua_dnp3_objects_c_template, "src/util-lua-dnp3-objects.c", context) generate(output_json_dnp3_objects_template, "src/output-json-dnp3-objects.c", context) if __name__ == "__main__": sys.exit(main())
daviddiallo/suricata
scripts/dnp3-gen/dnp3-gen.py
Python
gpl-2.0
22,538
/** * @file * @author Chrisitan Urich <christian.urich@gmail.com> * @version 1.0 * @section LICENSE * * This file is part of VIBe2 * * Copyright (C) 2011 Christian Urich * 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 "appendattributes.h" #include <rasterdatahelper.h> #include <tbvectordata.h> #include <rasterdatahelper.h> #include <guiappendattributes.h> DM_DECLARE_NODE_NAME( AppendAttributes ,Modules ) AppendAttributes::AppendAttributes() { this->median = false; this->multiplier = 1; this->addParameter("Multiplier", DM::DOUBLE, &this->multiplier); this->addParameter("Median", DM::BOOL, &this->median); this->addParameter("NameOfRasterData", DM::STRING, &this->NameOfRasterData); this->addParameter("NameOfExistingView", DM::STRING, &this->NameOfExistingView); this->addParameter("newAttribute", DM::STRING, &this->newAttribute); this->NameOfRasterData = ""; this->NameOfExistingView = ""; this->newAttribute = ""; data.push_back( DM::View ("dummy", DM::SUBSYSTEM, DM::MODIFY) ); this->addData("Data", data); } void AppendAttributes::run() { DM::RasterData * r = this->getRasterData("Data",vRasterData); if (!r) { DM::Logger(DM::Error) << "Raster Data " << vRasterData.getName() << " not found"; return; } DM::Logger(DM::Debug) << "VIEWNAME: " << NameOfExistingView; DM::System * sys = this->getData("Data"); foreach(DM::Component* c, sys->getAllComponentsInView(vExistingView)) { if(vExistingView.getType()==DM::FACE) { DM::Face * f = (DM::Face*)c; std::vector<DM::Node*> nl = TBVectorData::getNodeListFromFace(sys, f); double dattr = 0; if (median) { dattr = RasterDataHelper::meanOverArea(r,nl) * multiplier; } else { dattr = RasterDataHelper::sumOverArea(r,nl,0) * multiplier; } f->changeAttribute(newAttribute, dattr); } if(vExistingView.getType()==DM::NODE) { DM::Node * f = (DM::Node*)c; double dattr = r->getCell(f->getX(),f->getY()); f->changeAttribute(newAttribute, dattr); } } } bool AppendAttributes::createInputDialog() { QWidget * w = new GUIAppendAttributes(this); w->show(); return true; } string AppendAttributes::getHelpUrl() { return "https://github.com/iut-ibk/DynaMind-BasicModules/blob/master/doc/AppendAttributes.md"; } void AppendAttributes::init() { if (this->NameOfExistingView.empty()) return; if (this->newAttribute.empty()) return; this->vExistingView = this->getViewInStream("Data", NameOfExistingView); if (vExistingView.getName().empty()) return; vExistingView = vExistingView.clone(DM::READ); vExistingView.addAttribute(newAttribute, DM::Attribute::NOTYPE, DM::WRITE); this->vRasterData = DM::View(NameOfRasterData, DM::RASTERDATA, DM::READ); data.push_back(vExistingView); data.push_back(vRasterData); this->addData("Data", data); }
iut-ibk/DynaMind-BasicModules
src/DynaMind-BasicModules/appendattributes.cpp
C++
gpl-2.0
3,491
/* * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.replication; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Abortable; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.Server; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperListener; import org.apache.hadoop.hbase.zookeeper.ZooKeeperNodeTracker; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.ConnectionLossException; import org.apache.zookeeper.KeeperException.SessionExpiredException; /** * This class serves as a helper for all things related to zookeeper * in replication. * <p/> * The layout looks something like this under zookeeper.znode.parent * for the master cluster: * <p/> * <pre> * replication/ * state {contains true or false} * clusterId {contains a byte} * peers/ * 1/ {contains a full cluster address} * 2/ * ... * rs/ {lists all RS that replicate} * startcode1/ {lists all peer clusters} * 1/ {lists hlogs to process} * 10.10.1.76%3A53488.123456789 {contains nothing or a position} * 10.10.1.76%3A53488.123456790 * ... * 2/ * ... * startcode2/ * ... * </pre> */ public class ReplicationZookeeper { private static final Log LOG = LogFactory.getLog(ReplicationZookeeper.class); // Name of znode we use to lock when failover private final static String RS_LOCK_ZNODE = "lock"; // Our handle on zookeeper private final ZooKeeperWatcher zookeeper; // Map of peer clusters keyed by their id private Map<String, ReplicationPeer> peerClusters; // Path to the root replication znode private String replicationZNode; // Path to the peer clusters znode private String peersZNode; // Path to the znode that contains all RS that replicates private String rsZNode; // Path to this region server's name under rsZNode private String rsServerNameZnode; // Name node if the replicationState znode private String replicationStateNodeName; private final Configuration conf; // Is this cluster replicating at the moment? private AtomicBoolean replicating; // The key to our own cluster private String ourClusterKey; // Abortable private Abortable abortable; private ReplicationStatusTracker statusTracker; /** * Constructor used by clients of replication (like master and HBase clients) * @param conf conf to use * @param zk zk connection to use * @throws IOException */ public ReplicationZookeeper(final Abortable abortable, final Configuration conf, final ZooKeeperWatcher zk) throws KeeperException { this.conf = conf; this.zookeeper = zk; this.replicating = new AtomicBoolean(); setZNodes(abortable); } /** * Constructor used by region servers, connects to the peer cluster right away. * * @param server * @param replicating atomic boolean to start/stop replication * @throws IOException * @throws KeeperException */ public ReplicationZookeeper(final Server server, final AtomicBoolean replicating) throws IOException, KeeperException { this.abortable = server; this.zookeeper = server.getZooKeeper(); this.conf = server.getConfiguration(); this.replicating = replicating; setZNodes(server); this.peerClusters = new HashMap<String, ReplicationPeer>(); ZKUtil.createWithParents(this.zookeeper, ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName)); this.rsServerNameZnode = ZKUtil.joinZNode(rsZNode, server.getServerName().toString()); ZKUtil.createWithParents(this.zookeeper, this.rsServerNameZnode); connectExistingPeers(); } private void setZNodes(Abortable abortable) throws KeeperException { String replicationZNodeName = conf.get("zookeeper.znode.replication", "replication"); String peersZNodeName = conf.get("zookeeper.znode.replication.peers", "peers"); this.replicationStateNodeName = conf.get("zookeeper.znode.replication.state", "state"); String rsZNodeName = conf.get("zookeeper.znode.replication.rs", "rs"); this.ourClusterKey = ZKUtil.getZooKeeperClusterKey(this.conf); this.replicationZNode = ZKUtil.joinZNode(this.zookeeper.baseZNode, replicationZNodeName); this.peersZNode = ZKUtil.joinZNode(replicationZNode, peersZNodeName); ZKUtil.createWithParents(this.zookeeper, this.peersZNode); this.rsZNode = ZKUtil.joinZNode(replicationZNode, rsZNodeName); ZKUtil.createWithParents(this.zookeeper, this.rsZNode); // Set a tracker on replicationStateNodeNode this.statusTracker = new ReplicationStatusTracker(this.zookeeper, abortable); statusTracker.start(); readReplicationStateZnode(); } private void connectExistingPeers() throws IOException, KeeperException { List<String> znodes = ZKUtil.listChildrenNoWatch(this.zookeeper, this.peersZNode); if (znodes != null) { for (String z : znodes) { connectToPeer(z); } } } /** * List this cluster's peers' IDs * @return list of all peers' identifiers */ public List<String> listPeersIdsAndWatch() { List<String> ids = null; try { ids = ZKUtil.listChildrenAndWatchThem(this.zookeeper, this.peersZNode); } catch (KeeperException e) { this.abortable.abort("Cannot get the list of peers ", e); } return ids; } /** * Map of this cluster's peers for display. * @return A map of peer ids to peer cluster keys */ public Map<String,String> listPeers() { Map<String,String> peers = new TreeMap<String,String>(); List<String> ids = null; try { ids = ZKUtil.listChildrenNoWatch(this.zookeeper, this.peersZNode); for (String id : ids) { peers.put(id, Bytes.toString(ZKUtil.getData(this.zookeeper, ZKUtil.joinZNode(this.peersZNode, id)))); } } catch (KeeperException e) { this.abortable.abort("Cannot get the list of peers ", e); } return peers; } /** * Returns all region servers from given peer * * @param peerClusterId (byte) the cluster to interrogate * @return addresses of all region servers */ public List<ServerName> getSlavesAddresses(String peerClusterId) { if (this.peerClusters.size() == 0) { return new ArrayList<ServerName>(0); } ReplicationPeer peer = this.peerClusters.get(peerClusterId); if (peer == null) { return new ArrayList<ServerName>(0); } List<ServerName> addresses; try { addresses = fetchSlavesAddresses(peer.getZkw()); } catch (KeeperException ke) { if (ke instanceof ConnectionLossException || ke instanceof SessionExpiredException) { LOG.warn( "Lost the ZooKeeper connection for peer " + peer.getClusterKey(), ke); try { peer.reloadZkWatcher(); } catch(IOException io) { LOG.warn( "Creation of ZookeeperWatcher failed for peer " + peer.getClusterKey(), io); } } addresses = Collections.emptyList(); } peer.setRegionServers(addresses); return peer.getRegionServers(); } /** * Get the list of all the region servers from the specified peer * @param zkw zk connection to use * @return list of region server addresses or an empty list if the slave * is unavailable */ private List<ServerName> fetchSlavesAddresses(ZooKeeperWatcher zkw) throws KeeperException { return listChildrenAndGetAsServerNames(zkw, zkw.rsZNode); } /** * Lists the children of the specified znode, retrieving the data of each * child as a server address. * * Used to list the currently online regionservers and their addresses. * * Sets no watches at all, this method is best effort. * * Returns an empty list if the node has no children. Returns null if the * parent node itself does not exist. * * @param zkw zookeeper reference * @param znode node to get children of as addresses * @return list of data of children of specified znode, empty if no children, * null if parent does not exist * @throws KeeperException if unexpected zookeeper exception */ public static List<ServerName> listChildrenAndGetAsServerNames( ZooKeeperWatcher zkw, String znode) throws KeeperException { List<String> children = ZKUtil.listChildrenNoWatch(zkw, znode); if(children == null) { return null; } List<ServerName> addresses = new ArrayList<ServerName>(children.size()); for (String child : children) { addresses.add(ServerName.parseServerName(child)); } return addresses; } /** * This method connects this cluster to another one and registers it * in this region server's replication znode * @param peerId id of the peer cluster * @throws KeeperException */ public boolean connectToPeer(String peerId) throws IOException, KeeperException { if (peerClusters == null) { return false; } if (this.peerClusters.containsKey(peerId)) { return false; } ReplicationPeer peer = getPeer(peerId); if (peer == null) { return false; } this.peerClusters.put(peerId, peer); ZKUtil.createWithParents(this.zookeeper, ZKUtil.joinZNode( this.rsServerNameZnode, peerId)); LOG.info("Added new peer cluster " + peer.getClusterKey()); return true; } /** * Helper method to connect to a peer * @param peerId peer's identifier * @return object representing the peer * @throws IOException * @throws KeeperException */ public ReplicationPeer getPeer(String peerId) throws IOException, KeeperException{ String znode = ZKUtil.joinZNode(this.peersZNode, peerId); byte [] data = ZKUtil.getData(this.zookeeper, znode); String otherClusterKey = Bytes.toString(data); if (this.ourClusterKey.equals(otherClusterKey)) { LOG.debug("Not connecting to " + peerId + " because it's us"); return null; } // Construct the connection to the new peer Configuration otherConf = new Configuration(this.conf); try { ZKUtil.applyClusterKeyToConf(otherConf, otherClusterKey); } catch (IOException e) { LOG.error("Can't get peer because:", e); return null; } return new ReplicationPeer(otherConf, peerId, otherClusterKey); } /** * Set the new replication state for this cluster * @param newState */ public void setReplicating(boolean newState) throws KeeperException { ZKUtil.createWithParents(this.zookeeper, ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName)); ZKUtil.setData(this.zookeeper, ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName), Bytes.toBytes(Boolean.toString(newState))); } /** * Remove the peer from zookeeper. which will trigger the watchers on every * region server and close their sources * @param id * @throws IllegalArgumentException Thrown when the peer doesn't exist */ public void removePeer(String id) throws IOException { try { if (!peerExists(id)) { throw new IllegalArgumentException("Cannot remove inexisting peer"); } ZKUtil.deleteNode(this.zookeeper, ZKUtil.joinZNode(this.peersZNode, id)); } catch (KeeperException e) { throw new IOException("Unable to remove a peer", e); } } /** * Add a new peer to this cluster * @param id peer's identifier * @param clusterKey ZK ensemble's addresses, client port and root znode * @throws IllegalArgumentException Thrown when the peer doesn't exist * @throws IllegalStateException Thrown when a peer already exists, since * multi-slave isn't supported yet. */ public void addPeer(String id, String clusterKey) throws IOException { try { if (peerExists(id)) { throw new IllegalArgumentException("Cannot add existing peer"); } ZKUtil.createWithParents(this.zookeeper, this.peersZNode); ZKUtil.createAndWatch(this.zookeeper, ZKUtil.joinZNode(this.peersZNode, id), Bytes.toBytes(clusterKey)); } catch (KeeperException e) { throw new IOException("Unable to add peer", e); } } private boolean peerExists(String id) throws KeeperException { return ZKUtil.checkExists(this.zookeeper, ZKUtil.joinZNode(this.peersZNode, id)) >= 0; } /** * This reads the state znode for replication and sets the atomic boolean */ private void readReplicationStateZnode() { try { this.replicating.set(getReplication()); LOG.info("Replication is now " + (this.replicating.get()? "started" : "stopped")); } catch (KeeperException e) { this.abortable.abort("Failed getting data on from " + getRepStateNode(), e); } } /** * Get the replication status of this cluster. If the state znode doesn't * exist it will also create it and set it true. * @return returns true when it's enabled, else false * @throws KeeperException */ public boolean getReplication() throws KeeperException { byte [] data = this.statusTracker.getData(false); if (data == null || data.length == 0) { setReplicating(true); return true; } return Boolean.parseBoolean(Bytes.toString(data)); } private String getRepStateNode() { return ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName); } /** * Add a new log to the list of hlogs in zookeeper * @param filename name of the hlog's znode * @param peerId name of the cluster's znode */ public void addLogToList(String filename, String peerId) throws KeeperException{ String znode = ZKUtil.joinZNode(this.rsServerNameZnode, peerId); znode = ZKUtil.joinZNode(znode, filename); ZKUtil.createWithParents(this.zookeeper, znode); } /** * Remove a log from the list of hlogs in zookeeper * @param filename name of the hlog's znode * @param clusterId name of the cluster's znode */ public void removeLogFromList(String filename, String clusterId) { try { String znode = ZKUtil.joinZNode(rsServerNameZnode, clusterId); znode = ZKUtil.joinZNode(znode, filename); ZKUtil.deleteNode(this.zookeeper, znode); } catch (KeeperException e) { this.abortable.abort("Failed remove from list", e); } } /** * Set the current position of the specified cluster in the current hlog * @param filename filename name of the hlog's znode * @param clusterId clusterId name of the cluster's znode * @param position the position in the file * @throws IOException */ public void writeReplicationStatus(String filename, String clusterId, long position) { try { String znode = ZKUtil.joinZNode(this.rsServerNameZnode, clusterId); znode = ZKUtil.joinZNode(znode, filename); // Why serialize String of Long and note Long as bytes? ZKUtil.setData(this.zookeeper, znode, Bytes.toBytes(Long.toString(position))); } catch (KeeperException e) { this.abortable.abort("Writing replication status", e); } } /** * Get a list of all the other region servers in this cluster * and set a watch * @return a list of server nanes */ public List<String> getRegisteredRegionServers() { List<String> result = null; try { result = ZKUtil.listChildrenAndWatchThem( this.zookeeper, this.zookeeper.rsZNode); } catch (KeeperException e) { this.abortable.abort("Get list of registered region servers", e); } return result; } /** * Get the list of the replicators that have queues, they can be alive, dead * or simply from a previous run * @return a list of server names */ public List<String> getListOfReplicators() { List<String> result = null; try { result = ZKUtil.listChildrenNoWatch(this.zookeeper, rsZNode); } catch (KeeperException e) { this.abortable.abort("Get list of replicators", e); } return result; } /** * Get the list of peer clusters for the specified server names * @param rs server names of the rs * @return a list of peer cluster */ public List<String> getListPeersForRS(String rs) { String znode = ZKUtil.joinZNode(rsZNode, rs); List<String> result = null; try { result = ZKUtil.listChildrenNoWatch(this.zookeeper, znode); } catch (KeeperException e) { this.abortable.abort("Get list of peers for rs", e); } return result; } /** * Get the list of hlogs for the specified region server and peer cluster * @param rs server names of the rs * @param id peer cluster * @return a list of hlogs */ public List<String> getListHLogsForPeerForRS(String rs, String id) { String znode = ZKUtil.joinZNode(rsZNode, rs); znode = ZKUtil.joinZNode(znode, id); List<String> result = null; try { result = ZKUtil.listChildrenNoWatch(this.zookeeper, znode); } catch (KeeperException e) { this.abortable.abort("Get list of hlogs for peer", e); } return result; } /** * Try to set a lock in another server's znode. * @param znode the server names of the other server * @return true if the lock was acquired, false in every other cases */ public boolean lockOtherRS(String znode) { try { String parent = ZKUtil.joinZNode(this.rsZNode, znode); if (parent.equals(rsServerNameZnode)) { LOG.warn("Won't lock because this is us, we're dead!"); return false; } String p = ZKUtil.joinZNode(parent, RS_LOCK_ZNODE); ZKUtil.createAndWatch(this.zookeeper, p, Bytes.toBytes(rsServerNameZnode)); } catch (KeeperException e) { // This exception will pop up if the znode under which we're trying to // create the lock is already deleted by another region server, meaning // that the transfer already occurred. // NoNode => transfer is done and znodes are already deleted // NodeExists => lock znode already created by another RS if (e instanceof KeeperException.NoNodeException || e instanceof KeeperException.NodeExistsException) { LOG.info("Won't transfer the queue," + " another RS took care of it because of: " + e.getMessage()); } else { LOG.info("Failed lock other rs", e); } return false; } return true; } /** * This methods copies all the hlogs queues from another region server * and returns them all sorted per peer cluster (appended with the dead * server's znode) * @param znode server names to copy * @return all hlogs for all peers of that cluster, null if an error occurred */ public SortedMap<String, SortedSet<String>> copyQueuesFromRS(String znode) { // TODO this method isn't atomic enough, we could start copying and then // TODO fail for some reason and we would end up with znodes we don't want. SortedMap<String,SortedSet<String>> queues = new TreeMap<String,SortedSet<String>>(); try { String nodePath = ZKUtil.joinZNode(rsZNode, znode); List<String> clusters = ZKUtil.listChildrenNoWatch(this.zookeeper, nodePath); // We have a lock znode in there, it will count as one. if (clusters == null || clusters.size() <= 1) { return queues; } // The lock isn't a peer cluster, remove it clusters.remove(RS_LOCK_ZNODE); for (String cluster : clusters) { // We add the name of the recovered RS to the new znode, we can even // do that for queues that were recovered 10 times giving a znode like // number-startcode-number-otherstartcode-number-anotherstartcode-etc String newCluster = cluster+"-"+znode; String newClusterZnode = ZKUtil.joinZNode(rsServerNameZnode, newCluster); ZKUtil.createNodeIfNotExistsAndWatch(this.zookeeper, newClusterZnode, HConstants.EMPTY_BYTE_ARRAY); String clusterPath = ZKUtil.joinZNode(nodePath, cluster); List<String> hlogs = ZKUtil.listChildrenNoWatch(this.zookeeper, clusterPath); // That region server didn't have anything to replicate for this cluster if (hlogs == null || hlogs.size() == 0) { continue; } SortedSet<String> logQueue = new TreeSet<String>(); queues.put(newCluster, logQueue); for (String hlog : hlogs) { String z = ZKUtil.joinZNode(clusterPath, hlog); byte [] position = ZKUtil.getData(this.zookeeper, z); LOG.debug("Creating " + hlog + " with data " + Bytes.toString(position)); String child = ZKUtil.joinZNode(newClusterZnode, hlog); ZKUtil.createAndWatch(this.zookeeper, child, position); logQueue.add(hlog); } } } catch (KeeperException e) { this.abortable.abort("Copy queues from rs", e); } return queues; } /** * Delete a complete queue of hlogs * @param peerZnode znode of the peer cluster queue of hlogs to delete */ public void deleteSource(String peerZnode, boolean closeConnection) { try { ZKUtil.deleteNodeRecursively(this.zookeeper, ZKUtil.joinZNode(rsServerNameZnode, peerZnode)); if (closeConnection) { this.peerClusters.get(peerZnode).getZkw().close(); this.peerClusters.remove(peerZnode); } } catch (KeeperException e) { this.abortable.abort("Failed delete of " + peerZnode, e); } } /** * Recursive deletion of all znodes in specified rs' znode * @param znode */ public void deleteRsQueues(String znode) { String fullpath = ZKUtil.joinZNode(rsZNode, znode); try { List<String> clusters = ZKUtil.listChildrenNoWatch(this.zookeeper, fullpath); for (String cluster : clusters) { // We'll delete it later if (cluster.equals(RS_LOCK_ZNODE)) { continue; } String fullClusterPath = ZKUtil.joinZNode(fullpath, cluster); ZKUtil.deleteNodeRecursively(this.zookeeper, fullClusterPath); } // Finish cleaning up ZKUtil.deleteNodeRecursively(this.zookeeper, fullpath); } catch (KeeperException e) { if (e instanceof KeeperException.NoNodeException || e instanceof KeeperException.NotEmptyException) { // Testing a special case where another region server was able to // create a lock just after we deleted it, but then was also able to // delete the RS znode before us or its lock znode is still there. if (e.getPath().equals(fullpath)) { return; } } this.abortable.abort("Failed delete of " + znode, e); } } /** * Delete this cluster's queues */ public void deleteOwnRSZNode() { try { ZKUtil.deleteNodeRecursively(this.zookeeper, this.rsServerNameZnode); } catch (KeeperException e) { // if the znode is already expired, don't bother going further if (e instanceof KeeperException.SessionExpiredException) { return; } this.abortable.abort("Failed delete of " + this.rsServerNameZnode, e); } } /** * Get the position of the specified hlog in the specified peer znode * @param peerId znode of the peer cluster * @param hlog name of the hlog * @return the position in that hlog * @throws KeeperException */ public long getHLogRepPosition(String peerId, String hlog) throws KeeperException { String clusterZnode = ZKUtil.joinZNode(rsServerNameZnode, peerId); String znode = ZKUtil.joinZNode(clusterZnode, hlog); String data = Bytes.toString(ZKUtil.getData(this.zookeeper, znode)); return data == null || data.length() == 0 ? 0 : Long.parseLong(data); } public void registerRegionServerListener(ZooKeeperListener listener) { this.zookeeper.registerListener(listener); } /** * Get a map of all peer clusters * @return map of peer cluster keyed by id */ public Map<String, ReplicationPeer> getPeerClusters() { return this.peerClusters; } /** * Extracts the znode name of a peer cluster from a ZK path * @param fullPath Path to extract the id from * @return the id or an empty string if path is invalid */ public static String getZNodeName(String fullPath) { String[] parts = fullPath.split("/"); return parts.length > 0 ? parts[parts.length-1] : ""; } /** * Get this cluster's zk connection * @return zk connection */ public ZooKeeperWatcher getZookeeperWatcher() { return this.zookeeper; } /** * Get the full path to the peers' znode * @return path to peers in zk */ public String getPeersZNode() { return peersZNode; } /** * Tracker for status of the replication */ public class ReplicationStatusTracker extends ZooKeeperNodeTracker { public ReplicationStatusTracker(ZooKeeperWatcher watcher, Abortable abortable) { super(watcher, getRepStateNode(), abortable); } @Override public synchronized void nodeDataChanged(String path) { if (path.equals(node)) { super.nodeDataChanged(path); readReplicationStateZnode(); } } } }
lifeng5042/RStore
src/org/apache/hadoop/hbase/replication/ReplicationZookeeper.java
Java
gpl-2.0
26,675
/*! * jQuery JavaScript Library v1.8.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Thu Aug 30 2012 17:17:22 GMT-0400 (Eastern Daylight Time) */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" && ( !options.unique || !self.has( arg ) ) ) { list.push( arg ); } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return typeof obj === "object" ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Preliminary tests div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") > -1 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 鈥� // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var dirruns, cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), document = window.document, docElem = document.documentElement, done = 0, slice = [].slice, push = [].push, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value || true; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } return (cache[ key ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\(((?:-\\d)?\\d*)\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "POS": new RegExp( pos, "ig" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( nodeType !== 1 && nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector, context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function isXML( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var attr, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( Expr.attrHandle[ name ] ) { return Expr.attrHandle[ name ]( elem ); } if ( assertAttributes || xml ) { return elem.getAttribute( name ); } attr = elem.getAttributeNode( name ); return attr ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : attr.specified ? attr.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, order: new RegExp( "ID|TAG" + (assertUsableName ? "|NAME" : "") + (assertUsableClassName ? "|CLASS" : "") ), // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr.CHILD 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match, context, xml ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, context, xml, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className ]; if ( !pattern ) { pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") ); } return function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }; }, "ATTR": function( name, operator, check ) { if ( !operator ) { return function( elem ) { return Sizzle.attr( elem, name ) != null; }; } return function( elem ) { var result = Sizzle.attr( elem, name ), value = result + ""; if ( result == null ) { return operator === "!="; } switch ( operator ) { case "=": return value === check; case "!=": return value !== check; case "^=": return check && value.indexOf( check ) === 0; case "*=": return check && value.indexOf( check ) > -1; case "$=": return check && value.substr( value.length - check.length ) === check; case "~=": return ( " " + value + " " ).indexOf( check ) > -1; case "|=": return value === check || value.substr( 0, check.length + 1 ) === check + "-"; } }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { var doneName = done++; return function( elem ) { var parent, diff, count = 0, node = elem; if ( first === 1 && last === 0 ) { return true; } parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) { for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.sizset = ++count; if ( node === elem ) { break; } } } parent[ expando ] = doneName; } diff = elem.sizset - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument, context, xml ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters var args, fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ]; if ( !fn ) { Sizzle.error( "unsupported pseudo: " + pseudo ); } // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( !fn[ expando ] ) { if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return function( elem ) { return fn( elem, 0, args ); }; } return fn; } return fn( argument, context, xml ); } }, pseudos: { "not": markFunction(function( selector, context, xml ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var matcher = compile( selector.replace( rtrim, "$1" ), context, xml ); return function( elem ) { return !matcher( elem ); }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { "first": function( elements, argument, not ) { return not ? elements.slice( 1 ) : [ elements[0] ]; }, "last": function( elements, argument, not ) { var elem = elements.pop(); return not ? elements : [ elem ]; }, "even": function( elements, argument, not ) { var results = [], i = not ? 1 : 0, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "odd": function( elements, argument, not ) { var results = [], i = not ? 0 : 1, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "lt": function( elements, argument, not ) { return not ? elements.slice( +argument ) : elements.slice( 0, +argument ); }, "gt": function( elements, argument, not ) { return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 ); }, "eq": function( elements, argument, not ) { var elem = elements.splice( +argument, 1 ); return not ? elements : elem; } } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, i = 1; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, context, xml, parseOnly ) { var matched, match, tokens, type, soFar, groups, group, i, preFilters, filters, checkContext = !xml && context !== document, // Token cache should maintain spaces key = ( checkContext ? "<s>" : "" ) + selector.replace( rtrim, "$1<s>" ), cached = tokenCache[ expando ][ key ]; if ( cached ) { return parseOnly ? 0 : slice.call( cached, 0 ); } soFar = selector; groups = []; i = 0; preFilters = Expr.preFilter; filters = Expr.filter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { soFar = soFar.slice( match[0].length ); tokens.selector = group; } groups.push( tokens = [] ); group = ""; // Need to make sure we're within a narrower context if necessary // Adding a descendant combinator will generate what is needed if ( checkContext ) { soFar = " " + soFar; } } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { group += match[0]; soFar = soFar.slice( match[0].length ); // Cast descendant combinators to space matched = tokens.push({ part: match.pop().replace( rtrim, " " ), string: match[0], captures: match }); } // Filters for ( type in filters ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || ( match = preFilters[ type ](match, context, xml) )) ) { group += match[0]; soFar = soFar.slice( match[0].length ); matched = tokens.push({ part: type, string: match.shift(), captures: match }); } } if ( !matched ) { break; } } // Attach the full group as a selector if ( group ) { tokens.selector = group; } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens slice.call( tokenCache(key, groups), 0 ); } function addCombinator( matcher, combinator, context, xml ) { var dir = combinator.dir, doneName = done++; if ( !matcher ) { // If there is no matcher to check, check against the context matcher = function( elem ) { return elem === context; }; } return combinator.first ? function( elem ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { return matcher( elem ) && elem; } } } : xml ? function( elem ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { if ( matcher( elem ) ) { return elem; } } } } : function( elem ) { var cache, dirkey = doneName + "." + dirruns, cachedkey = dirkey + "." + cachedruns; while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } }; } function addMatcher( higher, deeper ) { return higher ? function( elem ) { var result = deeper( elem ); return result && higher( result === true ? elem : result ); } : deeper; } // ["TAG", ">", "ID", " ", "CLASS"] function matcherFromTokens( tokens, context, xml ) { var token, matcher, i = 0; for ( ; (token = tokens[i]); i++ ) { if ( Expr.relative[ token.part ] ) { matcher = addCombinator( matcher, Expr.relative[ token.part ], context, xml ); } else { matcher = addMatcher( matcher, Expr.filter[ token.part ].apply(null, token.captures.concat( context, xml )) ); } } return matcher; } function matcherFromGroupMatchers( matchers ) { return function( elem ) { var matcher, j = 0; for ( ; (matcher = matchers[j]); j++ ) { if ( matcher(elem) ) { return true; } } return false; }; } compile = Sizzle.compile = function( selector, context, xml ) { var group, i, len, cached = compilerCache[ expando ][ selector ]; // Return a cached group function if already generated (context dependent) if ( cached && cached.context === context ) { return cached; } // Generate a function of recursive functions that can be used to check each element group = tokenize( selector, context, xml ); for ( i = 0, len = group.length; i < len; i++ ) { group[i] = matcherFromTokens(group[i], context, xml); } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers(group) ); cached.context = context; cached.runs = cached.dirruns = 0; return cached; }; function multipleContexts( selector, contexts, results, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } } function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) { var results, fn = Expr.setFilters[ posfilter.toLowerCase() ]; if ( !fn ) { Sizzle.error( posfilter ); } if ( selector || !(results = seed) ) { multipleContexts( selector || "*", contexts, (results = []), seed ); } return results.length > 0 ? fn( results, argument, not ) : []; } function handlePOS( groups, context, results, seed ) { var group, part, j, groupLen, token, selector, anchor, elements, match, matched, lastIndex, currentContexts, not, i = 0, len = groups.length, rpos = matchExpr["POS"], // This is generated here in case matchExpr["POS"] is extended rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ), // This is for making sure non-participating // matching groups are represented cross-browser (IE6-8) setUndefined = function() { var i = 1, len = arguments.length - 2; for ( ; i < len; i++ ) { if ( arguments[i] === undefined ) { match[i] = undefined; } } }; for ( ; i < len; i++ ) { group = groups[i]; part = ""; elements = seed; for ( j = 0, groupLen = group.length; j < groupLen; j++ ) { token = group[j]; selector = token.string; if ( token.part === "PSEUDO" ) { // Reset regex index to 0 rpos.exec(""); anchor = 0; while ( (match = rpos.exec( selector )) ) { matched = true; lastIndex = rpos.lastIndex = match.index + match[0].length; if ( lastIndex > anchor ) { part += selector.slice( anchor, match.index ); anchor = lastIndex; currentContexts = [ context ]; if ( rcombinators.test(part) ) { if ( elements ) { currentContexts = elements; } elements = seed; } if ( (not = rendsWithNot.test( part )) ) { part = part.slice( 0, -5 ).replace( rcombinators, "$&*" ); anchor++; } if ( match.length > 1 ) { match[0].replace( rposgroups, setUndefined ); } elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not ); } part = ""; } } if ( !matched ) { part += selector; } matched = false; } if ( part ) { if ( rcombinators.test(part) ) { multipleContexts( part, elements || [ context ], results, seed ); } else { Sizzle( part, context, results, seed ? seed.concat(elements) : elements ); } } else { push.apply( results, elements ); } } // Do not sort if this is a single filter return len === 1 ? results : Sizzle.uniqueSort( results ); } function select( selector, context, results, seed, xml ) { // Remove excessive whitespace selector = selector.replace( rtrim, "$1" ); var elements, matcher, cached, elem, i, tokens, token, lastToken, findContext, type, match = tokenize( selector, context, xml ), contextNodeType = context.nodeType; // POS handling if ( matchExpr["POS"].test(selector) ) { return handlePOS( match, context, results, seed ); } if ( seed ) { elements = slice.call( seed, 0 ); // To maintain document order, only narrow the // set if there is one group } else if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID if ( (tokens = slice.call( match[0], 0 )).length > 2 && (token = tokens[0]).part === "ID" && contextNodeType === 9 && !xml && Expr.relative[ tokens[1].part ] ) { context = Expr.find["ID"]( token.captures[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().string.length ); } findContext = ( (match = rsibling.exec( tokens[0].string )) && !match.index && context.parentNode ) || context; // Reduce the set if possible lastToken = ""; for ( i = tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; type = token.part; lastToken = token.string + lastToken; if ( Expr.relative[ type ] ) { break; } if ( Expr.order.test(type) ) { elements = Expr.find[ type ]( token.captures[0].replace( rbackslash, "" ), findContext, xml ); if ( elements == null ) { continue; } else { selector = selector.slice( 0, selector.length - lastToken.length ) + lastToken.replace( matchExpr[ type ], "" ); if ( !selector ) { push.apply( results, slice.call(elements, 0) ); } break; } } } } // Only loop over the given elements once if ( selector ) { matcher = compile( selector, context, xml ); dirruns = matcher.dirruns++; if ( elements == null ) { elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context ); } for ( i = 0; (elem = elements[i]); i++ ) { cachedruns = matcher.runs++; if ( matcher(elem) ) { results.push( elem ); } } } return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, rbuggyQSA = [], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [":active"], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( context.nodeType === 9 ) { try { push.apply( results, slice.call(context.querySelectorAll( selector ), 0) ); return results; } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var groups, i, len, old = context.getAttribute("id"), nid = old || expando, newContext = rsibling.test( selector ) && context.parentNode || context; if ( old ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } groups = tokenize(selector, context, xml); // Trailing space is unnecessary // There is always a context check nid = "[id='" + nid + "']"; for ( i = 0, len = groups.length; i < len; i++ ) { groups[i] = nid + groups[i].selector; } try { push.apply( results, slice.call( newContext.querySelectorAll( groups.join(",") ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( matchExpr["PSEUDO"].source, matchExpr["POS"].source, "!=" ); } catch ( e ) {} }); // rbuggyMatches always contains :active, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.setFilters["nth"] = Expr.setFilters["eq"]; // Back-compat Expr.filters = Expr.pseudos; // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = {}, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { ret = computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocation, // Document location segments ajaxLocParts, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, prevScale, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below prevScale = scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zeroes from tween.cur() scale = tween.cur() / target; // Stop looping if we've hit the mark or scale is unchanged } while ( scale !== 1 && scale !== prevScale ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), percent = 1 - ( remaining / animation.duration || 0 ), index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var box, docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, top, left, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return { top: 0, left: 0 }; } box = elem.getBoundingClientRect(); win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
bylu/Test
dreamWeb/pages/js/jquery-1.8.1.js
JavaScript
gpl-2.0
269,298
/* -*- mode: C++; tab-width: 4; c-basic-offset: 4; -*- */ /* AbiWord * Copyright (C) 2000 AbiSource, Inc. * Copyright (C) 2004 Hubert Figuiere * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ #ifndef AP_COCOADIALOG_FORMATTOC_H #define AP_COCOADIALOG_FORMATTOC_H #include <Cocoa/Cocoa.h> #include "ap_Dialog_FormatTOC.h" @class AP_CocoaDialog_FormatTOC_Controller; @protocol XAP_CocoaDialogProtocol; /*****************************************************************/ class AP_CocoaDialog_FormatTOC: public AP_Dialog_FormatTOC { public: AP_CocoaDialog_FormatTOC(XAP_DialogFactory * pDlgFactory, XAP_Dialog_Id dlgid); virtual ~AP_CocoaDialog_FormatTOC(void); virtual void runModeless(XAP_Frame * pFrame); static XAP_Dialog * static_constructor(XAP_DialogFactory *, XAP_Dialog_Id dlgid); virtual void notifyActiveFrame(XAP_Frame * pFrame); virtual void setTOCPropsInGUI(void); virtual void setSensitivity(bool bSensitive); virtual void destroy(void); virtual void activate(void); private: void _populateWindowData(void); AP_CocoaDialog_FormatTOC_Controller *m_dlg; }; @interface AP_CocoaDialog_FormatTOC_Controller : NSWindowController <XAP_CocoaDialogProtocol> { IBOutlet NSButton * _applyBtn; IBOutlet NSButton * _hasHeadingBtn; IBOutlet NSButton * _hasLabelBtn; IBOutlet NSButton * _inheritLabelBtn; IBOutlet NSButton * _displayStyleBtn; IBOutlet NSButton * _fillStyleBtn; IBOutlet NSButton * _headingStyleBtn; IBOutlet NSPopUpButton * _layoutLevelPopup; IBOutlet NSPopUpButton * _mainLevelPopup; IBOutlet NSPopUpButton * _numberingTypeData; IBOutlet NSPopUpButton * _pageNumberingData; IBOutlet NSPopUpButton * _tabLeadersData; IBOutlet NSTextField * _displayStyleLabel; IBOutlet NSTextField * _displayStyleData; IBOutlet NSTextField * _fillStyleLabel; IBOutlet NSTextField * _fillStyleData; IBOutlet NSTextField * _headingStyleLabel; IBOutlet NSTextField * _headingStyleData; IBOutlet NSTextField * _headingTextData; IBOutlet NSTextField * _headingTextLabel; IBOutlet NSTextField * _indentData; IBOutlet NSTextField * _indentLabel; IBOutlet NSTextField * _numberingTypeLabel; IBOutlet NSTextField * _pageNumberingLabel; IBOutlet NSTextField * _startAtData; IBOutlet NSTextField * _startAtLabel; IBOutlet NSTextField * _tabLeadersLabel; IBOutlet NSTextField * _textAfterData; IBOutlet NSTextField * _textAfterLabel; IBOutlet NSTextField * _textBeforeData; IBOutlet NSTextField * _textBeforeLabel; IBOutlet NSBox * _defineMainLabel; IBOutlet NSBox * _labelDefinitionsLabel; IBOutlet NSBox * _tabsPageNoLabel; IBOutlet NSStepper * _startAtStepper; IBOutlet NSStepper * _indentStepper; // IBOutlet NSBox * _hasHeadingBox; // IBOutlet NSBox * _labelDefBox; // IBOutlet NSBox * _mainPropBox; // IBOutlet NSBox * _tabsAndPageNumbBox; IBOutlet NSTabView * _tabView; AP_CocoaDialog_FormatTOC * _xap; } - (IBAction)startAtStepperAction:(id)sender; - (IBAction)startAtAction:(id)sender; - (IBAction)indentStepperAction:(id)sender; - (IBAction)indentAction:(id)sender; - (IBAction)mainLevelAction:(id)sender; - (IBAction)detailLevelAction:(id)sender; - (IBAction)headingStyleAction:(id)sender; - (IBAction)fillStyleAction:(id)sender; - (IBAction)displayStyleAction:(id)sender; - (IBAction)applyAction:(id)sender; - (void)setSensitivity:(BOOL)enable; - (void)createLevelItems:(NSPopUpButton *)popup; - (void)createNumberingItems:(NSPopUpButton *)popup; - (void)sync; - (void)syncMainLevelSettings; - (void)syncDetailLevelSettings; - (void)saveMainLevelSettings; - (void)saveDetailLevelSettings; @end #endif /* AP_COCOADIALOG_FORMATOC_H */
hfiguiere/abiword
src/wp/ap/cocoa/ap_CocoaDialog_FormatTOC.h
C
gpl-2.0
4,392
package org.checkerframework.framework.qual; import static java.lang.annotation.ElementType.FIELD; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares that the field may not be accessed if the receiver is of the specified qualifier type * (or any supertype). * * <p>This property is verified by the checker that type-checks the {@code when} element value * qualifier. * * <p><b>Example</b> Consider a class, {@code Table}, with a locking field, {@code lock}. The lock * is used when a {@code Table} instance is shared across threads. When running in a local thread, * the {@code lock} field ought not to be used. * * <p>You can declare this behavior in the following way: * * <pre>{@code * class Table { * private @Unused(when=LocalToThread.class) final Lock lock; * ... * } * }</pre> * * The checker for {@code @LocalToThread} would issue an error for the following code: * * <pre> @LocalToThread Table table = ...; * ... table.lock ...; * </pre> */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({FIELD}) public @interface Unused { /** * The field that is annotated with @Unused may not be accessed via a receiver that is annotated * with the "when" annotation. */ Class<? extends Annotation> when(); }
CharlesZ-Chen/checker-framework
framework/src/org/checkerframework/framework/qual/Unused.java
Java
gpl-2.0
1,435
/* A Bison parser, made by GNU Bison 2.4.1. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.4.1" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Using locations. */ #define YYLSP_NEEDED 1 /* Substitute the variable and function names. */ #define yyparse ast_yyparse #define yylex ast_yylex #define yyerror ast_yyerror #define yylval ast_yylval #define yychar ast_yychar #define yydebug ast_yydebug #define yynerrs ast_yynerrs #define yylloc ast_yylloc /* Copy the first part of user declarations. */ /* Line 189 of yacc.c */ #line 1 "ast_expr2.y" /* Written by Pace Willisson (pace@blitz.com) * and placed in the public domain. * * Largely rewritten by J.T. Conklin (jtc@wimsey.com) * * And then overhauled twice by Steve Murphy (murf@digium.com) * to add double-quoted strings, allow mult. spaces, improve * error messages, and then to fold in a flex scanner for the * yylex operation. * * $FreeBSD: src/bin/expr/expr.y,v 1.16 2000/07/22 10:59:36 se Exp $ */ #include "asterisk.h" #include <sys/types.h> #include <stdio.h> #if !defined(STANDALONE) && !defined(STANDALONE2) \ ASTERISK_FILE_VERSION(__FILE__, "$Revision: 293198 $") #else #ifndef __USE_ISOC99 #define __USE_ISOC99 1 #endif #endif #ifdef __USE_ISOC99 #define FP___PRINTF "%.18Lg" #define FP___TYPE long double #else #define FP___PRINTF "%.16g" #define FP___TYPE double #endif #ifdef HAVE_COSL #define FUNC_COS cosl #elif defined(HAVE_COS) #define FUNC_COS (long double)cos #endif #ifdef HAVE_SINL #define FUNC_SIN sinl #elif defined(HAVE_SIN) #define FUNC_SIN (long double)sin #endif #ifdef HAVE_TANL #define FUNC_TAN tanl #elif defined(HAVE_TAN) #define FUNC_TAN (long double)tan #endif #ifdef HAVE_ACOSL #define FUNC_ACOS acosl #elif defined(HAVE_ACOS) #define FUNC_ACOS (long double)acos #endif #ifdef HAVE_ASINL #define FUNC_ASIN asinl #elif defined(HAVE_ASIN) #define FUNC_ASIN (long double)asin #endif #ifdef HAVE_ATANL #define FUNC_ATAN atanl #elif defined(HAVE_ATAN) #define FUNC_ATAN (long double)atan #endif #ifdef HAVE_ATAN2L #define FUNC_ATAN2 atan2l #elif defined(HAVE_ATAN2) #define FUNC_ATAN2 (long double)atan2 #endif #ifdef HAVE_POWL #define FUNC_POW powl #elif defined(HAVE_POW) #define FUNC_POW (long double)pow #endif #ifdef HAVE_SQRTL #define FUNC_SQRT sqrtl #elif defined(HAVE_SQRT) #define FUNC_SQRT (long double)sqrt #endif #ifdef HAVE_RINTL #define FUNC_RINT rintl #elif defined(HAVE_RINT) #define FUNC_RINT (long double)rint #endif #ifdef HAVE_EXPL #define FUNC_EXP expl #elif defined(HAVE_EXP) #define FUNC_EXP (long double)exp #endif #ifdef HAVE_LOGL #define FUNC_LOG logl #elif defined(HAVE_LOG) #define FUNC_LOG (long double)log #endif #ifdef HAVE_REMAINDERL #define FUNC_REMAINDER remainderl #elif defined(HAVE_REMAINDER) #define FUNC_REMAINDER (long double)remainder #endif #ifdef HAVE_FMODL #define FUNC_FMOD fmodl #elif defined(HAVE_FMOD) #define FUNC_FMOD (long double)fmod #endif #ifdef HAVE_STRTOLD #define FUNC_STRTOD strtold #elif defined(HAVE_STRTOD) #define FUNC_STRTOD (long double)strtod #endif #ifdef HAVE_FLOORL #define FUNC_FLOOR floorl #elif defined(HAVE_FLOOR) #define FUNC_FLOOR (long double)floor #endif #ifdef HAVE_CEILL #define FUNC_CEIL ceill #elif defined(HAVE_CEIL) #define FUNC_CEIL (long double)ceil #endif #ifdef HAVE_ROUNDL #define FUNC_ROUND roundl #elif defined(HAVE_ROUND) #define FUNC_ROUND (long double)round #endif #ifdef HAVE_TRUNCL #define FUNC_TRUNC truncl #elif defined(HAVE_TRUNC) #define FUNC_TRUNC (long double)trunc #endif /*! \note * Oddly enough, some platforms have some ISO C99 functions, but not others, so * we define the missing functions in terms of their mathematical identities. */ #ifdef HAVE_EXP2L #define FUNC_EXP2 exp2l #elif (defined(HAVE_EXPL) && defined(HAVE_LOGL)) #define FUNC_EXP2(x) expl((x) * logl(2.0)) #elif (defined(HAVE_EXP) && defined(HAVE_LOG)) #define FUNC_EXP2(x) (long double)exp((x) * log(2.0)) #endif #ifdef HAVE_EXP10L #define FUNC_EXP10 exp10l #elif (defined(HAVE_EXPL) && defined(HAVE_LOGL)) #define FUNC_EXP10(x) expl((x) * logl(10.0)) #elif (defined(HAVE_EXP) && defined(HAVE_LOG)) #define FUNC_EXP10(x) (long double)exp((x) * log(10.0)) #endif #ifdef HAVE_LOG2L #define FUNC_LOG2 log2l #elif defined(HAVE_LOGL) #define FUNC_LOG2(x) (logl(x) / logl(2.0)) #elif defined(HAVE_LOG10L) #define FUNC_LOG2(x) (log10l(x) / log10l(2.0)) #elif defined(HAVE_LOG2) #define FUNC_LOG2 (long double)log2 #elif defined(HAVE_LOG) #define FUNC_LOG2(x) ((long double)log(x) / log(2.0)) #endif #ifdef HAVE_LOG10L #define FUNC_LOG10 log10l #elif defined(HAVE_LOGL) #define FUNC_LOG10(x) (logl(x) / logl(10.0)) #elif defined(HAVE_LOG2L) #define FUNC_LOG10(x) (log2l(x) / log2l(10.0)) #elif defined(HAVE_LOG10) #define FUNC_LOG10(x) (long double)log10(x) #elif defined(HAVE_LOG) #define FUNC_LOG10(x) ((long double)log(x) / log(10.0)) #endif #include <stdlib.h> #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <string.h> #include <math.h> #include <locale.h> #include <unistd.h> #include <ctype.h> #if !defined(SOLARIS) && !defined(__CYGWIN__) /* #include <err.h> */ #else #define quad_t int64_t #endif #include <errno.h> #include <regex.h> #include <limits.h> #include "asterisk/ast_expr.h" #include "asterisk/logger.h" #if !defined(STANDALONE) && !defined(STANDALONE2) #include "asterisk/pbx.h" #endif #if defined(LONG_LONG_MIN) && !defined(QUAD_MIN) #define QUAD_MIN LONG_LONG_MIN #endif #if defined(LONG_LONG_MAX) && !defined(QUAD_MAX) #define QUAD_MAX LONG_LONG_MAX #endif # if ! defined(QUAD_MIN) # define QUAD_MIN (-0x7fffffffffffffffLL-1) # endif # if ! defined(QUAD_MAX) # define QUAD_MAX (0x7fffffffffffffffLL) # endif #define YYENABLE_NLS 0 #define YYPARSE_PARAM parseio #define YYLEX_PARAM ((struct parse_io *)parseio)->scanner #define YYERROR_VERBOSE 1 extern char extra_error_message[4095]; extern int extra_error_message_supplied; enum valtype { AST_EXPR_number, AST_EXPR_numeric_string, AST_EXPR_string } ; #if defined(STANDALONE) || defined(STANDALONE2) void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...) __attribute__ ((format (printf,5,6))); #endif struct val { enum valtype type; union { char *s; FP___TYPE i; /* either long double, or just double, on a bad day */ } u; } ; enum node_type { AST_EXPR_NODE_COMMA, AST_EXPR_NODE_STRING, AST_EXPR_NODE_VAL } ; struct expr_node { enum node_type type; struct val *val; struct expr_node *left; struct expr_node *right; }; typedef void *yyscan_t; struct parse_io { char *string; struct val *val; yyscan_t scanner; struct ast_channel *chan; }; static int chk_div __P((FP___TYPE, FP___TYPE)); static int chk_minus __P((FP___TYPE, FP___TYPE, FP___TYPE)); static int chk_plus __P((FP___TYPE, FP___TYPE, FP___TYPE)); static int chk_times __P((FP___TYPE, FP___TYPE, FP___TYPE)); static void free_value __P((struct val *)); static int is_zero_or_null __P((struct val *)); static int isstring __P((struct val *)); static struct val *make_number __P((FP___TYPE)); static struct val *make_str __P((const char *)); static struct val *op_and __P((struct val *, struct val *)); static struct val *op_colon __P((struct val *, struct val *)); static struct val *op_eqtilde __P((struct val *, struct val *)); static struct val *op_tildetilde __P((struct val *, struct val *)); static struct val *op_div __P((struct val *, struct val *)); static struct val *op_eq __P((struct val *, struct val *)); static struct val *op_ge __P((struct val *, struct val *)); static struct val *op_gt __P((struct val *, struct val *)); static struct val *op_le __P((struct val *, struct val *)); static struct val *op_lt __P((struct val *, struct val *)); static struct val *op_cond __P((struct val *, struct val *, struct val *)); static struct val *op_minus __P((struct val *, struct val *)); static struct val *op_negate __P((struct val *)); static struct val *op_compl __P((struct val *)); static struct val *op_ne __P((struct val *, struct val *)); static struct val *op_or __P((struct val *, struct val *)); static struct val *op_plus __P((struct val *, struct val *)); static struct val *op_rem __P((struct val *, struct val *)); static struct val *op_times __P((struct val *, struct val *)); static struct val *op_func(struct val *funcname, struct expr_node *arglist, struct ast_channel *chan); static int to_number __P((struct val *)); static void to_string __P((struct val *)); static struct expr_node *alloc_expr_node(enum node_type); static void destroy_arglist(struct expr_node *arglist); /* uh, if I want to predeclare yylex with a YYLTYPE, I have to predeclare the yyltype... sigh */ typedef struct yyltype { int first_line; int first_column; int last_line; int last_column; } yyltype; # define YYLTYPE yyltype # define YYLTYPE_IS_TRIVIAL 1 /* we will get warning about no prototype for yylex! But we can't define it here, we have no definition yet for YYSTYPE. */ int ast_yyerror(const char *,YYLTYPE *, struct parse_io *); /* I wanted to add args to the yyerror routine, so I could print out some useful info about the error. Not as easy as it looks, but it is possible. */ #define ast_yyerror(x) ast_yyerror(x,&yyloc,parseio) #define DESTROY(x) {if((x)->type == AST_EXPR_numeric_string || (x)->type == AST_EXPR_string) free((x)->u.s); (x)->u.s = 0; free(x);} /* Line 189 of yacc.c */ #line 419 "ast_expr2.c" /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { TOK_COMMA = 258, TOK_COLONCOLON = 259, TOK_COND = 260, TOK_OR = 261, TOK_AND = 262, TOK_NE = 263, TOK_LE = 264, TOK_GE = 265, TOK_LT = 266, TOK_GT = 267, TOK_EQ = 268, TOK_MINUS = 269, TOK_PLUS = 270, TOK_MOD = 271, TOK_DIV = 272, TOK_MULT = 273, TOK_COMPL = 274, TOK_TILDETILDE = 275, TOK_EQTILDE = 276, TOK_COLON = 277, TOK_LP = 278, TOK_RP = 279, TOKEN = 280 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 214 of yacc.c */ #line 345 "ast_expr2.y" struct val *val; struct expr_node *arglist; /* Line 214 of yacc.c */ #line 487 "ast_expr2.c" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 264 of yacc.c */ #line 350 "ast_expr2.y" extern int ast_yylex __P((YYSTYPE *, YYLTYPE *, yyscan_t)); /* Line 264 of yacc.c */ #line 517 "ast_expr2.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 11 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 159 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 26 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 4 /* YYNRULES -- Number of rules. */ #define YYNRULES 28 /* YYNRULES -- Number of states. */ #define YYNSTATES 54 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 280 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 5, 6, 8, 12, 15, 20, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62, 66, 69, 72, 76, 80, 84, 88, 92, 98 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 27, 0, -1, 29, -1, -1, 29, -1, 28, 3, 29, -1, 28, 3, -1, 25, 23, 28, 24, -1, 25, -1, 23, 29, 24, -1, 29, 6, 29, -1, 29, 7, 29, -1, 29, 13, 29, -1, 29, 12, 29, -1, 29, 11, 29, -1, 29, 10, 29, -1, 29, 9, 29, -1, 29, 8, 29, -1, 29, 15, 29, -1, 29, 14, 29, -1, 14, 29, -1, 19, 29, -1, 29, 18, 29, -1, 29, 17, 29, -1, 29, 16, 29, -1, 29, 22, 29, -1, 29, 21, 29, -1, 29, 5, 29, 4, 29, -1, 29, 20, 29, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 374, 374, 382, 389, 390, 396, 405, 411, 412, 416, 420, 424, 428, 432, 436, 440, 444, 448, 452, 456, 460, 464, 468, 472, 476, 480, 484, 489 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "TOK_COMMA", "TOK_COLONCOLON", "TOK_COND", "TOK_OR", "TOK_AND", "TOK_NE", "TOK_LE", "TOK_GE", "TOK_LT", "TOK_GT", "TOK_EQ", "TOK_MINUS", "TOK_PLUS", "TOK_MOD", "TOK_DIV", "TOK_MULT", "TOK_COMPL", "TOK_TILDETILDE", "TOK_EQTILDE", "TOK_COLON", "TOK_LP", "TOK_RP", "TOKEN", "$accept", "start", "arglist", "expr", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 26, 27, 27, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 0, 1, 3, 2, 4, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 5, 3 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 3, 0, 0, 0, 8, 0, 2, 20, 21, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 4, 0, 10, 11, 17, 16, 15, 14, 13, 12, 19, 18, 24, 23, 22, 28, 26, 25, 6, 7, 0, 5, 27 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 5, 30, 6 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -18 static const yytype_int16 yypact[] = { 118, 118, 118, 118, -15, 6, 65, -17, -17, 25, 118, -18, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, -18, 4, 65, 47, 98, 113, 130, 130, 130, 130, 130, 130, 137, 137, -17, -17, -17, -18, -18, -18, 118, -18, 118, 65, 82 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -18, -18, -18, -1 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint8 yytable[] = { 7, 8, 9, 26, 27, 28, 11, 49, 10, 31, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 0, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 26, 27, 28, 52, 29, 53, 51, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 26, 27, 28, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 26, 27, 28, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 26, 27, 28, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 26, 27, 28, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 1, 26, 27, 28, 0, 2, 0, 0, 0, 3, 0, 4, 21, 22, 23, 24, 25, 0, 26, 27, 28, 23, 24, 25, 0, 26, 27, 28 }; static const yytype_int8 yycheck[] = { 1, 2, 3, 20, 21, 22, 0, 3, 23, 10, -1, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 24, -1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, -1, 20, 21, 22, 49, 24, 51, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, -1, 20, 21, 22, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, -1, 20, 21, 22, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, -1, 20, 21, 22, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, -1, 20, 21, 22, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 14, 20, 21, 22, -1, 19, -1, -1, -1, 23, -1, 25, 14, 15, 16, 17, 18, -1, 20, 21, 22, 16, 17, 18, -1, 20, 21, 22 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 14, 19, 23, 25, 27, 29, 29, 29, 29, 23, 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 24, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 3, 24, 4, 29, 29 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; #endif { if (!yyvaluep) return; YYUSE (yylocationp); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule) #else static void yy_reduce_print (yyvsp, yylsp, yyrule) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { case 4: /* "TOK_COLONCOLON" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1479 "ast_expr2.c" break; case 5: /* "TOK_COND" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1488 "ast_expr2.c" break; case 6: /* "TOK_OR" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1497 "ast_expr2.c" break; case 7: /* "TOK_AND" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1506 "ast_expr2.c" break; case 8: /* "TOK_NE" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1515 "ast_expr2.c" break; case 9: /* "TOK_LE" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1524 "ast_expr2.c" break; case 10: /* "TOK_GE" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1533 "ast_expr2.c" break; case 11: /* "TOK_LT" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1542 "ast_expr2.c" break; case 12: /* "TOK_GT" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1551 "ast_expr2.c" break; case 13: /* "TOK_EQ" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1560 "ast_expr2.c" break; case 14: /* "TOK_MINUS" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1569 "ast_expr2.c" break; case 15: /* "TOK_PLUS" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1578 "ast_expr2.c" break; case 16: /* "TOK_MOD" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1587 "ast_expr2.c" break; case 17: /* "TOK_DIV" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1596 "ast_expr2.c" break; case 18: /* "TOK_MULT" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1605 "ast_expr2.c" break; case 19: /* "TOK_COMPL" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1614 "ast_expr2.c" break; case 20: /* "TOK_TILDETILDE" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1623 "ast_expr2.c" break; case 21: /* "TOK_EQTILDE" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1632 "ast_expr2.c" break; case 22: /* "TOK_COLON" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1641 "ast_expr2.c" break; case 23: /* "TOK_LP" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1650 "ast_expr2.c" break; case 24: /* "TOK_RP" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1659 "ast_expr2.c" break; case 25: /* "TOKEN" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1668 "ast_expr2.c" break; case 29: /* "expr" */ /* Line 1000 of yacc.c */ #line 368 "ast_expr2.y" { free_value((yyvaluep->val)); }; /* Line 1000 of yacc.c */ #line 1677 "ast_expr2.c" break; default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*-------------------------. | yyparse or yypush_parse. | `-------------------------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Location data for the lookahead symbol. */ YYLTYPE yylloc; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 1; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: /* Line 1455 of yacc.c */ #line 374 "ast_expr2.y" { ((struct parse_io *)parseio)->val = (struct val *)calloc(sizeof(struct val),1); ((struct parse_io *)parseio)->val->type = (yyvsp[(1) - (1)].val)->type; if( (yyvsp[(1) - (1)].val)->type == AST_EXPR_number ) ((struct parse_io *)parseio)->val->u.i = (yyvsp[(1) - (1)].val)->u.i; else ((struct parse_io *)parseio)->val->u.s = (yyvsp[(1) - (1)].val)->u.s; free((yyvsp[(1) - (1)].val)); ;} break; case 3: /* Line 1455 of yacc.c */ #line 382 "ast_expr2.y" {/* nothing */ ((struct parse_io *)parseio)->val = (struct val *)calloc(sizeof(struct val),1); ((struct parse_io *)parseio)->val->type = AST_EXPR_string; ((struct parse_io *)parseio)->val->u.s = strdup(""); ;} break; case 4: /* Line 1455 of yacc.c */ #line 389 "ast_expr2.y" { (yyval.arglist) = alloc_expr_node(AST_EXPR_NODE_VAL); (yyval.arglist)->val = (yyvsp[(1) - (1)].val);;} break; case 5: /* Line 1455 of yacc.c */ #line 390 "ast_expr2.y" {struct expr_node *x = alloc_expr_node(AST_EXPR_NODE_VAL); struct expr_node *t; DESTROY((yyvsp[(2) - (3)].val)); for (t=(yyvsp[(1) - (3)].arglist);t->right;t=t->right) ; (yyval.arglist) = (yyvsp[(1) - (3)].arglist); t->right = x; x->val = (yyvsp[(3) - (3)].val);;} break; case 6: /* Line 1455 of yacc.c */ #line 396 "ast_expr2.y" {struct expr_node *x = alloc_expr_node(AST_EXPR_NODE_VAL); struct expr_node *t; /* NULL args should OK */ DESTROY((yyvsp[(2) - (2)].val)); for (t=(yyvsp[(1) - (2)].arglist);t->right;t=t->right) ; (yyval.arglist) = (yyvsp[(1) - (2)].arglist); t->right = x; x->val = make_str("");;} break; case 7: /* Line 1455 of yacc.c */ #line 405 "ast_expr2.y" { (yyval.val) = op_func((yyvsp[(1) - (4)].val),(yyvsp[(3) - (4)].arglist), ((struct parse_io *)parseio)->chan); DESTROY((yyvsp[(2) - (4)].val)); DESTROY((yyvsp[(4) - (4)].val)); DESTROY((yyvsp[(1) - (4)].val)); destroy_arglist((yyvsp[(3) - (4)].arglist)); ;} break; case 8: /* Line 1455 of yacc.c */ #line 411 "ast_expr2.y" {(yyval.val) = (yyvsp[(1) - (1)].val);;} break; case 9: /* Line 1455 of yacc.c */ #line 412 "ast_expr2.y" { (yyval.val) = (yyvsp[(2) - (3)].val); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0; DESTROY((yyvsp[(1) - (3)].val)); DESTROY((yyvsp[(3) - (3)].val)); ;} break; case 10: /* Line 1455 of yacc.c */ #line 416 "ast_expr2.y" { (yyval.val) = op_or ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 11: /* Line 1455 of yacc.c */ #line 420 "ast_expr2.y" { (yyval.val) = op_and ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 12: /* Line 1455 of yacc.c */ #line 424 "ast_expr2.y" { (yyval.val) = op_eq ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 13: /* Line 1455 of yacc.c */ #line 428 "ast_expr2.y" { (yyval.val) = op_gt ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 14: /* Line 1455 of yacc.c */ #line 432 "ast_expr2.y" { (yyval.val) = op_lt ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 15: /* Line 1455 of yacc.c */ #line 436 "ast_expr2.y" { (yyval.val) = op_ge ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 16: /* Line 1455 of yacc.c */ #line 440 "ast_expr2.y" { (yyval.val) = op_le ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 17: /* Line 1455 of yacc.c */ #line 444 "ast_expr2.y" { (yyval.val) = op_ne ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 18: /* Line 1455 of yacc.c */ #line 448 "ast_expr2.y" { (yyval.val) = op_plus ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 19: /* Line 1455 of yacc.c */ #line 452 "ast_expr2.y" { (yyval.val) = op_minus ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 20: /* Line 1455 of yacc.c */ #line 456 "ast_expr2.y" { (yyval.val) = op_negate ((yyvsp[(2) - (2)].val)); DESTROY((yyvsp[(1) - (2)].val)); (yyloc).first_column = (yylsp[(1) - (2)]).first_column; (yyloc).last_column = (yylsp[(2) - (2)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 21: /* Line 1455 of yacc.c */ #line 460 "ast_expr2.y" { (yyval.val) = op_compl ((yyvsp[(2) - (2)].val)); DESTROY((yyvsp[(1) - (2)].val)); (yyloc).first_column = (yylsp[(1) - (2)]).first_column; (yyloc).last_column = (yylsp[(2) - (2)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 22: /* Line 1455 of yacc.c */ #line 464 "ast_expr2.y" { (yyval.val) = op_times ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 23: /* Line 1455 of yacc.c */ #line 468 "ast_expr2.y" { (yyval.val) = op_div ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 24: /* Line 1455 of yacc.c */ #line 472 "ast_expr2.y" { (yyval.val) = op_rem ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 25: /* Line 1455 of yacc.c */ #line 476 "ast_expr2.y" { (yyval.val) = op_colon ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 26: /* Line 1455 of yacc.c */ #line 480 "ast_expr2.y" { (yyval.val) = op_eqtilde ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 27: /* Line 1455 of yacc.c */ #line 484 "ast_expr2.y" { (yyval.val) = op_cond ((yyvsp[(1) - (5)].val), (yyvsp[(3) - (5)].val), (yyvsp[(5) - (5)].val)); DESTROY((yyvsp[(2) - (5)].val)); DESTROY((yyvsp[(4) - (5)].val)); (yyloc).first_column = (yylsp[(1) - (5)]).first_column; (yyloc).last_column = (yylsp[(3) - (5)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; case 28: /* Line 1455 of yacc.c */ #line 489 "ast_expr2.y" { (yyval.val) = op_tildetilde ((yyvsp[(1) - (3)].val), (yyvsp[(3) - (3)].val)); DESTROY((yyvsp[(2) - (3)].val)); (yyloc).first_column = (yylsp[(1) - (3)]).first_column; (yyloc).last_column = (yylsp[(3) - (3)]).last_column; (yyloc).first_line=0; (yyloc).last_line=0;;} break; /* Line 1455 of yacc.c */ #line 2283 "ast_expr2.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } /* Line 1675 of yacc.c */ #line 495 "ast_expr2.y" static struct expr_node *alloc_expr_node(enum node_type nt) { struct expr_node *x = calloc(1,sizeof(struct expr_node)); if (!x) { ast_log(LOG_ERROR, "Allocation for expr_node FAILED!!\n"); return 0; } x->type = nt; return x; } static struct val * make_number (FP___TYPE i) { struct val *vp; vp = (struct val *) malloc (sizeof (*vp)); if (vp == NULL) { ast_log(LOG_WARNING, "malloc() failed\n"); return(NULL); } vp->type = AST_EXPR_number; vp->u.i = i; return vp; } static struct val * make_str (const char *s) { struct val *vp; size_t i; int isint; /* this started out being a test for an integer, but then ended up being a test for a float */ vp = (struct val *) malloc (sizeof (*vp)); if (vp == NULL || ((vp->u.s = strdup (s)) == NULL)) { ast_log(LOG_WARNING,"malloc() failed\n"); return(NULL); } for (i = 0, isint = (isdigit(s[0]) || s[0] == '-' || s[0]=='.'); isint && i < strlen(s); i++) { if (!isdigit(s[i]) && s[i] != '.') { isint = 0; break; } } if (isint) vp->type = AST_EXPR_numeric_string; else vp->type = AST_EXPR_string; return vp; } static void free_value (struct val *vp) { if (vp==NULL) { return; } if (vp->type == AST_EXPR_string || vp->type == AST_EXPR_numeric_string) free (vp->u.s); free(vp); } static int to_number (struct val *vp) { FP___TYPE i; if (vp == NULL) { ast_log(LOG_WARNING,"vp==NULL in to_number()\n"); return(0); } if (vp->type == AST_EXPR_number) return 1; if (vp->type == AST_EXPR_string) return 0; /* vp->type == AST_EXPR_numeric_string, make it numeric */ errno = 0; i = FUNC_STRTOD(vp->u.s, (char**)0); /* either strtod, or strtold on a good day */ if (errno != 0) { ast_log(LOG_WARNING,"Conversion of %s to number under/overflowed!\n", vp->u.s); free(vp->u.s); vp->u.s = 0; return(0); } free (vp->u.s); vp->u.i = i; vp->type = AST_EXPR_number; return 1; } static void strip_quotes(struct val *vp) { if (vp->type != AST_EXPR_string && vp->type != AST_EXPR_numeric_string) return; if( vp->u.s[0] == '"' && vp->u.s[strlen(vp->u.s)-1] == '"' ) { char *f, *t; f = vp->u.s; t = vp->u.s; while( *f ) { if( *f && *f != '"' ) *t++ = *f++; else f++; } *t = *f; } } static void to_string (struct val *vp) { char *tmp; if (vp->type == AST_EXPR_string || vp->type == AST_EXPR_numeric_string) return; tmp = malloc ((size_t)25); if (tmp == NULL) { ast_log(LOG_WARNING,"malloc() failed\n"); return; } sprintf(tmp, FP___PRINTF, vp->u.i); vp->type = AST_EXPR_string; vp->u.s = tmp; } static int isstring (struct val *vp) { /* only TRUE if this string is not a valid number */ return (vp->type == AST_EXPR_string); } static int is_zero_or_null (struct val *vp) { if (vp->type == AST_EXPR_number) { return (vp->u.i == 0); } else { return (*vp->u.s == 0 || (to_number(vp) && vp->u.i == 0)); } /* NOTREACHED */ } #ifdef STANDALONE2 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...) { va_list vars; va_start(vars,fmt); printf("LOG: lev:%d file:%s line:%d func: %s ", level, file, line, function); vprintf(fmt, vars); fflush(stdout); va_end(vars); } int main(int argc,char **argv) { char s[4096]; char out[4096]; FILE *infile; if( !argv[1] ) exit(20); if( access(argv[1],F_OK)== 0 ) { int ret; infile = fopen(argv[1],"r"); if( !infile ) { printf("Sorry, couldn't open %s for reading!\n", argv[1]); exit(10); } while( fgets(s,sizeof(s),infile) ) { if( s[strlen(s)-1] == '\n' ) s[strlen(s)-1] = 0; ret = ast_expr(s, out, sizeof(out), NULL); printf("Expression: %s Result: [%d] '%s'\n", s, ret, out); } fclose(infile); } else { if (ast_expr(argv[1], s, sizeof(s), NULL)) printf("=====%s======\n",s); else printf("No result\n"); } return 0; } #endif #undef ast_yyerror #define ast_yyerror(x) ast_yyerror(x, YYLTYPE *yylloc, struct parse_io *parseio) /* I put the ast_yyerror func in the flex input file, because it refers to the buffer state. Best to let it access the BUFFER stuff there and not trying define all the structs, macros etc. in this file! */ static void destroy_arglist(struct expr_node *arglist) { struct expr_node *arglist_next; while (arglist) { arglist_next = arglist->right; if (arglist->val) free_value(arglist->val); arglist->val = 0; arglist->right = 0; free(arglist); arglist = arglist_next; } } #if !defined(STANDALONE) && !defined(STANDALONE2) static char *compose_func_args(struct expr_node *arglist) { struct expr_node *t = arglist; char *argbuf; int total_len = 0; while (t) { if (t != arglist) total_len += 1; /* for the sep */ if (t->val) { if (t->val->type == AST_EXPR_number) total_len += 25; /* worst case */ else total_len += strlen(t->val->u.s); } t = t->right; } total_len++; /* for the null */ ast_log(LOG_NOTICE,"argbuf allocated %d bytes;\n", total_len); argbuf = malloc(total_len); argbuf[0] = 0; t = arglist; while (t) { char numbuf[30]; if (t != arglist) strcat(argbuf,","); if (t->val) { if (t->val->type == AST_EXPR_number) { sprintf(numbuf,FP___PRINTF,t->val->u.i); strcat(argbuf,numbuf); } else strcat(argbuf,t->val->u.s); } t = t->right; } ast_log(LOG_NOTICE,"argbuf uses %d bytes;\n", (int) strlen(argbuf)); return argbuf; } static int is_really_num(char *str) { if ( strspn(str,"-0123456789. ") == strlen(str)) return 1; else return 0; } #endif static struct val *op_func(struct val *funcname, struct expr_node *arglist, struct ast_channel *chan) { if (strspn(funcname->u.s,"ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789") == strlen(funcname->u.s)) { struct val *result; if (0) { #ifdef FUNC_COS } else if (strcmp(funcname->u.s,"COS") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_COS(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_SIN } else if (strcmp(funcname->u.s,"SIN") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_SIN(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_TAN } else if (strcmp(funcname->u.s,"TAN") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_TAN(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_ACOS } else if (strcmp(funcname->u.s,"ACOS") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_ACOS(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_ASIN } else if (strcmp(funcname->u.s,"ASIN") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_ASIN(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_ATAN } else if (strcmp(funcname->u.s,"ATAN") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_ATAN(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_ATAN2 } else if (strcmp(funcname->u.s,"ATAN2") == 0) { if (arglist && arglist->right && !arglist->right->right && arglist->val && arglist->right->val){ to_number(arglist->val); to_number(arglist->right->val); result = make_number(FUNC_ATAN2(arglist->val->u.i, arglist->right->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_POW } else if (strcmp(funcname->u.s,"POW") == 0) { if (arglist && arglist->right && !arglist->right->right && arglist->val && arglist->right->val){ to_number(arglist->val); to_number(arglist->right->val); result = make_number(FUNC_POW(arglist->val->u.i, arglist->right->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_SQRT } else if (strcmp(funcname->u.s,"SQRT") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_SQRT(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_FLOOR } else if (strcmp(funcname->u.s,"FLOOR") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_FLOOR(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_CEIL } else if (strcmp(funcname->u.s,"CEIL") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_CEIL(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_ROUND } else if (strcmp(funcname->u.s,"ROUND") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_ROUND(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif /* defined(FUNC_ROUND) */ #ifdef FUNC_RINT } else if (strcmp(funcname->u.s,"RINT") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_RINT(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_TRUNC } else if (strcmp(funcname->u.s,"TRUNC") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_TRUNC(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif /* defined(FUNC_TRUNC) */ #ifdef FUNC_EXP } else if (strcmp(funcname->u.s,"EXP") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_EXP(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_EXP2 } else if (strcmp(funcname->u.s,"EXP2") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_EXP2(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_EXP10 } else if (strcmp(funcname->u.s,"EXP10") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_EXP10(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_LOG } else if (strcmp(funcname->u.s,"LOG") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_LOG(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_LOG2 } else if (strcmp(funcname->u.s,"LOG2") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_LOG2(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_LOG10 } else if (strcmp(funcname->u.s,"LOG10") == 0) { if (arglist && !arglist->right && arglist->val){ to_number(arglist->val); result = make_number(FUNC_LOG10(arglist->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif #ifdef FUNC_REMAINDER } else if (strcmp(funcname->u.s,"REMAINDER") == 0) { if (arglist && arglist->right && !arglist->right->right && arglist->val && arglist->right->val){ to_number(arglist->val); to_number(arglist->right->val); result = make_number(FUNC_REMAINDER(arglist->val->u.i, arglist->right->val->u.i)); return result; } else { ast_log(LOG_WARNING,"Wrong args to %s() function\n",funcname->u.s); return make_number(0.0); } #endif } else { /* is this a custom function we should execute and collect the results of? */ #if !defined(STANDALONE) && !defined(STANDALONE2) struct ast_custom_function *f = ast_custom_function_find(funcname->u.s); if (!chan) ast_log(LOG_WARNING,"Hey! chan is NULL.\n"); if (!f) ast_log(LOG_WARNING,"Hey! could not find func %s.\n", funcname->u.s); if (f && chan) { if (f->read) { char workspace[512]; char *argbuf = compose_func_args(arglist); f->read(chan, funcname->u.s, argbuf, workspace, sizeof(workspace)); free(argbuf); if (is_really_num(workspace)) return make_number(FUNC_STRTOD(workspace,(char **)NULL)); else return make_str(workspace); } else { ast_log(LOG_ERROR,"Error! Function '%s' cannot be read!\n", funcname->u.s); return (make_number ((FP___TYPE)0.0)); } } else { ast_log(LOG_ERROR, "Error! '%s' doesn't appear to be an available function!\n", funcname->u.s); return (make_number ((FP___TYPE)0.0)); } #else ast_log(LOG_ERROR, "Error! '%s' is not available in the standalone version!\n", funcname->u.s); return (make_number ((FP___TYPE)0.0)); #endif } } else { ast_log(LOG_ERROR, "Error! '%s' is not possibly a function name!\n", funcname->u.s); return (make_number ((FP___TYPE)0.0)); } return (make_number ((FP___TYPE)0.0)); } static struct val * op_or (struct val *a, struct val *b) { if (is_zero_or_null (a)) { free_value (a); return (b); } else { free_value (b); return (a); } } static struct val * op_and (struct val *a, struct val *b) { if (is_zero_or_null (a) || is_zero_or_null (b)) { free_value (a); free_value (b); return (make_number ((FP___TYPE)0.0)); } else { free_value (b); return (a); } } static struct val * op_eq (struct val *a, struct val *b) { struct val *r; if (isstring (a) || isstring (b)) { to_string (a); to_string (b); r = make_number ((FP___TYPE)(strcoll (a->u.s, b->u.s) == 0)); } else { #ifdef DEBUG_FOR_CONVERSIONS char buffer[2000]; sprintf(buffer,"Converting '%s' and '%s' ", a->u.s, b->u.s); #endif (void)to_number(a); (void)to_number(b); #ifdef DEBUG_FOR_CONVERSIONS ast_log(LOG_WARNING,"%s to '%lld' and '%lld'\n", buffer, a->u.i, b->u.i); #endif r = make_number ((FP___TYPE)(a->u.i == b->u.i)); } free_value (a); free_value (b); return r; } static struct val * op_gt (struct val *a, struct val *b) { struct val *r; if (isstring (a) || isstring (b)) { to_string (a); to_string (b); r = make_number ((FP___TYPE)(strcoll (a->u.s, b->u.s) > 0)); } else { (void)to_number(a); (void)to_number(b); r = make_number ((FP___TYPE)(a->u.i > b->u.i)); } free_value (a); free_value (b); return r; } static struct val * op_lt (struct val *a, struct val *b) { struct val *r; if (isstring (a) || isstring (b)) { to_string (a); to_string (b); r = make_number ((FP___TYPE)(strcoll (a->u.s, b->u.s) < 0)); } else { (void)to_number(a); (void)to_number(b); r = make_number ((FP___TYPE)(a->u.i < b->u.i)); } free_value (a); free_value (b); return r; } static struct val * op_ge (struct val *a, struct val *b) { struct val *r; if (isstring (a) || isstring (b)) { to_string (a); to_string (b); r = make_number ((FP___TYPE)(strcoll (a->u.s, b->u.s) >= 0)); } else { (void)to_number(a); (void)to_number(b); r = make_number ((FP___TYPE)(a->u.i >= b->u.i)); } free_value (a); free_value (b); return r; } static struct val * op_le (struct val *a, struct val *b) { struct val *r; if (isstring (a) || isstring (b)) { to_string (a); to_string (b); r = make_number ((FP___TYPE)(strcoll (a->u.s, b->u.s) <= 0)); } else { (void)to_number(a); (void)to_number(b); r = make_number ((FP___TYPE)(a->u.i <= b->u.i)); } free_value (a); free_value (b); return r; } static struct val * op_cond (struct val *a, struct val *b, struct val *c) { struct val *r; if( isstring(a) ) { if( strlen(a->u.s) && strcmp(a->u.s, "\"\"") != 0 && strcmp(a->u.s,"0") != 0 ) { free_value(a); free_value(c); r = b; } else { free_value(a); free_value(b); r = c; } } else { (void)to_number(a); if( a->u.i ) { free_value(a); free_value(c); r = b; } else { free_value(a); free_value(b); r = c; } } return r; } static struct val * op_ne (struct val *a, struct val *b) { struct val *r; if (isstring (a) || isstring (b)) { to_string (a); to_string (b); r = make_number ((FP___TYPE)(strcoll (a->u.s, b->u.s) != 0)); } else { (void)to_number(a); (void)to_number(b); r = make_number ((FP___TYPE)(a->u.i != b->u.i)); } free_value (a); free_value (b); return r; } static int chk_plus (FP___TYPE a, FP___TYPE b, FP___TYPE r) { /* sum of two positive numbers must be positive */ if (a > 0 && b > 0 && r <= 0) return 1; /* sum of two negative numbers must be negative */ if (a < 0 && b < 0 && r >= 0) return 1; /* all other cases are OK */ return 0; } static struct val * op_plus (struct val *a, struct val *b) { struct val *r; if (!to_number (a)) { if( !extra_error_message_supplied ) ast_log(LOG_WARNING,"non-numeric argument\n"); if (!to_number (b)) { free_value(a); free_value(b); return make_number(0); } else { free_value(a); return (b); } } else if (!to_number(b)) { free_value(b); return (a); } r = make_number (a->u.i + b->u.i); if (chk_plus (a->u.i, b->u.i, r->u.i)) { ast_log(LOG_WARNING,"overflow\n"); } free_value (a); free_value (b); return r; } static int chk_minus (FP___TYPE a, FP___TYPE b, FP___TYPE r) { /* special case subtraction of QUAD_MIN */ if (b == QUAD_MIN) { if (a >= 0) return 1; else return 0; } /* this is allowed for b != QUAD_MIN */ return chk_plus (a, -b, r); } static struct val * op_minus (struct val *a, struct val *b) { struct val *r; if (!to_number (a)) { if( !extra_error_message_supplied ) ast_log(LOG_WARNING, "non-numeric argument\n"); if (!to_number (b)) { free_value(a); free_value(b); return make_number(0); } else { r = make_number(0 - b->u.i); free_value(a); free_value(b); return (r); } } else if (!to_number(b)) { if( !extra_error_message_supplied ) ast_log(LOG_WARNING, "non-numeric argument\n"); free_value(b); return (a); } r = make_number (a->u.i - b->u.i); if (chk_minus (a->u.i, b->u.i, r->u.i)) { ast_log(LOG_WARNING, "overflow\n"); } free_value (a); free_value (b); return r; } static struct val * op_negate (struct val *a) { struct val *r; if (!to_number (a) ) { free_value(a); if( !extra_error_message_supplied ) ast_log(LOG_WARNING, "non-numeric argument\n"); return make_number(0); } r = make_number (- a->u.i); if (chk_minus (0, a->u.i, r->u.i)) { ast_log(LOG_WARNING, "overflow\n"); } free_value (a); return r; } static struct val * op_compl (struct val *a) { int v1 = 1; struct val *r; if( !a ) { v1 = 0; } else { switch( a->type ) { case AST_EXPR_number: if( a->u.i == 0 ) v1 = 0; break; case AST_EXPR_string: if( a->u.s == 0 ) v1 = 0; else { if( a->u.s[0] == 0 ) v1 = 0; else if (strlen(a->u.s) == 1 && a->u.s[0] == '0' ) v1 = 0; else v1 = atoi(a->u.s); } break; case AST_EXPR_numeric_string: if( a->u.s == 0 ) v1 = 0; else { if( a->u.s[0] == 0 ) v1 = 0; else if (strlen(a->u.s) == 1 && a->u.s[0] == '0' ) v1 = 0; else v1 = atoi(a->u.s); } break; } } r = make_number (!v1); free_value (a); return r; } static int chk_times (FP___TYPE a, FP___TYPE b, FP___TYPE r) { /* special case: first operand is 0, no overflow possible */ if (a == 0) return 0; /* cerify that result of division matches second operand */ if (r / a != b) return 1; return 0; } static struct val * op_times (struct val *a, struct val *b) { struct val *r; if (!to_number (a) || !to_number (b)) { free_value(a); free_value(b); if( !extra_error_message_supplied ) ast_log(LOG_WARNING, "non-numeric argument\n"); return(make_number(0)); } r = make_number (a->u.i * b->u.i); if (chk_times (a->u.i, b->u.i, r->u.i)) { ast_log(LOG_WARNING, "overflow\n"); } free_value (a); free_value (b); return (r); } static int chk_div (FP___TYPE a, FP___TYPE b) { /* div by zero has been taken care of before */ /* only QUAD_MIN / -1 causes overflow */ if (a == QUAD_MIN && b == -1) return 1; /* everything else is OK */ return 0; } static struct val * op_div (struct val *a, struct val *b) { struct val *r; if (!to_number (a)) { free_value(a); free_value(b); if( !extra_error_message_supplied ) ast_log(LOG_WARNING, "non-numeric argument\n"); return make_number(0); } else if (!to_number (b)) { free_value(a); free_value(b); if( !extra_error_message_supplied ) ast_log(LOG_WARNING, "non-numeric argument\n"); return make_number(INT_MAX); } if (b->u.i == 0) { ast_log(LOG_WARNING, "division by zero\n"); free_value(a); free_value(b); return make_number(INT_MAX); } r = make_number (a->u.i / b->u.i); if (chk_div (a->u.i, b->u.i)) { ast_log(LOG_WARNING, "overflow\n"); } free_value (a); free_value (b); return r; } static struct val * op_rem (struct val *a, struct val *b) { struct val *r; if (!to_number (a) || !to_number (b)) { if( !extra_error_message_supplied ) ast_log(LOG_WARNING, "non-numeric argument\n"); free_value(a); free_value(b); return make_number(0); } if (b->u.i == 0) { ast_log(LOG_WARNING, "div by zero\n"); free_value(a); return(b); } r = make_number (FUNC_FMOD(a->u.i, b->u.i)); /* either fmod or fmodl if FP___TYPE is available */ /* chk_rem necessary ??? */ free_value (a); free_value (b); return r; } static struct val * op_colon (struct val *a, struct val *b) { regex_t rp; regmatch_t rm[2]; char errbuf[256]; int eval; struct val *v; /* coerce to both arguments to strings */ to_string(a); to_string(b); /* strip double quotes from both -- they'll screw up the pattern, and the search string starting at ^ */ strip_quotes(a); strip_quotes(b); /* compile regular expression */ if ((eval = regcomp (&rp, b->u.s, REG_EXTENDED)) != 0) { regerror (eval, &rp, errbuf, sizeof(errbuf)); ast_log(LOG_WARNING, "regcomp() error : %s\n", errbuf); free_value(a); free_value(b); return make_str(""); } /* compare string against pattern */ /* remember that patterns are anchored to the beginning of the line */ if (regexec(&rp, a->u.s, (size_t)2, rm, 0) == 0 && rm[0].rm_so == 0) { if (rm[1].rm_so >= 0) { *(a->u.s + rm[1].rm_eo) = '\0'; v = make_str (a->u.s + rm[1].rm_so); } else { v = make_number ((FP___TYPE)(rm[0].rm_eo - rm[0].rm_so)); } } else { if (rp.re_nsub == 0) { v = make_number ((FP___TYPE)0); } else { v = make_str (""); } } /* free arguments and pattern buffer */ free_value (a); free_value (b); regfree (&rp); return v; } static struct val * op_eqtilde (struct val *a, struct val *b) { regex_t rp; regmatch_t rm[2]; char errbuf[256]; int eval; struct val *v; /* coerce to both arguments to strings */ to_string(a); to_string(b); /* strip double quotes from both -- they'll screw up the pattern, and the search string starting at ^ */ strip_quotes(a); strip_quotes(b); /* compile regular expression */ if ((eval = regcomp (&rp, b->u.s, REG_EXTENDED)) != 0) { regerror (eval, &rp, errbuf, sizeof(errbuf)); ast_log(LOG_WARNING, "regcomp() error : %s\n", errbuf); free_value(a); free_value(b); return make_str(""); } /* compare string against pattern */ /* remember that patterns are anchored to the beginning of the line */ if (regexec(&rp, a->u.s, (size_t)2, rm, 0) == 0 ) { if (rm[1].rm_so >= 0) { *(a->u.s + rm[1].rm_eo) = '\0'; v = make_str (a->u.s + rm[1].rm_so); } else { v = make_number ((FP___TYPE)(rm[0].rm_eo - rm[0].rm_so)); } } else { if (rp.re_nsub == 0) { v = make_number ((FP___TYPE)0.0); } else { v = make_str (""); } } /* free arguments and pattern buffer */ free_value (a); free_value (b); regfree (&rp); return v; } static struct val * /* this is a string concat operator */ op_tildetilde (struct val *a, struct val *b) { struct val *v; char *vs; /* coerce to both arguments to strings */ to_string(a); to_string(b); /* strip double quotes from both -- */ strip_quotes(a); strip_quotes(b); vs = malloc(strlen(a->u.s)+strlen(b->u.s)+1); strcpy(vs,a->u.s); strcat(vs,b->u.s); v = make_str(vs); /* free arguments */ free_value(a); free_value(b); return v; }
sameersethi/minorproject-asterisk
main/ast_expr2.c
C
gpl-2.0
97,632
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty upper modifier plugin * * Type: modifier<br> * Name: upper<br> * Purpose: convert string to uppercase * @link http://smarty.php.net/manual/en/language.modifier.upper.php * upper (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_upper($string) { return strtoupper($string); } ?>
chiamingyen/sgw745
src/lib/smarty/plugins/modifier.upper.php
PHP
gpl-2.0
480
//----------------------------------------------------------------------------- // Copyright (C) 2014 // // This code is licensed to you under the terms of the GNU GPL, version 2 or, // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- // Low frequency demod/decode commands //----------------------------------------------------------------------------- #include <stdlib.h> #include <string.h> #include "lfdemod.h" uint8_t justNoise(uint8_t *BitStream, size_t size) { static const uint8_t THRESHOLD = 123; //test samples are not just noise uint8_t justNoise1 = 1; for(size_t idx=0; idx < size && justNoise1 ;idx++){ justNoise1 = BitStream[idx] < THRESHOLD; } return justNoise1; } //by marshmellow //get high and low values of a wave with passed in fuzz factor. also return noise test = 1 for passed or 0 for only noise int getHiLo(uint8_t *BitStream, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo) { *high=0; *low=255; // get high and low thresholds for (size_t i=0; i < size; i++){ if (BitStream[i] > *high) *high = BitStream[i]; if (BitStream[i] < *low) *low = BitStream[i]; } if (*high < 123) return -1; // just noise *high = ((*high-128)*fuzzHi + 12800)/100; *low = ((*low-128)*fuzzLo + 12800)/100; return 1; } // by marshmellow // pass bits to be tested in bits, length bits passed in bitLen, and parity type (even=0 | odd=1) in pType // returns 1 if passed uint8_t parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType) { uint8_t ans = 0; for (uint8_t i = 0; i < bitLen; i++){ ans ^= ((bits >> i) & 1); } //PrintAndLog("DEBUG: ans: %d, ptype: %d",ans,pType); return (ans == pType); } //by marshmellow //search for given preamble in given BitStream and return success=1 or fail=0 and startIndex and length uint8_t preambleSearch(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx) { uint8_t foundCnt=0; for (int idx=0; idx < *size - pLen; idx++){ if (memcmp(BitStream+idx, preamble, pLen) == 0){ //first index found foundCnt++; if (foundCnt == 1){ *startIdx = idx; } if (foundCnt == 2){ *size = idx - *startIdx; return 1; } } } return 0; } //by marshmellow //takes 1s and 0s and searches for EM410x format - output EM ID uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo) { //no arguments needed - built this way in case we want this to be a direct call from "data " cmds in the future // otherwise could be a void with no arguments //set defaults uint32_t i = 0; if (BitStream[1]>1) return 0; //allow only 1s and 0s // 111111111 bit pattern represent start of frame // include 0 in front to help get start pos uint8_t preamble[] = {0,1,1,1,1,1,1,1,1,1}; uint32_t idx = 0; uint32_t parityBits = 0; uint8_t errChk = 0; uint8_t FmtLen = 10; *startIdx = 0; errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, startIdx); if (errChk == 0 || *size < 64) return 0; if (*size > 64) FmtLen = 22; *startIdx += 1; //get rid of 0 from preamble idx = *startIdx + 9; for (i=0; i<FmtLen; i++){ //loop through 10 or 22 sets of 5 bits (50-10p = 40 bits or 88 bits) parityBits = bytebits_to_byte(BitStream+(i*5)+idx,5); //check even parity - quit if failed if (parityTest(parityBits, 5, 0) == 0) return 0; //set uint64 with ID from BitStream for (uint8_t ii=0; ii<4; ii++){ *hi = (*hi << 1) | (*lo >> 63); *lo = (*lo << 1) | (BitStream[(i*5)+ii+idx]); } } if (errChk != 0) return 1; //skip last 5 bit parity test for simplicity. // *size = 64 | 128; return 0; } //by marshmellow //demodulates strong heavily clipped samples int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int high, int low) { size_t bitCnt=0, smplCnt=0, errCnt=0; uint8_t waveHigh = 0; for (size_t i=0; i < *size; i++){ if (BinStream[i] >= high && waveHigh){ smplCnt++; } else if (BinStream[i] <= low && !waveHigh){ smplCnt++; } else { //transition if ((BinStream[i] >= high && !waveHigh) || (BinStream[i] <= low && waveHigh)){ if (smplCnt > clk-(clk/4)-1) { //full clock if (smplCnt > clk + (clk/4)+1) { //too many samples errCnt++; BinStream[bitCnt++]=7; } else if (waveHigh) { BinStream[bitCnt++] = invert; BinStream[bitCnt++] = invert; } else if (!waveHigh) { BinStream[bitCnt++] = invert ^ 1; BinStream[bitCnt++] = invert ^ 1; } waveHigh ^= 1; smplCnt = 0; } else if (smplCnt > (clk/2) - (clk/4)-1) { if (waveHigh) { BinStream[bitCnt++] = invert; } else if (!waveHigh) { BinStream[bitCnt++] = invert ^ 1; } waveHigh ^= 1; smplCnt = 0; } else if (!bitCnt) { //first bit waveHigh = (BinStream[i] >= high); smplCnt = 1; } else { smplCnt++; //transition bit oops } } else { //haven't hit new high or new low yet smplCnt++; } } } *size = bitCnt; return errCnt; } //by marshmellow void askAmp(uint8_t *BitStream, size_t size) { for(size_t i = 1; i<size; i++){ if (BitStream[i]-BitStream[i-1]>=30) //large jump up BitStream[i]=127; else if(BitStream[i]-BitStream[i-1]<=-20) //large jump down BitStream[i]=-127; } return; } //by marshmellow //attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType) { if (*size==0) return -1; int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default if (*clk==0 || start < 0) return -3; if (*invert != 1) *invert = 0; if (amp==1) askAmp(BinStream, *size); uint8_t initLoopMax = 255; if (initLoopMax > *size) initLoopMax = *size; // Detect high and lows //25% clip in case highs and lows aren't clipped [marshmellow] int high, low; if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1) return -2; //just noise size_t errCnt = 0; // if clean clipped waves detected run alternate demod if (DetectCleanAskWave(BinStream, *size, high, low)) { errCnt = cleanAskRawDemod(BinStream, size, *clk, *invert, high, low); if (askType) //askman return manrawdecode(BinStream, size, 0); else //askraw return errCnt; } int lastBit; //set first clock check - can go negative size_t i, bitnum = 0; //output counter uint8_t midBit = 0; uint8_t tol = 0; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave if (*clk <= 32) tol = 1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely size_t MaxBits = 1024; lastBit = start - *clk; for (i = start; i < *size; ++i) { if (i-lastBit >= *clk-tol){ if (BinStream[i] >= high) { BinStream[bitnum++] = *invert; } else if (BinStream[i] <= low) { BinStream[bitnum++] = *invert ^ 1; } else if (i-lastBit >= *clk+tol) { if (bitnum > 0) { BinStream[bitnum++]=7; errCnt++; } } else { //in tolerance - looking for peak continue; } midBit = 0; lastBit += *clk; } else if (i-lastBit >= (*clk/2-tol) && !midBit && !askType){ if (BinStream[i] >= high) { BinStream[bitnum++] = *invert; } else if (BinStream[i] <= low) { BinStream[bitnum++] = *invert ^ 1; } else if (i-lastBit >= *clk/2+tol) { BinStream[bitnum] = BinStream[bitnum-1]; bitnum++; } else { //in tolerance - looking for peak continue; } midBit = 1; } if (bitnum >= MaxBits) break; } *size = bitnum; return errCnt; } //by marshmellow //take 10 and 01 and manchester decode //run through 2 times and take least errCnt int manrawdecode(uint8_t * BitStream, size_t *size, uint8_t invert) { uint16_t bitnum=0, MaxBits = 512, errCnt = 0; size_t i, ii; uint16_t bestErr = 1000, bestRun = 0; if (*size < 16) return -1; //find correct start position [alignment] for (ii=0;ii<2;++ii){ for (i=ii; i<*size-3; i+=2) if (BitStream[i]==BitStream[i+1]) errCnt++; if (bestErr>errCnt){ bestErr=errCnt; bestRun=ii; } errCnt=0; } //decode for (i=bestRun; i < *size-3; i+=2){ if(BitStream[i] == 1 && (BitStream[i+1] == 0)){ BitStream[bitnum++]=invert; } else if((BitStream[i] == 0) && BitStream[i+1] == 1){ BitStream[bitnum++]=invert^1; } else { BitStream[bitnum++]=7; } if(bitnum>MaxBits) break; } *size=bitnum; return bestErr; } //by marshmellow //encode binary data into binary manchester int ManchesterEncode(uint8_t *BitStream, size_t size) { size_t modIdx=20000, i=0; if (size>modIdx) return -1; for (size_t idx=0; idx < size; idx++){ BitStream[idx+modIdx++] = BitStream[idx]; BitStream[idx+modIdx++] = BitStream[idx]^1; } for (; i<(size*2); i++){ BitStream[i] = BitStream[i+20000]; } return i; } //by marshmellow //take 01 or 10 = 1 and 11 or 00 = 0 //check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010 //decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding int BiphaseRawDecode(uint8_t *BitStream, size_t *size, int offset, int invert) { uint16_t bitnum = 0; uint16_t errCnt = 0; size_t i = offset; uint16_t MaxBits=512; //if not enough samples - error if (*size < 51) return -1; //check for phase change faults - skip one sample if faulty uint8_t offsetA = 1, offsetB = 1; for (; i<48; i+=2){ if (BitStream[i+1]==BitStream[i+2]) offsetA=0; if (BitStream[i+2]==BitStream[i+3]) offsetB=0; } if (!offsetA && offsetB) offset++; for (i=offset; i<*size-3; i+=2){ //check for phase error if (BitStream[i+1]==BitStream[i+2]) { BitStream[bitnum++]=7; errCnt++; } if((BitStream[i]==1 && BitStream[i+1]==0) || (BitStream[i]==0 && BitStream[i+1]==1)){ BitStream[bitnum++]=1^invert; } else if((BitStream[i]==0 && BitStream[i+1]==0) || (BitStream[i]==1 && BitStream[i+1]==1)){ BitStream[bitnum++]=invert; } else { BitStream[bitnum++]=7; errCnt++; } if(bitnum>MaxBits) break; } *size=bitnum; return errCnt; } // by marshmellow // demod gProxIIDemod // error returns as -x // success returns start position in BitStream // BitStream must contain previously askrawdemod and biphasedemoded data int gProxII_Demod(uint8_t BitStream[], size_t *size) { size_t startIdx=0; uint8_t preamble[] = {1,1,1,1,1,0}; uint8_t errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, &startIdx); if (errChk == 0) return -3; //preamble not found if (*size != 96) return -2; //should have found 96 bits //check first 6 spacer bits to verify format if (!BitStream[startIdx+5] && !BitStream[startIdx+10] && !BitStream[startIdx+15] && !BitStream[startIdx+20] && !BitStream[startIdx+25] && !BitStream[startIdx+30]){ //confirmed proper separator bits found //return start position return (int) startIdx; } return -5; } //translate wave to 11111100000 (1 for each short wave 0 for each long wave) size_t fsk_wave_demod(uint8_t * dest, size_t size, uint8_t fchigh, uint8_t fclow) { size_t last_transition = 0; size_t idx = 1; //uint32_t maxVal=0; if (fchigh==0) fchigh=10; if (fclow==0) fclow=8; //set the threshold close to 0 (graph) or 128 std to avoid static uint8_t threshold_value = 123; // sync to first lo-hi transition, and threshold // Need to threshold first sample if(dest[0] < threshold_value) dest[0] = 0; else dest[0] = 1; size_t numBits = 0; // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8) // or 10 (fc/10) cycles but in practice due to noise etc we may end up with with anywhere // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10 for(idx = 1; idx < size; idx++) { // threshold current value if (dest[idx] < threshold_value) dest[idx] = 0; else dest[idx] = 1; // Check for 0->1 transition if (dest[idx-1] < dest[idx]) { // 0 -> 1 transition if ((idx-last_transition)<(fclow-2)){ //0-5 = garbage noise //do nothing with extra garbage } else if ((idx-last_transition) < (fchigh-1)) { //6-8 = 8 waves dest[numBits++]=1; } else if ((idx-last_transition) > (fchigh+1) && !numBits) { //12 + and first bit = garbage //do nothing with beginning garbage } else { //9+ = 10 waves dest[numBits++]=0; } last_transition = idx; } } return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0 } //translate 11111100000 to 10 size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow) { uint8_t lastval=dest[0]; size_t idx=0; size_t numBits=0; uint32_t n=1; for( idx=1; idx < size; idx++) { n++; if (dest[idx]==lastval) continue; //if lastval was 1, we have a 1->0 crossing if (dest[idx-1]==1) { if (!numBits && n < rfLen/fclow) { n=0; lastval = dest[idx]; continue; } n = (n * fclow + rfLen/2) / rfLen; } else {// 0->1 crossing //test first bitsample too small if (!numBits && n < rfLen/fchigh) { n=0; lastval = dest[idx]; continue; } n = (n * fchigh + rfLen/2) / rfLen; } if (n == 0) n = 1; memset(dest+numBits, dest[idx-1]^invert , n); numBits += n; n=0; lastval=dest[idx]; }//end for // if valid extra bits at the end were all the same frequency - add them in if (n > rfLen/fchigh) { if (dest[idx-2]==1) { n = (n * fclow + rfLen/2) / rfLen; } else { n = (n * fchigh + rfLen/2) / rfLen; } memset(dest+numBits, dest[idx-1]^invert , n); numBits += n; } return numBits; } //by marshmellow (from holiman's base) // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod) int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow) { // FSK demodulator size = fsk_wave_demod(dest, size, fchigh, fclow); size = aggregate_bits(dest, size, rfLen, invert, fchigh, fclow); return size; } // loop to get raw HID waveform then FSK demodulate the TAG ID from it int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo) { if (justNoise(dest, *size)) return -1; size_t numStart=0, size2=*size, startIdx=0; // FSK demodulator *size = fskdemod(dest, size2,50,1,10,8); //fsk2a if (*size < 96*2) return -2; // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1 uint8_t preamble[] = {0,0,0,1,1,1,0,1}; // find bitstring in array uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx); if (errChk == 0) return -3; //preamble not found numStart = startIdx + sizeof(preamble); // final loop, go over previously decoded FSK data and manchester decode into usable tag ID for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){ if (dest[idx] == dest[idx+1]){ return -4; //not manchester data } *hi2 = (*hi2<<1)|(*hi>>31); *hi = (*hi<<1)|(*lo>>31); //Then, shift in a 0 or one into low if (dest[idx] && !dest[idx+1]) // 1 0 *lo=(*lo<<1)|1; else // 0 1 *lo=(*lo<<1)|0; } return (int)startIdx; } // loop to get raw paradox waveform then FSK demodulate the TAG ID from it int ParadoxdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo) { if (justNoise(dest, *size)) return -1; size_t numStart=0, size2=*size, startIdx=0; // FSK demodulator *size = fskdemod(dest, size2,50,1,10,8); //fsk2a if (*size < 96) return -2; // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1 uint8_t preamble[] = {0,0,0,0,1,1,1,1}; uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx); if (errChk == 0) return -3; //preamble not found numStart = startIdx + sizeof(preamble); // final loop, go over previously decoded FSK data and manchester decode into usable tag ID for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){ if (dest[idx] == dest[idx+1]) return -4; //not manchester data *hi2 = (*hi2<<1)|(*hi>>31); *hi = (*hi<<1)|(*lo>>31); //Then, shift in a 0 or one into low if (dest[idx] && !dest[idx+1]) // 1 0 *lo=(*lo<<1)|1; else // 0 1 *lo=(*lo<<1)|0; } return (int)startIdx; } uint32_t bytebits_to_byte(uint8_t *src, size_t numbits) { uint32_t num = 0; for(int i = 0 ; i < numbits ; i++) { num = (num << 1) | (*src); src++; } return num; } //least significant bit first uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits) { uint32_t num = 0; for(int i = 0 ; i < numbits ; i++) { num = (num << 1) | *(src + (numbits-(i+1))); } return num; } int IOdemodFSK(uint8_t *dest, size_t size) { if (justNoise(dest, size)) return -1; //make sure buffer has data if (size < 66*64) return -2; // FSK demodulator size = fskdemod(dest, size, 64, 1, 10, 8); // FSK2a RF/64 if (size < 65) return -3; //did we get a good demod? //Index map //0 10 20 30 40 50 60 //| | | | | | | //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23 //----------------------------------------------------------------------------- //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11 // //XSF(version)facility:codeone+codetwo //Handle the data size_t startIdx = 0; uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,1}; uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), &size, &startIdx); if (errChk == 0) return -4; //preamble not found if (!dest[startIdx+8] && dest[startIdx+17]==1 && dest[startIdx+26]==1 && dest[startIdx+35]==1 && dest[startIdx+44]==1 && dest[startIdx+53]==1){ //confirmed proper separator bits found //return start position return (int) startIdx; } return -5; } // by marshmellow // takes a array of binary values, start position, length of bits per parity (includes parity bit), // Parity Type (1 for odd; 0 for even; 2 Always 1's), and binary Length (length to run) size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen) { uint32_t parityWd = 0; size_t j = 0, bitCnt = 0; for (int word = 0; word < (bLen); word+=pLen){ for (int bit=0; bit < pLen; bit++){ parityWd = (parityWd << 1) | BitStream[startIdx+word+bit]; BitStream[j++] = (BitStream[startIdx+word+bit]); } j--; // overwrite parity with next data // if parity fails then return 0 if (pType == 2) { // then marker bit which should be a 1 if (!BitStream[j]) return 0; } else { if (parityTest(parityWd, pLen, pType) == 0) return 0; } bitCnt+=(pLen-1); parityWd = 0; } // if we got here then all the parities passed //return ID start index and size return bitCnt; } // Ask/Biphase Demod then try to locate an ISO 11784/85 ID // BitStream must contain previously askrawdemod and biphasedemoded data int FDXBdemodBI(uint8_t *dest, size_t *size) { //make sure buffer has enough data if (*size < 128) return -1; size_t startIdx = 0; uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,1}; uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx); if (errChk == 0) return -2; //preamble not found return (int)startIdx; } // by marshmellow // FSK Demod then try to locate an AWID ID int AWIDdemodFSK(uint8_t *dest, size_t *size) { //make sure buffer has enough data if (*size < 96*50) return -1; if (justNoise(dest, *size)) return -2; // FSK demodulator *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50 if (*size < 96) return -3; //did we get a good demod? uint8_t preamble[] = {0,0,0,0,0,0,0,1}; size_t startIdx = 0; uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx); if (errChk == 0) return -4; //preamble not found if (*size != 96) return -5; return (int)startIdx; } // by marshmellow // FSK Demod then try to locate an Farpointe Data (pyramid) ID int PyramiddemodFSK(uint8_t *dest, size_t *size) { //make sure buffer has data if (*size < 128*50) return -5; //test samples are not just noise if (justNoise(dest, *size)) return -1; // FSK demodulator *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50 if (*size < 128) return -2; //did we get a good demod? uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; size_t startIdx = 0; uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx); if (errChk == 0) return -4; //preamble not found if (*size != 128) return -3; return (int)startIdx; } // by marshmellow // to detect a wave that has heavily clipped (clean) samples uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low) { uint16_t allPeaks=1; uint16_t cntPeaks=0; size_t loopEnd = 512+60; if (loopEnd > size) loopEnd = size; for (size_t i=60; i<loopEnd; i++){ if (dest[i]>low && dest[i]<high) allPeaks=0; else cntPeaks++; } if (allPeaks == 0){ if (cntPeaks > 300) return 1; } return allPeaks; } // by marshmellow // to help detect clocks on heavily clipped samples // based on count of low to low int DetectStrongAskClock(uint8_t dest[], size_t size, uint8_t high, uint8_t low) { uint8_t fndClk[] = {8,16,32,40,50,64,128}; size_t startwave; size_t i = 0; size_t minClk = 255; // get to first full low to prime loop and skip incomplete first pulse while ((dest[i] < high) && (i < size)) ++i; while ((dest[i] > low) && (i < size)) ++i; // loop through all samples while (i < size) { // measure from low to low while ((dest[i] > low) && (i < size)) ++i; startwave= i; while ((dest[i] < high) && (i < size)) ++i; while ((dest[i] > low) && (i < size)) ++i; //get minimum measured distance if (i-startwave < minClk && i < size) minClk = i - startwave; } // set clock for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) { if (minClk >= fndClk[clkCnt]-(fndClk[clkCnt]/8) && minClk <= fndClk[clkCnt]+1) return fndClk[clkCnt]; } return 0; } // by marshmellow // not perfect especially with lower clocks or VERY good antennas (heavy wave clipping) // maybe somehow adjust peak trimming value based on samples to fix? // return start index of best starting position for that clock and return clock (by reference) int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) { size_t i=1; uint8_t clk[] = {255,8,16,32,40,50,64,100,128,255}; uint8_t clkEnd = 9; uint8_t loopCnt = 255; //don't need to loop through entire array... if (size <= loopCnt) return -1; //not enough samples //if we already have a valid clock uint8_t clockFnd=0; for (;i<clkEnd;++i) if (clk[i] == *clock) clockFnd = i; //clock found but continue to find best startpos //get high and low peak int peak, low; if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return -1; //test for large clean peaks if (!clockFnd){ if (DetectCleanAskWave(dest, size, peak, low)==1){ int ans = DetectStrongAskClock(dest, size, peak, low); for (i=clkEnd-1; i>0; i--){ if (clk[i] == ans) { *clock = ans; //clockFnd = i; return 0; // for strong waves i don't use the 'best start position' yet... //break; //clock found but continue to find best startpos [not yet] } } } } uint8_t ii; uint8_t clkCnt, tol = 0; uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000}; uint8_t bestStart[]={0,0,0,0,0,0,0,0,0}; size_t errCnt = 0; size_t arrLoc, loopEnd; if (clockFnd>0) { clkCnt = clockFnd; clkEnd = clockFnd+1; } else clkCnt=1; //test each valid clock from smallest to greatest to see which lines up for(; clkCnt < clkEnd; clkCnt++){ if (clk[clkCnt] <= 32){ tol=1; }else{ tol=0; } //if no errors allowed - keep start within the first clock if (!maxErr && size > clk[clkCnt]*2 + tol && clk[clkCnt]<128) loopCnt=clk[clkCnt]*2; bestErr[clkCnt]=1000; //try lining up the peaks by moving starting point (try first few clocks) for (ii=0; ii < loopCnt; ii++){ if (dest[ii] < peak && dest[ii] > low) continue; errCnt=0; // now that we have the first one lined up test rest of wave array loopEnd = ((size-ii-tol) / clk[clkCnt]) - 1; for (i=0; i < loopEnd; ++i){ arrLoc = ii + (i * clk[clkCnt]); if (dest[arrLoc] >= peak || dest[arrLoc] <= low){ }else if (dest[arrLoc-tol] >= peak || dest[arrLoc-tol] <= low){ }else if (dest[arrLoc+tol] >= peak || dest[arrLoc+tol] <= low){ }else{ //error no peak detected errCnt++; } } //if we found no errors then we can stop here and a low clock (common clocks) // this is correct one - return this clock //PrintAndLog("DEBUG: clk %d, err %d, ii %d, i %d",clk[clkCnt],errCnt,ii,i); if(errCnt==0 && clkCnt<7) { if (!clockFnd) *clock = clk[clkCnt]; return ii; } //if we found errors see if it is lowest so far and save it as best run if(errCnt<bestErr[clkCnt]){ bestErr[clkCnt]=errCnt; bestStart[clkCnt]=ii; } } } uint8_t iii; uint8_t best=0; for (iii=1; iii<clkEnd; ++iii){ if (bestErr[iii] < bestErr[best]){ if (bestErr[iii] == 0) bestErr[iii]=1; // current best bit to error ratio vs new bit to error ratio if ( (size/clk[best])/bestErr[best] < (size/clk[iii])/bestErr[iii] ){ best = iii; } } } //if (bestErr[best] > maxErr) return -1; if (!clockFnd) *clock = clk[best]; return bestStart[best]; } //by marshmellow //detect psk clock by reading each phase shift // a phase shift is determined by measuring the sample length of each wave int DetectPSKClock(uint8_t dest[], size_t size, int clock) { uint8_t clk[]={255,16,32,40,50,64,100,128,255}; //255 is not a valid clock uint16_t loopCnt = 4096; //don't need to loop through entire array... if (size == 0) return 0; if (size<loopCnt) loopCnt = size; //if we already have a valid clock quit size_t i=1; for (; i < 8; ++i) if (clk[i] == clock) return clock; size_t waveStart=0, waveEnd=0, firstFullWave=0, lastClkBit=0; uint8_t clkCnt, fc=0, fullWaveLen=0, tol=1; uint16_t peakcnt=0, errCnt=0, waveLenCnt=0; uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000}; uint16_t peaksdet[]={0,0,0,0,0,0,0,0,0}; fc = countFC(dest, size, 0); if (fc!=2 && fc!=4 && fc!=8) return -1; //PrintAndLog("DEBUG: FC: %d",fc); //find first full wave for (i=0; i<loopCnt; i++){ if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){ if (waveStart == 0) { waveStart = i+1; //PrintAndLog("DEBUG: waveStart: %d",waveStart); } else { waveEnd = i+1; //PrintAndLog("DEBUG: waveEnd: %d",waveEnd); waveLenCnt = waveEnd-waveStart; if (waveLenCnt > fc){ firstFullWave = waveStart; fullWaveLen=waveLenCnt; break; } waveStart=0; } } } //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen); //test each valid clock from greatest to smallest to see which lines up for(clkCnt=7; clkCnt >= 1 ; clkCnt--){ lastClkBit = firstFullWave; //set end of wave as clock align waveStart = 0; errCnt=0; peakcnt=0; //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d",clk[clkCnt],lastClkBit); for (i = firstFullWave+fullWaveLen-1; i < loopCnt-2; i++){ //top edge of wave = start of new wave if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){ if (waveStart == 0) { waveStart = i+1; waveLenCnt=0; } else { //waveEnd waveEnd = i+1; waveLenCnt = waveEnd-waveStart; if (waveLenCnt > fc){ //if this wave is a phase shift //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, ii: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+clk[clkCnt]-tol,ii+1,fc); if (i+1 >= lastClkBit + clk[clkCnt] - tol){ //should be a clock bit peakcnt++; lastClkBit+=clk[clkCnt]; } else if (i<lastClkBit+8){ //noise after a phase shift - ignore } else { //phase shift before supposed to based on clock errCnt++; } } else if (i+1 > lastClkBit + clk[clkCnt] + tol + fc){ lastClkBit+=clk[clkCnt]; //no phase shift but clock bit } waveStart=i+1; } } } if (errCnt == 0){ return clk[clkCnt]; } if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt]=errCnt; if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt]=peakcnt; } //all tested with errors //return the highest clk with the most peaks found uint8_t best=7; for (i=7; i>=1; i--){ if (peaksdet[i] > peaksdet[best]) { best = i; } //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]); } return clk[best]; } //by marshmellow //detect nrz clock by reading #peaks vs no peaks(or errors) int DetectNRZClock(uint8_t dest[], size_t size, int clock) { size_t i=0; uint8_t clk[]={8,16,32,40,50,64,100,128,255}; size_t loopCnt = 4096; //don't need to loop through entire array... if (size == 0) return 0; if (size<loopCnt) loopCnt = size; //if we already have a valid clock quit for (; i < 8; ++i) if (clk[i] == clock) return clock; //get high and low peak int peak, low; if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return 0; //PrintAndLog("DEBUG: peak: %d, low: %d",peak,low); size_t ii; uint8_t clkCnt; uint8_t tol = 0; uint16_t peakcnt=0; uint16_t peaksdet[]={0,0,0,0,0,0,0,0}; uint16_t maxPeak=0; //test for large clipped waves for (i=0; i<loopCnt; i++){ if (dest[i] >= peak || dest[i] <= low){ peakcnt++; } else { if (peakcnt>0 && maxPeak < peakcnt){ maxPeak = peakcnt; } peakcnt=0; } } peakcnt=0; //test each valid clock from smallest to greatest to see which lines up for(clkCnt=0; clkCnt < 8; ++clkCnt){ //ignore clocks smaller than largest peak if (clk[clkCnt]<maxPeak) continue; //try lining up the peaks by moving starting point (try first 256) for (ii=0; ii< loopCnt; ++ii){ if ((dest[ii] >= peak) || (dest[ii] <= low)){ peakcnt=0; // now that we have the first one lined up test rest of wave array for (i=0; i < ((int)((size-ii-tol)/clk[clkCnt])-1); ++i){ if (dest[ii+(i*clk[clkCnt])]>=peak || dest[ii+(i*clk[clkCnt])]<=low){ peakcnt++; } } if(peakcnt>peaksdet[clkCnt]) { peaksdet[clkCnt]=peakcnt; } } } } int iii=7; uint8_t best=0; for (iii=7; iii > 0; iii--){ if (peaksdet[iii] > peaksdet[best]){ best = iii; } //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]); } return clk[best]; } // by marshmellow // convert psk1 demod to psk2 demod // only transition waves are 1s void psk1TOpsk2(uint8_t *BitStream, size_t size) { size_t i=1; uint8_t lastBit=BitStream[0]; for (; i<size; i++){ if (BitStream[i]==7){ //ignore errors } else if (lastBit!=BitStream[i]){ lastBit=BitStream[i]; BitStream[i]=1; } else { BitStream[i]=0; } } return; } // by marshmellow // convert psk2 demod to psk1 demod // from only transition waves are 1s to phase shifts change bit void psk2TOpsk1(uint8_t *BitStream, size_t size) { uint8_t phase=0; for (size_t i=0; i<size; i++){ if (BitStream[i]==1){ phase ^=1; } BitStream[i]=phase; } return; } // redesigned by marshmellow adjusted from existing decode functions // indala id decoding - only tested on 26 bit tags, but attempted to make it work for more int indala26decode(uint8_t *bitStream, size_t *size, uint8_t *invert) { //26 bit 40134 format (don't know other formats) int i; int long_wait=29;//29 leading zeros in format int start; int first = 0; int first2 = 0; int bitCnt = 0; int ii; // Finding the start of a UID for (start = 0; start <= *size - 250; start++) { first = bitStream[start]; for (i = start; i < start + long_wait; i++) { if (bitStream[i] != first) { break; } } if (i == (start + long_wait)) { break; } } if (start == *size - 250 + 1) { // did not find start sequence return -1; } // Inverting signal if needed if (first == 1) { for (i = start; i < *size; i++) { bitStream[i] = !bitStream[i]; } *invert = 1; }else *invert=0; int iii; //found start once now test length by finding next one for (ii=start+29; ii <= *size - 250; ii++) { first2 = bitStream[ii]; for (iii = ii; iii < ii + long_wait; iii++) { if (bitStream[iii] != first2) { break; } } if (iii == (ii + long_wait)) { break; } } if (ii== *size - 250 + 1){ // did not find second start sequence return -2; } bitCnt=ii-start; // Dumping UID i = start; for (ii = 0; ii < bitCnt; ii++) { bitStream[ii] = bitStream[i++]; } *size=bitCnt; return 1; } // by marshmellow - demodulate NRZ wave (both similar enough) // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak // there probably is a much simpler way to do this.... int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int maxErr) { if (justNoise(dest, *size)) return -1; *clk = DetectNRZClock(dest, *size, *clk); if (*clk==0) return -2; size_t i, gLen = 4096; if (gLen>*size) gLen = *size; int high, low; if (getHiLo(dest, gLen, &high, &low, 75, 75) < 1) return -3; //25% fuzz on high 25% fuzz on low int lastBit = 0; //set first clock check size_t iii = 0, bitnum = 0; //bitnum counter uint16_t errCnt = 0, MaxBits = 1000; size_t bestErrCnt = maxErr+1; size_t bestPeakCnt = 0, bestPeakStart = 0; uint8_t bestFirstPeakHigh=0, firstPeakHigh=0, curBit=0, bitHigh=0, errBitHigh=0; uint8_t tol = 1; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave uint16_t peakCnt=0; uint8_t ignoreWindow=4; uint8_t ignoreCnt=ignoreWindow; //in case of noise near peak //loop to find first wave that works - align to clock for (iii=0; iii < gLen; ++iii){ if ((dest[iii]>=high) || (dest[iii]<=low)){ if (dest[iii]>=high) firstPeakHigh=1; else firstPeakHigh=0; lastBit=iii-*clk; peakCnt=0; errCnt=0; //loop through to see if this start location works for (i = iii; i < *size; ++i) { // if we are at a clock bit if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) { //test high/low if (dest[i] >= high || dest[i] <= low) { bitHigh = 1; peakCnt++; errBitHigh = 0; ignoreCnt = ignoreWindow; lastBit += *clk; } else if (i == lastBit + *clk + tol) { lastBit += *clk; } //else if no bars found } else if (dest[i] < high && dest[i] > low){ if (ignoreCnt==0){ bitHigh=0; if (errBitHigh==1) errCnt++; errBitHigh=0; } else { ignoreCnt--; } } else if ((dest[i]>=high || dest[i]<=low) && (bitHigh==0)) { //error bar found no clock... errBitHigh=1; } if (((i-iii) / *clk)>=MaxBits) break; } //we got more than 64 good bits and not all errors if (((i-iii) / *clk) > 64 && (errCnt <= (maxErr))) { //possible good read if (!errCnt || peakCnt > bestPeakCnt){ bestFirstPeakHigh=firstPeakHigh; bestErrCnt = errCnt; bestPeakCnt = peakCnt; bestPeakStart = iii; if (!errCnt) break; //great read - finish } } } } //PrintAndLog("DEBUG: bestErrCnt: %d, maxErr: %d, bestStart: %d, bestPeakCnt: %d, bestPeakStart: %d",bestErrCnt,maxErr,bestStart,bestPeakCnt,bestPeakStart); if (bestErrCnt > maxErr) return bestErrCnt; //best run is good enough set to best run and set overwrite BinStream lastBit = bestPeakStart - *clk; memset(dest, bestFirstPeakHigh^1, bestPeakStart / *clk); bitnum += (bestPeakStart / *clk); for (i = bestPeakStart; i < *size; ++i) { // if expecting a clock bit if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) { // test high/low if (dest[i] >= high || dest[i] <= low) { peakCnt++; bitHigh = 1; errBitHigh = 0; ignoreCnt = ignoreWindow; curBit = *invert; if (dest[i] >= high) curBit ^= 1; dest[bitnum++] = curBit; lastBit += *clk; //else no bars found in clock area } else if (i == lastBit + *clk + tol) { dest[bitnum++] = curBit; lastBit += *clk; } //else if no bars found } else if (dest[i] < high && dest[i] > low){ if (ignoreCnt == 0){ bitHigh = 0; if (errBitHigh == 1){ dest[bitnum++] = 7; errCnt++; } errBitHigh=0; } else { ignoreCnt--; } } else if ((dest[i] >= high || dest[i] <= low) && (bitHigh == 0)) { //error bar found no clock... errBitHigh=1; } if (bitnum >= MaxBits) break; } *size = bitnum; return bestErrCnt; } //by marshmellow //detects the bit clock for FSK given the high and low Field Clocks uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow) { uint8_t clk[] = {8,16,32,40,50,64,100,128,0}; uint16_t rfLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; uint8_t rfCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; uint8_t rfLensFnd = 0; uint8_t lastFCcnt = 0; uint16_t fcCounter = 0; uint16_t rfCounter = 0; uint8_t firstBitFnd = 0; size_t i; if (size == 0) return 0; uint8_t fcTol = (uint8_t)(0.5+(float)(fcHigh-fcLow)/2); rfLensFnd=0; fcCounter=0; rfCounter=0; firstBitFnd=0; //PrintAndLog("DEBUG: fcTol: %d",fcTol); // prime i to first up transition for (i = 1; i < size-1; i++) if (BitStream[i] > BitStream[i-1] && BitStream[i]>=BitStream[i+1]) break; for (; i < size-1; i++){ fcCounter++; rfCounter++; if (BitStream[i] <= BitStream[i-1] || BitStream[i] < BitStream[i+1]) continue; // else new peak // if we got less than the small fc + tolerance then set it to the small fc if (fcCounter < fcLow+fcTol) fcCounter = fcLow; else //set it to the large fc fcCounter = fcHigh; //look for bit clock (rf/xx) if ((fcCounter < lastFCcnt || fcCounter > lastFCcnt)){ //not the same size as the last wave - start of new bit sequence if (firstBitFnd > 1){ //skip first wave change - probably not a complete bit for (int ii=0; ii<15; ii++){ if (rfLens[ii] == rfCounter){ rfCnts[ii]++; rfCounter = 0; break; } } if (rfCounter > 0 && rfLensFnd < 15){ //PrintAndLog("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter); rfCnts[rfLensFnd]++; rfLens[rfLensFnd++] = rfCounter; } } else { firstBitFnd++; } rfCounter=0; lastFCcnt=fcCounter; } fcCounter=0; } uint8_t rfHighest=15, rfHighest2=15, rfHighest3=15; for (i=0; i<15; i++){ //PrintAndLog("DEBUG: RF %d, cnts %d",rfLens[i], rfCnts[i]); //get highest 2 RF values (might need to get more values to compare or compare all?) if (rfCnts[i]>rfCnts[rfHighest]){ rfHighest3=rfHighest2; rfHighest2=rfHighest; rfHighest=i; } else if(rfCnts[i]>rfCnts[rfHighest2]){ rfHighest3=rfHighest2; rfHighest2=i; } else if(rfCnts[i]>rfCnts[rfHighest3]){ rfHighest3=i; } } // set allowed clock remainder tolerance to be 1 large field clock length+1 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off uint8_t tol1 = fcHigh+1; //PrintAndLog("DEBUG: hightest: 1 %d, 2 %d, 3 %d",rfLens[rfHighest],rfLens[rfHighest2],rfLens[rfHighest3]); // loop to find the highest clock that has a remainder less than the tolerance // compare samples counted divided by int ii=7; for (; ii>=0; ii--){ if (rfLens[rfHighest] % clk[ii] < tol1 || rfLens[rfHighest] % clk[ii] > clk[ii]-tol1){ if (rfLens[rfHighest2] % clk[ii] < tol1 || rfLens[rfHighest2] % clk[ii] > clk[ii]-tol1){ if (rfLens[rfHighest3] % clk[ii] < tol1 || rfLens[rfHighest3] % clk[ii] > clk[ii]-tol1){ break; } } } } if (ii<0) return 0; // oops we went too far return clk[ii]; } //by marshmellow //countFC is to detect the field clock lengths. //counts and returns the 2 most common wave lengths //mainly used for FSK field clock detection uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj) { uint8_t fcLens[] = {0,0,0,0,0,0,0,0,0,0}; uint16_t fcCnts[] = {0,0,0,0,0,0,0,0,0,0}; uint8_t fcLensFnd = 0; uint8_t lastFCcnt=0; uint8_t fcCounter = 0; size_t i; if (size == 0) return 0; // prime i to first up transition for (i = 1; i < size-1; i++) if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1]) break; for (; i < size-1; i++){ if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1]){ // new up transition fcCounter++; if (fskAdj){ //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8) if (lastFCcnt==5 && fcCounter==9) fcCounter--; //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5) if ((fcCounter==9) || fcCounter==4) fcCounter++; // save last field clock count (fc/xx) lastFCcnt = fcCounter; } // find which fcLens to save it to: for (int ii=0; ii<10; ii++){ if (fcLens[ii]==fcCounter){ fcCnts[ii]++; fcCounter=0; break; } } if (fcCounter>0 && fcLensFnd<10){ //add new fc length fcCnts[fcLensFnd]++; fcLens[fcLensFnd++]=fcCounter; } fcCounter=0; } else { // count sample fcCounter++; } } uint8_t best1=9, best2=9, best3=9; uint16_t maxCnt1=0; // go through fclens and find which ones are bigest 2 for (i=0; i<10; i++){ // PrintAndLog("DEBUG: FC %d, Cnt %d, Errs %d",fcLens[i],fcCnts[i],errCnt); // get the 3 best FC values if (fcCnts[i]>maxCnt1) { best3=best2; best2=best1; maxCnt1=fcCnts[i]; best1=i; } else if(fcCnts[i]>fcCnts[best2]){ best3=best2; best2=i; } else if(fcCnts[i]>fcCnts[best3]){ best3=i; } } uint8_t fcH=0, fcL=0; if (fcLens[best1]>fcLens[best2]){ fcH=fcLens[best1]; fcL=fcLens[best2]; } else{ fcH=fcLens[best2]; fcL=fcLens[best1]; } // TODO: take top 3 answers and compare to known Field clocks to get top 2 uint16_t fcs = (((uint16_t)fcH)<<8) | fcL; // PrintAndLog("DEBUG: Best %d best2 %d best3 %d",fcLens[best1],fcLens[best2],fcLens[best3]); if (fskAdj) return fcs; return fcLens[best1]; } //by marshmellow - demodulate PSK1 wave //uses wave lengths (# Samples) int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert) { if (size == 0) return -1; uint16_t loopCnt = 4096; //don't need to loop through entire array... if (*size<loopCnt) loopCnt = *size; uint8_t curPhase = *invert; size_t i, waveStart=1, waveEnd=0, firstFullWave=0, lastClkBit=0; uint8_t fc=0, fullWaveLen=0, tol=1; uint16_t errCnt=0, waveLenCnt=0; fc = countFC(dest, *size, 0); if (fc!=2 && fc!=4 && fc!=8) return -1; //PrintAndLog("DEBUG: FC: %d",fc); *clock = DetectPSKClock(dest, *size, *clock); if (*clock == 0) return -1; int avgWaveVal=0, lastAvgWaveVal=0; //find first phase shift for (i=0; i<loopCnt; i++){ if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){ waveEnd = i+1; //PrintAndLog("DEBUG: waveEnd: %d",waveEnd); waveLenCnt = waveEnd-waveStart; if (waveLenCnt > fc && waveStart > fc){ //not first peak and is a large wave lastAvgWaveVal = avgWaveVal/(waveLenCnt); firstFullWave = waveStart; fullWaveLen=waveLenCnt; //if average wave value is > graph 0 then it is an up wave or a 1 if (lastAvgWaveVal > 123) curPhase ^= 1; //fudge graph 0 a little 123 vs 128 break; } waveStart = i+1; avgWaveVal = 0; } avgWaveVal += dest[i+2]; } //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen); lastClkBit = firstFullWave; //set start of wave as clock align //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d", *clock, lastClkBit); waveStart = 0; size_t numBits=0; //set skipped bits memset(dest, curPhase^1, firstFullWave / *clock); numBits += (firstFullWave / *clock); dest[numBits++] = curPhase; //set first read bit for (i = firstFullWave + fullWaveLen - 1; i < *size-3; i++){ //top edge of wave = start of new wave if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){ if (waveStart == 0) { waveStart = i+1; waveLenCnt = 0; avgWaveVal = dest[i+1]; } else { //waveEnd waveEnd = i+1; waveLenCnt = waveEnd-waveStart; lastAvgWaveVal = avgWaveVal/waveLenCnt; if (waveLenCnt > fc){ //PrintAndLog("DEBUG: avgWaveVal: %d, waveSum: %d",lastAvgWaveVal,avgWaveVal); //this wave is a phase shift //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc); if (i+1 >= lastClkBit + *clock - tol){ //should be a clock bit curPhase ^= 1; dest[numBits++] = curPhase; lastClkBit += *clock; } else if (i < lastClkBit+10+fc){ //noise after a phase shift - ignore } else { //phase shift before supposed to based on clock errCnt++; dest[numBits++] = 7; } } else if (i+1 > lastClkBit + *clock + tol + fc){ lastClkBit += *clock; //no phase shift but clock bit dest[numBits++] = curPhase; } avgWaveVal = 0; waveStart = i+1; } } avgWaveVal += dest[i+1]; } *size = numBits; return errCnt; }
jessegit/proxmark3
common/lfdemod.c
C
gpl-2.0
45,160
<?php /** * Manage media uploaded file. * * There are many filters in here for media. Plugins can extend functionality * by hooking into the filters. * * @package WordPress * @subpackage Administration */ /** Load WordPress Administration Bootstrap */ require_once('./admin.php'); if (!current_user_can('upload_files')) wp_die(__('You do not have permission to upload files.')); wp_enqueue_script('plupload-handlers'); $post_id = 0; if ( isset( $_REQUEST['post_id'] ) ) { $post_id = absint( $_REQUEST['post_id'] ); if ( ! get_post( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) $post_id = 0; } if ( $_POST ) { $location = 'upload.php'; if ( isset($_POST['html-upload']) && !empty($_FILES) ) { check_admin_referer('media-form'); // Upload File button was clicked $id = media_handle_upload( 'async-upload', $post_id ); if ( is_wp_error( $id ) ) $location .= '?message=3'; } wp_redirect( admin_url( $location ) ); exit; } $title = __('Upload New Media'); $parent_file = 'upload.php'; get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __('You can upload media files here without creating a post first. This allows you to upload files to use with posts and pages later and/or to get a web link for a particular file that you can share. There are three options for uploading files:') . '</p>' . '<ul>' . '<li>' . __('<strong>Drag and drop</strong> your files into the area below. Multiple files are allowed.') . '</li>' . '<li>' . __('Clicking <strong>Select Files</strong> opens a navigation window showing you files in your operating system. Selecting <strong>Open</strong> after clicking on the file you want activates a progress bar on the uploader screen.') . '</li>' . '<li>' . __('Revert to the <strong>Browser Uploader</strong> by clicking the link below the drag and drop box.') . '</li>' . '</ul>' ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="http://codex.wordpress.org/Media_Add_New_Screen" target="_blank">Documentation on Uploading Media Files</a>') . '</p>' . '<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>' ); require_once( ABSPATH . 'wp-admin/admin-header.php' ); $form_class = 'media-upload-form type-form validate'; if ( get_user_setting('uploader') || isset( $_GET['browser-uploader'] ) ) $form_class .= ' html-uploader'; ?> <div class="wrap"> <?php screen_icon(); ?> <h2><?php echo esc_html( $title ); ?></h2> <?php add_action( 'wp_enqueue_script', 'load_jquery' ); function load_jquery() { wp_enqueue_script( 'jquery' ); }; ?> <script type="text/javascript"> jQuery(document).ready(function($) { console.log('Load category'); $('[name="category_parent"]').change(function(e){ i = $(this); $.ajax({ url: '<?php echo get_bloginfo('url') ?>/wp-upload-session.php', type: 'post', data: "id=" + i.val(), success: function(data){ $('#upload_category_current').html('<strong>Current category :</strong> ' + i.find(':selected').text()); }, error: function(){} }); }); }); </script> <div style="margin: 15px 0px;"> <span>Category : </span> <span> <?php wp_dropdown_categories(array('hide_empty' => 0, 'name' => 'category_parent', 'orderby' => 'name', 'selected' => $category->parent, 'hierarchical' => true, 'show_option_none' => __('None')));?> </span> <span id="upload_category_current" style="margin-left: 20px;"></span> </div> <form enctype="multipart/form-data" method="post" action="<?php echo admin_url('media-new.php'); ?>" class="<?php echo esc_attr( $form_class ); ?>" id="file-form"> <?php media_upload_form(); ?> <script type="text/javascript"> var post_id = <?php echo $post_id; ?>, shortform = 3; </script> <input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id; ?>" /> <?php wp_nonce_field('media-form'); ?> <div id="media-items" class="hide-if-no-js"></div> </form> </div> <?php include( ABSPATH . 'wp-admin/admin-footer.php' );
rongandat/best-picture
old3.6.1/wp-admin/media-new.php
PHP
gpl-2.0
4,157
/** * Some instructions are perniticky enough that its simpler * to write them separately instead of smushing them with * all the rest. The tableswitch instruction is one of them. * @author $Author: fqian $ * @version $Revision: 1.1 $ */ package jas; import java.io.*; public class TableswitchInsn extends Insn implements RuntimeConstants { /** * @param min minimum index value * @param max maximum index value * @param def default Label for switch * @param j array of Labels, one for each possible index. */ public TableswitchInsn(int min, int max, Label def, Label j[]) { opc = opc_tableswitch; operand = new TableswitchOperand(this, min, max, def, j); } }
BuddhaLabs/DeD-OSX
soot/jasmin-2.3.0/lib/jas/src/jas/TableswitchInsn.java
Java
gpl-2.0
729
/* * Copyright (c) 2014-2015 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ /****************************************************************************** * wlan_logging_sock_svc.c * ******************************************************************************/ #ifdef WLAN_LOGGING_SOCK_SVC_ENABLE #include <linux/rtc.h> #include <vmalloc.h> #include <wlan_nlink_srv.h> #include <vos_status.h> #include <vos_trace.h> #include <wlan_nlink_common.h> #include <wlan_logging_sock_svc.h> #include <vos_types.h> #include <kthread.h> #include "vos_memory.h" #include <linux/ratelimit.h> #include <asm/arch_timer.h> #define LOGGING_TRACE(level, args...) \ VOS_TRACE(VOS_MODULE_ID_SVC, level, ## args) /* Global variables */ #define ANI_NL_MSG_LOG_TYPE 89 #define ANI_NL_MSG_READY_IND_TYPE 90 #define ANI_NL_MSG_LOG_PKT_TYPE 91 #define ANI_NL_MSG_FW_LOG_PKT_TYPE 92 #define INVALID_PID -1 #define MAX_LOGMSG_LENGTH 4096 #define LOGGER_MGMT_DATA_PKT_POST_MASK 0x001 #define HOST_LOG_POST_MASK 0x002 #define LOGGER_FW_LOG_PKT_POST_MASK 0x003 #define LOGGER_FATAL_EVENT_POST_MASK 0x004 #define LOGGER_MAX_DATA_MGMT_PKT_Q_LEN (8) #define LOGGER_MAX_FW_LOG_PKT_Q_LEN (16) #define NL_BDCAST_RATELIMIT_INTERVAL (5*HZ) #define NL_BDCAST_RATELIMIT_BURST 1 /* Qtimer Frequency */ #define QTIMER_FREQ 19200000 static DEFINE_RATELIMIT_STATE(errCnt, \ NL_BDCAST_RATELIMIT_INTERVAL, \ NL_BDCAST_RATELIMIT_BURST); struct log_msg { struct list_head node; unsigned int radio; unsigned int index; /* indicates the current filled log length in logbuf */ unsigned int filled_length; /* * Buf to hold the log msg * tAniHdr + log */ char logbuf[MAX_LOGMSG_LENGTH]; }; struct logger_log_complete { uint32_t is_fatal; uint32_t indicator; uint32_t reason_code; bool is_report_in_progress; bool is_flush_complete; }; struct wlan_logging { /* Log Fatal and ERROR to console */ bool log_fe_to_console; /* Number of buffers to be used for logging */ int num_buf; /* Lock to synchronize access to shared logging resource */ spinlock_t spin_lock; /* Holds the free node which can be used for filling logs */ struct list_head free_list; /* Holds the filled nodes which needs to be indicated to APP */ struct list_head filled_list; /* Points to head of logger pkt queue */ vos_pkt_t *data_mgmt_pkt_queue; /* Holds number of pkts in vos pkt queue */ unsigned int data_mgmt_pkt_qcnt; /* Lock to synchronize of queue/dequeue of pkts in logger pkt queue */ spinlock_t data_mgmt_pkt_lock; /* Points to head of logger fw log pkt queue */ vos_pkt_t *fw_log_pkt_queue; /* Holds number of pkts in fw log vos pkt queue */ unsigned int fw_log_pkt_qcnt; /* Lock to synchronize of queue/dequeue of pkts in fw log pkt queue */ spinlock_t fw_log_pkt_lock; /* Wait queue for Logger thread */ wait_queue_head_t wait_queue; /* Logger thread */ struct task_struct *thread; /* Logging thread sets this variable on exit */ struct completion shutdown_comp; /* Indicates to logger thread to exit */ bool exit; /* Holds number of dropped logs*/ unsigned int drop_count; /* Holds number of dropped vos pkts*/ unsigned int pkt_drop_cnt; /* Holds number of dropped fw log vos pkts*/ unsigned int fw_log_pkt_drop_cnt; /* current logbuf to which the log will be filled to */ struct log_msg *pcur_node; /* Event flag used for wakeup and post indication*/ unsigned long event_flag; /* Indicates logger thread is activated */ bool is_active; /* data structure for log complete event*/ struct logger_log_complete log_complete; spinlock_t bug_report_lock; }; static struct wlan_logging gwlan_logging; static struct log_msg *gplog_msg; /* PID of the APP to log the message */ static int gapp_pid = INVALID_PID; static char wlan_logging_ready[] = "WLAN LOGGING READY"; /* * Broadcast Logging service ready indication to any Logging application * Each netlink message will have a message of type tAniMsgHdr inside. */ void wlan_logging_srv_nl_ready_indication(void) { struct sk_buff *skb = NULL; struct nlmsghdr *nlh; tAniNlHdr *wnl = NULL; int payload_len; int err; static int rate_limit; payload_len = sizeof(tAniHdr) + sizeof(wlan_logging_ready) + sizeof(wnl->radio); skb = dev_alloc_skb(NLMSG_SPACE(payload_len)); if (NULL == skb) { if (!rate_limit) { LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR, "NLINK: skb alloc fail %s", __func__); } rate_limit = 1; return; } rate_limit = 0; nlh = nlmsg_put(skb, 0, 0, ANI_NL_MSG_LOG, payload_len, NLM_F_REQUEST); if (NULL == nlh) { LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR, "%s: nlmsg_put() failed for msg size[%d]", __func__, payload_len); kfree_skb(skb); return; } wnl = (tAniNlHdr *) nlh; wnl->radio = 0; wnl->wmsg.type = ANI_NL_MSG_READY_IND_TYPE; wnl->wmsg.length = sizeof(wlan_logging_ready); memcpy((char*)&wnl->wmsg + sizeof(tAniHdr), wlan_logging_ready, sizeof(wlan_logging_ready)); /* sender is in group 1<<0 */ NETLINK_CB(skb).dst_group = WLAN_NLINK_MCAST_GRP_ID; /*multicast the message to all listening processes*/ err = nl_srv_bcast(skb); if (err) { LOGGING_TRACE(VOS_TRACE_LEVEL_INFO_LOW, "NLINK: Ready Indication Send Fail %s, err %d", __func__, err); } return; } /* Utility function to send a netlink message to an application * in user space */ static int wlan_send_sock_msg_to_app(tAniHdr *wmsg, int radio, int src_mod, int pid) { int err = -1; int payload_len; int tot_msg_len; tAniNlHdr *wnl = NULL; struct sk_buff *skb; struct nlmsghdr *nlh; int wmsg_length = wmsg->length; static int nlmsg_seq; if (radio < 0 || radio > ANI_MAX_RADIOS) { pr_err("%s: invalid radio id [%d]", __func__, radio); return -EINVAL; } payload_len = wmsg_length + sizeof(wnl->radio); tot_msg_len = NLMSG_SPACE(payload_len); skb = dev_alloc_skb(tot_msg_len); if (skb == NULL) { pr_err("%s: dev_alloc_skb() failed for msg size[%d]", __func__, tot_msg_len); return -ENOMEM; } nlh = nlmsg_put(skb, pid, nlmsg_seq++, src_mod, payload_len, NLM_F_REQUEST); if (NULL == nlh) { pr_err("%s: nlmsg_put() failed for msg size[%d]", __func__, tot_msg_len); kfree_skb(skb); return -ENOMEM; } wnl = (tAniNlHdr *) nlh; wnl->radio = radio; vos_mem_copy(&wnl->wmsg, wmsg, wmsg_length); err = nl_srv_ucast(skb, pid, MSG_DONTWAIT); return err; } static void set_default_logtoapp_log_level(void) { vos_trace_setValue(VOS_MODULE_ID_WDI, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_WDA, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_HDD_SOFTAP, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_PMC, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_SVC, VOS_TRACE_LEVEL_ALL, VOS_TRUE); } static void clear_default_logtoapp_log_level(void) { int module; for (module = 0; module < VOS_MODULE_ID_MAX; module++) { vos_trace_setValue(module, VOS_TRACE_LEVEL_NONE, VOS_FALSE); vos_trace_setValue(module, VOS_TRACE_LEVEL_FATAL, VOS_TRUE); vos_trace_setValue(module, VOS_TRACE_LEVEL_ERROR, VOS_TRUE); } vos_trace_setValue(VOS_MODULE_ID_RSV4, VOS_TRACE_LEVEL_NONE, VOS_FALSE); } /* Need to call this with spin_lock acquired */ static int wlan_queue_logmsg_for_app(void) { char *ptr; int ret = 0; ptr = &gwlan_logging.pcur_node->logbuf[sizeof(tAniHdr)]; ptr[gwlan_logging.pcur_node->filled_length] = '\0'; *(unsigned short *)(gwlan_logging.pcur_node->logbuf) = ANI_NL_MSG_LOG_TYPE; *(unsigned short *)(gwlan_logging.pcur_node->logbuf + 2) = gwlan_logging.pcur_node->filled_length; list_add_tail(&gwlan_logging.pcur_node->node, &gwlan_logging.filled_list); if (!list_empty(&gwlan_logging.free_list)) { /* Get buffer from free list */ gwlan_logging.pcur_node = (struct log_msg *)(gwlan_logging.free_list.next); list_del_init(gwlan_logging.free_list.next); } else if (!list_empty(&gwlan_logging.filled_list)) { /* Get buffer from filled list */ /* This condition will drop the packet from being * indicated to app */ gwlan_logging.pcur_node = (struct log_msg *)(gwlan_logging.filled_list.next); ++gwlan_logging.drop_count; /* print every 64th drop count */ if (vos_is_multicast_logging() && (!(gwlan_logging.drop_count % 0x40))) { pr_err("%s: drop_count = %u index = %d filled_length = %d\n", __func__, gwlan_logging.drop_count, gwlan_logging.pcur_node->index, gwlan_logging.pcur_node->filled_length); } list_del_init(gwlan_logging.filled_list.next); ret = 1; } /* Reset the current node values */ gwlan_logging.pcur_node->filled_length = 0; return ret; } int wlan_log_to_user(VOS_TRACE_LEVEL log_level, char *to_be_sent, int length) { /* Add the current time stamp */ char *ptr; char tbuf[100]; int tlen; int total_log_len; unsigned int *pfilled_length; bool wake_up_thread = false; unsigned long flags; struct timeval tv; struct rtc_time tm; unsigned long local_time; u64 qtimer_ticks; if (!vos_is_multicast_logging()) { /* * This is to make sure that we print the logs to kmsg console * when no logger app is running. This is also needed to * log the initial messages during loading of driver where even * if app is running it will not be able to * register with driver immediately and start logging all the * messages. */ pr_err("%s\n", to_be_sent); } else { /* Format the Log time [hr:min:sec.microsec] */ do_gettimeofday(&tv); /* Convert rtc to local time */ local_time = (u32)(tv.tv_sec - (sys_tz.tz_minuteswest * 60)); rtc_time_to_tm(local_time, &tm); /* Firmware Time Stamp */ qtimer_ticks = arch_counter_get_cntpct(); tlen = snprintf(tbuf, sizeof(tbuf), "[%02d:%02d:%02d.%06lu] [%016llX]" " [%s] ", tm.tm_hour, tm.tm_min, tm.tm_sec, tv.tv_usec, qtimer_ticks, current->comm); /* 1+1 indicate '\n'+'\0' */ total_log_len = length + tlen + 1 + 1; spin_lock_irqsave(&gwlan_logging.spin_lock, flags); // wlan logging svc resources are not yet initialized if (!gwlan_logging.pcur_node) { spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); return -EIO; } pfilled_length = &gwlan_logging.pcur_node->filled_length; /* Check if we can accomodate more log into current node/buffer */ if (MAX_LOGMSG_LENGTH < (*pfilled_length + sizeof(tAniNlHdr) + total_log_len)) { wake_up_thread = true; wlan_queue_logmsg_for_app(); pfilled_length = &gwlan_logging.pcur_node->filled_length; } ptr = &gwlan_logging.pcur_node->logbuf[sizeof(tAniHdr)]; /* Assumption here is that we receive logs which is always less than * MAX_LOGMSG_LENGTH, where we can accomodate the * tAniNlHdr + [context][timestamp] + log * VOS_ASSERT if we cannot accomodate the the complete log into * the available buffer. * * Continue and copy logs to the available length and discard the rest. */ if (MAX_LOGMSG_LENGTH < (sizeof(tAniNlHdr) + total_log_len)) { VOS_ASSERT(0); total_log_len = MAX_LOGMSG_LENGTH - sizeof(tAniNlHdr) - 2; } vos_mem_copy(&ptr[*pfilled_length], tbuf, tlen); vos_mem_copy(&ptr[*pfilled_length + tlen], to_be_sent, min(length, (total_log_len - tlen))); *pfilled_length += tlen + min(length, total_log_len - tlen); ptr[*pfilled_length] = '\n'; *pfilled_length += 1; spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); /* Wakeup logger thread */ if ((true == wake_up_thread)) { /* If there is logger app registered wakeup the logging * thread */ set_bit(HOST_LOG_POST_MASK, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } if (gwlan_logging.log_fe_to_console && ((VOS_TRACE_LEVEL_FATAL == log_level) || (VOS_TRACE_LEVEL_ERROR == log_level))) { pr_err("%s\n", to_be_sent); } } return 0; } static int send_fw_log_pkt_to_user(void) { int ret = -1; int extra_header_len, nl_payload_len; struct sk_buff *skb = NULL; static int nlmsg_seq; vos_pkt_t *current_pkt; vos_pkt_t *next_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; unsigned long flags; tAniNlHdr msg_header; do { spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (!gwlan_logging.fw_log_pkt_queue) { spin_unlock_irqrestore( &gwlan_logging.fw_log_pkt_lock, flags); return -EIO; } /* pick first pkt from queued chain */ current_pkt = gwlan_logging.fw_log_pkt_queue; /* get the pointer to the next packet in the chain */ status = vos_pkt_walk_packet_chain(current_pkt, &next_pkt, TRUE); /* both "success" and "empty" are acceptable results */ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.fw_log_pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.fw_log_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); return -EIO; } /* update queue head with next pkt ptr which could be NULL */ gwlan_logging.fw_log_pkt_queue = next_pkt; --gwlan_logging.fw_log_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); status = vos_pkt_get_os_packet(current_pkt, (v_VOID_t **)&skb, TRUE); if (!VOS_IS_STATUS_SUCCESS(status)) { ++gwlan_logging.fw_log_pkt_drop_cnt; pr_err("%s: Failure extracting skb from vos pkt", __func__); return -EIO; } /*return vos pkt since skb is already detached */ vos_pkt_return_packet(current_pkt); extra_header_len = sizeof(msg_header.radio) + sizeof(tAniHdr); nl_payload_len = NLMSG_ALIGN(extra_header_len + skb->len); msg_header.nlh.nlmsg_type = ANI_NL_MSG_LOG; msg_header.nlh.nlmsg_len = nl_payload_len; msg_header.nlh.nlmsg_flags = NLM_F_REQUEST; msg_header.nlh.nlmsg_pid = gapp_pid; msg_header.nlh.nlmsg_seq = nlmsg_seq++; msg_header.radio = 0; msg_header.wmsg.type = ANI_NL_MSG_FW_LOG_PKT_TYPE; msg_header.wmsg.length = skb->len; if (unlikely(skb_headroom(skb) < sizeof(msg_header))) { pr_err("VPKT [%d]: Insufficient headroom, head[%p]," " data[%p], req[%zu]", __LINE__, skb->head, skb->data, sizeof(msg_header)); return -EIO; } vos_mem_copy(skb_push(skb, sizeof(msg_header)), &msg_header, sizeof(msg_header)); ret = nl_srv_bcast(skb); if (ret < 0) { pr_info("%s: Send Failed %d drop_count = %u\n", __func__, ret, ++gwlan_logging.fw_log_pkt_drop_cnt); } else { ret = 0; } } while (next_pkt); return ret; } static int send_data_mgmt_log_pkt_to_user(void) { int ret = -1; int extra_header_len, nl_payload_len; struct sk_buff *skb = NULL; static int nlmsg_seq; vos_pkt_t *current_pkt; vos_pkt_t *next_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; unsigned long flags; tAniNlLogHdr msg_header; do { spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (!gwlan_logging.data_mgmt_pkt_queue) { spin_unlock_irqrestore( &gwlan_logging.data_mgmt_pkt_lock, flags); return -EIO; } /* pick first pkt from queued chain */ current_pkt = gwlan_logging.data_mgmt_pkt_queue; /* get the pointer to the next packet in the chain */ status = vos_pkt_walk_packet_chain(current_pkt, &next_pkt, TRUE); /* both "success" and "empty" are acceptable results */ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.data_mgmt_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); return -EIO; } /* update queue head with next pkt ptr which could be NULL */ gwlan_logging.data_mgmt_pkt_queue = next_pkt; --gwlan_logging.data_mgmt_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); status = vos_pkt_get_os_packet(current_pkt, (v_VOID_t **)&skb, TRUE); if (!VOS_IS_STATUS_SUCCESS(status)) { ++gwlan_logging.pkt_drop_cnt; pr_err("%s: Failure extracting skb from vos pkt", __func__); return -EIO; } /*return vos pkt since skb is already detached */ vos_pkt_return_packet(current_pkt); extra_header_len = sizeof(msg_header.radio) + sizeof(tAniHdr) + sizeof(msg_header.frameSize); nl_payload_len = NLMSG_ALIGN(extra_header_len + skb->len); msg_header.nlh.nlmsg_type = ANI_NL_MSG_LOG; msg_header.nlh.nlmsg_len = nl_payload_len; msg_header.nlh.nlmsg_flags = NLM_F_REQUEST; msg_header.nlh.nlmsg_pid = 0; msg_header.nlh.nlmsg_seq = nlmsg_seq++; msg_header.radio = 0; msg_header.wmsg.type = ANI_NL_MSG_LOG_PKT_TYPE; msg_header.wmsg.length = skb->len + sizeof(uint32); msg_header.frameSize = WLAN_MGMT_LOGGING_FRAMESIZE_128BYTES; if (unlikely(skb_headroom(skb) < sizeof(msg_header))) { pr_err("VPKT [%d]: Insufficient headroom, head[%p]," " data[%p], req[%zu]", __LINE__, skb->head, skb->data, sizeof(msg_header)); return -EIO; } vos_mem_copy(skb_push(skb, sizeof(msg_header)), &msg_header, sizeof(msg_header)); ret = nl_srv_bcast(skb); if (ret < 0) { pr_info("%s: Send Failed %d drop_count = %u\n", __func__, ret, ++gwlan_logging.pkt_drop_cnt); } else { ret = 0; } } while (next_pkt); return ret; } static int send_filled_buffers_to_user(void) { int ret = -1; struct log_msg *plog_msg; int payload_len; int tot_msg_len; tAniNlHdr *wnl; struct sk_buff *skb = NULL; struct nlmsghdr *nlh; static int nlmsg_seq; unsigned long flags; static int rate_limit; while (!list_empty(&gwlan_logging.filled_list) && !gwlan_logging.exit) { skb = dev_alloc_skb(MAX_LOGMSG_LENGTH); if (skb == NULL) { if (!rate_limit) { pr_err("%s: dev_alloc_skb() failed for msg size[%d] drop count = %u\n", __func__, MAX_LOGMSG_LENGTH, gwlan_logging.drop_count); } rate_limit = 1; ret = -ENOMEM; break; } rate_limit = 0; spin_lock_irqsave(&gwlan_logging.spin_lock, flags); plog_msg = (struct log_msg *) (gwlan_logging.filled_list.next); list_del_init(gwlan_logging.filled_list.next); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); /* 4 extra bytes for the radio idx */ payload_len = plog_msg->filled_length + sizeof(wnl->radio) + sizeof(tAniHdr); tot_msg_len = NLMSG_SPACE(payload_len); nlh = nlmsg_put(skb, 0, nlmsg_seq++, ANI_NL_MSG_LOG, payload_len, NLM_F_REQUEST); if (NULL == nlh) { spin_lock_irqsave(&gwlan_logging.spin_lock, flags); list_add_tail(&plog_msg->node, &gwlan_logging.free_list); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); pr_err("%s: drop_count = %u\n", __func__, ++gwlan_logging.drop_count); pr_err("%s: nlmsg_put() failed for msg size[%d]\n", __func__, tot_msg_len); dev_kfree_skb(skb); skb = NULL; ret = -EINVAL; continue; } wnl = (tAniNlHdr *) nlh; wnl->radio = plog_msg->radio; vos_mem_copy(&wnl->wmsg, plog_msg->logbuf, plog_msg->filled_length + sizeof(tAniHdr)); spin_lock_irqsave(&gwlan_logging.spin_lock, flags); list_add_tail(&plog_msg->node, &gwlan_logging.free_list); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); ret = nl_srv_bcast(skb); if (ret < 0) { if (__ratelimit(&errCnt)) { pr_info("%s: Send Failed %d drop_count = %u\n", __func__, ret, gwlan_logging.drop_count); } gwlan_logging.drop_count++; skb = NULL; break; } else { skb = NULL; ret = 0; } } return ret; } /** * wlan_logging_thread() - The WLAN Logger thread * @Arg - pointer to the HDD context * * This thread logs log message to App registered for the logs. */ static int wlan_logging_thread(void *Arg) { int ret_wait_status = 0; int ret = 0; set_user_nice(current, -2); #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) daemonize("wlan_logging_thread"); #endif while (!gwlan_logging.exit) { ret_wait_status = wait_event_interruptible( gwlan_logging.wait_queue, (test_bit(HOST_LOG_POST_MASK, &gwlan_logging.event_flag) || gwlan_logging.exit || test_bit(LOGGER_MGMT_DATA_PKT_POST_MASK,&gwlan_logging.event_flag) || test_bit(LOGGER_FW_LOG_PKT_POST_MASK, &gwlan_logging.event_flag) || test_bit(LOGGER_FATAL_EVENT_POST_MASK, &gwlan_logging.event_flag))); if (ret_wait_status == -ERESTARTSYS) { pr_err("%s: wait_event return -ERESTARTSYS", __func__); break; } if (gwlan_logging.exit) { break; } if (test_and_clear_bit(HOST_LOG_POST_MASK, &gwlan_logging.event_flag)) { ret = send_filled_buffers_to_user(); if (-ENOMEM == ret) { msleep(200); } } if (test_and_clear_bit(LOGGER_FW_LOG_PKT_POST_MASK, &gwlan_logging.event_flag)) { send_fw_log_pkt_to_user(); } if (test_and_clear_bit(LOGGER_MGMT_DATA_PKT_POST_MASK, &gwlan_logging.event_flag)) { send_data_mgmt_log_pkt_to_user(); } if (test_and_clear_bit(LOGGER_FATAL_EVENT_POST_MASK, &gwlan_logging.event_flag)) { if (gwlan_logging.log_complete.is_flush_complete == true) { gwlan_logging.log_complete.is_flush_complete = false; vos_send_fatal_event_done(); } else { gwlan_logging.log_complete.is_flush_complete = true; set_bit(HOST_LOG_POST_MASK,&gwlan_logging.event_flag); set_bit(LOGGER_FW_LOG_PKT_POST_MASK,&gwlan_logging.event_flag); set_bit(LOGGER_FATAL_EVENT_POST_MASK,&gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } } } complete_and_exit(&gwlan_logging.shutdown_comp, 0); return 0; } /* * Process all the Netlink messages from Logger Socket app in user space */ static int wlan_logging_proc_sock_rx_msg(struct sk_buff *skb) { tAniNlHdr *wnl; int radio; int type; int ret; if (TRUE == vos_isUnloadInProgress()) { pr_info("%s: unload in progress\n",__func__); return -ENODEV; } wnl = (tAniNlHdr *) skb->data; radio = wnl->radio; type = wnl->nlh.nlmsg_type; if (radio < 0 || radio > ANI_MAX_RADIOS) { pr_err("%s: invalid radio id [%d]\n", __func__, radio); return -EINVAL; } if (gapp_pid != INVALID_PID) { if (wnl->nlh.nlmsg_pid > gapp_pid) { gapp_pid = wnl->nlh.nlmsg_pid; } spin_lock_bh(&gwlan_logging.spin_lock); if (gwlan_logging.pcur_node->filled_length) { wlan_queue_logmsg_for_app(); } spin_unlock_bh(&gwlan_logging.spin_lock); set_bit(HOST_LOG_POST_MASK, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } else { /* This is to set the default levels (WLAN logging * default values not the VOS trace default) when * logger app is registered for the first time. */ gapp_pid = wnl->nlh.nlmsg_pid; } ret = wlan_send_sock_msg_to_app(&wnl->wmsg, 0, ANI_NL_MSG_LOG, wnl->nlh.nlmsg_pid); if (ret < 0) { pr_err("wlan_send_sock_msg_to_app: failed"); } return ret; } void wlan_init_log_completion(void) { gwlan_logging.log_complete.indicator = WLAN_LOG_TYPE_NON_FATAL; gwlan_logging.log_complete.is_fatal = WLAN_LOG_INDICATOR_UNUSED; gwlan_logging.log_complete.is_report_in_progress = false; gwlan_logging.log_complete.reason_code = WLAN_LOG_REASON_CODE_UNUSED; spin_lock_init(&gwlan_logging.bug_report_lock); } int wlan_set_log_completion(uint32 is_fatal, uint32 indicator, uint32 reason_code) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.bug_report_lock, flags); gwlan_logging.log_complete.indicator = indicator; gwlan_logging.log_complete.is_fatal = is_fatal; gwlan_logging.log_complete.is_report_in_progress = true; gwlan_logging.log_complete.reason_code = reason_code; spin_unlock_irqrestore(&gwlan_logging.bug_report_lock, flags); return 0; } void wlan_get_log_completion(uint32 *is_fatal, uint32 *indicator, uint32 *reason_code) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.bug_report_lock, flags); *indicator = gwlan_logging.log_complete.indicator; *is_fatal = gwlan_logging.log_complete.is_fatal; *reason_code = gwlan_logging.log_complete.reason_code; gwlan_logging.log_complete.is_report_in_progress = false; spin_unlock_irqrestore(&gwlan_logging.bug_report_lock, flags); } bool wlan_is_log_report_in_progress(void) { return gwlan_logging.log_complete.is_report_in_progress; } void wlan_reset_log_report_in_progress(void) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.bug_report_lock, flags); gwlan_logging.log_complete.is_report_in_progress = false; spin_unlock_irqrestore(&gwlan_logging.bug_report_lock, flags); } void wlan_deinit_log_completion(void) { return; } int wlan_logging_sock_activate_svc(int log_fe_to_console, int num_buf) { int i = 0; unsigned long irq_flag; gapp_pid = INVALID_PID; gplog_msg = (struct log_msg *) vmalloc( num_buf * sizeof(struct log_msg)); if (!gplog_msg) { pr_err("%s: Could not allocate memory\n", __func__); return -ENOMEM; } vos_mem_zero(gplog_msg, (num_buf * sizeof(struct log_msg))); gwlan_logging.log_fe_to_console = !!log_fe_to_console; gwlan_logging.num_buf = num_buf; spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag); INIT_LIST_HEAD(&gwlan_logging.free_list); INIT_LIST_HEAD(&gwlan_logging.filled_list); for (i = 0; i < num_buf; i++) { list_add(&gplog_msg[i].node, &gwlan_logging.free_list); gplog_msg[i].index = i; } gwlan_logging.pcur_node = (struct log_msg *) (gwlan_logging.free_list.next); list_del_init(gwlan_logging.free_list.next); spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag); init_waitqueue_head(&gwlan_logging.wait_queue); gwlan_logging.exit = false; clear_bit(HOST_LOG_POST_MASK, &gwlan_logging.event_flag); clear_bit(LOGGER_MGMT_DATA_PKT_POST_MASK, &gwlan_logging.event_flag); clear_bit(LOGGER_FW_LOG_PKT_POST_MASK, &gwlan_logging.event_flag); clear_bit(LOGGER_FATAL_EVENT_POST_MASK, &gwlan_logging.event_flag); init_completion(&gwlan_logging.shutdown_comp); gwlan_logging.thread = kthread_create(wlan_logging_thread, NULL, "wlan_logging_thread"); if (IS_ERR(gwlan_logging.thread)) { pr_err("%s: Could not Create LogMsg Thread Controller", __func__); spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag); vfree(gplog_msg); gplog_msg = NULL; gwlan_logging.pcur_node = NULL; spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag); return -ENOMEM; } wake_up_process(gwlan_logging.thread); gwlan_logging.is_active = true; nl_srv_register(ANI_NL_MSG_LOG, wlan_logging_proc_sock_rx_msg); //Broadcast SVC ready message to logging app/s running wlan_logging_srv_nl_ready_indication(); return 0; } int wlan_logging_flush_pkt_queue(void) { vos_pkt_t *pkt_queue_head; unsigned long flags; spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (NULL != gwlan_logging.data_mgmt_pkt_queue) { pkt_queue_head = gwlan_logging.data_mgmt_pkt_queue; gwlan_logging.data_mgmt_pkt_queue = NULL; gwlan_logging.pkt_drop_cnt = 0; gwlan_logging.data_mgmt_pkt_qcnt = 0; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); vos_pkt_return_packet(pkt_queue_head); } else { spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); } spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (NULL != gwlan_logging.fw_log_pkt_queue) { pkt_queue_head = gwlan_logging.fw_log_pkt_queue; gwlan_logging.fw_log_pkt_queue = NULL; gwlan_logging.fw_log_pkt_drop_cnt = 0; gwlan_logging.fw_log_pkt_qcnt = 0; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); vos_pkt_return_packet(pkt_queue_head); } else { spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); } return 0; } int wlan_logging_sock_deactivate_svc(void) { unsigned long irq_flag; if (!gplog_msg) return 0; nl_srv_unregister(ANI_NL_MSG_LOG, wlan_logging_proc_sock_rx_msg); clear_default_logtoapp_log_level(); gapp_pid = INVALID_PID; INIT_COMPLETION(gwlan_logging.shutdown_comp); gwlan_logging.exit = true; gwlan_logging.is_active = false; vos_set_multicast_logging(0); wake_up_interruptible(&gwlan_logging.wait_queue); wait_for_completion(&gwlan_logging.shutdown_comp); spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag); vfree(gplog_msg); gplog_msg = NULL; gwlan_logging.pcur_node = NULL; spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag); wlan_logging_flush_pkt_queue(); return 0; } int wlan_logging_sock_init_svc(void) { spin_lock_init(&gwlan_logging.spin_lock); spin_lock_init(&gwlan_logging.data_mgmt_pkt_lock); spin_lock_init(&gwlan_logging.fw_log_pkt_lock); gapp_pid = INVALID_PID; gwlan_logging.pcur_node = NULL; wlan_init_log_completion(); return 0; } int wlan_logging_sock_deinit_svc(void) { gwlan_logging.pcur_node = NULL; gapp_pid = INVALID_PID; wlan_deinit_log_completion(); return 0; } int wlan_queue_data_mgmt_pkt_for_app(vos_pkt_t *pPacket) { unsigned long flags; vos_pkt_t *next_pkt; vos_pkt_t *free_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (gwlan_logging.data_mgmt_pkt_qcnt >= LOGGER_MAX_DATA_MGMT_PKT_Q_LEN) { status = vos_pkt_walk_packet_chain( gwlan_logging.data_mgmt_pkt_queue, &next_pkt, TRUE); /*both "success" and "empty" are acceptable results*/ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.data_mgmt_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); /*keep returning pkts to avoid low resource cond*/ vos_pkt_return_packet(pPacket); return VOS_STATUS_E_FAILURE; } free_pkt = gwlan_logging.data_mgmt_pkt_queue; gwlan_logging.data_mgmt_pkt_queue = next_pkt; /*returning head of pkt queue. latest pkts are important*/ --gwlan_logging.data_mgmt_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); vos_pkt_return_packet(free_pkt); } else { spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); } spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (gwlan_logging.data_mgmt_pkt_queue) { vos_pkt_chain_packet(gwlan_logging.data_mgmt_pkt_queue, pPacket, TRUE); } else { gwlan_logging.data_mgmt_pkt_queue = pPacket; } ++gwlan_logging.data_mgmt_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); set_bit(LOGGER_MGMT_DATA_PKT_POST_MASK, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); return VOS_STATUS_SUCCESS; } /** * wlan_logging_set_log_level() - Set the logging level * * This function is used to set the logging level of host debug messages * * Return: None */ void wlan_logging_set_log_level(void) { set_default_logtoapp_log_level(); } int wlan_queue_fw_log_pkt_for_app(vos_pkt_t *pPacket) { unsigned long flags; vos_pkt_t *next_pkt; vos_pkt_t *free_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (gwlan_logging.fw_log_pkt_qcnt >= LOGGER_MAX_FW_LOG_PKT_Q_LEN) { status = vos_pkt_walk_packet_chain( gwlan_logging.fw_log_pkt_queue, &next_pkt, TRUE); /*both "success" and "empty" are acceptable results*/ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.fw_log_pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.fw_log_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); /*keep returning pkts to avoid low resource cond*/ vos_pkt_return_packet(pPacket); return VOS_STATUS_E_FAILURE; } free_pkt = gwlan_logging.fw_log_pkt_queue; gwlan_logging.fw_log_pkt_queue = next_pkt; /*returning head of pkt queue. latest pkts are important*/ --gwlan_logging.fw_log_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); vos_pkt_return_packet(free_pkt); } else { spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); } spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (gwlan_logging.fw_log_pkt_queue) { vos_pkt_chain_packet(gwlan_logging.fw_log_pkt_queue, pPacket, TRUE); } else { gwlan_logging.fw_log_pkt_queue = pPacket; } ++gwlan_logging.fw_log_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); set_bit(LOGGER_FW_LOG_PKT_POST_MASK, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); return VOS_STATUS_SUCCESS; } int wlan_queue_logpkt_for_app(vos_pkt_t *pPacket, uint32 pkt_type) { VOS_STATUS status = VOS_STATUS_E_FAILURE; if (pPacket == NULL) { pr_err("%s: Null param", __func__); VOS_ASSERT(0); return VOS_STATUS_E_FAILURE; } if (gwlan_logging.is_active == false) { /*return all packets queued*/ wlan_logging_flush_pkt_queue(); /*return currently received pkt*/ vos_pkt_return_packet(pPacket); return VOS_STATUS_E_FAILURE; } switch (pkt_type) { case LOG_PKT_TYPE_DATA_MGMT: status = wlan_queue_data_mgmt_pkt_for_app(pPacket); break; case LOG_PKT_TYPE_FW_LOG: status = wlan_queue_fw_log_pkt_for_app(pPacket); break; default: pr_info("%s: Unknown pkt received %d", __func__, pkt_type); status = VOS_STATUS_E_INVAL; break; }; return status; } void wlan_process_done_indication(uint8 type, uint32 reason_code) { if ((type == WLAN_QXDM_LOGGING) && (wlan_is_log_report_in_progress() == TRUE)) { pr_info("%s: Setting LOGGER_FATAL_EVENT\n", __func__); set_bit(LOGGER_FATAL_EVENT_POST_MASK, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } } #endif /* WLAN_LOGGING_SOCK_SVC_ENABLE */
T-Macgnolia/android_kernel_lge_c50-stock
drivers/staging/prima/CORE/SVC/src/logging/wlan_logging_sock_svc.c
C
gpl-2.0
34,721