code
stringlengths
1.03k
250k
repo_name
stringlengths
7
70
path
stringlengths
4
177
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
1.03k
250k
/* Eye Of Mate - Main Window * * Copyright (C) 2000-2008 The Free Software Foundation * * Author: Lucas Rocha <lucasr@gnome.org> * * Based on code by: * - Federico Mena-Quintero <federico@gnu.org> * - Jens Finke <jens@gnome.org> * Based on evince code (shell/ev-window.c) by: * - Martin Kretzschmar <martink@gnome.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 St, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include "eom-window.h" #include "eom-scroll-view.h" #include "eom-debug.h" #include "eom-file-chooser.h" #include "eom-thumb-view.h" #include "eom-list-store.h" #include "eom-sidebar.h" #include "eom-statusbar.h" #include "eom-preferences-dialog.h" #include "eom-properties-dialog.h" #include "eom-print.h" #include "eom-error-message-area.h" #include "eom-application.h" #include "eom-thumb-nav.h" #include "eom-config-keys.h" #include "eom-job-queue.h" #include "eom-jobs.h" #include "eom-util.h" #include "eom-save-as-dialog-helper.h" #include "eom-plugin-engine.h" #include "eom-close-confirmation-dialog.h" #include "eom-clipboard-handler.h" #include "eom-enum-types.h" #include "egg-toolbar-editor.h" #include "egg-editable-toolbar.h" #include "egg-toolbars-model.h" #include <glib.h> #include <glib-object.h> #include <glib/gi18n.h> #include <gio/gio.h> #include <gdk/gdkkeysyms.h> #include <gio/gdesktopappinfo.h> #include <gtk/gtk.h> #if HAVE_LCMS #include <X11/Xlib.h> #include <X11/Xatom.h> #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #include <lcms2.h> #endif #define MATE_DESKTOP_USE_UNSTABLE_API #include <libmate-desktop/mate-desktop-utils.h> #include <libmate-desktop/mate-aboutdialog.h> #define EOM_WINDOW_GET_PRIVATE(object) \ (G_TYPE_INSTANCE_GET_PRIVATE ((object), EOM_TYPE_WINDOW, EomWindowPrivate)) G_DEFINE_TYPE (EomWindow, eom_window, GTK_TYPE_WINDOW); #define EOM_WINDOW_MIN_WIDTH 440 #define EOM_WINDOW_MIN_HEIGHT 350 #define EOM_WINDOW_DEFAULT_WIDTH 540 #define EOM_WINDOW_DEFAULT_HEIGHT 450 #define EOM_WINDOW_FULLSCREEN_TIMEOUT 5 * 1000 #define EOM_WINDOW_FULLSCREEN_POPUP_THRESHOLD 5 #define EOM_RECENT_FILES_GROUP "Graphics" #define EOM_RECENT_FILES_APP_NAME "Eye of MATE Image Viewer" #define EOM_RECENT_FILES_LIMIT 5 #define EOM_WALLPAPER_FILENAME "eom-wallpaper" #define is_rtl (gtk_widget_get_default_direction () == GTK_TEXT_DIR_RTL) #if GTK_CHECK_VERSION (3, 2, 0) #define gtk_hbox_new(X,Y) gtk_box_new(GTK_ORIENTATION_HORIZONTAL,Y) #define gtk_vbox_new(X,Y) gtk_box_new(GTK_ORIENTATION_VERTICAL,Y) #endif typedef enum { EOM_WINDOW_STATUS_UNKNOWN, EOM_WINDOW_STATUS_INIT, EOM_WINDOW_STATUS_NORMAL } EomWindowStatus; enum { PROP_0, PROP_COLLECTION_POS, PROP_COLLECTION_RESIZABLE, PROP_STARTUP_FLAGS }; enum { SIGNAL_PREPARED, SIGNAL_LAST }; static guint signals[SIGNAL_LAST] = { 0 }; struct _EomWindowPrivate { GSettings *view_settings; GSettings *ui_settings; GSettings *fullscreen_settings; GSettings *lockdown_settings; EomListStore *store; EomImage *image; EomWindowMode mode; EomWindowStatus status; GtkUIManager *ui_mgr; GtkWidget *box; GtkWidget *layout; GtkWidget *cbox; GtkWidget *view; GtkWidget *sidebar; GtkWidget *thumbview; GtkWidget *statusbar; GtkWidget *nav; GtkWidget *message_area; GtkWidget *toolbar; GObject *properties_dlg; GtkActionGroup *actions_window; GtkActionGroup *actions_image; GtkActionGroup *actions_collection; GtkActionGroup *actions_recent; GtkWidget *fullscreen_popup; GSource *fullscreen_timeout_source; gboolean slideshow_random; gboolean slideshow_loop; gint slideshow_switch_timeout; GSource *slideshow_switch_source; guint recent_menu_id; EomJob *load_job; EomJob *transform_job; EomJob *save_job; GFile *last_save_as_folder; EomJob *copy_job; guint image_info_message_cid; guint tip_message_cid; guint copy_file_cid; EomStartupFlags flags; GSList *file_list; EomWindowCollectionPos collection_position; gboolean collection_resizable; GtkActionGroup *actions_open_with; guint open_with_menu_id; gboolean save_disabled; gboolean needs_reload_confirmation; GtkPageSetup *page_setup; #ifdef HAVE_LCMS cmsHPROFILE *display_profile; #endif }; static void eom_window_cmd_fullscreen (GtkAction *action, gpointer user_data); static void eom_window_run_fullscreen (EomWindow *window, gboolean slideshow); static void eom_window_cmd_slideshow (GtkAction *action, gpointer user_data); static void eom_window_cmd_pause_slideshow (GtkAction *action, gpointer user_data); static void eom_window_stop_fullscreen (EomWindow *window, gboolean slideshow); static void eom_job_load_cb (EomJobLoad *job, gpointer data); static void eom_job_save_progress_cb (EomJobSave *job, float progress, gpointer data); static void eom_job_progress_cb (EomJobLoad *job, float progress, gpointer data); static void eom_job_transform_cb (EomJobTransform *job, gpointer data); static void fullscreen_set_timeout (EomWindow *window); static void fullscreen_clear_timeout (EomWindow *window); static void update_action_groups_state (EomWindow *window); static void open_with_launch_application_cb (GtkAction *action, gpointer callback_data); static void eom_window_update_openwith_menu (EomWindow *window, EomImage *image); static void eom_window_list_store_image_added (GtkTreeModel *tree_model, GtkTreePath *path, GtkTreeIter *iter, gpointer user_data); static void eom_window_list_store_image_removed (GtkTreeModel *tree_model, GtkTreePath *path, gpointer user_data); static void eom_window_set_wallpaper (EomWindow *window, const gchar *filename, const gchar *visible_filename); static gboolean eom_window_save_images (EomWindow *window, GList *images); static void eom_window_finish_saving (EomWindow *window); static GAppInfo *get_appinfo_for_editor (EomWindow *window); static GQuark eom_window_error_quark (void) { static GQuark q = 0; if (q == 0) q = g_quark_from_static_string ("eom-window-error-quark"); return q; } static void eom_window_set_collection_mode (EomWindow *window, EomWindowCollectionPos position, gboolean resizable) { EomWindowPrivate *priv; GtkWidget *hpaned; EomThumbNavMode mode = EOM_THUMB_NAV_MODE_ONE_ROW; eom_debug (DEBUG_PREFERENCES); g_return_if_fail (EOM_IS_WINDOW (window)); priv = window->priv; if (priv->collection_position == position && priv->collection_resizable == resizable) return; priv->collection_position = position; priv->collection_resizable = resizable; hpaned = gtk_widget_get_parent (priv->sidebar); g_object_ref (hpaned); g_object_ref (priv->nav); gtk_container_remove (GTK_CONTAINER (priv->layout), hpaned); gtk_container_remove (GTK_CONTAINER (priv->layout), priv->nav); gtk_widget_destroy (priv->layout); switch (position) { case EOM_WINDOW_COLLECTION_POS_BOTTOM: case EOM_WINDOW_COLLECTION_POS_TOP: if (resizable) { mode = EOM_THUMB_NAV_MODE_MULTIPLE_ROWS; #if GTK_CHECK_VERSION (3, 2, 0) priv->layout = gtk_paned_new (GTK_ORIENTATION_VERTICAL); #else priv->layout = gtk_vpaned_new (); #endif if (position == EOM_WINDOW_COLLECTION_POS_BOTTOM) { gtk_paned_pack1 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); gtk_paned_pack2 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); } else { gtk_paned_pack1 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); gtk_paned_pack2 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); } } else { mode = EOM_THUMB_NAV_MODE_ONE_ROW; priv->layout = gtk_vbox_new (FALSE, 2); if (position == EOM_WINDOW_COLLECTION_POS_BOTTOM) { gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); } else { gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); } } break; case EOM_WINDOW_COLLECTION_POS_LEFT: case EOM_WINDOW_COLLECTION_POS_RIGHT: if (resizable) { mode = EOM_THUMB_NAV_MODE_MULTIPLE_COLUMNS; #if GTK_CHECK_VERSION (3, 2, 0) priv->layout = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL); #else priv->layout = gtk_hpaned_new (); #endif if (position == EOM_WINDOW_COLLECTION_POS_LEFT) { gtk_paned_pack1 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); gtk_paned_pack2 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); } else { gtk_paned_pack1 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); gtk_paned_pack2 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); } } else { mode = EOM_THUMB_NAV_MODE_ONE_COLUMN; priv->layout = gtk_hbox_new (FALSE, 2); if (position == EOM_WINDOW_COLLECTION_POS_LEFT) { gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); } else { gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); } } break; } gtk_box_pack_end (GTK_BOX (priv->cbox), priv->layout, TRUE, TRUE, 0); eom_thumb_nav_set_mode (EOM_THUMB_NAV (priv->nav), mode); if (priv->mode != EOM_WINDOW_MODE_UNKNOWN) { update_action_groups_state (window); } } static void eom_window_can_save_changed_cb (GSettings *settings, gchar *key, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; gboolean save_disabled = FALSE; GtkAction *action_save, *action_save_as; eom_debug (DEBUG_PREFERENCES); g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = EOM_WINDOW (user_data)->priv; save_disabled = g_settings_get_boolean (settings, key); priv->save_disabled = save_disabled; action_save = gtk_action_group_get_action (priv->actions_image, "ImageSave"); action_save_as = gtk_action_group_get_action (priv->actions_image, "ImageSaveAs"); if (priv->save_disabled) { gtk_action_set_sensitive (action_save, FALSE); gtk_action_set_sensitive (action_save_as, FALSE); } else { EomImage *image = eom_window_get_image (window); if (EOM_IS_IMAGE (image)) { gtk_action_set_sensitive (action_save, eom_image_is_modified (image)); gtk_action_set_sensitive (action_save_as, TRUE); } } } #ifdef HAVE_LCMS static cmsHPROFILE * eom_window_get_display_profile (GdkScreen *screen) { Display *dpy; Atom icc_atom, type; int format; gulong nitems; gulong bytes_after; gulong length; guchar *str; int result; cmsHPROFILE *profile; char *atom_name; dpy = GDK_DISPLAY_XDISPLAY (gdk_screen_get_display (screen)); if (gdk_screen_get_number (screen) > 0) atom_name = g_strdup_printf ("_ICC_PROFILE_%d", gdk_screen_get_number (screen)); else atom_name = g_strdup ("_ICC_PROFILE"); icc_atom = gdk_x11_get_xatom_by_name_for_display (gdk_screen_get_display (screen), atom_name); g_free (atom_name); result = XGetWindowProperty (dpy, GDK_WINDOW_XID (gdk_screen_get_root_window (screen)), icc_atom, 0, G_MAXLONG, False, XA_CARDINAL, &type, &format, &nitems, &bytes_after, (guchar **)&str); /* TODO: handle bytes_after != 0 */ if ((result == Success) && (type == XA_CARDINAL) && (nitems > 0)) { switch (format) { case 8: length = nitems; break; case 16: length = sizeof(short) * nitems; break; case 32: length = sizeof(long) * nitems; break; default: eom_debug_message (DEBUG_LCMS, "Unable to read profile, not correcting"); XFree (str); return NULL; } profile = cmsOpenProfileFromMem (str, length); if (G_UNLIKELY (profile == NULL)) { eom_debug_message (DEBUG_LCMS, "Invalid display profile, " "not correcting"); } XFree (str); } else { profile = NULL; eom_debug_message (DEBUG_LCMS, "No profile, not correcting"); } return profile; } #endif static void update_image_pos (EomWindow *window) { EomWindowPrivate *priv; gint pos = -1, n_images = 0; priv = window->priv; n_images = eom_list_store_length (EOM_LIST_STORE (priv->store)); if (n_images > 0) { pos = eom_list_store_get_pos_by_image (EOM_LIST_STORE (priv->store), priv->image); } /* Images: (image pos) / (n_total_images) */ eom_statusbar_set_image_number (EOM_STATUSBAR (priv->statusbar), pos + 1, n_images); } static void update_status_bar (EomWindow *window) { EomWindowPrivate *priv; char *str = NULL; g_return_if_fail (EOM_IS_WINDOW (window)); eom_debug (DEBUG_WINDOW); priv = window->priv; if (priv->image != NULL && eom_image_has_data (priv->image, EOM_IMAGE_DATA_DIMENSION)) { int zoom, width, height; goffset bytes = 0; zoom = floor (100 * eom_scroll_view_get_zoom (EOM_SCROLL_VIEW (priv->view)) + 0.5); eom_image_get_size (priv->image, &width, &height); bytes = eom_image_get_bytes (priv->image); if ((width > 0) && (height > 0)) { char *size_string; size_string = g_format_size (bytes); /* Translators: This is the string displayed in the statusbar * The tokens are from left to right: * - image width * - image height * - image size in bytes * - zoom in percent */ str = g_strdup_printf (ngettext("%i × %i pixel %s %i%%", "%i × %i pixels %s %i%%", height), width, height, size_string, zoom); g_free (size_string); } update_image_pos (window); } gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid, str ? str : ""); g_free (str); } static void eom_window_set_message_area (EomWindow *window, GtkWidget *message_area) { if (window->priv->message_area == message_area) return; if (window->priv->message_area != NULL) gtk_widget_destroy (window->priv->message_area); window->priv->message_area = message_area; if (message_area == NULL) return; gtk_box_pack_start (GTK_BOX (window->priv->cbox), window->priv->message_area, FALSE, FALSE, 0); g_object_add_weak_pointer (G_OBJECT (window->priv->message_area), (void *) &window->priv->message_area); } static void update_action_groups_state (EomWindow *window) { EomWindowPrivate *priv; GtkAction *action_collection; GtkAction *action_sidebar; GtkAction *action_fscreen; GtkAction *action_sshow; GtkAction *action_print; gboolean print_disabled = FALSE; gboolean show_image_collection = FALSE; gint n_images = 0; g_return_if_fail (EOM_IS_WINDOW (window)); eom_debug (DEBUG_WINDOW); priv = window->priv; action_collection = gtk_action_group_get_action (priv->actions_window, "ViewImageCollection"); action_sidebar = gtk_action_group_get_action (priv->actions_window, "ViewSidebar"); action_fscreen = gtk_action_group_get_action (priv->actions_image, "ViewFullscreen"); action_sshow = gtk_action_group_get_action (priv->actions_collection, "ViewSlideshow"); action_print = gtk_action_group_get_action (priv->actions_image, "ImagePrint"); g_assert (action_collection != NULL); g_assert (action_sidebar != NULL); g_assert (action_fscreen != NULL); g_assert (action_sshow != NULL); g_assert (action_print != NULL); if (priv->store != NULL) { n_images = eom_list_store_length (EOM_LIST_STORE (priv->store)); } if (n_images == 0) { gtk_widget_hide (priv->layout); gtk_action_group_set_sensitive (priv->actions_window, TRUE); gtk_action_group_set_sensitive (priv->actions_image, FALSE); gtk_action_group_set_sensitive (priv->actions_collection, FALSE); gtk_action_set_sensitive (action_fscreen, FALSE); gtk_action_set_sensitive (action_sshow, FALSE); /* If there are no images on model, initialization stops here. */ if (priv->status == EOM_WINDOW_STATUS_INIT) { priv->status = EOM_WINDOW_STATUS_NORMAL; } } else { if (priv->flags & EOM_STARTUP_DISABLE_COLLECTION) { g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION, FALSE); show_image_collection = FALSE; } else { show_image_collection = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION); } show_image_collection = show_image_collection && n_images > 1 && priv->mode != EOM_WINDOW_MODE_SLIDESHOW; gtk_widget_show (priv->layout); if (show_image_collection) gtk_widget_show (priv->nav); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action_collection), show_image_collection); gtk_action_group_set_sensitive (priv->actions_window, TRUE); gtk_action_group_set_sensitive (priv->actions_image, TRUE); gtk_action_set_sensitive (action_fscreen, TRUE); if (n_images == 1) { gtk_action_group_set_sensitive (priv->actions_collection, FALSE); gtk_action_set_sensitive (action_collection, FALSE); gtk_action_set_sensitive (action_sshow, FALSE); } else { gtk_action_group_set_sensitive (priv->actions_collection, TRUE); gtk_action_set_sensitive (action_sshow, TRUE); } if (show_image_collection) gtk_widget_grab_focus (priv->thumbview); else gtk_widget_grab_focus (priv->view); } print_disabled = g_settings_get_boolean (priv->lockdown_settings, EOM_CONF_LOCKDOWN_CAN_PRINT); if (print_disabled) { gtk_action_set_sensitive (action_print, FALSE); } if (eom_sidebar_is_empty (EOM_SIDEBAR (priv->sidebar))) { gtk_action_set_sensitive (action_sidebar, FALSE); gtk_widget_hide (priv->sidebar); } } static void update_selection_ui_visibility (EomWindow *window) { EomWindowPrivate *priv; GtkAction *wallpaper_action; gint n_selected; priv = window->priv; n_selected = eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview)); wallpaper_action = gtk_action_group_get_action (priv->actions_image, "ImageSetAsWallpaper"); if (n_selected == 1) { gtk_action_set_sensitive (wallpaper_action, TRUE); } else { gtk_action_set_sensitive (wallpaper_action, FALSE); } } static gboolean add_file_to_recent_files (GFile *file) { gchar *text_uri; GFileInfo *file_info; GtkRecentData *recent_data; static gchar *groups[2] = { EOM_RECENT_FILES_GROUP , NULL }; if (file == NULL) return FALSE; /* The password gets stripped here because ~/.recently-used.xbel is * readable by everyone (chmod 644). It also makes the workaround * for the bug with gtk_recent_info_get_uri_display() easier * (see the comment in eom_window_update_recent_files_menu()). */ text_uri = g_file_get_uri (file); if (text_uri == NULL) return FALSE; file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0, NULL, NULL); if (file_info == NULL) return FALSE; recent_data = g_slice_new (GtkRecentData); recent_data->display_name = NULL; recent_data->description = NULL; recent_data->mime_type = (gchar *) g_file_info_get_content_type (file_info); recent_data->app_name = EOM_RECENT_FILES_APP_NAME; recent_data->app_exec = g_strjoin(" ", g_get_prgname (), "%u", NULL); recent_data->groups = groups; recent_data->is_private = FALSE; gtk_recent_manager_add_full (gtk_recent_manager_get_default (), text_uri, recent_data); g_free (recent_data->app_exec); g_free (text_uri); g_object_unref (file_info); g_slice_free (GtkRecentData, recent_data); return FALSE; } static void image_thumb_changed_cb (EomImage *image, gpointer data) { EomWindow *window; EomWindowPrivate *priv; GdkPixbuf *thumb; g_return_if_fail (EOM_IS_WINDOW (data)); window = EOM_WINDOW (data); priv = window->priv; thumb = eom_image_get_thumbnail (image); if (thumb != NULL) { gtk_window_set_icon (GTK_WINDOW (window), thumb); if (window->priv->properties_dlg != NULL) { eom_properties_dialog_update (EOM_PROPERTIES_DIALOG (priv->properties_dlg), image); } g_object_unref (thumb); } else if (!gtk_widget_get_visible (window->priv->nav)) { gint img_pos = eom_list_store_get_pos_by_image (window->priv->store, image); GtkTreePath *path = gtk_tree_path_new_from_indices (img_pos,-1); GtkTreeIter iter; gtk_tree_model_get_iter (GTK_TREE_MODEL (window->priv->store), &iter, path); eom_list_store_thumbnail_set (window->priv->store, &iter); gtk_tree_path_free (path); } } static void file_changed_info_bar_response (GtkInfoBar *info_bar, gint response, EomWindow *window) { if (response == GTK_RESPONSE_YES) { eom_window_reload_image (window); } window->priv->needs_reload_confirmation = TRUE; eom_window_set_message_area (window, NULL); } static void image_file_changed_cb (EomImage *img, EomWindow *window) { GtkWidget *info_bar; gchar *text, *markup; GtkWidget *image; GtkWidget *label; GtkWidget *hbox; if (window->priv->needs_reload_confirmation == FALSE) return; window->priv->needs_reload_confirmation = FALSE; info_bar = gtk_info_bar_new_with_buttons (_("_Reload"), GTK_RESPONSE_YES, C_("MessageArea", "Hi_de"), GTK_RESPONSE_NO, NULL); gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), GTK_MESSAGE_QUESTION); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); label = gtk_label_new (NULL); /* The newline character is currently necessary due to a problem * with the automatic line break. */ text = g_strdup_printf (_("The image \"%s\" has been modified by an external application." "\nWould you like to reload it?"), eom_image_get_caption (img)); markup = g_markup_printf_escaped ("<b>%s</b>", text); gtk_label_set_markup (GTK_LABEL (label), markup); g_free (text); g_free (markup); hbox = gtk_hbox_new (FALSE, 8); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0); #if GTK_CHECK_VERSION (3, 14, 0) gtk_widget_set_valign (image, GTK_ALIGN_START); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_widget_set_halign (label, GTK_ALIGN_START); #else gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); #endif gtk_box_pack_start (GTK_BOX (gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar))), hbox, TRUE, TRUE, 0); gtk_widget_show_all (hbox); gtk_widget_show (info_bar); eom_window_set_message_area (window, info_bar); g_signal_connect (info_bar, "response", G_CALLBACK (file_changed_info_bar_response), window); } static void eom_window_display_image (EomWindow *window, EomImage *image) { EomWindowPrivate *priv; GFile *file; g_return_if_fail (EOM_IS_WINDOW (window)); g_return_if_fail (EOM_IS_IMAGE (image)); eom_debug (DEBUG_WINDOW); g_assert (eom_image_has_data (image, EOM_IMAGE_DATA_IMAGE)); priv = window->priv; if (image != NULL) { g_signal_connect (image, "thumbnail_changed", G_CALLBACK (image_thumb_changed_cb), window); g_signal_connect (image, "file-changed", G_CALLBACK (image_file_changed_cb), window); image_thumb_changed_cb (image, window); } priv->needs_reload_confirmation = TRUE; eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), image); gtk_window_set_title (GTK_WINDOW (window), eom_image_get_caption (image)); update_status_bar (window); file = eom_image_get_file (image); g_idle_add_full (G_PRIORITY_LOW, (GSourceFunc) add_file_to_recent_files, file, (GDestroyNotify) g_object_unref); eom_window_update_openwith_menu (window, image); } static void open_with_launch_application_cb (GtkAction *action, gpointer data) { EomImage *image; GAppInfo *app; GFile *file; GList *files = NULL; image = EOM_IMAGE (data); file = eom_image_get_file (image); app = g_object_get_data (G_OBJECT (action), "app"); files = g_list_append (files, file); g_app_info_launch (app, files, NULL, NULL); g_object_unref (file); g_list_free (files); } static void eom_window_update_openwith_menu (EomWindow *window, EomImage *image) { gboolean edit_button_active; GAppInfo *editor_app; GFile *file; GFileInfo *file_info; GList *iter; gchar *label, *tip; const gchar *mime_type; GtkAction *action; EomWindowPrivate *priv; GList *apps; guint action_id = 0; GIcon *app_icon; char *path; GtkWidget *menuitem; priv = window->priv; edit_button_active = FALSE; editor_app = get_appinfo_for_editor (window); file = eom_image_get_file (image); file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0, NULL, NULL); if (file_info == NULL) return; else { mime_type = g_file_info_get_content_type (file_info); } if (priv->open_with_menu_id != 0) { gtk_ui_manager_remove_ui (priv->ui_mgr, priv->open_with_menu_id); priv->open_with_menu_id = 0; } if (priv->actions_open_with != NULL) { gtk_ui_manager_remove_action_group (priv->ui_mgr, priv->actions_open_with); priv->actions_open_with = NULL; } if (mime_type == NULL) { g_object_unref (file_info); return; } apps = g_app_info_get_all_for_type (mime_type); g_object_unref (file_info); if (!apps) return; priv->actions_open_with = gtk_action_group_new ("OpenWithActions"); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_open_with, -1); priv->open_with_menu_id = gtk_ui_manager_new_merge_id (priv->ui_mgr); for (iter = apps; iter; iter = iter->next) { GAppInfo *app = iter->data; gchar name[64]; if (editor_app != NULL && g_app_info_equal (editor_app, app)) { edit_button_active = TRUE; } /* Do not include eom itself */ if (g_ascii_strcasecmp (g_app_info_get_executable (app), g_get_prgname ()) == 0) { g_object_unref (app); continue; } g_snprintf (name, sizeof (name), "OpenWith%u", action_id++); label = g_strdup (g_app_info_get_name (app)); tip = g_strdup_printf (_("Use \"%s\" to open the selected image"), g_app_info_get_name (app)); action = gtk_action_new (name, label, tip, NULL); app_icon = g_app_info_get_icon (app); if (G_LIKELY (app_icon != NULL)) { g_object_ref (app_icon); gtk_action_set_gicon (action, app_icon); g_object_unref (app_icon); } g_free (label); g_free (tip); g_object_set_data_full (G_OBJECT (action), "app", app, (GDestroyNotify) g_object_unref); g_signal_connect (action, "activate", G_CALLBACK (open_with_launch_application_cb), image); gtk_action_group_add_action (priv->actions_open_with, action); g_object_unref (action); gtk_ui_manager_add_ui (priv->ui_mgr, priv->open_with_menu_id, "/MainMenu/Image/ImageOpenWith/Applications Placeholder", name, name, GTK_UI_MANAGER_MENUITEM, FALSE); gtk_ui_manager_add_ui (priv->ui_mgr, priv->open_with_menu_id, "/ThumbnailPopup/ImageOpenWith/Applications Placeholder", name, name, GTK_UI_MANAGER_MENUITEM, FALSE); gtk_ui_manager_add_ui (priv->ui_mgr, priv->open_with_menu_id, "/ViewPopup/ImageOpenWith/Applications Placeholder", name, name, GTK_UI_MANAGER_MENUITEM, FALSE); path = g_strdup_printf ("/MainMenu/Image/ImageOpenWith/Applications Placeholder/%s", name); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path); /* Only force displaying the icon if it is an application icon */ gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL); g_free (path); path = g_strdup_printf ("/ThumbnailPopup/ImageOpenWith/Applications Placeholder/%s", name); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path); /* Only force displaying the icon if it is an application icon */ gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL); g_free (path); path = g_strdup_printf ("/ViewPopup/ImageOpenWith/Applications Placeholder/%s", name); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path); /* Only force displaying the icon if it is an application icon */ gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL); g_free (path); } g_list_free (apps); action = gtk_action_group_get_action (window->priv->actions_image, "OpenEditor"); if (action != NULL) { gtk_action_set_sensitive (action, edit_button_active); } } static void eom_window_clear_load_job (EomWindow *window) { EomWindowPrivate *priv = window->priv; if (priv->load_job != NULL) { if (!priv->load_job->finished) eom_job_queue_remove_job (priv->load_job); g_signal_handlers_disconnect_by_func (priv->load_job, eom_job_progress_cb, window); g_signal_handlers_disconnect_by_func (priv->load_job, eom_job_load_cb, window); eom_image_cancel_load (EOM_JOB_LOAD (priv->load_job)->image); g_object_unref (priv->load_job); priv->load_job = NULL; /* Hide statusbar */ eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), 0); } } static void eom_job_progress_cb (EomJobLoad *job, float progress, gpointer user_data) { EomWindow *window; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); eom_statusbar_set_progress (EOM_STATUSBAR (window->priv->statusbar), progress); } static void eom_job_save_progress_cb (EomJobSave *job, float progress, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; static EomImage *image = NULL; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), progress); if (image != job->current_image) { gchar *str_image, *status_message; guint n_images; image = job->current_image; n_images = g_list_length (job->images); str_image = eom_image_get_uri_for_display (image); /* Translators: This string is displayed in the statusbar * while saving images. The tokens are from left to right: * - the original filename * - the current image's position in the queue * - the total number of images queued for saving */ status_message = g_strdup_printf (_("Saving image \"%s\" (%u/%u)"), str_image, job->current_pos + 1, n_images); g_free (str_image); gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid, status_message); g_free (status_message); } if (progress == 1.0) image = NULL; } static void eom_window_obtain_desired_size (EomImage *image, gint width, gint height, EomWindow *window) { GdkScreen *screen; GdkRectangle monitor; GtkAllocation allocation; gint final_width, final_height; gint screen_width, screen_height; gint window_width, window_height; gint img_width, img_height; gint view_width, view_height; gint deco_width, deco_height; update_action_groups_state (window); img_width = width; img_height = height; if (!gtk_widget_get_realized (window->priv->view)) { gtk_widget_realize (window->priv->view); } gtk_widget_get_allocation (window->priv->view, &allocation); view_width = allocation.width; view_height = allocation.height; if (!gtk_widget_get_realized (GTK_WIDGET (window))) { gtk_widget_realize (GTK_WIDGET (window)); } gtk_widget_get_allocation (GTK_WIDGET (window), &allocation); window_width = allocation.width; window_height = allocation.height; screen = gtk_window_get_screen (GTK_WINDOW (window)); gdk_screen_get_monitor_geometry (screen, gdk_screen_get_monitor_at_window (screen, gtk_widget_get_window (GTK_WIDGET (window))), &monitor); screen_width = monitor.width; screen_height = monitor.height; deco_width = window_width - view_width; deco_height = window_height - view_height; if (img_width > 0 && img_height > 0) { if ((img_width + deco_width > screen_width) || (img_height + deco_height > screen_height)) { double factor; if (img_width > img_height) { factor = (screen_width * 0.75 - deco_width) / (double) img_width; } else { factor = (screen_height * 0.75 - deco_height) / (double) img_height; } img_width = img_width * factor; img_height = img_height * factor; } } final_width = MAX (EOM_WINDOW_MIN_WIDTH, img_width + deco_width); final_height = MAX (EOM_WINDOW_MIN_HEIGHT, img_height + deco_height); eom_debug_message (DEBUG_WINDOW, "Setting window size: %d x %d", final_width, final_height); gtk_window_set_default_size (GTK_WINDOW (window), final_width, final_height); g_signal_emit (window, signals[SIGNAL_PREPARED], 0); } static void eom_window_error_message_area_response (GtkInfoBar *message_area, gint response_id, EomWindow *window) { if (response_id != GTK_RESPONSE_OK) { eom_window_set_message_area (window, NULL); return; } /* Trigger loading for current image again */ eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_CURRENT); } static void eom_job_load_cb (EomJobLoad *job, gpointer data) { EomWindow *window; EomWindowPrivate *priv; GtkAction *action_undo, *action_save; g_return_if_fail (EOM_IS_WINDOW (data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (data); priv = window->priv; eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), 0.0); gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar), priv->image_info_message_cid); if (priv->image != NULL) { g_signal_handlers_disconnect_by_func (priv->image, image_thumb_changed_cb, window); g_signal_handlers_disconnect_by_func (priv->image, image_file_changed_cb, window); g_object_unref (priv->image); } priv->image = g_object_ref (job->image); if (EOM_JOB (job)->error == NULL) { #ifdef HAVE_LCMS eom_image_apply_display_profile (job->image, priv->display_profile); #endif gtk_action_group_set_sensitive (priv->actions_image, TRUE); eom_window_display_image (window, job->image); } else { GtkWidget *message_area; message_area = eom_image_load_error_message_area_new ( eom_image_get_caption (job->image), EOM_JOB (job)->error); g_signal_connect (message_area, "response", G_CALLBACK (eom_window_error_message_area_response), window); gtk_window_set_icon (GTK_WINDOW (window), NULL); gtk_window_set_title (GTK_WINDOW (window), eom_image_get_caption (job->image)); eom_window_set_message_area (window, message_area); gtk_info_bar_set_default_response (GTK_INFO_BAR (message_area), GTK_RESPONSE_CANCEL); gtk_widget_show (message_area); update_status_bar (window); eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), NULL); if (window->priv->status == EOM_WINDOW_STATUS_INIT) { update_action_groups_state (window); g_signal_emit (window, signals[SIGNAL_PREPARED], 0); } gtk_action_group_set_sensitive (priv->actions_image, FALSE); } eom_window_clear_load_job (window); if (window->priv->status == EOM_WINDOW_STATUS_INIT) { window->priv->status = EOM_WINDOW_STATUS_NORMAL; g_signal_handlers_disconnect_by_func (job->image, G_CALLBACK (eom_window_obtain_desired_size), window); } action_save = gtk_action_group_get_action (priv->actions_image, "ImageSave"); action_undo = gtk_action_group_get_action (priv->actions_image, "EditUndo"); /* Set Save and Undo sensitive according to image state. * Respect lockdown in case of Save.*/ gtk_action_set_sensitive (action_save, (!priv->save_disabled && eom_image_is_modified (job->image))); gtk_action_set_sensitive (action_undo, eom_image_is_modified (job->image)); g_object_unref (job->image); } static void eom_window_clear_transform_job (EomWindow *window) { EomWindowPrivate *priv = window->priv; if (priv->transform_job != NULL) { if (!priv->transform_job->finished) eom_job_queue_remove_job (priv->transform_job); g_signal_handlers_disconnect_by_func (priv->transform_job, eom_job_transform_cb, window); g_object_unref (priv->transform_job); priv->transform_job = NULL; } } static void eom_job_transform_cb (EomJobTransform *job, gpointer data) { EomWindow *window; GtkAction *action_undo, *action_save; EomImage *image; g_return_if_fail (EOM_IS_WINDOW (data)); window = EOM_WINDOW (data); eom_window_clear_transform_job (window); action_undo = gtk_action_group_get_action (window->priv->actions_image, "EditUndo"); action_save = gtk_action_group_get_action (window->priv->actions_image, "ImageSave"); image = eom_window_get_image (window); gtk_action_set_sensitive (action_undo, eom_image_is_modified (image)); if (!window->priv->save_disabled) { gtk_action_set_sensitive (action_save, eom_image_is_modified (image)); } } static void apply_transformation (EomWindow *window, EomTransform *trans) { EomWindowPrivate *priv; GList *images; g_return_if_fail (EOM_IS_WINDOW (window)); priv = window->priv; images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); eom_window_clear_transform_job (window); priv->transform_job = eom_job_transform_new (images, trans); g_signal_connect (priv->transform_job, "finished", G_CALLBACK (eom_job_transform_cb), window); g_signal_connect (priv->transform_job, "progress", G_CALLBACK (eom_job_progress_cb), window); eom_job_queue_add_job (priv->transform_job); } static void handle_image_selection_changed_cb (EomThumbView *thumbview, EomWindow *window) { EomWindowPrivate *priv; EomImage *image; gchar *status_message; gchar *str_image; priv = window->priv; if (eom_list_store_length (EOM_LIST_STORE (priv->store)) == 0) { gtk_window_set_title (GTK_WINDOW (window), g_get_application_name()); gtk_statusbar_remove_all (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), NULL); } if (eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview)) == 0) return; update_selection_ui_visibility (window); image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); g_assert (EOM_IS_IMAGE (image)); eom_window_clear_load_job (window); eom_window_set_message_area (window, NULL); gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); if (image == priv->image) { update_status_bar (window); return; } if (eom_image_has_data (image, EOM_IMAGE_DATA_IMAGE)) { if (priv->image != NULL) g_object_unref (priv->image); priv->image = image; eom_window_display_image (window, image); return; } if (priv->status == EOM_WINDOW_STATUS_INIT) { g_signal_connect (image, "size-prepared", G_CALLBACK (eom_window_obtain_desired_size), window); } priv->load_job = eom_job_load_new (image, EOM_IMAGE_DATA_ALL); g_signal_connect (priv->load_job, "finished", G_CALLBACK (eom_job_load_cb), window); g_signal_connect (priv->load_job, "progress", G_CALLBACK (eom_job_progress_cb), window); eom_job_queue_add_job (priv->load_job); str_image = eom_image_get_uri_for_display (image); status_message = g_strdup_printf (_("Opening image \"%s\""), str_image); g_free (str_image); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid, status_message); g_free (status_message); } static void view_zoom_changed_cb (GtkWidget *widget, double zoom, gpointer user_data) { EomWindow *window; GtkAction *action_zoom_in; GtkAction *action_zoom_out; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); update_status_bar (window); action_zoom_in = gtk_action_group_get_action (window->priv->actions_image, "ViewZoomIn"); action_zoom_out = gtk_action_group_get_action (window->priv->actions_image, "ViewZoomOut"); gtk_action_set_sensitive (action_zoom_in, !eom_scroll_view_get_zoom_is_max (EOM_SCROLL_VIEW (window->priv->view))); gtk_action_set_sensitive (action_zoom_out, !eom_scroll_view_get_zoom_is_min (EOM_SCROLL_VIEW (window->priv->view))); } static void eom_window_open_recent_cb (GtkAction *action, EomWindow *window) { GtkRecentInfo *info; const gchar *uri; GSList *list = NULL; info = g_object_get_data (G_OBJECT (action), "gtk-recent-info"); g_return_if_fail (info != NULL); uri = gtk_recent_info_get_uri (info); list = g_slist_prepend (list, g_strdup (uri)); eom_application_open_uri_list (EOM_APP, list, GDK_CURRENT_TIME, 0, NULL); g_slist_foreach (list, (GFunc) g_free, NULL); g_slist_free (list); } static void file_open_dialog_response_cb (GtkWidget *chooser, gint response_id, EomWindow *ev_window) { if (response_id == GTK_RESPONSE_OK) { GSList *uris; uris = gtk_file_chooser_get_uris (GTK_FILE_CHOOSER (chooser)); eom_application_open_uri_list (EOM_APP, uris, GDK_CURRENT_TIME, 0, NULL); g_slist_foreach (uris, (GFunc) g_free, NULL); g_slist_free (uris); } gtk_widget_destroy (chooser); } static void eom_window_update_fullscreen_action (EomWindow *window) { GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_image, "ViewFullscreen"); g_signal_handlers_block_by_func (action, G_CALLBACK (eom_window_cmd_fullscreen), window); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), window->priv->mode == EOM_WINDOW_MODE_FULLSCREEN); g_signal_handlers_unblock_by_func (action, G_CALLBACK (eom_window_cmd_fullscreen), window); } static void eom_window_update_slideshow_action (EomWindow *window) { GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_collection, "ViewSlideshow"); g_signal_handlers_block_by_func (action, G_CALLBACK (eom_window_cmd_slideshow), window); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW); g_signal_handlers_unblock_by_func (action, G_CALLBACK (eom_window_cmd_slideshow), window); } static void eom_window_update_pause_slideshow_action (EomWindow *window) { GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_image, "PauseSlideshow"); g_signal_handlers_block_by_func (action, G_CALLBACK (eom_window_cmd_pause_slideshow), window); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), window->priv->mode != EOM_WINDOW_MODE_SLIDESHOW); g_signal_handlers_unblock_by_func (action, G_CALLBACK (eom_window_cmd_pause_slideshow), window); } static void eom_window_update_fullscreen_popup (EomWindow *window) { GtkWidget *popup = window->priv->fullscreen_popup; GdkRectangle screen_rect; GdkScreen *screen; g_return_if_fail (popup != NULL); if (gtk_widget_get_window (GTK_WIDGET (window)) == NULL) return; screen = gtk_widget_get_screen (GTK_WIDGET (window)); gdk_screen_get_monitor_geometry (screen, gdk_screen_get_monitor_at_window (screen, gtk_widget_get_window (GTK_WIDGET (window))), &screen_rect); gtk_widget_set_size_request (popup, screen_rect.width, -1); gtk_window_move (GTK_WINDOW (popup), screen_rect.x, screen_rect.y); } static void screen_size_changed_cb (GdkScreen *screen, EomWindow *window) { eom_window_update_fullscreen_popup (window); } static void fullscreen_popup_size_request_cb (GtkWidget *popup, GtkRequisition *req, EomWindow *window) { eom_window_update_fullscreen_popup (window); } static gboolean fullscreen_timeout_cb (gpointer data) { EomWindow *window = EOM_WINDOW (data); gtk_widget_hide (window->priv->fullscreen_popup); eom_scroll_view_hide_cursor (EOM_SCROLL_VIEW (window->priv->view)); fullscreen_clear_timeout (window); return FALSE; } static gboolean slideshow_is_loop_end (EomWindow *window) { EomWindowPrivate *priv = window->priv; EomImage *image = NULL; gint pos; image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); pos = eom_list_store_get_pos_by_image (priv->store, image); return (pos == (eom_list_store_length (priv->store) - 1)); } static gboolean slideshow_switch_cb (gpointer data) { EomWindow *window = EOM_WINDOW (data); EomWindowPrivate *priv = window->priv; eom_debug (DEBUG_WINDOW); if (priv->slideshow_random) { eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RANDOM); return TRUE; } if (!priv->slideshow_loop && slideshow_is_loop_end (window)) { eom_window_stop_fullscreen (window, TRUE); return FALSE; } eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RIGHT); return TRUE; } static void fullscreen_clear_timeout (EomWindow *window) { eom_debug (DEBUG_WINDOW); if (window->priv->fullscreen_timeout_source != NULL) { g_source_unref (window->priv->fullscreen_timeout_source); g_source_destroy (window->priv->fullscreen_timeout_source); } window->priv->fullscreen_timeout_source = NULL; } static void fullscreen_set_timeout (EomWindow *window) { GSource *source; eom_debug (DEBUG_WINDOW); fullscreen_clear_timeout (window); source = g_timeout_source_new (EOM_WINDOW_FULLSCREEN_TIMEOUT); g_source_set_callback (source, fullscreen_timeout_cb, window, NULL); g_source_attach (source, NULL); window->priv->fullscreen_timeout_source = source; eom_scroll_view_show_cursor (EOM_SCROLL_VIEW (window->priv->view)); } static void slideshow_clear_timeout (EomWindow *window) { eom_debug (DEBUG_WINDOW); if (window->priv->slideshow_switch_source != NULL) { g_source_unref (window->priv->slideshow_switch_source); g_source_destroy (window->priv->slideshow_switch_source); } window->priv->slideshow_switch_source = NULL; } static void slideshow_set_timeout (EomWindow *window) { GSource *source; eom_debug (DEBUG_WINDOW); slideshow_clear_timeout (window); if (window->priv->slideshow_switch_timeout <= 0) return; source = g_timeout_source_new (window->priv->slideshow_switch_timeout * 1000); g_source_set_callback (source, slideshow_switch_cb, window, NULL); g_source_attach (source, NULL); window->priv->slideshow_switch_source = source; } static void show_fullscreen_popup (EomWindow *window) { eom_debug (DEBUG_WINDOW); if (!gtk_widget_get_visible (window->priv->fullscreen_popup)) { gtk_widget_show_all (GTK_WIDGET (window->priv->fullscreen_popup)); } fullscreen_set_timeout (window); } static gboolean fullscreen_motion_notify_cb (GtkWidget *widget, GdkEventMotion *event, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); eom_debug (DEBUG_WINDOW); if (event->y < EOM_WINDOW_FULLSCREEN_POPUP_THRESHOLD) { show_fullscreen_popup (window); } else { fullscreen_set_timeout (window); } return FALSE; } static gboolean fullscreen_leave_notify_cb (GtkWidget *widget, GdkEventCrossing *event, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); eom_debug (DEBUG_WINDOW); fullscreen_clear_timeout (window); return FALSE; } static void exit_fullscreen_button_clicked_cb (GtkWidget *button, EomWindow *window) { GtkAction *action; eom_debug (DEBUG_WINDOW); if (window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) { action = gtk_action_group_get_action (window->priv->actions_collection, "ViewSlideshow"); } else { action = gtk_action_group_get_action (window->priv->actions_image, "ViewFullscreen"); } g_return_if_fail (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), FALSE); } static GtkWidget * eom_window_get_exit_fullscreen_button (EomWindow *window) { GtkWidget *button; button = gtk_button_new_from_stock (GTK_STOCK_LEAVE_FULLSCREEN); g_signal_connect (button, "clicked", G_CALLBACK (exit_fullscreen_button_clicked_cb), window); return button; } static GtkWidget * eom_window_create_fullscreen_popup (EomWindow *window) { GtkWidget *popup; GtkWidget *hbox; GtkWidget *button; GtkWidget *toolbar; GdkScreen *screen; eom_debug (DEBUG_WINDOW); popup = gtk_window_new (GTK_WINDOW_POPUP); hbox = gtk_hbox_new (FALSE, 0); gtk_container_add (GTK_CONTAINER (popup), hbox); toolbar = gtk_ui_manager_get_widget (window->priv->ui_mgr, "/FullscreenToolbar"); g_assert (GTK_IS_WIDGET (toolbar)); gtk_toolbar_set_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_ICONS); gtk_box_pack_start (GTK_BOX (hbox), toolbar, TRUE, TRUE, 0); button = eom_window_get_exit_fullscreen_button (window); gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0); gtk_window_set_resizable (GTK_WINDOW (popup), FALSE); screen = gtk_widget_get_screen (GTK_WIDGET (window)); g_signal_connect_object (screen, "size-changed", G_CALLBACK (screen_size_changed_cb), window, 0); g_signal_connect_object (popup, "size_request", G_CALLBACK (fullscreen_popup_size_request_cb), window, 0); g_signal_connect (popup, "enter-notify-event", G_CALLBACK (fullscreen_leave_notify_cb), window); gtk_window_set_screen (GTK_WINDOW (popup), screen); return popup; } static void update_ui_visibility (EomWindow *window) { EomWindowPrivate *priv; GtkAction *action; GtkWidget *menubar; gboolean fullscreen_mode, visible; g_return_if_fail (EOM_IS_WINDOW (window)); eom_debug (DEBUG_WINDOW); priv = window->priv; fullscreen_mode = priv->mode == EOM_WINDOW_MODE_FULLSCREEN || priv->mode == EOM_WINDOW_MODE_SLIDESHOW; menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_TOOLBAR); visible = visible && !fullscreen_mode; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/ToolbarToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); g_object_set (G_OBJECT (priv->toolbar), "visible", visible, NULL); visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_STATUSBAR); visible = visible && !fullscreen_mode; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/StatusbarToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); g_object_set (G_OBJECT (priv->statusbar), "visible", visible, NULL); if (priv->status != EOM_WINDOW_STATUS_INIT) { visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION); visible = visible && priv->mode != EOM_WINDOW_MODE_SLIDESHOW; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/ImageCollectionToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); if (visible) { gtk_widget_show (priv->nav); } else { gtk_widget_hide (priv->nav); } } visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_SIDEBAR); visible = visible && !fullscreen_mode; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/SidebarToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); if (visible) { gtk_widget_show (priv->sidebar); } else { gtk_widget_hide (priv->sidebar); } if (priv->fullscreen_popup != NULL) { gtk_widget_hide (priv->fullscreen_popup); } } static void eom_window_run_fullscreen (EomWindow *window, gboolean slideshow) { #if GTK_CHECK_VERSION (3, 0, 0) static const GdkRGBA black = { 0., 0., 0., 1.}; #endif EomWindowPrivate *priv; GtkWidget *menubar; gboolean upscale; eom_debug (DEBUG_WINDOW); priv = window->priv; if (slideshow) { priv->mode = EOM_WINDOW_MODE_SLIDESHOW; } else { /* Stop the timer if we come from slideshowing */ if (priv->mode == EOM_WINDOW_MODE_SLIDESHOW) slideshow_clear_timeout (window); priv->mode = EOM_WINDOW_MODE_FULLSCREEN; } if (window->priv->fullscreen_popup == NULL) priv->fullscreen_popup = eom_window_create_fullscreen_popup (window); update_ui_visibility (window); menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); gtk_widget_hide (menubar); g_signal_connect (priv->view, "motion-notify-event", G_CALLBACK (fullscreen_motion_notify_cb), window); g_signal_connect (priv->view, "leave-notify-event", G_CALLBACK (fullscreen_leave_notify_cb), window); g_signal_connect (priv->thumbview, "motion-notify-event", G_CALLBACK (fullscreen_motion_notify_cb), window); g_signal_connect (priv->thumbview, "leave-notify-event", G_CALLBACK (fullscreen_leave_notify_cb), window); fullscreen_set_timeout (window); if (slideshow) { priv->slideshow_random = g_settings_get_boolean (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_RANDOM); priv->slideshow_loop = g_settings_get_boolean (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_LOOP); priv->slideshow_switch_timeout = g_settings_get_int (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_SECONDS); slideshow_set_timeout (window); } upscale = g_settings_get_boolean (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_UPSCALE); eom_scroll_view_set_zoom_upscale (EOM_SCROLL_VIEW (priv->view), upscale); gtk_widget_grab_focus (priv->view); eom_scroll_view_override_bg_color (EOM_SCROLL_VIEW (window->priv->view), #if GTK_CHECK_VERSION (3, 0, 0) &black); #else &(gtk_widget_get_style (GTK_WIDGET (window))->black)); #endif #if !GTK_CHECK_VERSION (3, 0, 0) { GtkStyle *style; style = gtk_style_copy (gtk_widget_get_style (gtk_widget_get_parent (priv->view))); style->xthickness = 0; style->ythickness = 0; gtk_widget_set_style (gtk_widget_get_parent (priv->view), style); g_object_unref (style); } #endif gtk_window_fullscreen (GTK_WINDOW (window)); eom_window_update_fullscreen_popup (window); #ifdef HAVE_DBUS eom_application_screensaver_disable (EOM_APP); #endif /* Update both actions as we could've already been in one those modes */ eom_window_update_slideshow_action (window); eom_window_update_fullscreen_action (window); eom_window_update_pause_slideshow_action (window); } static void eom_window_stop_fullscreen (EomWindow *window, gboolean slideshow) { EomWindowPrivate *priv; GtkWidget *menubar; eom_debug (DEBUG_WINDOW); priv = window->priv; if (priv->mode != EOM_WINDOW_MODE_SLIDESHOW && priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return; priv->mode = EOM_WINDOW_MODE_NORMAL; fullscreen_clear_timeout (window); if (slideshow) { slideshow_clear_timeout (window); } g_signal_handlers_disconnect_by_func (priv->view, (gpointer) fullscreen_motion_notify_cb, window); g_signal_handlers_disconnect_by_func (priv->view, (gpointer) fullscreen_leave_notify_cb, window); g_signal_handlers_disconnect_by_func (priv->thumbview, (gpointer) fullscreen_motion_notify_cb, window); g_signal_handlers_disconnect_by_func (priv->thumbview, (gpointer) fullscreen_leave_notify_cb, window); update_ui_visibility (window); menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); gtk_widget_show (menubar); eom_scroll_view_set_zoom_upscale (EOM_SCROLL_VIEW (priv->view), FALSE); eom_scroll_view_override_bg_color (EOM_SCROLL_VIEW (window->priv->view), NULL); #if !GTK_CHECK_VERSION (3, 0, 0) gtk_widget_set_style (gtk_widget_get_parent (window->priv->view), NULL); #endif gtk_window_unfullscreen (GTK_WINDOW (window)); if (slideshow) { eom_window_update_slideshow_action (window); } else { eom_window_update_fullscreen_action (window); } eom_scroll_view_show_cursor (EOM_SCROLL_VIEW (priv->view)); #ifdef HAVE_DBUS eom_application_screensaver_enable (EOM_APP); #endif } static void eom_window_print (EomWindow *window) { GtkWidget *dialog; GError *error = NULL; GtkPrintOperation *print; GtkPrintOperationResult res; GtkPageSetup *page_setup; GtkPrintSettings *print_settings; gboolean page_setup_disabled = FALSE; eom_debug (DEBUG_PRINTING); print_settings = eom_print_get_print_settings (); /* Make sure the window stays valid while printing */ g_object_ref (window); if (window->priv->page_setup !=NULL) page_setup = g_object_ref (window->priv->page_setup); else page_setup = NULL; print = eom_print_operation_new (window->priv->image, print_settings, page_setup); // Disable page setup options if they are locked down page_setup_disabled = g_settings_get_boolean (window->priv->lockdown_settings, EOM_CONF_LOCKDOWN_CAN_SETUP_PAGE); if (page_setup_disabled) gtk_print_operation_set_embed_page_setup (print, FALSE); res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, GTK_WINDOW (window), &error); if (res == GTK_PRINT_OPERATION_RESULT_ERROR) { dialog = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _("Error printing file:\n%s"), error->message); g_signal_connect (dialog, "response", G_CALLBACK (gtk_widget_destroy), NULL); gtk_widget_show (dialog); g_error_free (error); } else if (res == GTK_PRINT_OPERATION_RESULT_APPLY) { GtkPageSetup *new_page_setup; eom_print_set_print_settings (gtk_print_operation_get_print_settings (print)); new_page_setup = gtk_print_operation_get_default_page_setup (print); if (window->priv->page_setup != NULL) g_object_unref (window->priv->page_setup); window->priv->page_setup = g_object_ref (new_page_setup); } if (page_setup != NULL) g_object_unref (page_setup); g_object_unref (print_settings); g_object_unref (window); } static void eom_window_cmd_file_open (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; EomImage *current; GtkWidget *dlg; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; dlg = eom_file_chooser_new (GTK_FILE_CHOOSER_ACTION_OPEN); current = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); if (current != NULL) { gchar *dir_uri, *file_uri; file_uri = eom_image_get_uri_for_display (current); dir_uri = g_path_get_dirname (file_uri); gtk_file_chooser_set_current_folder_uri (GTK_FILE_CHOOSER (dlg), dir_uri); g_free (file_uri); g_free (dir_uri); g_object_unref (current); } else { /* If desired by the user, fallback to the XDG_PICTURES_DIR (if available) */ const gchar *pics_dir; gboolean use_fallback; use_fallback = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_FILECHOOSER_XDG_FALLBACK); pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES); if (use_fallback && pics_dir) { gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg), pics_dir); } } g_signal_connect (dlg, "response", G_CALLBACK (file_open_dialog_response_cb), window); gtk_widget_show_all (dlg); } static void eom_job_close_save_cb (EomJobSave *job, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); g_signal_handlers_disconnect_by_func (job, eom_job_close_save_cb, window); gtk_widget_destroy (GTK_WIDGET (window)); } static void close_confirmation_dialog_response_handler (EomCloseConfirmationDialog *dlg, gint response_id, EomWindow *window) { GList *selected_images; EomWindowPrivate *priv; priv = window->priv; switch (response_id) { case GTK_RESPONSE_YES: /* save selected images */ selected_images = eom_close_confirmation_dialog_get_selected_images (dlg); eom_close_confirmation_dialog_set_sensitive (dlg, FALSE); if (eom_window_save_images (window, selected_images)) { g_signal_connect (priv->save_job, "finished", G_CALLBACK (eom_job_close_save_cb), window); eom_job_queue_add_job (priv->save_job); } break; case GTK_RESPONSE_NO: /* dont save */ gtk_widget_destroy (GTK_WIDGET (window)); break; default: /* Cancel */ gtk_widget_destroy (GTK_WIDGET (dlg)); break; } } static gboolean eom_window_unsaved_images_confirm (EomWindow *window) { EomWindowPrivate *priv; gboolean disabled; GtkWidget *dialog; GList *list; EomImage *image; GtkTreeIter iter; priv = window->priv; disabled = g_settings_get_boolean(priv->ui_settings, EOM_CONF_UI_DISABLE_CLOSE_CONFIRMATION); disabled |= window->priv->save_disabled; if (disabled) { return FALSE; } list = NULL; if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (priv->store), &iter)) { do { gtk_tree_model_get (GTK_TREE_MODEL (priv->store), &iter, EOM_LIST_STORE_EOM_IMAGE, &image, -1); if (!image) continue; if (eom_image_is_modified (image)) { list = g_list_prepend (list, image); } } while (gtk_tree_model_iter_next (GTK_TREE_MODEL (priv->store), &iter)); } if (list) { list = g_list_reverse (list); dialog = eom_close_confirmation_dialog_new (GTK_WINDOW (window), list); g_list_free (list); g_signal_connect (dialog, "response", G_CALLBACK (close_confirmation_dialog_response_handler), window); gtk_window_set_destroy_with_parent (GTK_WINDOW (dialog), TRUE); gtk_widget_show (dialog); return TRUE; } return FALSE; } static void eom_window_cmd_close_window (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; if (priv->save_job != NULL) { eom_window_finish_saving (window); } if (!eom_window_unsaved_images_confirm (window)) { gtk_widget_destroy (GTK_WIDGET (user_data)); } } static void eom_window_cmd_preferences (GtkAction *action, gpointer user_data) { EomWindow *window; GObject *pref_dlg; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); pref_dlg = eom_preferences_dialog_get_instance (GTK_WINDOW (window)); eom_dialog_show (EOM_DIALOG (pref_dlg)); } #define EOM_TB_EDITOR_DLG_RESET_RESPONSE 128 static void eom_window_cmd_edit_toolbar_cb (GtkDialog *dialog, gint response, gpointer data) { EomWindow *window = EOM_WINDOW (data); if (response == EOM_TB_EDITOR_DLG_RESET_RESPONSE) { EggToolbarsModel *model; EggToolbarEditor *editor; editor = g_object_get_data (G_OBJECT (dialog), "EggToolbarEditor"); g_return_if_fail (editor != NULL); egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), FALSE); eom_application_reset_toolbars_model (EOM_APP); model = eom_application_get_toolbars_model (EOM_APP); egg_editable_toolbar_set_model (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), model); egg_toolbar_editor_set_model (editor, model); /* Toolbar would be uneditable now otherwise */ egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), TRUE); } else if (response == GTK_RESPONSE_HELP) { eom_util_show_help ("eom-toolbareditor", NULL); } else { egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), FALSE); eom_application_save_toolbars_model (EOM_APP); gtk_widget_destroy (GTK_WIDGET (dialog)); } } static void eom_window_cmd_edit_toolbar (GtkAction *action, gpointer *user_data) { EomWindow *window; GtkWidget *dialog; GtkWidget *editor; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); dialog = gtk_dialog_new_with_buttons (_("Toolbar Editor"), GTK_WINDOW (window), GTK_DIALOG_DESTROY_WITH_PARENT, _("_Reset to Default"), EOM_TB_EDITOR_DLG_RESET_RESPONSE, GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, GTK_STOCK_HELP, GTK_RESPONSE_HELP, NULL); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CLOSE); gtk_container_set_border_width (GTK_CONTAINER (dialog), 5); gtk_box_set_spacing (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), 2); gtk_window_set_default_size (GTK_WINDOW (dialog), 500, 400); editor = egg_toolbar_editor_new (window->priv->ui_mgr, eom_application_get_toolbars_model (EOM_APP)); gtk_container_set_border_width (GTK_CONTAINER (editor), 5); #if GTK_CHECK_VERSION (3, 0, 0) // Use as much vertical space as available gtk_widget_set_vexpand (GTK_WIDGET (editor), TRUE); #endif gtk_box_set_spacing (GTK_BOX (EGG_TOOLBAR_EDITOR (editor)), 5); gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), editor); egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), TRUE); g_object_set_data (G_OBJECT (dialog), "EggToolbarEditor", editor); g_signal_connect (dialog, "response", G_CALLBACK (eom_window_cmd_edit_toolbar_cb), window); gtk_widget_show_all (dialog); } static void eom_window_cmd_help (GtkAction *action, gpointer user_data) { EomWindow *window; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); eom_util_show_help (NULL, GTK_WINDOW (window)); } static void eom_window_cmd_about (GtkAction *action, gpointer user_data) { EomWindow *window; g_return_if_fail (EOM_IS_WINDOW (user_data)); static const char *authors[] = { "Perberos <perberos@gmail.com>", "Steve Zesch <stevezesch2@gmail.com>", "Stefano Karapetsas <stefano@karapetsas.com>", "", "Claudio Saavedra <csaavedra@igalia.com> (maintainer)", "Felix Riemann <friemann@gnome.org> (maintainer)", "", "Lucas Rocha <lucasr@gnome.org>", "Tim Gerla <tim+matebugs@gerla.net>", "Philip Van Hoof <pvanhoof@gnome.org>", "Paolo Borelli <pborelli@katamail.com>", "Jens Finke <jens@triq.net>", "Martin Baulig <martin@home-of-linux.org>", "Arik Devens <arik@gnome.org>", "Michael Meeks <mmeeks@gnu.org>", "Federico Mena-Quintero <federico@gnu.org>", "Lutz M\xc3\xbcller <urc8@rz.uni-karlsruhe.de>", NULL }; static const char *documenters[] = { "Eliot Landrum <eliot@landrum.cx>", "Federico Mena-Quintero <federico@gnu.org>", "Sun GNOME Documentation Team <gdocteam@sun.com>", NULL }; const char *translators; translators = _("translator-credits"); const char *license[] = { N_("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.\n"), N_("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.\n"), N_("You should have received a copy of the GNU General Public License " "along with this program; if not, write to the Free Software " "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.") }; char *license_trans; license_trans = g_strconcat (_(license[0]), "\n", _(license[1]), "\n", _(license[2]), "\n", NULL); window = EOM_WINDOW (user_data); mate_show_about_dialog (GTK_WINDOW (window), "program-name", _("Eye of MATE"), "version", VERSION, "copyright", "Copyright \xc2\xa9 2000-2010 Free Software Foundation, Inc.\n" "Copyright \xc2\xa9 2011 Perberos\n" "Copyright \xc2\xa9 2012-2014 MATE developers", "comments",_("The MATE image viewer."), "authors", authors, "documenters", documenters, "translator-credits", translators, "website", "http://www.mate-desktop.org/", "logo-icon-name", "eom", "wrap-license", TRUE, "license", license_trans, NULL); g_free (license_trans); } static void eom_window_cmd_show_hide_bar (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; gboolean visible; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; if (priv->mode != EOM_WINDOW_MODE_NORMAL && priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return; visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewToolbar") == 0) { g_object_set (G_OBJECT (priv->toolbar), "visible", visible, NULL); if (priv->mode == EOM_WINDOW_MODE_NORMAL) g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_TOOLBAR, visible); } else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewStatusbar") == 0) { g_object_set (G_OBJECT (priv->statusbar), "visible", visible, NULL); if (priv->mode == EOM_WINDOW_MODE_NORMAL) g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_STATUSBAR, visible); } else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewImageCollection") == 0) { if (visible) { /* Make sure the focus widget is realized to * avoid warnings on keypress events */ if (!gtk_widget_get_realized (window->priv->thumbview)) gtk_widget_realize (window->priv->thumbview); gtk_widget_show (priv->nav); gtk_widget_grab_focus (priv->thumbview); } else { /* Make sure the focus widget is realized to * avoid warnings on keypress events. * Don't do it during init phase or the view * will get a bogus allocation. */ if (!gtk_widget_get_realized (priv->view) && priv->status == EOM_WINDOW_STATUS_NORMAL) gtk_widget_realize (priv->view); gtk_widget_hide (priv->nav); if (gtk_widget_get_realized (priv->view)) gtk_widget_grab_focus (priv->view); } g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION, visible); } else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewSidebar") == 0) { if (visible) { gtk_widget_show (priv->sidebar); } else { gtk_widget_hide (priv->sidebar); } g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_SIDEBAR, visible); } } static void wallpaper_info_bar_response (GtkInfoBar *bar, gint response, EomWindow *window) { if (response == GTK_RESPONSE_YES) { GdkScreen *screen; screen = gtk_widget_get_screen (GTK_WIDGET (window)); mate_gdk_spawn_command_line_on_screen (screen, "mate-appearance-properties" " --show-page=background", NULL); } /* Close message area on every response */ eom_window_set_message_area (window, NULL); } static void eom_window_set_wallpaper (EomWindow *window, const gchar *filename, const gchar *visible_filename) { GtkWidget *info_bar; GtkWidget *image; GtkWidget *label; GtkWidget *hbox; gchar *markup; gchar *text; gchar *basename; GSettings *wallpaper_settings; wallpaper_settings = g_settings_new (EOM_CONF_BACKGROUND_SCHEMA); g_settings_set_string (wallpaper_settings, EOM_CONF_BACKGROUND_FILE, filename); g_object_unref (wallpaper_settings); /* I18N: When setting mnemonics for these strings, watch out to not clash with mnemonics from eom's menubar */ info_bar = gtk_info_bar_new_with_buttons (_("_Open Background Preferences"), GTK_RESPONSE_YES, C_("MessageArea","Hi_de"), GTK_RESPONSE_NO, NULL); gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), GTK_MESSAGE_QUESTION); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); label = gtk_label_new (NULL); if (!visible_filename) basename = g_path_get_basename (filename); /* The newline character is currently necessary due to a problem * with the automatic line break. */ text = g_strdup_printf (_("The image \"%s\" has been set as Desktop Background." "\nWould you like to modify its appearance?"), visible_filename ? visible_filename : basename); markup = g_markup_printf_escaped ("<b>%s</b>", text); gtk_label_set_markup (GTK_LABEL (label), markup); g_free (markup); g_free (text); if (!visible_filename) g_free (basename); hbox = gtk_hbox_new (FALSE, 8); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0); #if GTK_CHECK_VERSION (3, 14, 0) gtk_widget_set_valign (image, GTK_ALIGN_START); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_widget_set_halign (label, GTK_ALIGN_START); #else gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); #endif gtk_box_pack_start (GTK_BOX (gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar))), hbox, TRUE, TRUE, 0); gtk_widget_show_all (hbox); gtk_widget_show (info_bar); eom_window_set_message_area (window, info_bar); gtk_info_bar_set_default_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_YES); g_signal_connect (info_bar, "response", G_CALLBACK (wallpaper_info_bar_response), window); } static void eom_job_save_cb (EomJobSave *job, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); GtkAction *action_save; g_signal_handlers_disconnect_by_func (job, eom_job_save_cb, window); g_signal_handlers_disconnect_by_func (job, eom_job_save_progress_cb, window); g_object_unref (window->priv->save_job); window->priv->save_job = NULL; update_status_bar (window); action_save = gtk_action_group_get_action (window->priv->actions_image, "ImageSave"); gtk_action_set_sensitive (action_save, FALSE); } static void eom_job_copy_cb (EomJobCopy *job, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); gchar *filepath, *basename, *filename, *extension; GtkAction *action; GFile *source_file, *dest_file; /* Create source GFile */ basename = g_file_get_basename (job->images->data); filepath = g_build_filename (job->dest, basename, NULL); source_file = g_file_new_for_path (filepath); g_free (filepath); /* Create destination GFile */ extension = eom_util_filename_get_extension (basename); filename = g_strdup_printf ("%s.%s", EOM_WALLPAPER_FILENAME, extension); filepath = g_build_filename (job->dest, filename, NULL); dest_file = g_file_new_for_path (filepath); g_free (filename); g_free (extension); /* Move the file */ g_file_move (source_file, dest_file, G_FILE_COPY_OVERWRITE, NULL, NULL, NULL, NULL); /* Set the wallpaper */ eom_window_set_wallpaper (window, filepath, basename); g_free (basename); g_free (filepath); gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar), window->priv->copy_file_cid); action = gtk_action_group_get_action (window->priv->actions_image, "ImageSetAsWallpaper"); gtk_action_set_sensitive (action, TRUE); window->priv->copy_job = NULL; g_object_unref (source_file); g_object_unref (dest_file); g_object_unref (G_OBJECT (job->images->data)); g_list_free (job->images); g_object_unref (job); } static gboolean eom_window_save_images (EomWindow *window, GList *images) { EomWindowPrivate *priv; priv = window->priv; if (window->priv->save_job != NULL) return FALSE; priv->save_job = eom_job_save_new (images); g_signal_connect (priv->save_job, "finished", G_CALLBACK (eom_job_save_cb), window); g_signal_connect (priv->save_job, "progress", G_CALLBACK (eom_job_save_progress_cb), window); return TRUE; } static void eom_window_cmd_save (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; GList *images; window = EOM_WINDOW (user_data); priv = window->priv; if (window->priv->save_job != NULL) return; images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); if (eom_window_save_images (window, images)) { eom_job_queue_add_job (priv->save_job); } } static GFile* eom_window_retrieve_save_as_file (EomWindow *window, EomImage *image) { GtkWidget *dialog; GFile *save_file = NULL; GFile *last_dest_folder; gint response; g_assert (image != NULL); dialog = eom_file_chooser_new (GTK_FILE_CHOOSER_ACTION_SAVE); last_dest_folder = window->priv->last_save_as_folder; if (last_dest_folder && g_file_query_exists (last_dest_folder, NULL)) { gtk_file_chooser_set_current_folder_file (GTK_FILE_CHOOSER (dialog), last_dest_folder, NULL); gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), eom_image_get_caption (image)); } else { GFile *image_file; image_file = eom_image_get_file (image); /* Setting the file will also navigate to its parent folder */ gtk_file_chooser_set_file (GTK_FILE_CHOOSER (dialog), image_file, NULL); g_object_unref (image_file); } response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_hide (dialog); if (response == GTK_RESPONSE_OK) { save_file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog)); if (window->priv->last_save_as_folder) g_object_unref (window->priv->last_save_as_folder); window->priv->last_save_as_folder = g_file_get_parent (save_file); } gtk_widget_destroy (dialog); return save_file; } static void eom_window_cmd_save_as (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; GList *images; guint n_images; window = EOM_WINDOW (user_data); priv = window->priv; if (window->priv->save_job != NULL) return; images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); n_images = g_list_length (images); if (n_images == 1) { GFile *file; file = eom_window_retrieve_save_as_file (window, images->data); if (!file) { g_list_free (images); return; } priv->save_job = eom_job_save_as_new (images, NULL, file); g_object_unref (file); } else if (n_images > 1) { GFile *base_file; GtkWidget *dialog; gchar *basedir; EomURIConverter *converter; basedir = g_get_current_dir (); base_file = g_file_new_for_path (basedir); g_free (basedir); dialog = eom_save_as_dialog_new (GTK_WINDOW (window), images, base_file); gtk_widget_show_all (dialog); if (gtk_dialog_run (GTK_DIALOG (dialog)) != GTK_RESPONSE_OK) { g_object_unref (base_file); g_list_free (images); gtk_widget_destroy (dialog); return; } converter = eom_save_as_dialog_get_converter (dialog); g_assert (converter != NULL); priv->save_job = eom_job_save_as_new (images, converter, NULL); gtk_widget_destroy (dialog); g_object_unref (converter); g_object_unref (base_file); } else { /* n_images = 0 -- No Image selected */ return; } g_signal_connect (priv->save_job, "finished", G_CALLBACK (eom_job_save_cb), window); g_signal_connect (priv->save_job, "progress", G_CALLBACK (eom_job_save_progress_cb), window); eom_job_queue_add_job (priv->save_job); } static void eom_window_cmd_print (GtkAction *action, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); eom_window_print (window); } static void eom_window_cmd_properties (GtkAction *action, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); EomWindowPrivate *priv; GtkAction *next_image_action, *previous_image_action; priv = window->priv; next_image_action = gtk_action_group_get_action (priv->actions_collection, "GoNext"); previous_image_action = gtk_action_group_get_action (priv->actions_collection, "GoPrevious"); if (window->priv->properties_dlg == NULL) { window->priv->properties_dlg = eom_properties_dialog_new (GTK_WINDOW (window), EOM_THUMB_VIEW (priv->thumbview), next_image_action, previous_image_action); eom_properties_dialog_update (EOM_PROPERTIES_DIALOG (priv->properties_dlg), priv->image); g_settings_bind (priv->ui_settings, EOM_CONF_UI_PROPSDIALOG_NETBOOK_MODE, priv->properties_dlg, "netbook-mode", G_SETTINGS_BIND_GET); } eom_dialog_show (EOM_DIALOG (window->priv->properties_dlg)); } static void eom_window_cmd_undo (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), NULL); } static void eom_window_cmd_flip_horizontal (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_flip_new (EOM_TRANSFORM_FLIP_HORIZONTAL)); } static void eom_window_cmd_flip_vertical (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_flip_new (EOM_TRANSFORM_FLIP_VERTICAL)); } static void eom_window_cmd_rotate_90 (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_rotate_new (90)); } static void eom_window_cmd_rotate_270 (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_rotate_new (270)); } static void eom_window_cmd_wallpaper (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; EomImage *image; GFile *file; char *filename = NULL; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; /* If currently copying an image to set it as wallpaper, return. */ if (priv->copy_job != NULL) return; image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); g_return_if_fail (EOM_IS_IMAGE (image)); file = eom_image_get_file (image); filename = g_file_get_path (file); /* Currently only local files can be set as wallpaper */ if (filename == NULL || !eom_util_file_is_persistent (file)) { GList *files = NULL; GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_image, "ImageSetAsWallpaper"); gtk_action_set_sensitive (action, FALSE); priv->copy_file_cid = gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar), "copy_file_cid"); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->copy_file_cid, _("Saving image locally…")); files = g_list_append (files, eom_image_get_file (image)); priv->copy_job = eom_job_copy_new (files, g_get_user_data_dir ()); g_signal_connect (priv->copy_job, "finished", G_CALLBACK (eom_job_copy_cb), window); g_signal_connect (priv->copy_job, "progress", G_CALLBACK (eom_job_progress_cb), window); eom_job_queue_add_job (priv->copy_job); g_object_unref (file); g_free (filename); return; } g_object_unref (file); eom_window_set_wallpaper (window, filename, NULL); g_free (filename); } static gboolean eom_window_all_images_trasheable (GList *images) { GFile *file; GFileInfo *file_info; GList *iter; EomImage *image; gboolean can_trash = TRUE; for (iter = images; iter != NULL; iter = g_list_next (iter)) { image = (EomImage *) iter->data; file = eom_image_get_file (image); file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH, 0, NULL, NULL); can_trash = g_file_info_get_attribute_boolean (file_info, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH); g_object_unref (file_info); g_object_unref (file); if (can_trash == FALSE) break; } return can_trash; } static int show_move_to_trash_confirm_dialog (EomWindow *window, GList *images, gboolean can_trash) { GtkWidget *dlg; char *prompt; int response; int n_images; EomImage *image; static gboolean dontaskagain = FALSE; gboolean neverask = FALSE; GtkWidget* dontask_cbutton = NULL; /* Check if the user never wants to be bugged. */ neverask = g_settings_get_boolean (window->priv->ui_settings, EOM_CONF_UI_DISABLE_TRASH_CONFIRMATION); /* Assume agreement, if the user doesn't want to be * asked and the trash is available */ if (can_trash && (dontaskagain || neverask)) return GTK_RESPONSE_OK; n_images = g_list_length (images); if (n_images == 1) { image = EOM_IMAGE (images->data); if (can_trash) { prompt = g_strdup_printf (_("Are you sure you want to move\n\"%s\" to the trash?"), eom_image_get_caption (image)); } else { prompt = g_strdup_printf (_("A trash for \"%s\" couldn't be found. Do you want to remove " "this image permanently?"), eom_image_get_caption (image)); } } else { if (can_trash) { prompt = g_strdup_printf (ngettext("Are you sure you want to move\n" "the selected image to the trash?", "Are you sure you want to move\n" "the %d selected images to the trash?", n_images), n_images); } else { prompt = g_strdup (_("Some of the selected images can't be moved to the trash " "and will be removed permanently. Are you sure you want " "to proceed?")); } } dlg = gtk_message_dialog_new_with_markup (GTK_WINDOW (window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE, "<span weight=\"bold\" size=\"larger\">%s</span>", prompt); g_free (prompt); gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL); if (can_trash) { gtk_dialog_add_button (GTK_DIALOG (dlg), _("Move to _Trash"), GTK_RESPONSE_OK); dontask_cbutton = gtk_check_button_new_with_mnemonic (_("_Do not ask again during this session")); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (dontask_cbutton), FALSE); gtk_box_pack_end (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dlg))), dontask_cbutton, TRUE, TRUE, 0); } else { if (n_images == 1) { gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_DELETE, GTK_RESPONSE_OK); } else { gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_YES, GTK_RESPONSE_OK); } } gtk_dialog_set_default_response (GTK_DIALOG (dlg), GTK_RESPONSE_OK); gtk_window_set_title (GTK_WINDOW (dlg), ""); gtk_widget_show_all (dlg); response = gtk_dialog_run (GTK_DIALOG (dlg)); /* Only update the property if the user has accepted */ if (can_trash && response == GTK_RESPONSE_OK) dontaskagain = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (dontask_cbutton)); /* The checkbutton is destroyed together with the dialog */ gtk_widget_destroy (dlg); return response; } static gboolean move_to_trash_real (EomImage *image, GError **error) { GFile *file; GFileInfo *file_info; gboolean can_trash, result; g_return_val_if_fail (EOM_IS_IMAGE (image), FALSE); file = eom_image_get_file (image); file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH, 0, NULL, NULL); if (file_info == NULL) { g_set_error (error, EOM_WINDOW_ERROR, EOM_WINDOW_ERROR_TRASH_NOT_FOUND, _("Couldn't access trash.")); return FALSE; } can_trash = g_file_info_get_attribute_boolean (file_info, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH); g_object_unref (file_info); if (can_trash) { result = g_file_trash (file, NULL, NULL); if (result == FALSE) { g_set_error (error, EOM_WINDOW_ERROR, EOM_WINDOW_ERROR_TRASH_NOT_FOUND, _("Couldn't access trash.")); } } else { result = g_file_delete (file, NULL, NULL); if (result == FALSE) { g_set_error (error, EOM_WINDOW_ERROR, EOM_WINDOW_ERROR_IO, _("Couldn't delete file")); } } g_object_unref (file); return result; } static void eom_window_cmd_copy_image (GtkAction *action, gpointer user_data) { GtkClipboard *clipboard; EomWindow *window; EomWindowPrivate *priv; EomImage *image; EomClipboardHandler *cbhandler; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); g_return_if_fail (EOM_IS_IMAGE (image)); clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD); cbhandler = eom_clipboard_handler_new (image); // cbhandler will self-destruct when it's not needed anymore eom_clipboard_handler_copy_to_clipboard (cbhandler, clipboard); } static void eom_window_cmd_move_to_trash (GtkAction *action, gpointer user_data) { GList *images; GList *it; EomWindowPrivate *priv; EomListStore *list; int pos; EomImage *img; EomWindow *window; int response; int n_images; gboolean success; gboolean can_trash; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; list = priv->store; n_images = eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview)); if (n_images < 1) return; /* save position of selected image after the deletion */ images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); g_assert (images != NULL); /* HACK: eom_list_store_get_n_selected return list in reverse order */ images = g_list_reverse (images); can_trash = eom_window_all_images_trasheable (images); if (g_ascii_strcasecmp (gtk_action_get_name (action), "Delete") == 0 || can_trash == FALSE) { response = show_move_to_trash_confirm_dialog (window, images, can_trash); if (response != GTK_RESPONSE_OK) return; } pos = eom_list_store_get_pos_by_image (list, EOM_IMAGE (images->data)); /* FIXME: make a nice progress dialog */ /* Do the work actually. First try to delete the image from the disk. If this * is successfull, remove it from the screen. Otherwise show error dialog. */ for (it = images; it != NULL; it = it->next) { GError *error = NULL; EomImage *image; image = EOM_IMAGE (it->data); success = move_to_trash_real (image, &error); if (success) { eom_list_store_remove_image (list, image); } else { char *header; GtkWidget *dlg; header = g_strdup_printf (_("Error on deleting image %s"), eom_image_get_caption (image)); dlg = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", header); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dlg), "%s", error->message); gtk_dialog_run (GTK_DIALOG (dlg)); gtk_widget_destroy (dlg); g_free (header); } } /* free list */ g_list_foreach (images, (GFunc) g_object_unref, NULL); g_list_free (images); /* select image at previously saved position */ pos = MIN (pos, eom_list_store_length (list) - 1); if (pos >= 0) { img = eom_list_store_get_image_by_pos (list, pos); eom_thumb_view_set_current_image (EOM_THUMB_VIEW (priv->thumbview), img, TRUE); if (img != NULL) { g_object_unref (img); } } } static void eom_window_cmd_fullscreen (GtkAction *action, gpointer user_data) { EomWindow *window; gboolean fullscreen; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (user_data); fullscreen = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (fullscreen) { eom_window_run_fullscreen (window, FALSE); } else { eom_window_stop_fullscreen (window, FALSE); } } static void eom_window_cmd_slideshow (GtkAction *action, gpointer user_data) { EomWindow *window; gboolean slideshow; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (user_data); slideshow = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (slideshow) { eom_window_run_fullscreen (window, TRUE); } else { eom_window_stop_fullscreen (window, TRUE); } } static void eom_window_cmd_pause_slideshow (GtkAction *action, gpointer user_data) { EomWindow *window; gboolean slideshow; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (user_data); slideshow = window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW; if (!slideshow && window->priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return; eom_window_run_fullscreen (window, !slideshow); } static void eom_window_cmd_zoom_in (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_zoom_in (EOM_SCROLL_VIEW (priv->view), FALSE); } } static void eom_window_cmd_zoom_out (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_zoom_out (EOM_SCROLL_VIEW (priv->view), FALSE); } } static void eom_window_cmd_zoom_normal (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_set_zoom (EOM_SCROLL_VIEW (priv->view), 1.0); } } static void eom_window_cmd_zoom_fit (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_zoom_fit (EOM_SCROLL_VIEW (priv->view)); } } static void eom_window_cmd_go_prev (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_LEFT); } static void eom_window_cmd_go_next (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RIGHT); } static void eom_window_cmd_go_first (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_FIRST); } static void eom_window_cmd_go_last (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_LAST); } static void eom_window_cmd_go_random (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RANDOM); } static const GtkActionEntry action_entries_window[] = { { "Image", NULL, N_("_Image") }, { "Edit", NULL, N_("_Edit") }, { "View", NULL, N_("_View") }, { "Go", NULL, N_("_Go") }, { "Tools", NULL, N_("_Tools") }, { "Help", NULL, N_("_Help") }, { "ImageOpen", GTK_STOCK_OPEN, N_("_Open…"), "<control>O", N_("Open a file"), G_CALLBACK (eom_window_cmd_file_open) }, { "ImageClose", GTK_STOCK_CLOSE, N_("_Close"), "<control>W", N_("Close window"), G_CALLBACK (eom_window_cmd_close_window) }, { "EditToolbar", NULL, N_("T_oolbar"), NULL, N_("Edit the application toolbar"), G_CALLBACK (eom_window_cmd_edit_toolbar) }, { "EditPreferences", GTK_STOCK_PREFERENCES, N_("Prefere_nces"), NULL, N_("Preferences for Eye of MATE"), G_CALLBACK (eom_window_cmd_preferences) }, { "HelpManual", GTK_STOCK_HELP, N_("_Contents"), "F1", N_("Help on this application"), G_CALLBACK (eom_window_cmd_help) }, { "HelpAbout", GTK_STOCK_ABOUT, N_("_About"), NULL, N_("About this application"), G_CALLBACK (eom_window_cmd_about) } }; static const GtkToggleActionEntry toggle_entries_window[] = { { "ViewToolbar", NULL, N_("_Toolbar"), NULL, N_("Changes the visibility of the toolbar in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, { "ViewStatusbar", NULL, N_("_Statusbar"), NULL, N_("Changes the visibility of the statusbar in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, { "ViewImageCollection", "eom-image-collection", N_("_Image Collection"), "F9", N_("Changes the visibility of the image collection pane in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, { "ViewSidebar", NULL, N_("Side _Pane"), "<control>F9", N_("Changes the visibility of the side pane in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, }; static const GtkActionEntry action_entries_image[] = { { "ImageSave", GTK_STOCK_SAVE, N_("_Save"), "<control>s", N_("Save changes in currently selected images"), G_CALLBACK (eom_window_cmd_save) }, { "ImageOpenWith", NULL, N_("Open _with"), NULL, N_("Open the selected image with a different application"), NULL}, { "ImageSaveAs", GTK_STOCK_SAVE_AS, N_("Save _As…"), "<control><shift>s", N_("Save the selected images with a different name"), G_CALLBACK (eom_window_cmd_save_as) }, { "ImagePrint", GTK_STOCK_PRINT, N_("_Print…"), "<control>p", N_("Print the selected image"), G_CALLBACK (eom_window_cmd_print) }, { "ImageProperties", GTK_STOCK_PROPERTIES, N_("Prope_rties"), "<alt>Return", N_("Show the properties and metadata of the selected image"), G_CALLBACK (eom_window_cmd_properties) }, { "EditUndo", GTK_STOCK_UNDO, N_("_Undo"), "<control>z", N_("Undo the last change in the image"), G_CALLBACK (eom_window_cmd_undo) }, { "EditFlipHorizontal", "object-flip-horizontal", N_("Flip _Horizontal"), NULL, N_("Mirror the image horizontally"), G_CALLBACK (eom_window_cmd_flip_horizontal) }, { "EditFlipVertical", "object-flip-vertical", N_("Flip _Vertical"), NULL, N_("Mirror the image vertically"), G_CALLBACK (eom_window_cmd_flip_vertical) }, { "EditRotate90", "object-rotate-right", N_("_Rotate Clockwise"), "<control>r", N_("Rotate the image 90 degrees to the right"), G_CALLBACK (eom_window_cmd_rotate_90) }, { "EditRotate270", "object-rotate-left", N_("Rotate Counterc_lockwise"), "<ctrl><shift>r", N_("Rotate the image 90 degrees to the left"), G_CALLBACK (eom_window_cmd_rotate_270) }, { "ImageSetAsWallpaper", NULL, N_("Set as _Desktop Background"), "<control>F8", N_("Set the selected image as the desktop background"), G_CALLBACK (eom_window_cmd_wallpaper) }, { "EditMoveToTrash", "user-trash", N_("Move to _Trash"), NULL, N_("Move the selected image to the trash folder"), G_CALLBACK (eom_window_cmd_move_to_trash) }, { "EditCopyImage", "edit-copy", N_("_Copy"), "<control>C", N_("Copy the selected image to the clipboard"), G_CALLBACK (eom_window_cmd_copy_image) }, { "ViewZoomIn", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>plus", N_("Enlarge the image"), G_CALLBACK (eom_window_cmd_zoom_in) }, { "ViewZoomOut", GTK_STOCK_ZOOM_OUT, N_("Zoom _Out"), "<control>minus", N_("Shrink the image"), G_CALLBACK (eom_window_cmd_zoom_out) }, { "ViewZoomNormal", GTK_STOCK_ZOOM_100, N_("_Normal Size"), "<control>0", N_("Show the image at its normal size"), G_CALLBACK (eom_window_cmd_zoom_normal) }, { "ViewZoomFit", GTK_STOCK_ZOOM_FIT, N_("_Best Fit"), "F", N_("Fit the image to the window"), G_CALLBACK (eom_window_cmd_zoom_fit) }, { "ControlEqual", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>equal", N_("Enlarge the image"), G_CALLBACK (eom_window_cmd_zoom_in) }, { "ControlKpAdd", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>KP_Add", N_("Shrink the image"), G_CALLBACK (eom_window_cmd_zoom_in) }, { "ControlKpSub", GTK_STOCK_ZOOM_OUT, N_("Zoom _Out"), "<control>KP_Subtract", N_("Shrink the image"), G_CALLBACK (eom_window_cmd_zoom_out) }, { "Delete", NULL, N_("Move to _Trash"), "Delete", NULL, G_CALLBACK (eom_window_cmd_move_to_trash) }, }; static const GtkToggleActionEntry toggle_entries_image[] = { { "ViewFullscreen", GTK_STOCK_FULLSCREEN, N_("_Fullscreen"), "F11", N_("Show the current image in fullscreen mode"), G_CALLBACK (eom_window_cmd_fullscreen), FALSE }, { "PauseSlideshow", "media-playback-pause", N_("Pause Slideshow"), NULL, N_("Pause or resume the slideshow"), G_CALLBACK (eom_window_cmd_pause_slideshow), FALSE }, }; static const GtkActionEntry action_entries_collection[] = { { "GoPrevious", GTK_STOCK_GO_BACK, N_("_Previous Image"), "<Alt>Left", N_("Go to the previous image of the collection"), G_CALLBACK (eom_window_cmd_go_prev) }, { "GoNext", GTK_STOCK_GO_FORWARD, N_("_Next Image"), "<Alt>Right", N_("Go to the next image of the collection"), G_CALLBACK (eom_window_cmd_go_next) }, { "GoFirst", GTK_STOCK_GOTO_FIRST, N_("_First Image"), "<Alt>Home", N_("Go to the first image of the collection"), G_CALLBACK (eom_window_cmd_go_first) }, { "GoLast", GTK_STOCK_GOTO_LAST, N_("_Last Image"), "<Alt>End", N_("Go to the last image of the collection"), G_CALLBACK (eom_window_cmd_go_last) }, { "GoRandom", NULL, N_("_Random Image"), "<control>M", N_("Go to a random image of the collection"), G_CALLBACK (eom_window_cmd_go_random) }, { "BackSpace", NULL, N_("_Previous Image"), "BackSpace", NULL, G_CALLBACK (eom_window_cmd_go_prev) }, { "Home", NULL, N_("_First Image"), "Home", NULL, G_CALLBACK (eom_window_cmd_go_first) }, { "End", NULL, N_("_Last Image"), "End", NULL, G_CALLBACK (eom_window_cmd_go_last) }, }; static const GtkToggleActionEntry toggle_entries_collection[] = { { "ViewSlideshow", "slideshow-play", N_("S_lideshow"), "F5", N_("Start a slideshow view of the images"), G_CALLBACK (eom_window_cmd_slideshow), FALSE }, }; static void menu_item_select_cb (GtkMenuItem *proxy, EomWindow *window) { GtkAction *action; char *message; action = gtk_activatable_get_related_action (GTK_ACTIVATABLE (proxy)); g_return_if_fail (action != NULL); g_object_get (G_OBJECT (action), "tooltip", &message, NULL); if (message) { gtk_statusbar_push (GTK_STATUSBAR (window->priv->statusbar), window->priv->tip_message_cid, message); g_free (message); } } static void menu_item_deselect_cb (GtkMenuItem *proxy, EomWindow *window) { gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar), window->priv->tip_message_cid); } static void connect_proxy_cb (GtkUIManager *manager, GtkAction *action, GtkWidget *proxy, EomWindow *window) { if (GTK_IS_MENU_ITEM (proxy)) { g_signal_connect (proxy, "select", G_CALLBACK (menu_item_select_cb), window); g_signal_connect (proxy, "deselect", G_CALLBACK (menu_item_deselect_cb), window); } } static void disconnect_proxy_cb (GtkUIManager *manager, GtkAction *action, GtkWidget *proxy, EomWindow *window) { if (GTK_IS_MENU_ITEM (proxy)) { g_signal_handlers_disconnect_by_func (proxy, G_CALLBACK (menu_item_select_cb), window); g_signal_handlers_disconnect_by_func (proxy, G_CALLBACK (menu_item_deselect_cb), window); } } static void set_action_properties (GtkActionGroup *window_group, GtkActionGroup *image_group, GtkActionGroup *collection_group) { GtkAction *action; action = gtk_action_group_get_action (collection_group, "GoPrevious"); g_object_set (action, "short_label", _("Previous"), NULL); g_object_set (action, "is-important", TRUE, NULL); action = gtk_action_group_get_action (collection_group, "GoNext"); g_object_set (action, "short_label", _("Next"), NULL); g_object_set (action, "is-important", TRUE, NULL); action = gtk_action_group_get_action (image_group, "EditRotate90"); g_object_set (action, "short_label", _("Right"), NULL); action = gtk_action_group_get_action (image_group, "EditRotate270"); g_object_set (action, "short_label", _("Left"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomIn"); g_object_set (action, "short_label", _("In"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomOut"); g_object_set (action, "short_label", _("Out"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomNormal"); g_object_set (action, "short_label", _("Normal"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomFit"); g_object_set (action, "short_label", _("Fit"), NULL); action = gtk_action_group_get_action (window_group, "ViewImageCollection"); g_object_set (action, "short_label", _("Collection"), NULL); action = gtk_action_group_get_action (image_group, "EditMoveToTrash"); g_object_set (action, "short_label", C_("action (to trash)", "Trash"), NULL); } static gint sort_recents_mru (GtkRecentInfo *a, GtkRecentInfo *b) { gboolean has_eom_a, has_eom_b; /* We need to check this first as gtk_recent_info_get_application_info * will treat it as a non-fatal error when the GtkRecentInfo doesn't * have the application registered. */ has_eom_a = gtk_recent_info_has_application (a, EOM_RECENT_FILES_APP_NAME); has_eom_b = gtk_recent_info_has_application (b, EOM_RECENT_FILES_APP_NAME); if (has_eom_a && has_eom_b) { time_t time_a, time_b; /* These should not fail as we already checked that * the application is registered with the info objects */ gtk_recent_info_get_application_info (a, EOM_RECENT_FILES_APP_NAME, NULL, NULL, &time_a); gtk_recent_info_get_application_info (b, EOM_RECENT_FILES_APP_NAME, NULL, NULL, &time_b); return (time_b - time_a); } else if (has_eom_a) { return -1; } else if (has_eom_b) { return 1; } return 0; } static void eom_window_update_recent_files_menu (EomWindow *window) { EomWindowPrivate *priv; GList *actions = NULL, *li = NULL, *items = NULL; guint count_recent = 0; priv = window->priv; if (priv->recent_menu_id != 0) gtk_ui_manager_remove_ui (priv->ui_mgr, priv->recent_menu_id); actions = gtk_action_group_list_actions (priv->actions_recent); for (li = actions; li != NULL; li = li->next) { g_signal_handlers_disconnect_by_func (GTK_ACTION (li->data), G_CALLBACK(eom_window_open_recent_cb), window); gtk_action_group_remove_action (priv->actions_recent, GTK_ACTION (li->data)); } g_list_free (actions); priv->recent_menu_id = gtk_ui_manager_new_merge_id (priv->ui_mgr); items = gtk_recent_manager_get_items (gtk_recent_manager_get_default()); items = g_list_sort (items, (GCompareFunc) sort_recents_mru); for (li = items; li != NULL && count_recent < EOM_RECENT_FILES_LIMIT; li = li->next) { gchar *action_name; gchar *label; gchar *tip; gchar **display_name; gchar *label_filename; GtkAction *action; GtkRecentInfo *info = li->data; /* Sorting moves non-EOM files to the end of the list. * So no file of interest will follow if this test fails */ if (!gtk_recent_info_has_application (info, EOM_RECENT_FILES_APP_NAME)) break; count_recent++; action_name = g_strdup_printf ("recent-info-%d", count_recent); display_name = g_strsplit (gtk_recent_info_get_display_name (info), "_", -1); label_filename = g_strjoinv ("__", display_name); label = g_strdup_printf ("%s_%d. %s", (is_rtl ? "\xE2\x80\x8F" : ""), count_recent, label_filename); g_free (label_filename); g_strfreev (display_name); tip = gtk_recent_info_get_uri_display (info); /* This is a workaround for a bug (#351945) regarding * gtk_recent_info_get_uri_display() and remote URIs. * mate_vfs_format_uri_for_display is sufficient here * since the password gets stripped when adding the * file to the recently used list. */ if (tip == NULL) tip = g_uri_unescape_string (gtk_recent_info_get_uri (info), NULL); action = gtk_action_new (action_name, label, tip, NULL); gtk_action_set_always_show_image (action, TRUE); g_object_set_data_full (G_OBJECT (action), "gtk-recent-info", gtk_recent_info_ref (info), (GDestroyNotify) gtk_recent_info_unref); g_object_set (G_OBJECT (action), "icon-name", "image-x-generic", NULL); g_signal_connect (action, "activate", G_CALLBACK (eom_window_open_recent_cb), window); gtk_action_group_add_action (priv->actions_recent, action); g_object_unref (action); gtk_ui_manager_add_ui (priv->ui_mgr, priv->recent_menu_id, "/MainMenu/Image/RecentDocuments", action_name, action_name, GTK_UI_MANAGER_AUTO, FALSE); g_free (action_name); g_free (label); g_free (tip); } g_list_foreach (items, (GFunc) gtk_recent_info_unref, NULL); g_list_free (items); } static void eom_window_recent_manager_changed_cb (GtkRecentManager *manager, EomWindow *window) { eom_window_update_recent_files_menu (window); } static void eom_window_drag_data_received (GtkWidget *widget, GdkDragContext *context, gint x, gint y, GtkSelectionData *selection_data, guint info, guint time) { GSList *file_list; EomWindow *window; GdkAtom target; GtkWidget *src; target = gtk_selection_data_get_target (selection_data); if (!gtk_targets_include_uri (&target, 1)) return; /* if the request is from another process this will return NULL */ src = gtk_drag_get_source_widget (context); /* if the drag request originates from the current eom instance, ignore the request if the source window is the same as the dest window */ if (src && gtk_widget_get_toplevel (src) == gtk_widget_get_toplevel (widget)) { gdk_drag_status (context, 0, time); return; } if (gdk_drag_context_get_suggested_action (context) == GDK_ACTION_COPY) { window = EOM_WINDOW (widget); file_list = eom_util_parse_uri_string_list_to_file_list ((const gchar *) gtk_selection_data_get_data (selection_data)); eom_window_open_file_list (window, file_list); } } static void eom_window_set_drag_dest (EomWindow *window) { gtk_drag_dest_set (GTK_WIDGET (window), GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_DROP, NULL, 0, GDK_ACTION_COPY | GDK_ACTION_ASK); gtk_drag_dest_add_uri_targets (GTK_WIDGET (window)); } static void eom_window_sidebar_visibility_changed (GtkWidget *widget, EomWindow *window) { GtkAction *action; gboolean visible; visible = gtk_widget_get_visible (window->priv->sidebar); g_settings_set_boolean (window->priv->ui_settings, EOM_CONF_UI_SIDEBAR, visible); action = gtk_action_group_get_action (window->priv->actions_window, "ViewSidebar"); if (gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)) != visible) gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); /* Focus the image */ if (!visible && window->priv->image != NULL) gtk_widget_grab_focus (window->priv->view); } static void eom_window_sidebar_page_added (EomSidebar *sidebar, GtkWidget *main_widget, EomWindow *window) { if (eom_sidebar_get_n_pages (sidebar) == 1) { GtkAction *action; gboolean show; action = gtk_action_group_get_action (window->priv->actions_window, "ViewSidebar"); gtk_action_set_sensitive (action, TRUE); show = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (show) gtk_widget_show (GTK_WIDGET (sidebar)); } } static void eom_window_sidebar_page_removed (EomSidebar *sidebar, GtkWidget *main_widget, EomWindow *window) { if (eom_sidebar_is_empty (sidebar)) { GtkAction *action; gtk_widget_hide (GTK_WIDGET (sidebar)); action = gtk_action_group_get_action (window->priv->actions_window, "ViewSidebar"); gtk_action_set_sensitive (action, FALSE); } } static void eom_window_finish_saving (EomWindow *window) { EomWindowPrivate *priv = window->priv; gtk_widget_set_sensitive (GTK_WIDGET (window), FALSE); do { gtk_main_iteration (); } while (priv->save_job != NULL); } static GAppInfo * get_appinfo_for_editor (EomWindow *window) { /* We want this function to always return the same thing, not * just for performance reasons, but because if someone edits * GConf while eom is running, the application could get into an * inconsistent state. If the editor exists once, it gets added * to the "available" list of the EggToolbarsModel (for which * there is no API to remove it). If later the editor no longer * existed when constructing a new window, we'd be unable to * construct a GtkAction for the editor for that window, causing * assertion failures when viewing the "Edit Toolbars" dialog * (item is available, but can't find the GtkAction for it). * * By ensuring we keep the GAppInfo around, we avoid the * possibility of that situation occuring. */ static GDesktopAppInfo *app_info = NULL; static gboolean initialised; if (!initialised) { gchar *editor; editor = g_settings_get_string (window->priv->ui_settings, EOM_CONF_UI_EXTERNAL_EDITOR); if (editor != NULL) { app_info = g_desktop_app_info_new (editor); } initialised = TRUE; g_free (editor); } return (GAppInfo *) app_info; } static void eom_window_open_editor (GtkAction *action, EomWindow *window) { GdkAppLaunchContext *context; GAppInfo *app_info; GList files; app_info = get_appinfo_for_editor (window); if (app_info == NULL) return; #if GTK_CHECK_VERSION (3, 0, 0) context = gdk_display_get_app_launch_context ( gtk_widget_get_display (GTK_WIDGET (window))); #else context = gdk_app_launch_context_new (); #endif gdk_app_launch_context_set_screen (context, gtk_widget_get_screen (GTK_WIDGET (window))); gdk_app_launch_context_set_icon (context, g_app_info_get_icon (app_info)); gdk_app_launch_context_set_timestamp (context, gtk_get_current_event_time ()); { GList f = { eom_image_get_file (window->priv->image) }; files = f; } g_app_info_launch (app_info, &files, G_APP_LAUNCH_CONTEXT (context), NULL); g_object_unref (files.data); g_object_unref (context); } static void eom_window_add_open_editor_action (EomWindow *window) { EggToolbarsModel *model; GAppInfo *app_info; GtkAction *action; gchar *tooltip; app_info = get_appinfo_for_editor (window); if (app_info == NULL) return; model = eom_application_get_toolbars_model (EOM_APP); egg_toolbars_model_set_name_flags (model, "OpenEditor", EGG_TB_MODEL_NAME_KNOWN); tooltip = g_strdup_printf (_("Edit the current image using %s"), g_app_info_get_name (app_info)); action = gtk_action_new ("OpenEditor", _("Edit Image"), tooltip, NULL); gtk_action_set_gicon (action, g_app_info_get_icon (app_info)); gtk_action_set_is_important (action, TRUE); g_signal_connect (action, "activate", G_CALLBACK (eom_window_open_editor), window); gtk_action_group_add_action (window->priv->actions_image, action); g_object_unref (action); g_free (tooltip); } static void eom_window_construct_ui (EomWindow *window) { EomWindowPrivate *priv; GError *error = NULL; GtkWidget *menubar; GtkWidget *thumb_popup; GtkWidget *view_popup; GtkWidget *hpaned; GtkWidget *menuitem; g_return_if_fail (EOM_IS_WINDOW (window)); priv = window->priv; priv->box = gtk_vbox_new (FALSE, 0); gtk_container_add (GTK_CONTAINER (window), priv->box); gtk_widget_show (priv->box); priv->ui_mgr = gtk_ui_manager_new (); priv->actions_window = gtk_action_group_new ("MenuActionsWindow"); gtk_action_group_set_translation_domain (priv->actions_window, GETTEXT_PACKAGE); gtk_action_group_add_actions (priv->actions_window, action_entries_window, G_N_ELEMENTS (action_entries_window), window); gtk_action_group_add_toggle_actions (priv->actions_window, toggle_entries_window, G_N_ELEMENTS (toggle_entries_window), window); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_window, 0); priv->actions_image = gtk_action_group_new ("MenuActionsImage"); gtk_action_group_set_translation_domain (priv->actions_image, GETTEXT_PACKAGE); gtk_action_group_add_actions (priv->actions_image, action_entries_image, G_N_ELEMENTS (action_entries_image), window); eom_window_add_open_editor_action (window); gtk_action_group_add_toggle_actions (priv->actions_image, toggle_entries_image, G_N_ELEMENTS (toggle_entries_image), window); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_image, 0); priv->actions_collection = gtk_action_group_new ("MenuActionsCollection"); gtk_action_group_set_translation_domain (priv->actions_collection, GETTEXT_PACKAGE); gtk_action_group_add_actions (priv->actions_collection, action_entries_collection, G_N_ELEMENTS (action_entries_collection), window); gtk_action_group_add_toggle_actions (priv->actions_collection, toggle_entries_collection, G_N_ELEMENTS (toggle_entries_collection), window); set_action_properties (priv->actions_window, priv->actions_image, priv->actions_collection); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_collection, 0); if (!gtk_ui_manager_add_ui_from_file (priv->ui_mgr, EOM_DATA_DIR"/eom-ui.xml", &error)) { g_warning ("building menus failed: %s", error->message); g_error_free (error); } g_signal_connect (priv->ui_mgr, "connect_proxy", G_CALLBACK (connect_proxy_cb), window); g_signal_connect (priv->ui_mgr, "disconnect_proxy", G_CALLBACK (disconnect_proxy_cb), window); menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); gtk_box_pack_start (GTK_BOX (priv->box), menubar, FALSE, FALSE, 0); gtk_widget_show (menubar); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditFlipHorizontal"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditFlipVertical"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditRotate90"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditRotate270"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); priv->toolbar = GTK_WIDGET (g_object_new (EGG_TYPE_EDITABLE_TOOLBAR, "ui-manager", priv->ui_mgr, "model", eom_application_get_toolbars_model (EOM_APP), NULL)); #if GTK_CHECK_VERSION (3, 0, 2) gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (priv->toolbar)), GTK_STYLE_CLASS_PRIMARY_TOOLBAR); #endif egg_editable_toolbar_show (EGG_EDITABLE_TOOLBAR (priv->toolbar), "Toolbar"); gtk_box_pack_start (GTK_BOX (priv->box), priv->toolbar, FALSE, FALSE, 0); gtk_widget_show (priv->toolbar); gtk_window_add_accel_group (GTK_WINDOW (window), gtk_ui_manager_get_accel_group (priv->ui_mgr)); priv->actions_recent = gtk_action_group_new ("RecentFilesActions"); gtk_action_group_set_translation_domain (priv->actions_recent, GETTEXT_PACKAGE); g_signal_connect (gtk_recent_manager_get_default (), "changed", G_CALLBACK (eom_window_recent_manager_changed_cb), window); eom_window_update_recent_files_menu (window); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_recent, 0); priv->cbox = gtk_vbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (priv->box), priv->cbox, TRUE, TRUE, 0); gtk_widget_show (priv->cbox); priv->statusbar = eom_statusbar_new (); gtk_box_pack_end (GTK_BOX (priv->box), GTK_WIDGET (priv->statusbar), FALSE, FALSE, 0); gtk_widget_show (priv->statusbar); priv->image_info_message_cid = gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar), "image_info_message"); priv->tip_message_cid = gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar), "tip_message"); priv->layout = gtk_vbox_new (FALSE, 2); #if GTK_CHECK_VERSION (3, 2, 0) hpaned = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL); #else hpaned = gtk_hpaned_new (); #endif priv->sidebar = eom_sidebar_new (); /* The sidebar shouldn't be shown automatically on show_all(), but only when the user actually wants it. */ gtk_widget_set_no_show_all (priv->sidebar, TRUE); gtk_widget_set_size_request (priv->sidebar, 210, -1); g_signal_connect_after (priv->sidebar, "show", G_CALLBACK (eom_window_sidebar_visibility_changed), window); g_signal_connect_after (priv->sidebar, "hide", G_CALLBACK (eom_window_sidebar_visibility_changed), window); g_signal_connect_after (priv->sidebar, "page-added", G_CALLBACK (eom_window_sidebar_page_added), window); g_signal_connect_after (priv->sidebar, "page-removed", G_CALLBACK (eom_window_sidebar_page_removed), window); priv->view = eom_scroll_view_new (); gtk_widget_set_size_request (GTK_WIDGET (priv->view), 100, 100); g_signal_connect (G_OBJECT (priv->view), "zoom_changed", G_CALLBACK (view_zoom_changed_cb), window); g_settings_bind (priv->view_settings, EOM_CONF_VIEW_SCROLL_WHEEL_ZOOM, priv->view, "scrollwheel-zoom", G_SETTINGS_BIND_GET); g_settings_bind (priv->view_settings, EOM_CONF_VIEW_ZOOM_MULTIPLIER, priv->view, "zoom-multiplier", G_SETTINGS_BIND_GET); view_popup = gtk_ui_manager_get_widget (priv->ui_mgr, "/ViewPopup"); eom_scroll_view_set_popup (EOM_SCROLL_VIEW (priv->view), GTK_MENU (view_popup)); gtk_paned_pack1 (GTK_PANED (hpaned), priv->sidebar, FALSE, FALSE); gtk_paned_pack2 (GTK_PANED (hpaned), priv->view, TRUE, FALSE); gtk_widget_show_all (hpaned); gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); priv->thumbview = g_object_ref (eom_thumb_view_new ()); /* giving shape to the view */ gtk_icon_view_set_margin (GTK_ICON_VIEW (priv->thumbview), 4); gtk_icon_view_set_row_spacing (GTK_ICON_VIEW (priv->thumbview), 0); g_signal_connect (G_OBJECT (priv->thumbview), "selection_changed", G_CALLBACK (handle_image_selection_changed_cb), window); priv->nav = eom_thumb_nav_new (priv->thumbview, EOM_THUMB_NAV_MODE_ONE_ROW, g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_SCROLL_BUTTONS)); // Bind the scroll buttons to their GSettings key g_settings_bind (priv->ui_settings, EOM_CONF_UI_SCROLL_BUTTONS, priv->nav, "show-buttons", G_SETTINGS_BIND_GET); thumb_popup = gtk_ui_manager_get_widget (priv->ui_mgr, "/ThumbnailPopup"); eom_thumb_view_set_thumbnail_popup (EOM_THUMB_VIEW (priv->thumbview), GTK_MENU (thumb_popup)); gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); gtk_box_pack_end (GTK_BOX (priv->cbox), priv->layout, TRUE, TRUE, 0); eom_window_can_save_changed_cb (priv->lockdown_settings, EOM_CONF_LOCKDOWN_CAN_SAVE, window); g_settings_bind (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION_POSITION, window, "collection-position", G_SETTINGS_BIND_GET); g_settings_bind (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION_RESIZABLE, window, "collection-resizable", G_SETTINGS_BIND_GET); if ((priv->flags & EOM_STARTUP_FULLSCREEN) || (priv->flags & EOM_STARTUP_SLIDE_SHOW)) { eom_window_run_fullscreen (window, (priv->flags & EOM_STARTUP_SLIDE_SHOW)); } else { priv->mode = EOM_WINDOW_MODE_NORMAL; update_ui_visibility (window); } eom_window_set_drag_dest (window); } static void eom_window_init (EomWindow *window) { GdkGeometry hints; GdkScreen *screen; EomWindowPrivate *priv; eom_debug (DEBUG_WINDOW); hints.min_width = EOM_WINDOW_MIN_WIDTH; hints.min_height = EOM_WINDOW_MIN_HEIGHT; screen = gtk_widget_get_screen (GTK_WIDGET (window)); priv = window->priv = EOM_WINDOW_GET_PRIVATE (window); priv->view_settings = g_settings_new (EOM_CONF_VIEW); priv->ui_settings = g_settings_new (EOM_CONF_UI); priv->fullscreen_settings = g_settings_new (EOM_CONF_FULLSCREEN); priv->lockdown_settings = g_settings_new (EOM_CONF_LOCKDOWN_SCHEMA); g_signal_connect (priv->lockdown_settings, "changed::" EOM_CONF_LOCKDOWN_CAN_SAVE, G_CALLBACK (eom_window_can_save_changed_cb), window); window->priv->store = NULL; window->priv->image = NULL; window->priv->fullscreen_popup = NULL; window->priv->fullscreen_timeout_source = NULL; window->priv->slideshow_random = FALSE; window->priv->slideshow_loop = FALSE; window->priv->slideshow_switch_timeout = 0; window->priv->slideshow_switch_source = NULL; gtk_window_set_geometry_hints (GTK_WINDOW (window), GTK_WIDGET (window), &hints, GDK_HINT_MIN_SIZE); gtk_window_set_default_size (GTK_WINDOW (window), EOM_WINDOW_DEFAULT_WIDTH, EOM_WINDOW_DEFAULT_HEIGHT); gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER); window->priv->mode = EOM_WINDOW_MODE_UNKNOWN; window->priv->status = EOM_WINDOW_STATUS_UNKNOWN; #ifdef HAVE_LCMS window->priv->display_profile = eom_window_get_display_profile (screen); #endif window->priv->recent_menu_id = 0; window->priv->collection_position = 0; window->priv->collection_resizable = FALSE; window->priv->save_disabled = FALSE; window->priv->page_setup = NULL; } static void eom_window_dispose (GObject *object) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (object != NULL); g_return_if_fail (EOM_IS_WINDOW (object)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (object); priv = window->priv; if (priv->page_setup != NULL) { g_object_unref (priv->page_setup); priv->page_setup = NULL; } if (priv->thumbview) { /* Disconnect so we don't get any unwanted callbacks * when the thumb view is disposed. */ g_signal_handlers_disconnect_by_func (priv->thumbview, G_CALLBACK (handle_image_selection_changed_cb), window); g_clear_object (&priv->thumbview); } eom_plugin_engine_garbage_collect (); if (priv->store != NULL) { g_signal_handlers_disconnect_by_func (priv->store, eom_window_list_store_image_added, window); g_signal_handlers_disconnect_by_func (priv->store, eom_window_list_store_image_removed, window); g_object_unref (priv->store); priv->store = NULL; } if (priv->image != NULL) { g_signal_handlers_disconnect_by_func (priv->image, image_thumb_changed_cb, window); g_signal_handlers_disconnect_by_func (priv->image, image_file_changed_cb, window); g_object_unref (priv->image); priv->image = NULL; } if (priv->actions_window != NULL) { g_object_unref (priv->actions_window); priv->actions_window = NULL; } if (priv->actions_image != NULL) { g_object_unref (priv->actions_image); priv->actions_image = NULL; } if (priv->actions_collection != NULL) { g_object_unref (priv->actions_collection); priv->actions_collection = NULL; } if (priv->actions_recent != NULL) { g_object_unref (priv->actions_recent); priv->actions_recent = NULL; } if (priv->actions_open_with != NULL) { g_object_unref (priv->actions_open_with); priv->actions_open_with = NULL; } fullscreen_clear_timeout (window); if (window->priv->fullscreen_popup != NULL) { gtk_widget_destroy (priv->fullscreen_popup); priv->fullscreen_popup = NULL; } slideshow_clear_timeout (window); g_signal_handlers_disconnect_by_func (gtk_recent_manager_get_default (), G_CALLBACK (eom_window_recent_manager_changed_cb), window); priv->recent_menu_id = 0; eom_window_clear_load_job (window); eom_window_clear_transform_job (window); if (priv->view_settings) { g_object_unref (priv->view_settings); priv->view_settings = NULL; } if (priv->ui_settings) { g_object_unref (priv->ui_settings); priv->ui_settings = NULL; } if (priv->fullscreen_settings) { g_object_unref (priv->fullscreen_settings); priv->fullscreen_settings = NULL; } if (priv->lockdown_settings) { g_object_unref (priv->lockdown_settings); priv->lockdown_settings = NULL; } if (priv->file_list != NULL) { g_slist_foreach (priv->file_list, (GFunc) g_object_unref, NULL); g_slist_free (priv->file_list); priv->file_list = NULL; } #ifdef HAVE_LCMS if (priv->display_profile != NULL) { cmsCloseProfile (priv->display_profile); priv->display_profile = NULL; } #endif if (priv->last_save_as_folder != NULL) { g_object_unref (priv->last_save_as_folder); priv->last_save_as_folder = NULL; } eom_plugin_engine_garbage_collect (); G_OBJECT_CLASS (eom_window_parent_class)->dispose (object); } static void eom_window_finalize (GObject *object) { GList *windows = eom_application_get_windows (EOM_APP); g_return_if_fail (EOM_IS_WINDOW (object)); eom_debug (DEBUG_WINDOW); if (windows == NULL) { eom_application_shutdown (EOM_APP); } else { g_list_free (windows); } G_OBJECT_CLASS (eom_window_parent_class)->finalize (object); } static gint eom_window_delete (GtkWidget *widget, GdkEventAny *event) { EomWindow *window; EomWindowPrivate *priv; g_return_val_if_fail (EOM_IS_WINDOW (widget), FALSE); window = EOM_WINDOW (widget); priv = window->priv; if (priv->save_job != NULL) { eom_window_finish_saving (window); } if (eom_window_unsaved_images_confirm (window)) { return TRUE; } gtk_widget_destroy (widget); return TRUE; } static gint eom_window_key_press (GtkWidget *widget, GdkEventKey *event) { GtkContainer *tbcontainer = GTK_CONTAINER ((EOM_WINDOW (widget)->priv->toolbar)); gint result = FALSE; gboolean handle_selection = FALSE; switch (event->keyval) { case GDK_KEY_space: if (event->state & GDK_CONTROL_MASK) { handle_selection = TRUE; break; } case GDK_KEY_Return: if (gtk_container_get_focus_child (tbcontainer) == NULL) { /* Image properties dialog case */ if (event->state & GDK_MOD1_MASK) { result = FALSE; break; } if (event->state & GDK_SHIFT_MASK) { eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } result = TRUE; } break; case GDK_KEY_p: case GDK_KEY_P: if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_FULLSCREEN || EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) { gboolean slideshow; slideshow = EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW; eom_window_run_fullscreen (EOM_WINDOW (widget), !slideshow); } break; case GDK_KEY_Q: case GDK_KEY_q: case GDK_KEY_Escape: if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_FULLSCREEN) { eom_window_stop_fullscreen (EOM_WINDOW (widget), FALSE); } else if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) { eom_window_stop_fullscreen (EOM_WINDOW (widget), TRUE); } else { eom_window_cmd_close_window (NULL, EOM_WINDOW (widget)); return TRUE; } break; case GDK_KEY_Left: if (event->state & GDK_MOD1_MASK) { /* Alt+Left moves to previous image */ if (is_rtl) { /* move to next in RTL mode */ eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } /* else fall-trough is intended */ case GDK_KEY_Up: if (eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { /* break to let scrollview handle the key */ break; } if (gtk_container_get_focus_child (tbcontainer) != NULL) break; if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { if (is_rtl && event->keyval == GDK_KEY_Left) { /* handle RTL fall-through, * need to behave like GDK_Down then */ eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } case GDK_KEY_Right: if (event->state & GDK_MOD1_MASK) { /* Alt+Right moves to next image */ if (is_rtl) { /* move to previous in RTL mode */ eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } /* else fall-trough is intended */ case GDK_KEY_Down: if (eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { /* break to let scrollview handle the key */ break; } if (gtk_container_get_focus_child (tbcontainer) != NULL) break; if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { if (is_rtl && event->keyval == GDK_KEY_Right) { /* handle RTL fall-through, * need to behave like GDK_Up then */ eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } case GDK_KEY_Page_Up: if (!eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { /* If the iconview is not visible skip to the * previous image manually as it won't handle * the keypress then. */ eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); result = TRUE; } else handle_selection = TRUE; } break; case GDK_KEY_Page_Down: if (!eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { /* If the iconview is not visible skip to the * next image manually as it won't handle * the keypress then. */ eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); result = TRUE; } else handle_selection = TRUE; } break; } /* Update slideshow timeout */ if (result && (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW)) { slideshow_set_timeout (EOM_WINDOW (widget)); } if (handle_selection == TRUE && result == FALSE) { gtk_widget_grab_focus (GTK_WIDGET (EOM_WINDOW (widget)->priv->thumbview)); result = gtk_widget_event (GTK_WIDGET (EOM_WINDOW (widget)->priv->thumbview), (GdkEvent *) event); } /* If the focus is not in the toolbar and we still haven't handled the event, give the scrollview a chance to do it. */ if (!gtk_container_get_focus_child (tbcontainer) && result == FALSE && gtk_widget_get_realized (GTK_WIDGET (EOM_WINDOW (widget)->priv->view))) { result = gtk_widget_event (GTK_WIDGET (EOM_WINDOW (widget)->priv->view), (GdkEvent *) event); } if (result == FALSE && GTK_WIDGET_CLASS (eom_window_parent_class)->key_press_event) { result = (* GTK_WIDGET_CLASS (eom_window_parent_class)->key_press_event) (widget, event); } return result; } static gint eom_window_button_press (GtkWidget *widget, GdkEventButton *event) { EomWindow *window = EOM_WINDOW (widget); gint result = FALSE; if (event->type == GDK_BUTTON_PRESS) { switch (event->button) { case 6: eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_LEFT); result = TRUE; break; case 7: eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_RIGHT); result = TRUE; break; } } if (result == FALSE && GTK_WIDGET_CLASS (eom_window_parent_class)->button_press_event) { result = (* GTK_WIDGET_CLASS (eom_window_parent_class)->button_press_event) (widget, event); } return result; } static gboolean eom_window_focus_out_event (GtkWidget *widget, GdkEventFocus *event) { EomWindow *window = EOM_WINDOW (widget); EomWindowPrivate *priv = window->priv; gboolean fullscreen; eom_debug (DEBUG_WINDOW); fullscreen = priv->mode == EOM_WINDOW_MODE_FULLSCREEN || priv->mode == EOM_WINDOW_MODE_SLIDESHOW; if (fullscreen) { gtk_widget_hide (priv->fullscreen_popup); } return GTK_WIDGET_CLASS (eom_window_parent_class)->focus_out_event (widget, event); } static void eom_window_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (object)); window = EOM_WINDOW (object); priv = window->priv; switch (property_id) { case PROP_COLLECTION_POS: eom_window_set_collection_mode (window, g_value_get_enum (value), priv->collection_resizable); break; case PROP_COLLECTION_RESIZABLE: eom_window_set_collection_mode (window, priv->collection_position, g_value_get_boolean (value)); break; case PROP_STARTUP_FLAGS: priv->flags = g_value_get_flags (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void eom_window_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (object)); window = EOM_WINDOW (object); priv = window->priv; switch (property_id) { case PROP_COLLECTION_POS: g_value_set_enum (value, priv->collection_position); break; case PROP_COLLECTION_RESIZABLE: g_value_set_boolean (value, priv->collection_resizable); break; case PROP_STARTUP_FLAGS: g_value_set_flags (value, priv->flags); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static GObject * eom_window_constructor (GType type, guint n_construct_properties, GObjectConstructParam *construct_params) { GObject *object; object = G_OBJECT_CLASS (eom_window_parent_class)->constructor (type, n_construct_properties, construct_params); eom_window_construct_ui (EOM_WINDOW (object)); eom_plugin_engine_update_plugins_ui (EOM_WINDOW (object), TRUE); return object; } static void eom_window_class_init (EomWindowClass *class) { GObjectClass *g_object_class = (GObjectClass *) class; GtkWidgetClass *widget_class = (GtkWidgetClass *) class; g_object_class->constructor = eom_window_constructor; g_object_class->dispose = eom_window_dispose; g_object_class->finalize = eom_window_finalize; g_object_class->set_property = eom_window_set_property; g_object_class->get_property = eom_window_get_property; widget_class->delete_event = eom_window_delete; widget_class->key_press_event = eom_window_key_press; widget_class->button_press_event = eom_window_button_press; widget_class->drag_data_received = eom_window_drag_data_received; widget_class->focus_out_event = eom_window_focus_out_event; /** * EomWindow:collection-position: * * Determines the position of the image collection in the window * relative to the image. */ g_object_class_install_property ( g_object_class, PROP_COLLECTION_POS, g_param_spec_enum ("collection-position", NULL, NULL, EOM_TYPE_WINDOW_COLLECTION_POS, EOM_WINDOW_COLLECTION_POS_BOTTOM, G_PARAM_READWRITE | G_PARAM_STATIC_NAME)); /** * EomWindow:collection-resizable: * * If %TRUE the collection will be resizable by the user otherwise it will be * in single column/row mode. */ g_object_class_install_property ( g_object_class, PROP_COLLECTION_RESIZABLE, g_param_spec_boolean ("collection-resizable", NULL, NULL, FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_NAME)); /** * EomWindow:startup-flags: * * A bitwise OR of #EomStartupFlags elements, indicating how the window * should behave upon creation. */ g_object_class_install_property (g_object_class, PROP_STARTUP_FLAGS, g_param_spec_flags ("startup-flags", NULL, NULL, EOM_TYPE_STARTUP_FLAGS, 0, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); /** * EomWindow::prepared: * @window: the object which received the signal. * * The #EomWindow::prepared signal is emitted when the @window is ready * to be shown. */ signals [SIGNAL_PREPARED] = g_signal_new ("prepared", EOM_TYPE_WINDOW, G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (EomWindowClass, prepared), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); g_type_class_add_private (g_object_class, sizeof (EomWindowPrivate)); } /** * eom_window_new: * @flags: the initialization parameters for the new window. * * * Creates a new and empty #EomWindow. Use @flags to indicate * if the window should be initialized fullscreen, in slideshow mode, * and/or without the thumbnails collection visible. See #EomStartupFlags. * * Returns: a newly created #EomWindow. **/ GtkWidget* eom_window_new (EomStartupFlags flags) { EomWindow *window; eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (g_object_new (EOM_TYPE_WINDOW, "type", GTK_WINDOW_TOPLEVEL, "startup-flags", flags, NULL)); return GTK_WIDGET (window); } static void eom_window_list_store_image_added (GtkTreeModel *tree_model, GtkTreePath *path, GtkTreeIter *iter, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); update_image_pos (window); update_action_groups_state (window); } static void eom_window_list_store_image_removed (GtkTreeModel *tree_model, GtkTreePath *path, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); update_image_pos (window); update_action_groups_state (window); } static void eom_job_model_cb (EomJobModel *job, gpointer data) { EomWindow *window; EomWindowPrivate *priv; gint n_images; eom_debug (DEBUG_WINDOW); #ifdef HAVE_EXIF int i; EomImage *image; #endif g_return_if_fail (EOM_IS_WINDOW (data)); window = EOM_WINDOW (data); priv = window->priv; if (priv->store != NULL) { g_object_unref (priv->store); priv->store = NULL; } priv->store = g_object_ref (job->store); n_images = eom_list_store_length (EOM_LIST_STORE (priv->store)); #ifdef HAVE_EXIF if (g_settings_get_boolean (priv->view_settings, EOM_CONF_VIEW_AUTOROTATE)) { for (i = 0; i < n_images; i++) { image = eom_list_store_get_image_by_pos (priv->store, i); eom_image_autorotate (image); g_object_unref (image); } } #endif eom_thumb_view_set_model (EOM_THUMB_VIEW (priv->thumbview), priv->store); g_signal_connect (G_OBJECT (priv->store), "row-inserted", G_CALLBACK (eom_window_list_store_image_added), window); g_signal_connect (G_OBJECT (priv->store), "row-deleted", G_CALLBACK (eom_window_list_store_image_removed), window); if (n_images == 0) { gint n_files; priv->status = EOM_WINDOW_STATUS_NORMAL; update_action_groups_state (window); n_files = g_slist_length (priv->file_list); if (n_files > 0) { GtkWidget *message_area; GFile *file = NULL; if (n_files == 1) { file = (GFile *) priv->file_list->data; } message_area = eom_no_images_error_message_area_new (file); eom_window_set_message_area (window, message_area); gtk_widget_show (message_area); } g_signal_emit (window, signals[SIGNAL_PREPARED], 0); } } /** * eom_window_open_file_list: * @window: An #EomWindow. * @file_list: (element-type GFile): A %NULL-terminated list of #GFile's. * * Opens a list of files, adding them to the collection in @window. * Files will be checked to be readable and later filtered according * with eom_list_store_add_files(). **/ void eom_window_open_file_list (EomWindow *window, GSList *file_list) { EomJob *job; eom_debug (DEBUG_WINDOW); window->priv->status = EOM_WINDOW_STATUS_INIT; g_slist_foreach (file_list, (GFunc) g_object_ref, NULL); window->priv->file_list = file_list; job = eom_job_model_new (file_list); g_signal_connect (job, "finished", G_CALLBACK (eom_job_model_cb), window); eom_job_queue_add_job (job); g_object_unref (job); } /** * eom_window_get_ui_manager: * @window: An #EomWindow. * * Gets the #GtkUIManager that describes the UI of @window. * * Returns: (transfer none): A #GtkUIManager. **/ GtkUIManager * eom_window_get_ui_manager (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->ui_mgr; } /** * eom_window_get_mode: * @window: An #EomWindow. * * Gets the mode of @window. See #EomWindowMode for details. * * Returns: An #EomWindowMode. **/ EomWindowMode eom_window_get_mode (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), EOM_WINDOW_MODE_UNKNOWN); return window->priv->mode; } /** * eom_window_set_mode: * @window: an #EomWindow. * @mode: an #EomWindowMode value. * * Changes the mode of @window to normal, fullscreen, or slideshow. * See #EomWindowMode for details. **/ void eom_window_set_mode (EomWindow *window, EomWindowMode mode) { g_return_if_fail (EOM_IS_WINDOW (window)); if (window->priv->mode == mode) return; switch (mode) { case EOM_WINDOW_MODE_NORMAL: eom_window_stop_fullscreen (window, window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW); break; case EOM_WINDOW_MODE_FULLSCREEN: eom_window_run_fullscreen (window, FALSE); break; case EOM_WINDOW_MODE_SLIDESHOW: eom_window_run_fullscreen (window, TRUE); break; case EOM_WINDOW_MODE_UNKNOWN: break; } } /** * eom_window_get_store: * @window: An #EomWindow. * * Gets the #EomListStore that contains the images in the collection * of @window. * * Returns: (transfer none): an #EomListStore. **/ EomListStore * eom_window_get_store (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return EOM_LIST_STORE (window->priv->store); } /** * eom_window_get_view: * @window: An #EomWindow. * * Gets the #EomScrollView in the window. * * Returns: (transfer none): the #EomScrollView. **/ GtkWidget * eom_window_get_view (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->view; } /** * eom_window_get_sidebar: * @window: An #EomWindow. * * Gets the sidebar widget of @window. * * Returns: (transfer none): the #EomSidebar. **/ GtkWidget * eom_window_get_sidebar (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->sidebar; } /** * eom_window_get_thumb_view: * @window: an #EomWindow. * * Gets the thumbnails view in @window. * * Returns: (transfer none): an #EomThumbView. **/ GtkWidget * eom_window_get_thumb_view (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->thumbview; } /** * eom_window_get_thumb_nav: * @window: an #EomWindow. * * Gets the thumbnails navigation pane in @window. * * Returns: (transfer none): an #EomThumbNav. **/ GtkWidget * eom_window_get_thumb_nav (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->nav; } /** * eom_window_get_statusbar: * @window: an #EomWindow. * * Gets the statusbar in @window. * * Returns: (transfer none): a #EomStatusBar. **/ GtkWidget * eom_window_get_statusbar (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->statusbar; } /** * eom_window_get_image: * @window: an #EomWindow. * * Gets the image currently displayed in @window or %NULL if * no image is being displayed. * * Returns: (transfer none): an #EomImage. **/ EomImage * eom_window_get_image (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->image; } /** * eom_window_is_empty: * @window: an #EomWindow. * * Tells whether @window is currently empty or not. * * Returns: %TRUE if @window has no images, %FALSE otherwise. **/ gboolean eom_window_is_empty (EomWindow *window) { EomWindowPrivate *priv; gboolean empty = TRUE; eom_debug (DEBUG_WINDOW); g_return_val_if_fail (EOM_IS_WINDOW (window), FALSE); priv = window->priv; if (priv->store != NULL) { empty = (eom_list_store_length (EOM_LIST_STORE (priv->store)) == 0); } return empty; } void eom_window_reload_image (EomWindow *window) { GtkWidget *view; g_return_if_fail (EOM_IS_WINDOW (window)); if (window->priv->image == NULL) return; g_object_unref (window->priv->image); window->priv->image = NULL; view = eom_window_get_view (window); eom_scroll_view_set_image (EOM_SCROLL_VIEW (view), NULL); eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_CURRENT); }
monsta/eom
src/eom-window.c
C
gpl-2.0
153,265
/* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2004-2012 OpenWorks LLP info@open-works.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. The GNU General Public License is contained in the file COPYING. Neither the names of the U.S. Department of Energy nor the University of California nor the names of its contributors may be used to endorse or promote products derived from this software without prior written permission. */ #include "libvex_basictypes.h" #include "libvex_ir.h" #include "libvex.h" #include "ir_match.h" #include "main_util.h" #include "main_globals.h" #include "host_generic_regs.h" #include "host_generic_simd64.h" #include "host_ppc_defs.h" #define HRcGPR(__mode64) (__mode64 ? HRcInt64 : HRcInt32) static IRExpr* unop ( IROp op, IRExpr* a ) { return IRExpr_Unop(op, a); } static IRExpr* mkU32 ( UInt i ) { return IRExpr_Const(IRConst_U32(i)); } static IRExpr* bind ( Int binder ) { return IRExpr_Binder(binder); } typedef struct { IRTypeEnv* type_env; HReg* vregmapLo; HReg* vregmapMedLo; HReg* vregmapMedHi; HReg* vregmapHi; Int n_vregmap; UInt hwcaps; Bool mode64; VexAbiInfo* vbi; Bool chainingAllowed; Addr64 max_ga; HInstrArray* code; Int vreg_ctr; IRExpr* previous_rm; } ISelEnv; static HReg lookupIRTemp ( ISelEnv* env, IRTemp tmp ) { vassert(tmp >= 0); vassert(tmp < env->n_vregmap); return env->vregmapLo[tmp]; } static void lookupIRTempPair ( HReg* vrHI, HReg* vrLO, ISelEnv* env, IRTemp tmp ) { vassert(tmp >= 0); vassert(tmp < env->n_vregmap); vassert(env->vregmapMedLo[tmp] != INVALID_HREG); *vrLO = env->vregmapLo[tmp]; *vrHI = env->vregmapMedLo[tmp]; } static void lookupIRTempQuad ( HReg* vrHi, HReg* vrMedHi, HReg* vrMedLo, HReg* vrLo, ISelEnv* env, IRTemp tmp ) { vassert(!env->mode64); vassert(tmp >= 0); vassert(tmp < env->n_vregmap); vassert(env->vregmapMedLo[tmp] != INVALID_HREG); *vrHi = env->vregmapHi[tmp]; *vrMedHi = env->vregmapMedHi[tmp]; *vrMedLo = env->vregmapMedLo[tmp]; *vrLo = env->vregmapLo[tmp]; } static void addInstr ( ISelEnv* env, PPCInstr* instr ) { addHInstr(env->code, instr); if (vex_traceflags & VEX_TRACE_VCODE) { ppPPCInstr(instr, env->mode64); vex_printf("\n"); } } static HReg newVRegI ( ISelEnv* env ) { HReg reg = mkHReg(env->vreg_ctr, HRcGPR(env->mode64), True); env->vreg_ctr++; return reg; } static HReg newVRegF ( ISelEnv* env ) { HReg reg = mkHReg(env->vreg_ctr, HRcFlt64, True); env->vreg_ctr++; return reg; } static HReg newVRegV ( ISelEnv* env ) { HReg reg = mkHReg(env->vreg_ctr, HRcVec128, True); env->vreg_ctr++; return reg; } static HReg iselWordExpr_R_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselWordExpr_R ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH_wrk ( ISelEnv* env, Bool syned, IRExpr* e ); static PPCRH* iselWordExpr_RH ( ISelEnv* env, Bool syned, IRExpr* e ); static PPCRI* iselWordExpr_RI_wrk ( ISelEnv* env, IRExpr* e ); static PPCRI* iselWordExpr_RI ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH5u_wrk ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH5u ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH6u_wrk ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH6u ( ISelEnv* env, IRExpr* e ); static PPCAMode* iselWordExpr_AMode_wrk ( ISelEnv* env, IRExpr* e, IRType xferTy ); static PPCAMode* iselWordExpr_AMode ( ISelEnv* env, IRExpr* e, IRType xferTy ); static void iselInt128Expr_to_32x4_wrk ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt128Expr_to_32x4 ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt64Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt64Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt128Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt128Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static PPCCondCode iselCondCode_wrk ( ISelEnv* env, IRExpr* e ); static PPCCondCode iselCondCode ( ISelEnv* env, IRExpr* e ); static HReg iselDblExpr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselDblExpr ( ISelEnv* env, IRExpr* e ); static HReg iselFltExpr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselFltExpr ( ISelEnv* env, IRExpr* e ); static HReg iselVecExpr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselVecExpr ( ISelEnv* env, IRExpr* e ); static HReg iselDfp64Expr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselDfp64Expr ( ISelEnv* env, IRExpr* e ); static void iselDfp128Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselDfp128Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static PPCInstr* mk_iMOVds_RR ( HReg r_dst, HReg r_src ) { vassert(hregClass(r_dst) == hregClass(r_src)); vassert(hregClass(r_src) == HRcInt32 || hregClass(r_src) == HRcInt64); return PPCInstr_Alu(Palu_OR, r_dst, r_src, PPCRH_Reg(r_src)); } static void add_to_sp ( ISelEnv* env, UInt n ) { HReg sp = StackFramePtr(env->mode64); vassert(n < 256 && (n%16) == 0); addInstr(env, PPCInstr_Alu( Palu_ADD, sp, sp, PPCRH_Imm(True,toUShort(n)) )); } static void sub_from_sp ( ISelEnv* env, UInt n ) { HReg sp = StackFramePtr(env->mode64); vassert(n < 256 && (n%16) == 0); addInstr(env, PPCInstr_Alu( Palu_SUB, sp, sp, PPCRH_Imm(True,toUShort(n)) )); } static HReg get_sp_aligned16 ( ISelEnv* env ) { HReg r = newVRegI(env); HReg align16 = newVRegI(env); addInstr(env, mk_iMOVds_RR(r, StackFramePtr(env->mode64))); addInstr(env, PPCInstr_Alu( Palu_ADD, r, r, PPCRH_Imm(True,toUShort(16)) )); addInstr(env, PPCInstr_LI(align16, 0xFFFFFFFFFFFFFFF0ULL, env->mode64)); addInstr(env, PPCInstr_Alu(Palu_AND, r,r, PPCRH_Reg(align16))); return r; } static HReg mk_LoadRR32toFPR ( ISelEnv* env, HReg r_srcHi, HReg r_srcLo ) { HReg fr_dst = newVRegF(env); PPCAMode *am_addr0, *am_addr1; vassert(!env->mode64); vassert(hregClass(r_srcHi) == HRcInt32); vassert(hregClass(r_srcLo) == HRcInt32); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); am_addr1 = PPCAMode_IR( 4, StackFramePtr(env->mode64) ); addInstr(env, PPCInstr_Store( 4, am_addr0, r_srcHi, env->mode64 )); addInstr(env, PPCInstr_Store( 4, am_addr1, r_srcLo, env->mode64 )); addInstr(env, PPCInstr_FpLdSt(True, 8, fr_dst, am_addr0)); add_to_sp( env, 16 ); return fr_dst; } static HReg mk_LoadR64toFPR ( ISelEnv* env, HReg r_src ) { HReg fr_dst = newVRegF(env); PPCAMode *am_addr0; vassert(env->mode64); vassert(hregClass(r_src) == HRcInt64); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); addInstr(env, PPCInstr_Store( 8, am_addr0, r_src, env->mode64 )); addInstr(env, PPCInstr_FpLdSt(True, 8, fr_dst, am_addr0)); add_to_sp( env, 16 ); return fr_dst; } static PPCAMode* advance4 ( ISelEnv* env, PPCAMode* am ) { PPCAMode* am4 = dopyPPCAMode( am ); if (am4->tag == Pam_IR && am4->Pam.IR.index + 4 <= 32767) { am4->Pam.IR.index += 4; } else { vpanic("advance4(ppc,host)"); } return am4; } static PPCAMode* genGuestArrayOffset ( ISelEnv* env, IRRegArray* descr, IRExpr* off, Int bias ) { HReg rtmp, roff; Int elemSz = sizeofIRType(descr->elemTy); Int nElems = descr->nElems; Int shift = 0; if (nElems != 16 && nElems != 32) vpanic("genGuestArrayOffset(ppc host)(1)"); switch (elemSz) { case 4: shift = 2; break; case 8: shift = 3; break; default: vpanic("genGuestArrayOffset(ppc host)(2)"); } if (bias < -100 || bias > 100) vpanic("genGuestArrayOffset(ppc host)(3)"); if (descr->base < 0 || descr->base > 5000) vpanic("genGuestArrayOffset(ppc host)(4)"); roff = iselWordExpr_R(env, off); rtmp = newVRegI(env); addInstr(env, PPCInstr_Alu( Palu_ADD, rtmp, roff, PPCRH_Imm(True, toUShort(bias)))); addInstr(env, PPCInstr_Alu( Palu_AND, rtmp, rtmp, PPCRH_Imm(False, toUShort(nElems-1)))); addInstr(env, PPCInstr_Shft( Pshft_SHL, env->mode64 ? False : True, rtmp, rtmp, PPCRH_Imm(False, toUShort(shift)))); addInstr(env, PPCInstr_Alu( Palu_ADD, rtmp, rtmp, PPCRH_Imm(True, toUShort(descr->base)))); return PPCAMode_RR( GuestStatePtr(env->mode64), rtmp ); } static Bool mightRequireFixedRegs ( IRExpr* e ) { switch (e->tag) { case Iex_RdTmp: case Iex_Const: case Iex_Get: return False; default: return True; } } static void doHelperCall ( ISelEnv* env, Bool passBBP, IRExpr* guard, IRCallee* cee, IRExpr** args ) { PPCCondCode cc; HReg argregs[PPC_N_REGPARMS]; HReg tmpregs[PPC_N_REGPARMS]; Bool go_fast; Int n_args, i, argreg; UInt argiregs; ULong target; Bool mode64 = env->mode64; Bool regalign_int64s = (!mode64) && env->vbi->host_ppc32_regalign_int64_args; n_args = 0; for (i = 0; args[i]; i++) n_args++; if (PPC_N_REGPARMS < n_args + (passBBP ? 1 : 0)) { vpanic("doHelperCall(PPC): cannot currently handle > 8 args"); } argregs[0] = hregPPC_GPR3(mode64); argregs[1] = hregPPC_GPR4(mode64); argregs[2] = hregPPC_GPR5(mode64); argregs[3] = hregPPC_GPR6(mode64); argregs[4] = hregPPC_GPR7(mode64); argregs[5] = hregPPC_GPR8(mode64); argregs[6] = hregPPC_GPR9(mode64); argregs[7] = hregPPC_GPR10(mode64); argiregs = 0; tmpregs[0] = tmpregs[1] = tmpregs[2] = tmpregs[3] = tmpregs[4] = tmpregs[5] = tmpregs[6] = tmpregs[7] = INVALID_HREG; go_fast = True; if (guard) { if (guard->tag == Iex_Const && guard->Iex.Const.con->tag == Ico_U1 && guard->Iex.Const.con->Ico.U1 == True) { } else { go_fast = False; } } if (go_fast) { for (i = 0; i < n_args; i++) { if (mightRequireFixedRegs(args[i])) { go_fast = False; break; } } } if (go_fast) { argreg = 0; if (passBBP) { argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], GuestStatePtr(mode64) )); argreg++; } for (i = 0; i < n_args; i++) { vassert(argreg < PPC_N_REGPARMS); vassert(typeOfIRExpr(env->type_env, args[i]) == Ity_I32 || typeOfIRExpr(env->type_env, args[i]) == Ity_I64); if (!mode64) { if (typeOfIRExpr(env->type_env, args[i]) == Ity_I32) { argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], iselWordExpr_R(env, args[i]) )); } else { HReg rHi, rLo; if (regalign_int64s && (argreg%2) == 1) argreg++; vassert(argreg < PPC_N_REGPARMS-1); iselInt64Expr(&rHi,&rLo, env, args[i]); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], rHi )); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], rLo)); } } else { argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], iselWordExpr_R(env, args[i]) )); } argreg++; } cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); } else { argreg = 0; if (passBBP) { tmpregs[argreg] = newVRegI(env); addInstr(env, mk_iMOVds_RR( tmpregs[argreg], GuestStatePtr(mode64) )); argreg++; } for (i = 0; i < n_args; i++) { vassert(argreg < PPC_N_REGPARMS); vassert(typeOfIRExpr(env->type_env, args[i]) == Ity_I32 || typeOfIRExpr(env->type_env, args[i]) == Ity_I64); if (!mode64) { if (typeOfIRExpr(env->type_env, args[i]) == Ity_I32) { tmpregs[argreg] = iselWordExpr_R(env, args[i]); } else { HReg rHi, rLo; if (regalign_int64s && (argreg%2) == 1) argreg++; vassert(argreg < PPC_N_REGPARMS-1); iselInt64Expr(&rHi,&rLo, env, args[i]); tmpregs[argreg++] = rHi; tmpregs[argreg] = rLo; } } else { tmpregs[argreg] = iselWordExpr_R(env, args[i]); } argreg++; } cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); if (guard) { if (guard->tag == Iex_Const && guard->Iex.Const.con->tag == Ico_U1 && guard->Iex.Const.con->Ico.U1 == True) { } else { cc = iselCondCode( env, guard ); } } for (i = 0; i < argreg; i++) { if (tmpregs[i] == INVALID_HREG) continue; argiregs |= (1 << (i+3)); addInstr( env, mk_iMOVds_RR( argregs[i], tmpregs[i] ) ); } } target = mode64 ? Ptr_to_ULong(cee->addr) : toUInt(Ptr_to_ULong(cee->addr)); addInstr(env, PPCInstr_Call( cc, (Addr64)target, argiregs )); } static HReg roundModeIRtoPPC ( ISelEnv* env, HReg r_rmIR ) { HReg r_rmPPC = newVRegI(env); HReg r_tmp1 = newVRegI(env); HReg r_tmp2 = newVRegI(env); vassert(hregClass(r_rmIR) == HRcGPR(env->mode64)); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_tmp1, r_rmIR, PPCRH_Imm(False,1))); addInstr( env, PPCInstr_Alu( Palu_AND, r_tmp2, r_tmp1, PPCRH_Imm( False, 3 ) ) ); addInstr( env, PPCInstr_Alu( Palu_XOR, r_rmPPC, r_rmIR, PPCRH_Reg( r_tmp2 ) ) ); return r_rmPPC; } static void _set_FPU_rounding_mode ( ISelEnv* env, IRExpr* mode, Bool dfp_rm ) { HReg fr_src = newVRegF(env); HReg r_src; vassert(typeOfIRExpr(env->type_env,mode) == Ity_I32); if (env->previous_rm && env->previous_rm->tag == Iex_RdTmp && mode->tag == Iex_RdTmp && env->previous_rm->Iex.RdTmp.tmp == mode->Iex.RdTmp.tmp) { vassert(typeOfIRExpr(env->type_env, env->previous_rm) == Ity_I32); return; } env->previous_rm = mode; r_src = roundModeIRtoPPC( env, iselWordExpr_R(env, mode) ); if (env->mode64) { if (dfp_rm) { HReg r_tmp1 = newVRegI( env ); addInstr( env, PPCInstr_Shft( Pshft_SHL, False, r_tmp1, r_src, PPCRH_Imm( False, 32 ) ) ); fr_src = mk_LoadR64toFPR( env, r_tmp1 ); } else { fr_src = mk_LoadR64toFPR( env, r_src ); } } else { if (dfp_rm) { HReg r_zero = newVRegI( env ); addInstr( env, PPCInstr_LI( r_zero, 0, env->mode64 ) ); fr_src = mk_LoadRR32toFPR( env, r_src, r_zero ); } else { fr_src = mk_LoadRR32toFPR( env, r_src, r_src ); } } addInstr(env, PPCInstr_FpLdFPSCR( fr_src, dfp_rm )); } static void set_FPU_rounding_mode ( ISelEnv* env, IRExpr* mode ) { _set_FPU_rounding_mode(env, mode, False); } static void set_FPU_DFP_rounding_mode ( ISelEnv* env, IRExpr* mode ) { _set_FPU_rounding_mode(env, mode, True); } static HReg generate_zeroes_V128 ( ISelEnv* env ) { HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, dst, dst, dst)); return dst; } static HReg generate_ones_V128 ( ISelEnv* env ) { HReg dst = newVRegV(env); PPCVI5s * src = PPCVI5s_Imm(-1); addInstr(env, PPCInstr_AvSplat(8, dst, src)); return dst; } static HReg mk_AvDuplicateRI( ISelEnv* env, IRExpr* e ) { HReg r_src; HReg dst = newVRegV(env); PPCRI* ri = iselWordExpr_RI(env, e); IRType ty = typeOfIRExpr(env->type_env,e); UInt sz = (ty == Ity_I8) ? 8 : (ty == Ity_I16) ? 16 : 32; vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32); if (ri->tag == Pri_Imm) { Int simm32 = (Int)ri->Pri.Imm; if (simm32 >= -32 && simm32 <= 31) { Char simm6 = (Char)simm32; if (simm6 > 15) { HReg v1 = newVRegV(env); HReg v2 = newVRegV(env); addInstr(env, PPCInstr_AvSplat(sz, v1, PPCVI5s_Imm(-16))); addInstr(env, PPCInstr_AvSplat(sz, v2, PPCVI5s_Imm(simm6-16))); addInstr(env, (sz== 8) ? PPCInstr_AvBin8x16(Pav_SUBU, dst, v2, v1) : (sz==16) ? PPCInstr_AvBin16x8(Pav_SUBU, dst, v2, v1) : PPCInstr_AvBin32x4(Pav_SUBU, dst, v2, v1) ); return dst; } if (simm6 < -16) { HReg v1 = newVRegV(env); HReg v2 = newVRegV(env); addInstr(env, PPCInstr_AvSplat(sz, v1, PPCVI5s_Imm(-16))); addInstr(env, PPCInstr_AvSplat(sz, v2, PPCVI5s_Imm(simm6+16))); addInstr(env, (sz== 8) ? PPCInstr_AvBin8x16(Pav_ADDU, dst, v2, v1) : (sz==16) ? PPCInstr_AvBin16x8(Pav_ADDU, dst, v2, v1) : PPCInstr_AvBin32x4(Pav_ADDU, dst, v2, v1) ); return dst; } addInstr(env, PPCInstr_AvSplat(sz, dst, PPCVI5s_Imm(simm6))); return dst; } r_src = newVRegI(env); addInstr(env, PPCInstr_LI(r_src, (Long)simm32, env->mode64)); } else { r_src = ri->Pri.Reg; } { HReg r_aligned16; HReg v_src = newVRegV(env); PPCAMode *am_off12; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off12 = PPCAMode_IR( 12, r_aligned16 ); addInstr(env, PPCInstr_Store( 4, am_off12, r_src, env->mode64 )); addInstr(env, PPCInstr_AvLdSt( True, 4, v_src, am_off12 ) ); add_to_sp( env, 32 ); addInstr(env, PPCInstr_AvSplat(sz, dst, PPCVI5s_Reg(v_src))); return dst; } } static HReg isNan ( ISelEnv* env, HReg vSrc ) { HReg zeros, msk_exp, msk_mnt, expt, mnts, vIsNan; vassert(hregClass(vSrc) == HRcVec128); zeros = mk_AvDuplicateRI(env, mkU32(0)); msk_exp = mk_AvDuplicateRI(env, mkU32(0x7F800000)); msk_mnt = mk_AvDuplicateRI(env, mkU32(0x7FFFFF)); expt = newVRegV(env); mnts = newVRegV(env); vIsNan = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_AND, expt, vSrc, msk_exp)); addInstr(env, PPCInstr_AvBin32x4(Pav_CMPEQU, expt, expt, msk_exp)); addInstr(env, PPCInstr_AvBinary(Pav_AND, mnts, vSrc, msk_mnt)); addInstr(env, PPCInstr_AvBin32x4(Pav_CMPGTU, mnts, mnts, zeros)); addInstr(env, PPCInstr_AvBinary(Pav_AND, vIsNan, expt, mnts)); return vIsNan; } static HReg iselWordExpr_R ( ISelEnv* env, IRExpr* e ) { HReg r = iselWordExpr_R_wrk(env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcGPR(env->mode64)); vassert(hregIsVirtual(r)); return r; } static HReg iselWordExpr_R_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; MatchInfo mi; DECLARE_PATTERN(p_32to1_then_1Uto8); IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)); switch (e->tag) { case Iex_RdTmp: return lookupIRTemp(env, e->Iex.RdTmp.tmp); case Iex_Load: { HReg r_dst; PPCAMode* am_addr; if (e->Iex.Load.end != Iend_BE) goto irreducible; r_dst = newVRegI(env); am_addr = iselWordExpr_AMode( env, e->Iex.Load.addr, ty ); addInstr(env, PPCInstr_Load( toUChar(sizeofIRType(ty)), r_dst, am_addr, mode64 )); return r_dst; } case Iex_Binop: { PPCAluOp aluOp; PPCShftOp shftOp; switch (e->Iex.Binop.op) { case Iop_Add8: case Iop_Add16: case Iop_Add32: case Iop_Add64: aluOp = Palu_ADD; break; case Iop_Sub8: case Iop_Sub16: case Iop_Sub32: case Iop_Sub64: aluOp = Palu_SUB; break; case Iop_And8: case Iop_And16: case Iop_And32: case Iop_And64: aluOp = Palu_AND; break; case Iop_Or8: case Iop_Or16: case Iop_Or32: case Iop_Or64: aluOp = Palu_OR; break; case Iop_Xor8: case Iop_Xor16: case Iop_Xor32: case Iop_Xor64: aluOp = Palu_XOR; break; default: aluOp = Palu_INVALID; break; } if (aluOp != Palu_INVALID) { HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri_srcR = NULL; switch (aluOp) { case Palu_ADD: case Palu_SUB: ri_srcR = iselWordExpr_RH(env, True, e->Iex.Binop.arg2); break; case Palu_AND: case Palu_OR: case Palu_XOR: ri_srcR = iselWordExpr_RH(env, False, e->Iex.Binop.arg2); break; default: vpanic("iselWordExpr_R_wrk-aluOp-arg2"); } addInstr(env, PPCInstr_Alu(aluOp, r_dst, r_srcL, ri_srcR)); return r_dst; } switch (e->Iex.Binop.op) { case Iop_Shl8: case Iop_Shl16: case Iop_Shl32: case Iop_Shl64: shftOp = Pshft_SHL; break; case Iop_Shr8: case Iop_Shr16: case Iop_Shr32: case Iop_Shr64: shftOp = Pshft_SHR; break; case Iop_Sar8: case Iop_Sar16: case Iop_Sar32: case Iop_Sar64: shftOp = Pshft_SAR; break; default: shftOp = Pshft_INVALID; break; } if (shftOp != Pshft_INVALID) { HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri_srcR = NULL; switch (shftOp) { case Pshft_SHL: case Pshft_SHR: case Pshft_SAR: if (!mode64) ri_srcR = iselWordExpr_RH5u(env, e->Iex.Binop.arg2); else ri_srcR = iselWordExpr_RH6u(env, e->Iex.Binop.arg2); break; default: vpanic("iselIntExpr_R_wrk-shftOp-arg2"); } if (shftOp == Pshft_SHR || shftOp == Pshft_SAR) { if (ty == Ity_I8 || ty == Ity_I16) { PPCRH* amt = PPCRH_Imm(False, toUShort(ty == Ity_I8 ? 24 : 16)); HReg tmp = newVRegI(env); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, tmp, r_srcL, amt)); addInstr(env, PPCInstr_Shft(shftOp, True, tmp, tmp, amt)); r_srcL = tmp; vassert(0); } } if (ty == Ity_I64) { vassert(mode64); addInstr(env, PPCInstr_Shft(shftOp, False, r_dst, r_srcL, ri_srcR)); } else { addInstr(env, PPCInstr_Shft(shftOp, True, r_dst, r_srcL, ri_srcR)); } return r_dst; } if (e->Iex.Binop.op == Iop_DivS32 || e->Iex.Binop.op == Iop_DivU32 || e->Iex.Binop.op == Iop_DivS32E || e->Iex.Binop.op == Iop_DivU32E) { Bool syned = toBool((e->Iex.Binop.op == Iop_DivS32) || (e->Iex.Binop.op == Iop_DivS32E)); HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr( env, PPCInstr_Div( ( ( e->Iex.Binop.op == Iop_DivU32E ) || ( e->Iex.Binop.op == Iop_DivS32E ) ) ? True : False, syned, True, r_dst, r_srcL, r_srcR ) ); return r_dst; } if (e->Iex.Binop.op == Iop_DivS64 || e->Iex.Binop.op == Iop_DivU64 || e->Iex.Binop.op == Iop_DivS64E || e->Iex.Binop.op == Iop_DivU64E ) { Bool syned = toBool((e->Iex.Binop.op == Iop_DivS64) ||(e->Iex.Binop.op == Iop_DivS64E)); HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); vassert(mode64); addInstr( env, PPCInstr_Div( ( ( e->Iex.Binop.op == Iop_DivS64E ) || ( e->Iex.Binop.op == Iop_DivU64E ) ) ? True : False, syned, False, r_dst, r_srcL, r_srcR ) ); return r_dst; } if (e->Iex.Binop.op == Iop_Mul32 || e->Iex.Binop.op == Iop_Mul64) { Bool syned = False; Bool sz32 = (e->Iex.Binop.op != Iop_Mul64); HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(syned, False, sz32, r_dst, r_srcL, r_srcR)); return r_dst; } if (mode64 && (e->Iex.Binop.op == Iop_MullU32 || e->Iex.Binop.op == Iop_MullS32)) { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg r_dst = newVRegI(env); Bool syned = toBool(e->Iex.Binop.op == Iop_MullS32); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(False, False, True, tLo, r_srcL, r_srcR)); addInstr(env, PPCInstr_MulL(syned, True, True, tHi, r_srcL, r_srcR)); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, tHi, PPCRH_Imm(False,32))); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(tLo))); return r_dst; } if (e->Iex.Binop.op == Iop_CmpORD32S || e->Iex.Binop.op == Iop_CmpORD32U) { Bool syned = toBool(e->Iex.Binop.op == Iop_CmpORD32S); HReg dst = newVRegI(env); HReg srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* srcR = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Cmp(syned, True, 7, srcL, srcR)); addInstr(env, PPCInstr_MfCR(dst)); addInstr(env, PPCInstr_Alu(Palu_AND, dst, dst, PPCRH_Imm(False,7<<1))); return dst; } if (e->Iex.Binop.op == Iop_CmpORD64S || e->Iex.Binop.op == Iop_CmpORD64U) { Bool syned = toBool(e->Iex.Binop.op == Iop_CmpORD64S); HReg dst = newVRegI(env); HReg srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* srcR = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); vassert(mode64); addInstr(env, PPCInstr_Cmp(syned, False, 7, srcL, srcR)); addInstr(env, PPCInstr_MfCR(dst)); addInstr(env, PPCInstr_Alu(Palu_AND, dst, dst, PPCRH_Imm(False,7<<1))); return dst; } if (e->Iex.Binop.op == Iop_Max32U) { HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r2 = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg rdst = newVRegI(env); PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7LT ); addInstr(env, mk_iMOVds_RR(rdst, r1)); addInstr(env, PPCInstr_Cmp(False, True, 7, rdst, PPCRH_Reg(r2))); addInstr(env, PPCInstr_CMov(cc, rdst, PPCRI_Reg(r2))); return rdst; } if (e->Iex.Binop.op == Iop_32HLto64) { HReg r_Hi = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_Lo = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg r_dst = newVRegI(env); HReg msk = newVRegI(env); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_Hi, PPCRH_Imm(False,32))); addInstr(env, PPCInstr_LI(msk, 0xFFFFFFFF, mode64)); addInstr(env, PPCInstr_Alu( Palu_AND, r_Lo, r_Lo, PPCRH_Reg(msk) )); addInstr(env, PPCInstr_Alu( Palu_OR, r_dst, r_dst, PPCRH_Reg(r_Lo) )); return r_dst; } if ((e->Iex.Binop.op == Iop_CmpF64) || (e->Iex.Binop.op == Iop_CmpD64) || (e->Iex.Binop.op == Iop_CmpD128)) { HReg fr_srcL; HReg fr_srcL_lo; HReg fr_srcR; HReg fr_srcR_lo; HReg r_ccPPC = newVRegI(env); HReg r_ccIR = newVRegI(env); HReg r_ccIR_b0 = newVRegI(env); HReg r_ccIR_b2 = newVRegI(env); HReg r_ccIR_b6 = newVRegI(env); if (e->Iex.Binop.op == Iop_CmpF64) { fr_srcL = iselDblExpr(env, e->Iex.Binop.arg1); fr_srcR = iselDblExpr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_FpCmp(r_ccPPC, fr_srcL, fr_srcR)); } else if (e->Iex.Binop.op == Iop_CmpD64) { fr_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1); fr_srcR = iselDfp64Expr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp64Cmp(r_ccPPC, fr_srcL, fr_srcR)); } else { iselDfp128Expr(&fr_srcL, &fr_srcL_lo, env, e->Iex.Binop.arg1); iselDfp128Expr(&fr_srcR, &fr_srcR_lo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp128Cmp(r_ccPPC, fr_srcL, fr_srcL_lo, fr_srcR, fr_srcR_lo)); } addInstr(env, PPCInstr_Shft(Pshft_SHR, True, r_ccIR_b0, r_ccPPC, PPCRH_Imm(False,0x3))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR_b0, r_ccPPC, PPCRH_Reg(r_ccIR_b0))); addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b0, r_ccIR_b0, PPCRH_Imm(False,0x1))); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_ccIR_b2, r_ccPPC, PPCRH_Imm(False,0x2))); addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b2, r_ccIR_b2, PPCRH_Imm(False,0x4))); addInstr(env, PPCInstr_Shft(Pshft_SHR, True, r_ccIR_b6, r_ccPPC, PPCRH_Imm(False,0x1))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR_b6, r_ccPPC, PPCRH_Reg(r_ccIR_b6))); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_ccIR_b6, r_ccIR_b6, PPCRH_Imm(False,0x6))); addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b6, r_ccIR_b6, PPCRH_Imm(False,0x40))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR, r_ccIR_b0, PPCRH_Reg(r_ccIR_b2))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR, r_ccIR, PPCRH_Reg(r_ccIR_b6))); return r_ccIR; } if ( e->Iex.Binop.op == Iop_F64toI32S || e->Iex.Binop.op == Iop_F64toI32U ) { HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2); HReg ftmp = newVRegF(env); HReg idst = newVRegI(env); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpCftI(False, True, e->Iex.Binop.op == Iop_F64toI32S ? True : False, True, ftmp, fsrc)); addInstr(env, PPCInstr_FpSTFIW(r1, ftmp)); addInstr(env, PPCInstr_Load(4, idst, zero_r1, mode64)); if (mode64) addInstr(env, PPCInstr_Unary(Pun_EXTSW, idst, idst)); add_to_sp( env, 16 ); return idst; } if (e->Iex.Binop.op == Iop_F64toI64S || e->Iex.Binop.op == Iop_F64toI64U ) { if (mode64) { HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2); HReg idst = newVRegI(env); HReg ftmp = newVRegF(env); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpCftI(False, False, ( e->Iex.Binop.op == Iop_F64toI64S ) ? True : False, True, ftmp, fsrc)); addInstr(env, PPCInstr_FpLdSt(False, 8, ftmp, zero_r1)); addInstr(env, PPCInstr_Load(8, idst, zero_r1, True)); add_to_sp( env, 16 ); return idst; } } break; } case Iex_Unop: { IROp op_unop = e->Iex.Unop.op; DEFINE_PATTERN(p_32to1_then_1Uto8, unop(Iop_1Uto8,unop(Iop_32to1,bind(0)))); if (matchIRExpr(&mi,p_32to1_then_1Uto8,e)) { IRExpr* expr32 = mi.bindee[0]; HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, expr32); addInstr(env, PPCInstr_Alu(Palu_AND, r_dst, r_src, PPCRH_Imm(False,1))); return r_dst; } { DECLARE_PATTERN(p_LDbe16_then_16Uto32); DEFINE_PATTERN(p_LDbe16_then_16Uto32, unop(Iop_16Uto32, IRExpr_Load(Iend_BE,Ity_I16,bind(0))) ); if (matchIRExpr(&mi,p_LDbe16_then_16Uto32,e)) { HReg r_dst = newVRegI(env); PPCAMode* amode = iselWordExpr_AMode( env, mi.bindee[0], Ity_I16 ); addInstr(env, PPCInstr_Load(2,r_dst,amode, mode64)); return r_dst; } } switch (op_unop) { case Iop_8Uto16: case Iop_8Uto32: case Iop_8Uto64: case Iop_16Uto32: case Iop_16Uto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort mask = toUShort(op_unop==Iop_16Uto64 ? 0xFFFF : op_unop==Iop_16Uto32 ? 0xFFFF : 0xFF); addInstr(env, PPCInstr_Alu(Palu_AND,r_dst,r_src, PPCRH_Imm(False,mask))); return r_dst; } case Iop_32Uto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_src, PPCRH_Imm(False,32))); addInstr(env, PPCInstr_Shft(Pshft_SHR, False, r_dst, r_dst, PPCRH_Imm(False,32))); return r_dst; } case Iop_8Sto16: case Iop_8Sto32: case Iop_16Sto32: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort amt = toUShort(op_unop==Iop_16Sto32 ? 16 : 24); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_dst, r_src, PPCRH_Imm(False,amt))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_dst, PPCRH_Imm(False,amt))); return r_dst; } case Iop_8Sto64: case Iop_16Sto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort amt = toUShort(op_unop==Iop_8Sto64 ? 56 : 48); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_src, PPCRH_Imm(False,amt))); addInstr(env, PPCInstr_Shft(Pshft_SAR, False, r_dst, r_dst, PPCRH_Imm(False,amt))); return r_dst; } case Iop_32Sto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_src, PPCRH_Imm(False,0))); return r_dst; } case Iop_Not8: case Iop_Not16: case Iop_Not32: case Iop_Not64: { if (op_unop == Iop_Not64) vassert(mode64); HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NOT,r_dst,r_src)); return r_dst; } case Iop_64HIto32: { if (!mode64) { HReg rHi, rLo; iselInt64Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rHi; } else { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Shft(Pshft_SHR, False, r_dst, r_src, PPCRH_Imm(False,32))); return r_dst; } } case Iop_64to32: { if (!mode64) { HReg rHi, rLo; iselInt64Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rLo; } else { return iselWordExpr_R(env, e->Iex.Unop.arg); } } case Iop_64to16: { if (mode64) { return iselWordExpr_R(env, e->Iex.Unop.arg); } break; } case Iop_16HIto8: case Iop_32HIto16: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort shift = toUShort(op_unop == Iop_16HIto8 ? 8 : 16); addInstr(env, PPCInstr_Shft(Pshft_SHR, True, r_dst, r_src, PPCRH_Imm(False,shift))); return r_dst; } case Iop_128HIto64: if (mode64) { HReg rHi, rLo; iselInt128Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rHi; } break; case Iop_128to64: if (mode64) { HReg rHi, rLo; iselInt128Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rLo; } break; case Iop_1Uto64: case Iop_1Uto32: case Iop_1Uto8: if ((op_unop != Iop_1Uto64) || mode64) { HReg r_dst = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,r_dst)); return r_dst; } break; case Iop_1Sto8: case Iop_1Sto16: case Iop_1Sto32: { HReg r_dst = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,r_dst)); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_dst, r_dst, PPCRH_Imm(False,31))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_dst, PPCRH_Imm(False,31))); return r_dst; } case Iop_1Sto64: if (mode64) { HReg r_dst = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,r_dst)); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_dst, PPCRH_Imm(False,63))); addInstr(env, PPCInstr_Shft(Pshft_SAR, False, r_dst, r_dst, PPCRH_Imm(False,63))); return r_dst; } break; case Iop_Clz32: case Iop_Clz64: { HReg r_src, r_dst; PPCUnaryOp op_clz = (op_unop == Iop_Clz32) ? Pun_CLZ32 : Pun_CLZ64; if (op_unop == Iop_Clz64 && !mode64) goto irreducible; r_dst = newVRegI(env); r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(op_clz,r_dst,r_src)); return r_dst; } case Iop_Left8: case Iop_Left32: case Iop_Left64: { HReg r_src, r_dst; if (op_unop == Iop_Left64 && !mode64) goto irreducible; r_dst = newVRegI(env); r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src)); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src))); return r_dst; } case Iop_CmpwNEZ32: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src)); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_dst, PPCRH_Imm(False, 31))); return r_dst; } case Iop_CmpwNEZ64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); if (!mode64) goto irreducible; addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src)); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src))); addInstr(env, PPCInstr_Shft(Pshft_SAR, False, r_dst, r_dst, PPCRH_Imm(False, 63))); return r_dst; } case Iop_V128to32: { HReg r_aligned16; HReg dst = newVRegI(env); HReg vec = iselVecExpr(env, e->Iex.Unop.arg); PPCAMode *am_off0, *am_off12; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off12 = PPCAMode_IR( 12,r_aligned16 ); addInstr(env, PPCInstr_AvLdSt( False, 16, vec, am_off0 )); addInstr(env, PPCInstr_Load( 4, dst, am_off12, mode64 )); add_to_sp( env, 32 ); return dst; } case Iop_V128to64: case Iop_V128HIto64: if (mode64) { HReg r_aligned16; HReg dst = newVRegI(env); HReg vec = iselVecExpr(env, e->Iex.Unop.arg); PPCAMode *am_off0, *am_off8; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off8 = PPCAMode_IR( 8 ,r_aligned16 ); addInstr(env, PPCInstr_AvLdSt( False, 16, vec, am_off0 )); addInstr(env, PPCInstr_Load( 8, dst, op_unop == Iop_V128HIto64 ? am_off0 : am_off8, mode64 )); add_to_sp( env, 32 ); return dst; } break; case Iop_16to8: case Iop_32to8: case Iop_32to16: case Iop_64to8: return iselWordExpr_R(env, e->Iex.Unop.arg); case Iop_ReinterpF64asI64: if (mode64) { PPCAMode *am_addr; HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg); HReg r_dst = newVRegI(env); sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr )); addInstr(env, PPCInstr_Load( 8, r_dst, am_addr, mode64 )); add_to_sp( env, 16 ); return r_dst; } break; case Iop_ReinterpF32asI32: { PPCAMode *am_addr; HReg fr_src = iselFltExpr(env, e->Iex.Unop.arg); HReg r_dst = newVRegI(env); sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 4, fr_src, am_addr )); addInstr(env, PPCInstr_Load( 4, r_dst, am_addr, mode64 )); add_to_sp( env, 16 ); return r_dst; } break; case Iop_ReinterpD64asI64: if (mode64) { PPCAMode *am_addr; HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); HReg r_dst = newVRegI(env); sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr )); addInstr(env, PPCInstr_Load( 8, r_dst, am_addr, mode64 )); add_to_sp( env, 16 ); return r_dst; } break; case Iop_BCDtoDPB: { PPCCondCode cc; UInt argiregs; HReg argregs[1]; HReg r_dst = newVRegI(env); Int argreg; HWord* fdescr; argiregs = 0; argreg = 0; argregs[0] = hregPPC_GPR3(mode64); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], iselWordExpr_R(env, e->Iex.Unop.arg) ) ); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); fdescr = (HWord*)h_BCDtoDPB; addInstr(env, PPCInstr_Call( cc, (Addr64)(fdescr[0]), argiregs ) ); addInstr(env, mk_iMOVds_RR(r_dst, argregs[0])); return r_dst; } case Iop_DPBtoBCD: { PPCCondCode cc; UInt argiregs; HReg argregs[1]; HReg r_dst = newVRegI(env); Int argreg; HWord* fdescr; argiregs = 0; argreg = 0; argregs[0] = hregPPC_GPR3(mode64); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], iselWordExpr_R(env, e->Iex.Unop.arg) ) ); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); fdescr = (HWord*)h_DPBtoBCD; addInstr(env, PPCInstr_Call( cc, (Addr64)(fdescr[0]), argiregs ) ); addInstr(env, mk_iMOVds_RR(r_dst, argregs[0])); return r_dst; } default: break; } break; } case Iex_Get: { if (ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) { HReg r_dst = newVRegI(env); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_Load( toUChar(sizeofIRType(ty)), r_dst, am_addr, mode64 )); return r_dst; } break; } case Iex_GetI: { PPCAMode* src_am = genGuestArrayOffset( env, e->Iex.GetI.descr, e->Iex.GetI.ix, e->Iex.GetI.bias ); HReg r_dst = newVRegI(env); if (mode64 && ty == Ity_I64) { addInstr(env, PPCInstr_Load( toUChar(8), r_dst, src_am, mode64 )); return r_dst; } if ((!mode64) && ty == Ity_I32) { addInstr(env, PPCInstr_Load( toUChar(4), r_dst, src_am, mode64 )); return r_dst; } break; } case Iex_CCall: { HReg r_dst = newVRegI(env); vassert(ty == Ity_I32); if (e->Iex.CCall.retty != Ity_I32) goto irreducible; doHelperCall( env, False, NULL, e->Iex.CCall.cee, e->Iex.CCall.args ); addInstr(env, mk_iMOVds_RR(r_dst, hregPPC_GPR3(mode64))); return r_dst; } case Iex_Const: { Long l; HReg r_dst = newVRegI(env); IRConst* con = e->Iex.Const.con; switch (con->tag) { case Ico_U64: if (!mode64) goto irreducible; l = (Long) con->Ico.U64; break; case Ico_U32: l = (Long)(Int) con->Ico.U32; break; case Ico_U16: l = (Long)(Int)(Short)con->Ico.U16; break; case Ico_U8: l = (Long)(Int)(Char )con->Ico.U8; break; default: vpanic("iselIntExpr_R.const(ppc)"); } addInstr(env, PPCInstr_LI(r_dst, (ULong)l, mode64)); return r_dst; } case Iex_Mux0X: { if ((ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) && typeOfIRExpr(env->type_env,e->Iex.Mux0X.cond) == Ity_I8) { PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond); HReg rX = iselWordExpr_R(env, e->Iex.Mux0X.exprX); PPCRI* r0 = iselWordExpr_RI(env, e->Iex.Mux0X.expr0); HReg r_dst = newVRegI(env); HReg r_tmp = newVRegI(env); addInstr(env, mk_iMOVds_RR(r_dst,rX)); addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp, r_cond, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_Cmp(False, True, 7, r_tmp, PPCRH_Imm(False,0))); addInstr(env, PPCInstr_CMov(cc,r_dst,r0)); return r_dst; } break; } default: break; } irreducible: ppIRExpr(e); vpanic("iselIntExpr_R(ppc): cannot reduce tree"); } static Bool uInt_fits_in_16_bits ( UInt u ) { Int i = u & 0xFFFF; i <<= 16; i >>= 16; return toBool(u == (UInt)i); } static Bool uLong_fits_in_16_bits ( ULong u ) { Long i = u & 0xFFFFULL; i <<= 48; i >>= 48; return toBool(u == (ULong)i); } static Bool uLong_is_4_aligned ( ULong u ) { return toBool((u & 3ULL) == 0); } static Bool sane_AMode ( ISelEnv* env, PPCAMode* am ) { Bool mode64 = env->mode64; switch (am->tag) { case Pam_IR: return toBool( hregClass(am->Pam.IR.base) == HRcGPR(mode64) && hregIsVirtual(am->Pam.IR.base) && uInt_fits_in_16_bits(am->Pam.IR.index) ); case Pam_RR: return toBool( hregClass(am->Pam.RR.base) == HRcGPR(mode64) && hregIsVirtual(am->Pam.RR.base) && hregClass(am->Pam.RR.index) == HRcGPR(mode64) && hregIsVirtual(am->Pam.IR.index) ); default: vpanic("sane_AMode: unknown ppc amode tag"); } } static PPCAMode* iselWordExpr_AMode ( ISelEnv* env, IRExpr* e, IRType xferTy ) { PPCAMode* am = iselWordExpr_AMode_wrk(env, e, xferTy); vassert(sane_AMode(env, am)); return am; } static PPCAMode* iselWordExpr_AMode_wrk ( ISelEnv* env, IRExpr* e, IRType xferTy ) { IRType ty = typeOfIRExpr(env->type_env,e); if (env->mode64) { Bool aligned4imm = toBool(xferTy == Ity_I32 || xferTy == Ity_I64); vassert(ty == Ity_I64); if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add64 && e->Iex.Binop.arg2->tag == Iex_Const && e->Iex.Binop.arg2->Iex.Const.con->tag == Ico_U64 && (aligned4imm ? uLong_is_4_aligned(e->Iex.Binop.arg2 ->Iex.Const.con->Ico.U64) : True) && uLong_fits_in_16_bits(e->Iex.Binop.arg2 ->Iex.Const.con->Ico.U64)) { return PPCAMode_IR( (Int)e->Iex.Binop.arg2->Iex.Const.con->Ico.U64, iselWordExpr_R(env, e->Iex.Binop.arg1) ); } if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add64) { HReg r_base = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_idx = iselWordExpr_R(env, e->Iex.Binop.arg2); return PPCAMode_RR( r_idx, r_base ); } } else { vassert(ty == Ity_I32); if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add32 && e->Iex.Binop.arg2->tag == Iex_Const && e->Iex.Binop.arg2->Iex.Const.con->tag == Ico_U32 && uInt_fits_in_16_bits(e->Iex.Binop.arg2 ->Iex.Const.con->Ico.U32)) { return PPCAMode_IR( (Int)e->Iex.Binop.arg2->Iex.Const.con->Ico.U32, iselWordExpr_R(env, e->Iex.Binop.arg1) ); } if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add32) { HReg r_base = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_idx = iselWordExpr_R(env, e->Iex.Binop.arg2); return PPCAMode_RR( r_idx, r_base ); } } return PPCAMode_IR( 0, iselWordExpr_R(env,e) ); } static PPCRH* iselWordExpr_RH ( ISelEnv* env, Bool syned, IRExpr* e ) { PPCRH* ri = iselWordExpr_RH_wrk(env, syned, e); switch (ri->tag) { case Prh_Imm: vassert(ri->Prh.Imm.syned == syned); if (syned) vassert(ri->Prh.Imm.imm16 != 0x8000); return ri; case Prh_Reg: vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Prh.Reg.reg)); return ri; default: vpanic("iselIntExpr_RH: unknown ppc RH tag"); } } static PPCRH* iselWordExpr_RH_wrk ( ISelEnv* env, Bool syned, IRExpr* e ) { ULong u; Long l; IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && env->mode64)); if (e->tag == Iex_Const) { IRConst* con = e->Iex.Const.con; switch (con->tag) { case Ico_U64: vassert(env->mode64); u = con->Ico.U64; break; case Ico_U32: u = 0xFFFFFFFF & con->Ico.U32; break; case Ico_U16: u = 0x0000FFFF & con->Ico.U16; break; case Ico_U8: u = 0x000000FF & con->Ico.U8; break; default: vpanic("iselIntExpr_RH.Iex_Const(ppch)"); } l = (Long)u; if (!syned && u <= 65535) { return PPCRH_Imm(False, toUShort(u & 0xFFFF)); } if (syned && l >= -32767 && l <= 32767) { return PPCRH_Imm(True, toUShort(u & 0xFFFF)); } } return PPCRH_Reg( iselWordExpr_R ( env, e ) ); } static PPCRI* iselWordExpr_RI ( ISelEnv* env, IRExpr* e ) { PPCRI* ri = iselWordExpr_RI_wrk(env, e); switch (ri->tag) { case Pri_Imm: return ri; case Pri_Reg: vassert(hregClass(ri->Pri.Reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Pri.Reg)); return ri; default: vpanic("iselIntExpr_RI: unknown ppc RI tag"); } } static PPCRI* iselWordExpr_RI_wrk ( ISelEnv* env, IRExpr* e ) { Long l; IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && env->mode64)); if (e->tag == Iex_Const) { IRConst* con = e->Iex.Const.con; switch (con->tag) { case Ico_U64: vassert(env->mode64); l = (Long) con->Ico.U64; break; case Ico_U32: l = (Long)(Int) con->Ico.U32; break; case Ico_U16: l = (Long)(Int)(Short)con->Ico.U16; break; case Ico_U8: l = (Long)(Int)(Char )con->Ico.U8; break; default: vpanic("iselIntExpr_RI.Iex_Const(ppch)"); } return PPCRI_Imm((ULong)l); } return PPCRI_Reg( iselWordExpr_R ( env, e ) ); } static PPCRH* iselWordExpr_RH5u ( ISelEnv* env, IRExpr* e ) { PPCRH* ri; vassert(!env->mode64); ri = iselWordExpr_RH5u_wrk(env, e); switch (ri->tag) { case Prh_Imm: vassert(ri->Prh.Imm.imm16 >= 1 && ri->Prh.Imm.imm16 <= 31); vassert(!ri->Prh.Imm.syned); return ri; case Prh_Reg: vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Prh.Reg.reg)); return ri; default: vpanic("iselIntExpr_RH5u: unknown ppc RI tag"); } } static PPCRH* iselWordExpr_RH5u_wrk ( ISelEnv* env, IRExpr* e ) { IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8); if (e->tag == Iex_Const && e->Iex.Const.con->tag == Ico_U8 && e->Iex.Const.con->Ico.U8 >= 1 && e->Iex.Const.con->Ico.U8 <= 31) { return PPCRH_Imm(False, e->Iex.Const.con->Ico.U8); } return PPCRH_Reg( iselWordExpr_R ( env, e ) ); } static PPCRH* iselWordExpr_RH6u ( ISelEnv* env, IRExpr* e ) { PPCRH* ri; vassert(env->mode64); ri = iselWordExpr_RH6u_wrk(env, e); switch (ri->tag) { case Prh_Imm: vassert(ri->Prh.Imm.imm16 >= 1 && ri->Prh.Imm.imm16 <= 63); vassert(!ri->Prh.Imm.syned); return ri; case Prh_Reg: vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Prh.Reg.reg)); return ri; default: vpanic("iselIntExpr_RH6u: unknown ppc64 RI tag"); } } static PPCRH* iselWordExpr_RH6u_wrk ( ISelEnv* env, IRExpr* e ) { IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8); if (e->tag == Iex_Const && e->Iex.Const.con->tag == Ico_U8 && e->Iex.Const.con->Ico.U8 >= 1 && e->Iex.Const.con->Ico.U8 <= 63) { return PPCRH_Imm(False, e->Iex.Const.con->Ico.U8); } return PPCRH_Reg( iselWordExpr_R ( env, e ) ); } static PPCCondCode iselCondCode ( ISelEnv* env, IRExpr* e ) { return iselCondCode_wrk(env,e); } static PPCCondCode iselCondCode_wrk ( ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I1); if (e->tag == Iex_Const && e->Iex.Const.con->Ico.U1 == True) { HReg r_zero = newVRegI(env); addInstr(env, PPCInstr_LI(r_zero, 0, env->mode64)); addInstr(env, PPCInstr_Cmp(False, True, 7, r_zero, PPCRH_Reg(r_zero))); return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_Not1) { PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); cond.test = invertCondTest(cond.test); return cond; } if (e->tag == Iex_Unop && (e->Iex.Unop.op == Iop_32to1 || e->Iex.Unop.op == Iop_64to1)) { HReg src = iselWordExpr_R(env, e->Iex.Unop.arg); HReg tmp = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, tmp, src, PPCRH_Imm(False,1))); addInstr(env, PPCInstr_Cmp(False, True, 7, tmp, PPCRH_Imm(False,1))); return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_CmpNEZ8) { HReg arg = iselWordExpr_R(env, e->Iex.Unop.arg); HReg tmp = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, tmp, arg, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_Cmp(False, True, 7, tmp, PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_CmpNEZ32) { HReg r1 = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Cmp(False, True, 7, r1, PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } if (e->tag == Iex_Binop && (e->Iex.Binop.op == Iop_CmpEQ32 || e->Iex.Binop.op == Iop_CmpNE32 || e->Iex.Binop.op == Iop_CmpLT32S || e->Iex.Binop.op == Iop_CmpLT32U || e->Iex.Binop.op == Iop_CmpLE32S || e->Iex.Binop.op == Iop_CmpLE32U)) { Bool syned = (e->Iex.Binop.op == Iop_CmpLT32S || e->Iex.Binop.op == Iop_CmpLE32S); HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri2 = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Cmp(syned, True, 7, r1, ri2)); switch (e->Iex.Binop.op) { case Iop_CmpEQ32: return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); case Iop_CmpNE32: return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); case Iop_CmpLT32U: case Iop_CmpLT32S: return mk_PPCCondCode( Pct_TRUE, Pcf_7LT ); case Iop_CmpLE32U: case Iop_CmpLE32S: return mk_PPCCondCode( Pct_FALSE, Pcf_7GT ); default: vpanic("iselCondCode(ppc): CmpXX32"); } } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_CmpNEZ64) { if (!env->mode64) { HReg hi, lo; HReg tmp = newVRegI(env); iselInt64Expr( &hi, &lo, env, e->Iex.Unop.arg ); addInstr(env, PPCInstr_Alu(Palu_OR, tmp, lo, PPCRH_Reg(hi))); addInstr(env, PPCInstr_Cmp(False, True, 7, tmp,PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } else { HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Cmp(False, False, 7, r_src,PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } } if (e->tag == Iex_Binop && (e->Iex.Binop.op == Iop_CmpEQ64 || e->Iex.Binop.op == Iop_CmpNE64 || e->Iex.Binop.op == Iop_CmpLT64S || e->Iex.Binop.op == Iop_CmpLT64U || e->Iex.Binop.op == Iop_CmpLE64S || e->Iex.Binop.op == Iop_CmpLE64U)) { Bool syned = (e->Iex.Binop.op == Iop_CmpLT64S || e->Iex.Binop.op == Iop_CmpLE64S); HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri2 = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); vassert(env->mode64); addInstr(env, PPCInstr_Cmp(syned, False, 7, r1, ri2)); switch (e->Iex.Binop.op) { case Iop_CmpEQ64: return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); case Iop_CmpNE64: return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); case Iop_CmpLT64U: return mk_PPCCondCode( Pct_TRUE, Pcf_7LT ); case Iop_CmpLE64U: return mk_PPCCondCode( Pct_FALSE, Pcf_7GT ); default: vpanic("iselCondCode(ppc): CmpXX64"); } } if (e->tag == Iex_RdTmp) { HReg r_src = lookupIRTemp(env, e->Iex.RdTmp.tmp); HReg src_masked = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, src_masked, r_src, PPCRH_Imm(False,1))); addInstr(env, PPCInstr_Cmp(False, True, 7, src_masked, PPCRH_Imm(False,1))); return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); } vex_printf("iselCondCode(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselCondCode(ppc)"); } static void iselInt128Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(env->mode64); iselInt128Expr_wrk(rHi, rLo, env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(*rHi) == HRcGPR(env->mode64)); vassert(hregIsVirtual(*rHi)); vassert(hregClass(*rLo) == HRcGPR(env->mode64)); vassert(hregIsVirtual(*rLo)); } static void iselInt128Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I128); if (e->tag == Iex_RdTmp) { lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp); return; } if (e->tag == Iex_Binop) { switch (e->Iex.Binop.op) { case Iop_MullU64: case Iop_MullS64: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); Bool syned = toBool(e->Iex.Binop.op == Iop_MullS64); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(False, False, False, tLo, r_srcL, r_srcR)); addInstr(env, PPCInstr_MulL(syned, True, False, tHi, r_srcL, r_srcR)); *rHi = tHi; *rLo = tLo; return; } case Iop_64HLto128: *rHi = iselWordExpr_R(env, e->Iex.Binop.arg1); *rLo = iselWordExpr_R(env, e->Iex.Binop.arg2); return; default: break; } } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { default: break; } } vex_printf("iselInt128Expr(ppc64): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselInt128Expr(ppc64)"); } static void iselInt128Expr_to_32x4 ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(!env->mode64); iselInt128Expr_to_32x4_wrk(rHi, rMedHi, rMedLo, rLo, env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(*rHi) == HRcInt32); vassert(hregIsVirtual(*rHi)); vassert(hregClass(*rMedHi) == HRcInt32); vassert(hregIsVirtual(*rMedHi)); vassert(hregClass(*rMedLo) == HRcInt32); vassert(hregIsVirtual(*rMedLo)); vassert(hregClass(*rLo) == HRcInt32); vassert(hregIsVirtual(*rLo)); } static void iselInt128Expr_to_32x4_wrk ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I128); if (e->tag == Iex_RdTmp) { lookupIRTempQuad( rHi, rMedHi, rMedLo, rLo, env, e->Iex.RdTmp.tmp); return; } if (e->tag == Iex_Binop) { IROp op_binop = e->Iex.Binop.op; switch (op_binop) { case Iop_64HLto128: iselInt64Expr(rHi, rMedHi, env, e->Iex.Binop.arg1); iselInt64Expr(rMedLo, rLo, env, e->Iex.Binop.arg2); return; default: vex_printf("iselInt128Expr_to_32x4_wrk: Binop case 0x%x not found\n", op_binop); break; } } vex_printf("iselInt128Expr_to_32x4_wrk: e->tag 0x%x not found\n", e->tag); return; } static void iselInt64Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(!env->mode64); iselInt64Expr_wrk(rHi, rLo, env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(*rHi) == HRcInt32); vassert(hregIsVirtual(*rHi)); vassert(hregClass(*rLo) == HRcInt32); vassert(hregIsVirtual(*rLo)); } static void iselInt64Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I64); if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg r_addr = iselWordExpr_R(env, e->Iex.Load.addr); vassert(!env->mode64); addInstr(env, PPCInstr_Load( 4, tHi, PPCAMode_IR( 0, r_addr ), False) ); addInstr(env, PPCInstr_Load( 4, tLo, PPCAMode_IR( 4, r_addr ), False) ); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_Const) { ULong w64 = e->Iex.Const.con->Ico.U64; UInt wHi = ((UInt)(w64 >> 32)) & 0xFFFFFFFF; UInt wLo = ((UInt)w64) & 0xFFFFFFFF; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); vassert(e->Iex.Const.con->tag == Ico_U64); addInstr(env, PPCInstr_LI(tHi, (Long)(Int)wHi, False)); addInstr(env, PPCInstr_LI(tLo, (Long)(Int)wLo, False)); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_RdTmp) { lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp); return; } if (e->tag == Iex_Get) { PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(False) ); PPCAMode* am_addr4 = advance4(env, am_addr); HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); addInstr(env, PPCInstr_Load( 4, tHi, am_addr, False )); addInstr(env, PPCInstr_Load( 4, tLo, am_addr4, False )); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_Mux0X) { HReg e0Lo, e0Hi, eXLo, eXHi; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond); HReg r_tmp = newVRegI(env); iselInt64Expr(&e0Hi, &e0Lo, env, e->Iex.Mux0X.expr0); iselInt64Expr(&eXHi, &eXLo, env, e->Iex.Mux0X.exprX); addInstr(env, mk_iMOVds_RR(tHi,eXHi)); addInstr(env, mk_iMOVds_RR(tLo,eXLo)); addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp, r_cond, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_Cmp(False, True, 7, r_tmp, PPCRH_Imm(False,0))); addInstr(env, PPCInstr_CMov(cc,tHi,PPCRI_Reg(e0Hi))); addInstr(env, PPCInstr_CMov(cc,tLo,PPCRI_Reg(e0Lo))); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_Binop) { IROp op_binop = e->Iex.Binop.op; switch (op_binop) { case Iop_MullU32: case Iop_MullS32: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); Bool syned = toBool(op_binop == Iop_MullS32); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(False, False, True, tLo, r_srcL, r_srcR)); addInstr(env, PPCInstr_MulL(syned, True, True, tHi, r_srcL, r_srcR)); *rHi = tHi; *rLo = tLo; return; } case Iop_Or64: case Iop_And64: case Iop_Xor64: { HReg xLo, xHi, yLo, yHi; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); PPCAluOp op = (op_binop == Iop_Or64) ? Palu_OR : (op_binop == Iop_And64) ? Palu_AND : Palu_XOR; iselInt64Expr(&xHi, &xLo, env, e->Iex.Binop.arg1); iselInt64Expr(&yHi, &yLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Alu(op, tHi, xHi, PPCRH_Reg(yHi))); addInstr(env, PPCInstr_Alu(op, tLo, xLo, PPCRH_Reg(yLo))); *rHi = tHi; *rLo = tLo; return; } case Iop_Add64: { HReg xLo, xHi, yLo, yHi; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); iselInt64Expr(&xHi, &xLo, env, e->Iex.Binop.arg1); iselInt64Expr(&yHi, &yLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AddSubC( True, True , tLo, xLo, yLo)); addInstr(env, PPCInstr_AddSubC( True, False, tHi, xHi, yHi)); *rHi = tHi; *rLo = tLo; return; } case Iop_32HLto64: *rHi = iselWordExpr_R(env, e->Iex.Binop.arg1); *rLo = iselWordExpr_R(env, e->Iex.Binop.arg2); return; case Iop_F64toI64S: case Iop_F64toI64U: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); PPCAMode* four_r1 = PPCAMode_IR( 4, r1 ); HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2); HReg ftmp = newVRegF(env); vassert(!env->mode64); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpCftI(False, False, (op_binop == Iop_F64toI64S) ? True : False, True, ftmp, fsrc)); addInstr(env, PPCInstr_FpLdSt(False, 8, ftmp, zero_r1)); addInstr(env, PPCInstr_Load(4, tHi, zero_r1, False)); addInstr(env, PPCInstr_Load(4, tLo, four_r1, False)); add_to_sp( env, 16 ); *rHi = tHi; *rLo = tLo; return; } default: break; } } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { case Iop_CmpwNEZ64: { HReg argHi, argLo; HReg tmp1 = newVRegI(env); HReg tmp2 = newVRegI(env); iselInt64Expr(&argHi, &argLo, env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Alu(Palu_OR, tmp1, argHi, PPCRH_Reg(argLo))); addInstr(env, PPCInstr_Unary(Pun_NEG,tmp2,tmp1)); addInstr(env, PPCInstr_Alu(Palu_OR, tmp2, tmp2, PPCRH_Reg(tmp1))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, tmp2, tmp2, PPCRH_Imm(False, 31))); *rHi = tmp2; *rLo = tmp2; return; } case Iop_Left64: { HReg argHi, argLo; HReg zero32 = newVRegI(env); HReg resHi = newVRegI(env); HReg resLo = newVRegI(env); iselInt64Expr(&argHi, &argLo, env, e->Iex.Unop.arg); vassert(env->mode64 == False); addInstr(env, PPCInstr_LI(zero32, 0, env->mode64)); addInstr(env, PPCInstr_AddSubC( False, True, resLo, zero32, argLo )); addInstr(env, PPCInstr_AddSubC( False, False, resHi, zero32, argHi )); addInstr(env, PPCInstr_Alu(Palu_OR, resLo, resLo, PPCRH_Reg(argLo))); addInstr(env, PPCInstr_Alu(Palu_OR, resHi, resHi, PPCRH_Reg(argHi))); *rHi = resHi; *rLo = resLo; return; } case Iop_32Sto64: { HReg tHi = newVRegI(env); HReg src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, tHi, src, PPCRH_Imm(False,31))); *rHi = tHi; *rLo = src; return; } case Iop_32Uto64: { HReg tHi = newVRegI(env); HReg tLo = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_LI(tHi, 0, False)); *rHi = tHi; *rLo = tLo; return; } case Iop_128to64: { HReg r_Hi = INVALID_HREG; HReg r_MedHi = INVALID_HREG; HReg r_MedLo = INVALID_HREG; HReg r_Lo = INVALID_HREG; iselInt128Expr_to_32x4(&r_Hi, &r_MedHi, &r_MedLo, &r_Lo, env, e->Iex.Unop.arg); *rHi = r_MedLo; *rLo = r_Lo; return; } case Iop_128HIto64: { HReg r_Hi = INVALID_HREG; HReg r_MedHi = INVALID_HREG; HReg r_MedLo = INVALID_HREG; HReg r_Lo = INVALID_HREG; iselInt128Expr_to_32x4(&r_Hi, &r_MedHi, &r_MedLo, &r_Lo, env, e->Iex.Unop.arg); *rHi = r_Hi; *rLo = r_MedHi; return; } case Iop_V128HIto64: case Iop_V128to64: { HReg r_aligned16; Int off = e->Iex.Unop.op==Iop_V128HIto64 ? 0 : 8; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg vec = iselVecExpr(env, e->Iex.Unop.arg); PPCAMode *am_off0, *am_offLO, *am_offHI; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_offHI = PPCAMode_IR( off, r_aligned16 ); am_offLO = PPCAMode_IR( off+4, r_aligned16 ); addInstr(env, PPCInstr_AvLdSt( False, 16, vec, am_off0 )); addInstr(env, PPCInstr_Load( 4, tHi, am_offHI, False )); addInstr(env, PPCInstr_Load( 4, tLo, am_offLO, False )); add_to_sp( env, 32 ); *rHi = tHi; *rLo = tLo; return; } case Iop_1Sto64: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,tLo)); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, tLo, tLo, PPCRH_Imm(False,31))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, tLo, tLo, PPCRH_Imm(False,31))); addInstr(env, mk_iMOVds_RR(tHi, tLo)); *rHi = tHi; *rLo = tLo; return; } case Iop_Not64: { HReg xLo, xHi; HReg tmpLo = newVRegI(env); HReg tmpHi = newVRegI(env); iselInt64Expr(&xHi, &xLo, env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NOT,tmpLo,xLo)); addInstr(env, PPCInstr_Unary(Pun_NOT,tmpHi,xHi)); *rHi = tmpHi; *rLo = tmpLo; return; } case Iop_ReinterpF64asI64: { PPCAMode *am_addr0, *am_addr1; HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg); HReg r_dstLo = newVRegI(env); HReg r_dstHi = newVRegI(env); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(False) ); am_addr1 = PPCAMode_IR( 4, StackFramePtr(False) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr0 )); addInstr(env, PPCInstr_Load( 4, r_dstHi, am_addr0, False )); addInstr(env, PPCInstr_Load( 4, r_dstLo, am_addr1, False )); *rHi = r_dstHi; *rLo = r_dstLo; add_to_sp( env, 16 ); return; } case Iop_ReinterpD64asI64: { HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); PPCAMode *am_addr0, *am_addr1; HReg r_dstLo = newVRegI(env); HReg r_dstHi = newVRegI(env); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(False) ); am_addr1 = PPCAMode_IR( 4, StackFramePtr(False) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr0 )); addInstr(env, PPCInstr_Load( 4, r_dstHi, am_addr0, False )); addInstr(env, PPCInstr_Load( 4, r_dstLo, am_addr1, False )); *rHi = r_dstHi; *rLo = r_dstLo; add_to_sp( env, 16 ); return; } case Iop_BCDtoDPB: { PPCCondCode cc; UInt argiregs; HReg argregs[2]; Int argreg; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg tmpHi; HReg tmpLo; ULong target; Bool mode64 = env->mode64; argregs[0] = hregPPC_GPR3(mode64); argregs[1] = hregPPC_GPR4(mode64); argiregs = 0; argreg = 0; iselInt64Expr( &tmpHi, &tmpLo, env, e->Iex.Unop.arg ); argiregs |= ( 1 << (argreg+3 ) ); addInstr( env, mk_iMOVds_RR( argregs[argreg++], tmpHi ) ); argiregs |= ( 1 << (argreg+3 ) ); addInstr( env, mk_iMOVds_RR( argregs[argreg], tmpLo ) ); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); target = toUInt( Ptr_to_ULong(h_BCDtoDPB ) ); addInstr( env, PPCInstr_Call( cc, (Addr64)target, argiregs ) ); addInstr( env, mk_iMOVds_RR( tHi, argregs[argreg-1] ) ); addInstr( env, mk_iMOVds_RR( tLo, argregs[argreg] ) ); *rHi = tHi; *rLo = tLo; return; } case Iop_DPBtoBCD: { PPCCondCode cc; UInt argiregs; HReg argregs[2]; Int argreg; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg tmpHi; HReg tmpLo; ULong target; Bool mode64 = env->mode64; argregs[0] = hregPPC_GPR3(mode64); argregs[1] = hregPPC_GPR4(mode64); argiregs = 0; argreg = 0; iselInt64Expr(&tmpHi, &tmpLo, env, e->Iex.Unop.arg); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], tmpHi )); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], tmpLo)); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); target = toUInt( Ptr_to_ULong( h_DPBtoBCD ) ); addInstr(env, PPCInstr_Call( cc, (Addr64)target, argiregs ) ); addInstr(env, mk_iMOVds_RR(tHi, argregs[argreg-1])); addInstr(env, mk_iMOVds_RR(tLo, argregs[argreg])); *rHi = tHi; *rLo = tLo; return; } default: break; } } vex_printf("iselInt64Expr(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselInt64Expr(ppc)"); } static HReg iselFltExpr ( ISelEnv* env, IRExpr* e ) { HReg r = iselFltExpr_wrk( env, e ); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcFlt64); vassert(hregIsVirtual(r)); return r; } static HReg iselFltExpr_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_F32); if (e->tag == Iex_RdTmp) { return lookupIRTemp(env, e->Iex.RdTmp.tmp); } if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { PPCAMode* am_addr; HReg r_dst = newVRegF(env); vassert(e->Iex.Load.ty == Ity_F32); am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_F32); addInstr(env, PPCInstr_FpLdSt(True, 4, r_dst, am_addr)); return r_dst; } if (e->tag == Iex_Get) { HReg r_dst = newVRegF(env); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(env->mode64) ); addInstr(env, PPCInstr_FpLdSt( True, 4, r_dst, am_addr )); return r_dst; } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_TruncF64asF32) { /* This is quite subtle. The only way to do the relevant truncation is to do a single-precision store and then a double precision load to get it back into a register. The problem is, if the data is then written to memory a second time, as in STbe(...) = TruncF64asF32(...) then will the second truncation further alter the value? The answer is no: flds (as generated here) followed by fsts (generated for the STbe) is the identity function on 32-bit floats, so we are safe. Another upshot of this is that if iselStmt can see the entirety of STbe(...) = TruncF64asF32(arg) then it can short circuit having to deal with TruncF64asF32 individually; instead just compute arg into a 64-bit FP register and do 'fsts' (since that itself does the truncation). We generate pretty poor code here (should be ok both for 32-bit and 64-bit mode); but it is expected that for the most part the latter optimisation will apply and hence this code will not often be used. */ HReg fsrc = iselDblExpr(env, e->Iex.Unop.arg); HReg fdst = newVRegF(env); PPCAMode* zero_r1 = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpLdSt( False, 4, fsrc, zero_r1 )); addInstr(env, PPCInstr_FpLdSt( True, 4, fdst, zero_r1 )); add_to_sp( env, 16 ); return fdst; } if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_I64UtoF32) { if (mode64) { HReg fdst = newVRegF(env); HReg isrc = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(8, zero_r1, isrc, True)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, False, False, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } else { HReg fdst = newVRegF(env); HReg isrcHi, isrcLo; HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); PPCAMode* four_r1 = PPCAMode_IR( 4, r1 ); iselInt64Expr(&isrcHi, &isrcLo, env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(4, zero_r1, isrcHi, False)); addInstr(env, PPCInstr_Store(4, four_r1, isrcLo, False)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, False, False, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } } vex_printf("iselFltExpr(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselFltExpr_wrk(ppc)"); } static HReg iselDblExpr ( ISelEnv* env, IRExpr* e ) { HReg r = iselDblExpr_wrk( env, e ); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcFlt64); vassert(hregIsVirtual(r)); return r; } static HReg iselDblExpr_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; IRType ty = typeOfIRExpr(env->type_env,e); vassert(e); vassert(ty == Ity_F64); if (e->tag == Iex_RdTmp) { return lookupIRTemp(env, e->Iex.RdTmp.tmp); } if (e->tag == Iex_Const) { union { UInt u32x2[2]; ULong u64; Double f64; } u; vassert(sizeof(u) == 8); vassert(sizeof(u.u64) == 8); vassert(sizeof(u.f64) == 8); vassert(sizeof(u.u32x2) == 8); if (e->Iex.Const.con->tag == Ico_F64) { u.f64 = e->Iex.Const.con->Ico.F64; } else if (e->Iex.Const.con->tag == Ico_F64i) { u.u64 = e->Iex.Const.con->Ico.F64i; } else vpanic("iselDblExpr(ppc): const"); if (!mode64) { HReg r_srcHi = newVRegI(env); HReg r_srcLo = newVRegI(env); addInstr(env, PPCInstr_LI(r_srcHi, u.u32x2[0], mode64)); addInstr(env, PPCInstr_LI(r_srcLo, u.u32x2[1], mode64)); return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo ); } else { HReg r_src = newVRegI(env); addInstr(env, PPCInstr_LI(r_src, u.u64, mode64)); return mk_LoadR64toFPR( env, r_src ); } } if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { HReg r_dst = newVRegF(env); PPCAMode* am_addr; vassert(e->Iex.Load.ty == Ity_F64); am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_F64); addInstr(env, PPCInstr_FpLdSt(True, 8, r_dst, am_addr)); return r_dst; } if (e->tag == Iex_Get) { HReg r_dst = newVRegF(env); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( True, 8, r_dst, am_addr )); return r_dst; } if (e->tag == Iex_Qop) { PPCFpOp fpop = Pfp_INVALID; switch (e->Iex.Qop.details->op) { case Iop_MAddF64: fpop = Pfp_MADDD; break; case Iop_MAddF64r32: fpop = Pfp_MADDS; break; case Iop_MSubF64: fpop = Pfp_MSUBD; break; case Iop_MSubF64r32: fpop = Pfp_MSUBS; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcML = iselDblExpr(env, e->Iex.Qop.details->arg2); HReg r_srcMR = iselDblExpr(env, e->Iex.Qop.details->arg3); HReg r_srcAcc = iselDblExpr(env, e->Iex.Qop.details->arg4); set_FPU_rounding_mode( env, e->Iex.Qop.details->arg1 ); addInstr(env, PPCInstr_FpMulAcc(fpop, r_dst, r_srcML, r_srcMR, r_srcAcc)); return r_dst; } } if (e->tag == Iex_Triop) { IRTriop *triop = e->Iex.Triop.details; PPCFpOp fpop = Pfp_INVALID; switch (triop->op) { case Iop_AddF64: fpop = Pfp_ADDD; break; case Iop_SubF64: fpop = Pfp_SUBD; break; case Iop_MulF64: fpop = Pfp_MULD; break; case Iop_DivF64: fpop = Pfp_DIVD; break; case Iop_AddF64r32: fpop = Pfp_ADDS; break; case Iop_SubF64r32: fpop = Pfp_SUBS; break; case Iop_MulF64r32: fpop = Pfp_MULS; break; case Iop_DivF64r32: fpop = Pfp_DIVS; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcL = iselDblExpr(env, triop->arg2); HReg r_srcR = iselDblExpr(env, triop->arg3); set_FPU_rounding_mode( env, triop->arg1 ); addInstr(env, PPCInstr_FpBinary(fpop, r_dst, r_srcL, r_srcR)); return r_dst; } switch (triop->op) { case Iop_QuantizeD64: fpop = Pfp_DQUA; break; case Iop_SignificanceRoundD64: fpop = Pfp_RRDTR; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcL = iselDblExpr(env, triop->arg2); HReg r_srcR = iselDblExpr(env, triop->arg3); PPCRI* rmc = iselWordExpr_RI(env, triop->arg1); addInstr(env, PPCInstr_DfpQuantize(fpop, r_dst, r_srcL, r_srcR, rmc)); return r_dst; } } if (e->tag == Iex_Binop) { PPCFpOp fpop = Pfp_INVALID; switch (e->Iex.Binop.op) { case Iop_SqrtF64: fpop = Pfp_SQRT; break; case Iop_I64StoD64: fpop = Pfp_DCFFIX; break; case Iop_D64toI64S: fpop = Pfp_DCTFIX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_dst = newVRegF(env); HReg fr_src = iselDblExpr(env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); addInstr(env, PPCInstr_FpUnary(fpop, fr_dst, fr_src)); return fr_dst; } } if (e->tag == Iex_Binop) { if (e->Iex.Binop.op == Iop_RoundF64toF32) { HReg r_dst = newVRegF(env); HReg r_src = iselDblExpr(env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); addInstr(env, PPCInstr_FpRSP(r_dst, r_src)); return r_dst; } if (e->Iex.Binop.op == Iop_I64StoF64 || e->Iex.Binop.op == Iop_I64UtoF64) { if (mode64) { HReg fdst = newVRegF(env); HReg isrc = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(8, zero_r1, isrc, True)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, e->Iex.Binop.op == Iop_I64StoF64, True, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } else { HReg fdst = newVRegF(env); HReg isrcHi, isrcLo; HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); PPCAMode* four_r1 = PPCAMode_IR( 4, r1 ); iselInt64Expr(&isrcHi, &isrcLo, env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(4, zero_r1, isrcHi, False)); addInstr(env, PPCInstr_Store(4, four_r1, isrcLo, False)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, e->Iex.Binop.op == Iop_I64StoF64, True, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } } } if (e->tag == Iex_Unop) { PPCFpOp fpop = Pfp_INVALID; switch (e->Iex.Unop.op) { case Iop_NegF64: fpop = Pfp_NEG; break; case Iop_AbsF64: fpop = Pfp_ABS; break; case Iop_Est5FRSqrt: fpop = Pfp_RSQRTE; break; case Iop_RoundF64toF64_NegINF: fpop = Pfp_FRIM; break; case Iop_RoundF64toF64_PosINF: fpop = Pfp_FRIP; break; case Iop_RoundF64toF64_NEAREST: fpop = Pfp_FRIN; break; case Iop_RoundF64toF64_ZERO: fpop = Pfp_FRIZ; break; case Iop_ExtractExpD64: fpop = Pfp_DXEX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_dst = newVRegF(env); HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_FpUnary(fpop, fr_dst, fr_src)); return fr_dst; } } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { case Iop_ReinterpI64asF64: { if (!mode64) { HReg r_srcHi, r_srcLo; iselInt64Expr( &r_srcHi, &r_srcLo, env, e->Iex.Unop.arg); return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo ); } else { HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); return mk_LoadR64toFPR( env, r_src ); } } case Iop_F32toF64: { if (e->Iex.Unop.arg->tag == Iex_Unop && e->Iex.Unop.arg->Iex.Unop.op == Iop_ReinterpI32asF32 ) { e = e->Iex.Unop.arg; HReg src = iselWordExpr_R(env, e->Iex.Unop.arg); HReg fr_dst = newVRegF(env); PPCAMode *am_addr; sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); addInstr(env, PPCInstr_Store( 4, am_addr, src, env->mode64 )); addInstr(env, PPCInstr_FpLdSt(True, 4, fr_dst, am_addr)); add_to_sp( env, 16 ); return fr_dst; } HReg res = iselFltExpr(env, e->Iex.Unop.arg); return res; } default: break; } } if (e->tag == Iex_Mux0X) { if (ty == Ity_F64 && typeOfIRExpr(env->type_env,e->Iex.Mux0X.cond) == Ity_I8) { PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond); HReg frX = iselDblExpr(env, e->Iex.Mux0X.exprX); HReg fr0 = iselDblExpr(env, e->Iex.Mux0X.expr0); HReg fr_dst = newVRegF(env); HReg r_tmp = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp, r_cond, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_FpUnary( Pfp_MOV, fr_dst, frX )); addInstr(env, PPCInstr_Cmp(False, True, 7, r_tmp, PPCRH_Imm(False,0))); addInstr(env, PPCInstr_FpCMov( cc, fr_dst, fr0 )); return fr_dst; } } vex_printf("iselDblExpr(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselDblExpr_wrk(ppc)"); } static HReg iselDfp64Expr(ISelEnv* env, IRExpr* e) { HReg r = iselDfp64Expr_wrk( env, e ); vassert(hregClass(r) == HRcFlt64); vassert( hregIsVirtual(r) ); return r; } static HReg iselDfp64Expr_wrk(ISelEnv* env, IRExpr* e) { Bool mode64 = env->mode64; IRType ty = typeOfIRExpr( env->type_env, e ); HReg r_dstHi, r_dstLo; vassert( e ); vassert( ty == Ity_D64 ); if (e->tag == Iex_RdTmp) { return lookupIRTemp( env, e->Iex.RdTmp.tmp ); } if (e->tag == Iex_Get) { HReg r_dst = newVRegF( env ); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ); addInstr( env, PPCInstr_FpLdSt( True, 8, r_dst, am_addr ) ); return r_dst; } if (e->tag == Iex_Qop) { HReg r_dst = newVRegF( env ); return r_dst; } if (e->tag == Iex_Unop) { HReg fr_dst = newVRegF(env); switch (e->Iex.Unop.op) { case Iop_ReinterpI64asD64: { if (!mode64) { HReg r_srcHi, r_srcLo; iselInt64Expr( &r_srcHi, &r_srcLo, env, e->Iex.Unop.arg); return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo ); } else { HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); return mk_LoadR64toFPR( env, r_src ); } } case Iop_ExtractExpD64: { HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Dfp64Unary(Pfp_DXEX, fr_dst, fr_src)); return fr_dst; } case Iop_ExtractExpD128: { HReg r_srcHi; HReg r_srcLo; iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Unop.arg); addInstr(env, PPCInstr_ExtractExpD128(Pfp_DXEXQ, fr_dst, r_srcHi, r_srcLo)); return fr_dst; } case Iop_D32toD64: { HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Dfp64Unary(Pfp_DCTDP, fr_dst, fr_src)); return fr_dst; } case Iop_D128HItoD64: iselDfp128Expr( &r_dstHi, &r_dstLo, env, e->Iex.Unop.arg ); return r_dstHi; case Iop_D128LOtoD64: iselDfp128Expr( &r_dstHi, &r_dstLo, env, e->Iex.Unop.arg ); return r_dstLo; case Iop_InsertExpD64: { HReg fr_srcL = iselDblExpr(env, e->Iex.Binop.arg1); HReg fr_srcR = iselDblExpr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp64Binary(Pfp_DIEX, fr_dst, fr_srcL, fr_srcR)); return fr_dst; } default: vex_printf( "ERROR: iselDfp64Expr_wrk, UNKNOWN unop case %d\n", e->Iex.Unop.op ); } } if (e->tag == Iex_Binop) { switch (e->Iex.Binop.op) { case Iop_D128toI64S: { PPCFpOp fpop = Pfp_DCTFIXQ; HReg fr_dst = newVRegF(env); HReg r_srcHi = newVRegF(env); HReg r_srcLo = newVRegF(env); set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 ); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo)); return fr_dst; } case Iop_D128toD64: { PPCFpOp fpop = Pfp_DRDPQ; HReg fr_dst = newVRegF(env); HReg r_srcHi = newVRegF(env); HReg r_srcLo = newVRegF(env); set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 ); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo)); return fr_dst; } break; default: break; } if (e->Iex.Unop.op == Iop_RoundD64toInt) { HReg fr_dst = newVRegF(env); HReg fr_src = newVRegF(env); PPCRI* r_rmc = iselWordExpr_RI(env, e->Iex.Binop.arg1); fr_src = iselDfp64Expr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpRound(fr_dst, fr_src, r_rmc)); return fr_dst; } } if (e->tag == Iex_Binop) { PPCFpOp fpop = Pfp_INVALID; HReg fr_dst = newVRegF(env); switch (e->Iex.Binop.op) { case Iop_D64toD32: fpop = Pfp_DRSP; break; case Iop_I64StoD64: fpop = Pfp_DCFFIX; break; case Iop_D64toI64S: fpop = Pfp_DCTFIX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_src = iselDfp64Expr(env, e->Iex.Binop.arg2); set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 ); addInstr(env, PPCInstr_Dfp64Unary(fpop, fr_dst, fr_src)); return fr_dst; } switch (e->Iex.Binop.op) { case Iop_ShlD64: fpop = Pfp_DSCLI; break; case Iop_ShrD64: fpop = Pfp_DSCRI; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_src = iselDfp64Expr(env, e->Iex.Binop.arg1); PPCRI* shift = iselWordExpr_RI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpShift(fpop, fr_dst, fr_src, shift)); return fr_dst; } switch (e->Iex.Binop.op) { case Iop_InsertExpD64: fpop = Pfp_DIEX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1); HReg fr_srcR = iselDfp64Expr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp64Binary(fpop, fr_dst, fr_srcL, fr_srcR)); return fr_dst; } } if (e->tag == Iex_Triop) { IRTriop *triop = e->Iex.Triop.details; PPCFpOp fpop = Pfp_INVALID; switch (triop->op) { case Iop_AddD64: fpop = Pfp_DFPADD; break; case Iop_SubD64: fpop = Pfp_DFPSUB; break; case Iop_MulD64: fpop = Pfp_DFPMUL; break; case Iop_DivD64: fpop = Pfp_DFPDIV; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF( env ); HReg r_srcL = iselDfp64Expr( env, triop->arg2 ); HReg r_srcR = iselDfp64Expr( env, triop->arg3 ); set_FPU_DFP_rounding_mode( env, triop->arg1 ); addInstr( env, PPCInstr_Dfp64Binary( fpop, r_dst, r_srcL, r_srcR ) ); return r_dst; } switch (triop->op) { case Iop_QuantizeD64: fpop = Pfp_DQUA; break; case Iop_SignificanceRoundD64: fpop = Pfp_RRDTR; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcL = iselDfp64Expr(env, triop->arg2); HReg r_srcR = iselDfp64Expr(env, triop->arg3); PPCRI* rmc = iselWordExpr_RI(env, triop->arg1); addInstr(env, PPCInstr_DfpQuantize(fpop, r_dst, r_srcL, r_srcR, rmc)); return r_dst; } } ppIRExpr( e ); vpanic( "iselDfp64Expr_wrk(ppc)" ); } static void iselDfp128Expr(HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e) { iselDfp128Expr_wrk( rHi, rLo, env, e ); vassert( hregIsVirtual(*rHi) ); vassert( hregIsVirtual(*rLo) ); } static void iselDfp128Expr_wrk(HReg* rHi, HReg *rLo, ISelEnv* env, IRExpr* e) { vassert( e ); vassert( typeOfIRExpr(env->type_env,e) == Ity_D128 ); if (e->tag == Iex_RdTmp) { lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp ); return; } if (e->tag == Iex_Unop) { PPCFpOp fpop = Pfp_INVALID; HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); if (e->Iex.Unop.op == Iop_I64StoD128) { HReg r_src = iselDfp64Expr(env, e->Iex.Unop.arg); fpop = Pfp_DCFFIXQ; addInstr(env, PPCInstr_DfpI64StoD128(fpop, r_dstHi, r_dstLo, r_src)); } if (e->Iex.Unop.op == Iop_D64toD128) { HReg r_src = iselDfp64Expr(env, e->Iex.Unop.arg); fpop = Pfp_DCTQPQ; addInstr(env, PPCInstr_Dfp128Unary(fpop, r_dstHi, r_dstLo, r_src, r_src)); } *rHi = r_dstHi; *rLo = r_dstLo; return; } if (e->tag == Iex_Binop) { HReg r_srcHi; HReg r_srcLo; switch (e->Iex.Binop.op) { case Iop_D64HLtoD128: r_srcHi = iselDfp64Expr( env, e->Iex.Binop.arg1 ); r_srcLo = iselDfp64Expr( env, e->Iex.Binop.arg2 ); *rHi = r_srcHi; *rLo = r_srcLo; return; break; case Iop_D128toD64: { PPCFpOp fpop = Pfp_DRDPQ; HReg fr_dst = newVRegF(env); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo)); *rHi = fr_dst; *rLo = fr_dst; return; } case Iop_ShlD128: case Iop_ShrD128: { HReg fr_dst_hi = newVRegF(env); HReg fr_dst_lo = newVRegF(env); PPCRI* shift = iselWordExpr_RI(env, e->Iex.Binop.arg2); PPCFpOp fpop = Pfp_DSCLIQ; iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg1); if (e->Iex.Binop.op == Iop_ShrD128) fpop = Pfp_DSCRIQ; addInstr(env, PPCInstr_DfpShift128(fpop, fr_dst_hi, fr_dst_lo, r_srcHi, r_srcLo, shift)); *rHi = fr_dst_hi; *rLo = fr_dst_lo; return; } case Iop_RoundD128toInt: { HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); PPCRI* r_rmc = iselWordExpr_RI(env, e->Iex.Binop.arg1); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpRound128(r_dstHi, r_dstLo, r_srcHi, r_srcLo, r_rmc)); *rHi = r_dstHi; *rLo = r_dstLo; return; } case Iop_InsertExpD128: { HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); HReg r_srcL = newVRegF(env); r_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_InsertExpD128(Pfp_DIEXQ, r_dstHi, r_dstLo, r_srcL, r_srcHi, r_srcLo)); *rHi = r_dstHi; *rLo = r_dstLo; return; } default: vex_printf( "ERROR: iselDfp128Expr_wrk, UNKNOWN binop case %d\n", e->Iex.Binop.op ); break; } } if (e->tag == Iex_Triop) { IRTriop *triop = e->Iex.Triop.details; PPCFpOp fpop = Pfp_INVALID; switch (triop->op) { case Iop_AddD128: fpop = Pfp_DFPADDQ; break; case Iop_SubD128: fpop = Pfp_DFPSUBQ; break; case Iop_MulD128: fpop = Pfp_DFPMULQ; break; case Iop_DivD128: fpop = Pfp_DFPDIVQ; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dstHi = newVRegV( env ); HReg r_dstLo = newVRegV( env ); HReg r_srcRHi = newVRegV( env ); HReg r_srcRLo = newVRegV( env ); iselDfp128Expr( &r_dstHi, &r_dstLo, env, triop->arg2 ); iselDfp128Expr( &r_srcRHi, &r_srcRLo, env, triop->arg3 ); set_FPU_rounding_mode( env, triop->arg1 ); addInstr( env, PPCInstr_Dfp128Binary( fpop, r_dstHi, r_dstLo, r_srcRHi, r_srcRLo ) ); *rHi = r_dstHi; *rLo = r_dstLo; return; } switch (triop->op) { case Iop_QuantizeD128: fpop = Pfp_DQUAQ; break; case Iop_SignificanceRoundD128: fpop = Pfp_DRRNDQ; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); HReg r_srcHi = newVRegF(env); HReg r_srcLo = newVRegF(env); PPCRI* rmc = iselWordExpr_RI(env, triop->arg1); iselDfp128Expr(&r_dstHi, &r_dstLo, env, triop->arg2); iselDfp128Expr(&r_srcHi, &r_srcLo, env, triop->arg3); addInstr(env, PPCInstr_DfpQuantize128(fpop, r_dstHi, r_dstLo, r_srcHi, r_srcLo, rmc)); *rHi = r_dstHi; *rLo = r_dstLo; return; } } ppIRExpr( e ); vpanic( "iselDfp128Expr(ppc64)" ); } static HReg iselVecExpr ( ISelEnv* env, IRExpr* e ) { HReg r = iselVecExpr_wrk( env, e ); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcVec128); vassert(hregIsVirtual(r)); return r; } static HReg iselVecExpr_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; PPCAvOp op = Pav_INVALID; PPCAvFpOp fpop = Pavfp_INVALID; IRType ty = typeOfIRExpr(env->type_env,e); vassert(e); vassert(ty == Ity_V128); if (e->tag == Iex_RdTmp) { return lookupIRTemp(env, e->Iex.RdTmp.tmp); } if (e->tag == Iex_Get) { HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvLdSt( True, 16, dst, PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ))); return dst; } if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { PPCAMode* am_addr; HReg v_dst = newVRegV(env); vassert(e->Iex.Load.ty == Ity_V128); am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_V128); addInstr(env, PPCInstr_AvLdSt( True, 16, v_dst, am_addr)); return v_dst; } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { case Iop_NotV128: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, arg)); return dst; } case Iop_CmpNEZ8x16: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg zero = newVRegV(env); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero)); addInstr(env, PPCInstr_AvBin8x16(Pav_CMPEQU, dst, arg, zero)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_CmpNEZ16x8: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg zero = newVRegV(env); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero)); addInstr(env, PPCInstr_AvBin16x8(Pav_CMPEQU, dst, arg, zero)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_CmpNEZ32x4: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg zero = newVRegV(env); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero)); addInstr(env, PPCInstr_AvBin32x4(Pav_CMPEQU, dst, arg, zero)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_Recip32Fx4: fpop = Pavfp_RCPF; goto do_32Fx4_unary; case Iop_RSqrt32Fx4: fpop = Pavfp_RSQRTF; goto do_32Fx4_unary; case Iop_I32UtoFx4: fpop = Pavfp_CVTU2F; goto do_32Fx4_unary; case Iop_I32StoFx4: fpop = Pavfp_CVTS2F; goto do_32Fx4_unary; case Iop_QFtoI32Ux4_RZ: fpop = Pavfp_QCVTF2U; goto do_32Fx4_unary; case Iop_QFtoI32Sx4_RZ: fpop = Pavfp_QCVTF2S; goto do_32Fx4_unary; case Iop_RoundF32x4_RM: fpop = Pavfp_ROUNDM; goto do_32Fx4_unary; case Iop_RoundF32x4_RP: fpop = Pavfp_ROUNDP; goto do_32Fx4_unary; case Iop_RoundF32x4_RN: fpop = Pavfp_ROUNDN; goto do_32Fx4_unary; case Iop_RoundF32x4_RZ: fpop = Pavfp_ROUNDZ; goto do_32Fx4_unary; do_32Fx4_unary: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvUn32Fx4(fpop, dst, arg)); return dst; } case Iop_32UtoV128: { HReg r_aligned16, r_zeros; HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); HReg dst = newVRegV(env); PPCAMode *am_off0, *am_off4, *am_off8, *am_off12; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off4 = PPCAMode_IR( 4, r_aligned16 ); am_off8 = PPCAMode_IR( 8, r_aligned16 ); am_off12 = PPCAMode_IR( 12, r_aligned16 ); r_zeros = newVRegI(env); addInstr(env, PPCInstr_LI(r_zeros, 0x0, mode64)); addInstr(env, PPCInstr_Store( 4, am_off0, r_zeros, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off4, r_zeros, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off8, r_zeros, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off12, r_src, mode64 )); addInstr(env, PPCInstr_AvLdSt( True, 4, dst, am_off12 )); add_to_sp( env, 32 ); return dst; } case Iop_Dup8x16: case Iop_Dup16x8: case Iop_Dup32x4: return mk_AvDuplicateRI(env, e->Iex.Unop.arg); default: break; } } if (e->tag == Iex_Binop) { switch (e->Iex.Binop.op) { case Iop_64HLtoV128: { if (!mode64) { HReg r3, r2, r1, r0, r_aligned16; PPCAMode *am_off0, *am_off4, *am_off8, *am_off12; HReg dst = newVRegV(env); sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off4 = PPCAMode_IR( 4, r_aligned16 ); am_off8 = PPCAMode_IR( 8, r_aligned16 ); am_off12 = PPCAMode_IR( 12, r_aligned16 ); iselInt64Expr(&r1, &r0, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Store( 4, am_off12, r0, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off8, r1, mode64 )); iselInt64Expr(&r3, &r2, env, e->Iex.Binop.arg1); addInstr(env, PPCInstr_Store( 4, am_off4, r2, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off0, r3, mode64 )); addInstr(env, PPCInstr_AvLdSt(True, 16, dst, am_off0)); add_to_sp( env, 32 ); return dst; } else { HReg rHi = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg rLo = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); HReg r_aligned16; PPCAMode *am_off0, *am_off8; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off8 = PPCAMode_IR( 8, r_aligned16 ); addInstr(env, PPCInstr_Store( 8, am_off0, rHi, mode64 )); addInstr(env, PPCInstr_Store( 8, am_off8, rLo, mode64 )); addInstr(env, PPCInstr_AvLdSt(True, 16, dst, am_off0)); add_to_sp( env, 32 ); return dst; } } case Iop_Add32Fx4: fpop = Pavfp_ADDF; goto do_32Fx4; case Iop_Sub32Fx4: fpop = Pavfp_SUBF; goto do_32Fx4; case Iop_Max32Fx4: fpop = Pavfp_MAXF; goto do_32Fx4; case Iop_Min32Fx4: fpop = Pavfp_MINF; goto do_32Fx4; case Iop_Mul32Fx4: fpop = Pavfp_MULF; goto do_32Fx4; case Iop_CmpEQ32Fx4: fpop = Pavfp_CMPEQF; goto do_32Fx4; case Iop_CmpGT32Fx4: fpop = Pavfp_CMPGTF; goto do_32Fx4; case Iop_CmpGE32Fx4: fpop = Pavfp_CMPGEF; goto do_32Fx4; do_32Fx4: { HReg argL = iselVecExpr(env, e->Iex.Binop.arg1); HReg argR = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin32Fx4(fpop, dst, argL, argR)); return dst; } case Iop_CmpLE32Fx4: { HReg argL = iselVecExpr(env, e->Iex.Binop.arg1); HReg argR = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); HReg isNanLR = newVRegV(env); HReg isNanL = isNan(env, argL); HReg isNanR = isNan(env, argR); addInstr(env, PPCInstr_AvBinary(Pav_OR, isNanLR, isNanL, isNanR)); addInstr(env, PPCInstr_AvBin32Fx4(Pavfp_CMPGTF, dst, argL, argR)); addInstr(env, PPCInstr_AvBinary(Pav_OR, dst, dst, isNanLR)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_AndV128: op = Pav_AND; goto do_AvBin; case Iop_OrV128: op = Pav_OR; goto do_AvBin; case Iop_XorV128: op = Pav_XOR; goto do_AvBin; do_AvBin: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(op, dst, arg1, arg2)); return dst; } case Iop_Shl8x16: op = Pav_SHL; goto do_AvBin8x16; case Iop_Shr8x16: op = Pav_SHR; goto do_AvBin8x16; case Iop_Sar8x16: op = Pav_SAR; goto do_AvBin8x16; case Iop_Rol8x16: op = Pav_ROTL; goto do_AvBin8x16; case Iop_InterleaveHI8x16: op = Pav_MRGHI; goto do_AvBin8x16; case Iop_InterleaveLO8x16: op = Pav_MRGLO; goto do_AvBin8x16; case Iop_Add8x16: op = Pav_ADDU; goto do_AvBin8x16; case Iop_QAdd8Ux16: op = Pav_QADDU; goto do_AvBin8x16; case Iop_QAdd8Sx16: op = Pav_QADDS; goto do_AvBin8x16; case Iop_Sub8x16: op = Pav_SUBU; goto do_AvBin8x16; case Iop_QSub8Ux16: op = Pav_QSUBU; goto do_AvBin8x16; case Iop_QSub8Sx16: op = Pav_QSUBS; goto do_AvBin8x16; case Iop_Avg8Ux16: op = Pav_AVGU; goto do_AvBin8x16; case Iop_Avg8Sx16: op = Pav_AVGS; goto do_AvBin8x16; case Iop_Max8Ux16: op = Pav_MAXU; goto do_AvBin8x16; case Iop_Max8Sx16: op = Pav_MAXS; goto do_AvBin8x16; case Iop_Min8Ux16: op = Pav_MINU; goto do_AvBin8x16; case Iop_Min8Sx16: op = Pav_MINS; goto do_AvBin8x16; case Iop_MullEven8Ux16: op = Pav_OMULU; goto do_AvBin8x16; case Iop_MullEven8Sx16: op = Pav_OMULS; goto do_AvBin8x16; case Iop_CmpEQ8x16: op = Pav_CMPEQU; goto do_AvBin8x16; case Iop_CmpGT8Ux16: op = Pav_CMPGTU; goto do_AvBin8x16; case Iop_CmpGT8Sx16: op = Pav_CMPGTS; goto do_AvBin8x16; do_AvBin8x16: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin8x16(op, dst, arg1, arg2)); return dst; } case Iop_Shl16x8: op = Pav_SHL; goto do_AvBin16x8; case Iop_Shr16x8: op = Pav_SHR; goto do_AvBin16x8; case Iop_Sar16x8: op = Pav_SAR; goto do_AvBin16x8; case Iop_Rol16x8: op = Pav_ROTL; goto do_AvBin16x8; case Iop_NarrowBin16to8x16: op = Pav_PACKUU; goto do_AvBin16x8; case Iop_QNarrowBin16Uto8Ux16: op = Pav_QPACKUU; goto do_AvBin16x8; case Iop_QNarrowBin16Sto8Sx16: op = Pav_QPACKSS; goto do_AvBin16x8; case Iop_InterleaveHI16x8: op = Pav_MRGHI; goto do_AvBin16x8; case Iop_InterleaveLO16x8: op = Pav_MRGLO; goto do_AvBin16x8; case Iop_Add16x8: op = Pav_ADDU; goto do_AvBin16x8; case Iop_QAdd16Ux8: op = Pav_QADDU; goto do_AvBin16x8; case Iop_QAdd16Sx8: op = Pav_QADDS; goto do_AvBin16x8; case Iop_Sub16x8: op = Pav_SUBU; goto do_AvBin16x8; case Iop_QSub16Ux8: op = Pav_QSUBU; goto do_AvBin16x8; case Iop_QSub16Sx8: op = Pav_QSUBS; goto do_AvBin16x8; case Iop_Avg16Ux8: op = Pav_AVGU; goto do_AvBin16x8; case Iop_Avg16Sx8: op = Pav_AVGS; goto do_AvBin16x8; case Iop_Max16Ux8: op = Pav_MAXU; goto do_AvBin16x8; case Iop_Max16Sx8: op = Pav_MAXS; goto do_AvBin16x8; case Iop_Min16Ux8: op = Pav_MINU; goto do_AvBin16x8; case Iop_Min16Sx8: op = Pav_MINS; goto do_AvBin16x8; case Iop_MullEven16Ux8: op = Pav_OMULU; goto do_AvBin16x8; case Iop_MullEven16Sx8: op = Pav_OMULS; goto do_AvBin16x8; case Iop_CmpEQ16x8: op = Pav_CMPEQU; goto do_AvBin16x8; case Iop_CmpGT16Ux8: op = Pav_CMPGTU; goto do_AvBin16x8; case Iop_CmpGT16Sx8: op = Pav_CMPGTS; goto do_AvBin16x8; do_AvBin16x8: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin16x8(op, dst, arg1, arg2)); return dst; } case Iop_Shl32x4: op = Pav_SHL; goto do_AvBin32x4; case Iop_Shr32x4: op = Pav_SHR; goto do_AvBin32x4; case Iop_Sar32x4: op = Pav_SAR; goto do_AvBin32x4; case Iop_Rol32x4: op = Pav_ROTL; goto do_AvBin32x4; case Iop_NarrowBin32to16x8: op = Pav_PACKUU; goto do_AvBin32x4; case Iop_QNarrowBin32Uto16Ux8: op = Pav_QPACKUU; goto do_AvBin32x4; case Iop_QNarrowBin32Sto16Sx8: op = Pav_QPACKSS; goto do_AvBin32x4; case Iop_InterleaveHI32x4: op = Pav_MRGHI; goto do_AvBin32x4; case Iop_InterleaveLO32x4: op = Pav_MRGLO; goto do_AvBin32x4; case Iop_Add32x4: op = Pav_ADDU; goto do_AvBin32x4; case Iop_QAdd32Ux4: op = Pav_QADDU; goto do_AvBin32x4; case Iop_QAdd32Sx4: op = Pav_QADDS; goto do_AvBin32x4; case Iop_Sub32x4: op = Pav_SUBU; goto do_AvBin32x4; case Iop_QSub32Ux4: op = Pav_QSUBU; goto do_AvBin32x4; case Iop_QSub32Sx4: op = Pav_QSUBS; goto do_AvBin32x4; case Iop_Avg32Ux4: op = Pav_AVGU; goto do_AvBin32x4; case Iop_Avg32Sx4: op = Pav_AVGS; goto do_AvBin32x4; case Iop_Max32Ux4: op = Pav_MAXU; goto do_AvBin32x4; case Iop_Max32Sx4: op = Pav_MAXS; goto do_AvBin32x4; case Iop_Min32Ux4: op = Pav_MINU; goto do_AvBin32x4; case Iop_Min32Sx4: op = Pav_MINS; goto do_AvBin32x4; case Iop_CmpEQ32x4: op = Pav_CMPEQU; goto do_AvBin32x4; case Iop_CmpGT32Ux4: op = Pav_CMPGTU; goto do_AvBin32x4; case Iop_CmpGT32Sx4: op = Pav_CMPGTS; goto do_AvBin32x4; do_AvBin32x4: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin32x4(op, dst, arg1, arg2)); return dst; } case Iop_ShlN8x16: op = Pav_SHL; goto do_AvShift8x16; case Iop_SarN8x16: op = Pav_SAR; goto do_AvShift8x16; do_AvShift8x16: { HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg dst = newVRegV(env); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBin8x16(op, dst, r_src, v_shft)); return dst; } case Iop_ShlN16x8: op = Pav_SHL; goto do_AvShift16x8; case Iop_ShrN16x8: op = Pav_SHR; goto do_AvShift16x8; case Iop_SarN16x8: op = Pav_SAR; goto do_AvShift16x8; do_AvShift16x8: { HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg dst = newVRegV(env); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBin16x8(op, dst, r_src, v_shft)); return dst; } case Iop_ShlN32x4: op = Pav_SHL; goto do_AvShift32x4; case Iop_ShrN32x4: op = Pav_SHR; goto do_AvShift32x4; case Iop_SarN32x4: op = Pav_SAR; goto do_AvShift32x4; do_AvShift32x4: { HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg dst = newVRegV(env); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBin32x4(op, dst, r_src, v_shft)); return dst; } case Iop_ShrV128: op = Pav_SHR; goto do_AvShiftV128; case Iop_ShlV128: op = Pav_SHL; goto do_AvShiftV128; do_AvShiftV128: { HReg dst = newVRegV(env); HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBinary(op, dst, r_src, v_shft)); return dst; } case Iop_Perm8x16: { HReg dst = newVRegV(env); HReg v_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg v_ctl = iselVecExpr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvPerm(dst, v_src, v_src, v_ctl)); return dst; } default: break; } } if (e->tag == Iex_Const ) { vassert(e->Iex.Const.con->tag == Ico_V128); if (e->Iex.Const.con->Ico.V128 == 0x0000) { return generate_zeroes_V128(env); } else if (e->Iex.Const.con->Ico.V128 == 0xffff) { return generate_ones_V128(env); } } vex_printf("iselVecExpr(ppc) (subarch = %s): can't reduce\n", LibVEX_ppVexHwCaps(mode64 ? VexArchPPC64 : VexArchPPC32, env->hwcaps)); ppIRExpr(e); vpanic("iselVecExpr_wrk(ppc)"); } static void iselStmt ( ISelEnv* env, IRStmt* stmt ) { Bool mode64 = env->mode64; if (vex_traceflags & VEX_TRACE_VCODE) { vex_printf("\n -- "); ppIRStmt(stmt); vex_printf("\n"); } switch (stmt->tag) { case Ist_Store: { IRType tya = typeOfIRExpr(env->type_env, stmt->Ist.Store.addr); IRType tyd = typeOfIRExpr(env->type_env, stmt->Ist.Store.data); IREndness end = stmt->Ist.Store.end; if (end != Iend_BE) goto stmt_fail; if (!mode64 && (tya != Ity_I32)) goto stmt_fail; if (mode64 && (tya != Ity_I64)) goto stmt_fail; if (tyd == Ity_I8 || tyd == Ity_I16 || tyd == Ity_I32 || (mode64 && (tyd == Ity_I64))) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg r_src = iselWordExpr_R(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_Store( toUChar(sizeofIRType(tyd)), am_addr, r_src, mode64 )); return; } if (tyd == Ity_F64) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg fr_src = iselDblExpr(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_FpLdSt(False, 8, fr_src, am_addr)); return; } if (tyd == Ity_F32) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg fr_src = iselFltExpr(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_FpLdSt(False, 4, fr_src, am_addr)); return; } if (tyd == Ity_V128) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg v_src = iselVecExpr(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_AvLdSt(False, 16, v_src, am_addr)); return; } if (tyd == Ity_I64 && !mode64) { HReg rHi32, rLo32; HReg r_addr = iselWordExpr_R(env, stmt->Ist.Store.addr); iselInt64Expr( &rHi32, &rLo32, env, stmt->Ist.Store.data ); addInstr(env, PPCInstr_Store( 4, PPCAMode_IR( 0, r_addr ), rHi32, False) ); addInstr(env, PPCInstr_Store( 4, PPCAMode_IR( 4, r_addr ), rLo32, False) ); return; } break; } case Ist_Put: { IRType ty = typeOfIRExpr(env->type_env, stmt->Ist.Put.data); if (ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) { HReg r_src = iselWordExpr_R(env, stmt->Ist.Put.data); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_Store( toUChar(sizeofIRType(ty)), am_addr, r_src, mode64 )); return; } if (!mode64 && ty == Ity_I64) { HReg rHi, rLo; PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); PPCAMode* am_addr4 = advance4(env, am_addr); iselInt64Expr(&rHi,&rLo, env, stmt->Ist.Put.data); addInstr(env, PPCInstr_Store( 4, am_addr, rHi, mode64 )); addInstr(env, PPCInstr_Store( 4, am_addr4, rLo, mode64 )); return; } if (ty == Ity_V128) { HReg v_src = iselVecExpr(env, stmt->Ist.Put.data); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_AvLdSt(False, 16, v_src, am_addr)); return; } if (ty == Ity_F64) { HReg fr_src = iselDblExpr(env, stmt->Ist.Put.data); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr )); return; } if (ty == Ity_D64) { HReg fr_src = iselDfp64Expr( env, stmt->Ist.Put.data ); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr( env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr ) ); return; } break; } case Ist_PutI: { IRPutI *puti = stmt->Ist.PutI.details; PPCAMode* dst_am = genGuestArrayOffset( env, puti->descr, puti->ix, puti->bias ); IRType ty = typeOfIRExpr(env->type_env, puti->data); if (mode64 && ty == Ity_I64) { HReg r_src = iselWordExpr_R(env, puti->data); addInstr(env, PPCInstr_Store( toUChar(8), dst_am, r_src, mode64 )); return; } if ((!mode64) && ty == Ity_I32) { HReg r_src = iselWordExpr_R(env, puti->data); addInstr(env, PPCInstr_Store( toUChar(4), dst_am, r_src, mode64 )); return; } break; } case Ist_WrTmp: { IRTemp tmp = stmt->Ist.WrTmp.tmp; IRType ty = typeOfIRTemp(env->type_env, tmp); if (ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) { HReg r_dst = lookupIRTemp(env, tmp); HReg r_src = iselWordExpr_R(env, stmt->Ist.WrTmp.data); addInstr(env, mk_iMOVds_RR( r_dst, r_src )); return; } if (!mode64 && ty == Ity_I64) { HReg r_srcHi, r_srcLo, r_dstHi, r_dstLo; iselInt64Expr(&r_srcHi,&r_srcLo, env, stmt->Ist.WrTmp.data); lookupIRTempPair( &r_dstHi, &r_dstLo, env, tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) ); addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) ); return; } if (mode64 && ty == Ity_I128) { HReg r_srcHi, r_srcLo, r_dstHi, r_dstLo; iselInt128Expr(&r_srcHi,&r_srcLo, env, stmt->Ist.WrTmp.data); lookupIRTempPair( &r_dstHi, &r_dstLo, env, tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) ); addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) ); return; } if (!mode64 && ty == Ity_I128) { HReg r_srcHi, r_srcMedHi, r_srcMedLo, r_srcLo; HReg r_dstHi, r_dstMedHi, r_dstMedLo, r_dstLo; iselInt128Expr_to_32x4(&r_srcHi, &r_srcMedHi, &r_srcMedLo, &r_srcLo, env, stmt->Ist.WrTmp.data); lookupIRTempQuad( &r_dstHi, &r_dstMedHi, &r_dstMedLo, &r_dstLo, env, tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) ); addInstr(env, mk_iMOVds_RR(r_dstMedHi, r_srcMedHi) ); addInstr(env, mk_iMOVds_RR(r_dstMedLo, r_srcMedLo) ); addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) ); return; } if (ty == Ity_I1) { PPCCondCode cond = iselCondCode(env, stmt->Ist.WrTmp.data); HReg r_dst = lookupIRTemp(env, tmp); addInstr(env, PPCInstr_Set(cond, r_dst)); return; } if (ty == Ity_F64) { HReg fr_dst = lookupIRTemp(env, tmp); HReg fr_src = iselDblExpr(env, stmt->Ist.WrTmp.data); addInstr(env, PPCInstr_FpUnary(Pfp_MOV, fr_dst, fr_src)); return; } if (ty == Ity_F32) { HReg fr_dst = lookupIRTemp(env, tmp); HReg fr_src = iselFltExpr(env, stmt->Ist.WrTmp.data); addInstr(env, PPCInstr_FpUnary(Pfp_MOV, fr_dst, fr_src)); return; } if (ty == Ity_V128) { HReg v_dst = lookupIRTemp(env, tmp); HReg v_src = iselVecExpr(env, stmt->Ist.WrTmp.data); addInstr(env, PPCInstr_AvUnary(Pav_MOV, v_dst, v_src)); return; } if (ty == Ity_D64) { HReg fr_dst = lookupIRTemp( env, tmp ); HReg fr_src = iselDfp64Expr( env, stmt->Ist.WrTmp.data ); addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dst, fr_src ) ); return; } if (ty == Ity_D128) { HReg fr_srcHi, fr_srcLo, fr_dstHi, fr_dstLo; lookupIRTempPair( &fr_dstHi, &fr_dstLo, env, tmp ); iselDfp128Expr( &fr_srcHi, &fr_srcLo, env, stmt->Ist.WrTmp.data ); addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dstHi, fr_srcHi ) ); addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dstLo, fr_srcLo ) ); return; } break; } case Ist_LLSC: { IRTemp res = stmt->Ist.LLSC.result; IRType tyRes = typeOfIRTemp(env->type_env, res); IRType tyAddr = typeOfIRExpr(env->type_env, stmt->Ist.LLSC.addr); if (stmt->Ist.LLSC.end != Iend_BE) goto stmt_fail; if (!mode64 && (tyAddr != Ity_I32)) goto stmt_fail; if (mode64 && (tyAddr != Ity_I64)) goto stmt_fail; if (stmt->Ist.LLSC.storedata == NULL) { HReg r_addr = iselWordExpr_R( env, stmt->Ist.LLSC.addr ); HReg r_dst = lookupIRTemp(env, res); if (tyRes == Ity_I32) { addInstr(env, PPCInstr_LoadL( 4, r_dst, r_addr, mode64 )); return; } if (tyRes == Ity_I64 && mode64) { addInstr(env, PPCInstr_LoadL( 8, r_dst, r_addr, mode64 )); return; } ; } else { HReg r_res = lookupIRTemp(env, res); HReg r_a = iselWordExpr_R(env, stmt->Ist.LLSC.addr); HReg r_src = iselWordExpr_R(env, stmt->Ist.LLSC.storedata); HReg r_tmp = newVRegI(env); IRType tyData = typeOfIRExpr(env->type_env, stmt->Ist.LLSC.storedata); vassert(tyRes == Ity_I1); if (tyData == Ity_I32 || (tyData == Ity_I64 && mode64)) { addInstr(env, PPCInstr_StoreC( tyData==Ity_I32 ? 4 : 8, r_a, r_src, mode64 )); addInstr(env, PPCInstr_MfCR( r_tmp )); addInstr(env, PPCInstr_Shft( Pshft_SHR, env->mode64 ? False : True , r_tmp, r_tmp, PPCRH_Imm(False, 29))); addInstr(env, PPCInstr_Alu( Palu_AND, r_res, r_tmp, PPCRH_Imm(False, 1))); return; } } goto stmt_fail; } case Ist_Dirty: { IRType retty; IRDirty* d = stmt->Ist.Dirty.details; Bool passBBP = False; if (d->nFxState == 0) vassert(!d->needsBBP); passBBP = toBool(d->nFxState > 0 && d->needsBBP); doHelperCall( env, passBBP, d->guard, d->cee, d->args ); if (d->tmp == IRTemp_INVALID) return; retty = typeOfIRTemp(env->type_env, d->tmp); if (!mode64 && retty == Ity_I64) { HReg r_dstHi, r_dstLo; lookupIRTempPair( &r_dstHi, &r_dstLo, env, d->tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, hregPPC_GPR3(mode64))); addInstr(env, mk_iMOVds_RR(r_dstLo, hregPPC_GPR4(mode64))); return; } if (retty == Ity_I8 || retty == Ity_I16 || retty == Ity_I32 || ((retty == Ity_I64) && mode64)) { HReg r_dst = lookupIRTemp(env, d->tmp); addInstr(env, mk_iMOVds_RR(r_dst, hregPPC_GPR3(mode64))); return; } break; } case Ist_MBE: switch (stmt->Ist.MBE.event) { case Imbe_Fence: addInstr(env, PPCInstr_MFence()); return; default: break; } break; case Ist_IMark: return; case Ist_AbiHint: return; case Ist_NoOp: return; case Ist_Exit: { IRConst* dst = stmt->Ist.Exit.dst; if (!mode64 && dst->tag != Ico_U32) vpanic("iselStmt(ppc): Ist_Exit: dst is not a 32-bit value"); if (mode64 && dst->tag != Ico_U64) vpanic("iselStmt(ppc64): Ist_Exit: dst is not a 64-bit value"); PPCCondCode cc = iselCondCode(env, stmt->Ist.Exit.guard); PPCAMode* amCIA = PPCAMode_IR(stmt->Ist.Exit.offsIP, hregPPC_GPR31(mode64)); if (stmt->Ist.Exit.jk == Ijk_Boring || stmt->Ist.Exit.jk == Ijk_Call ) { if (env->chainingAllowed) { Bool toFastEP = mode64 ? (((Addr64)stmt->Ist.Exit.dst->Ico.U64) > (Addr64)env->max_ga) : (((Addr32)stmt->Ist.Exit.dst->Ico.U32) > (Addr32)env->max_ga); if (0) vex_printf("%s", toFastEP ? "Y" : ","); addInstr(env, PPCInstr_XDirect( mode64 ? (Addr64)stmt->Ist.Exit.dst->Ico.U64 : (Addr64)stmt->Ist.Exit.dst->Ico.U32, amCIA, cc, toFastEP)); } else { HReg r = iselWordExpr_R(env, IRExpr_Const(stmt->Ist.Exit.dst)); addInstr(env, PPCInstr_XAssisted(r, amCIA, cc, Ijk_Boring)); } return; } switch (stmt->Ist.Exit.jk) { case Ijk_ClientReq: case Ijk_EmFail: case Ijk_EmWarn: case Ijk_NoDecode: case Ijk_NoRedir: case Ijk_SigBUS: case Ijk_SigTRAP: case Ijk_Sys_syscall: case Ijk_TInval: { HReg r = iselWordExpr_R(env, IRExpr_Const(stmt->Ist.Exit.dst)); addInstr(env, PPCInstr_XAssisted(r, amCIA, cc, stmt->Ist.Exit.jk)); return; } default: break; } goto stmt_fail; } default: break; } stmt_fail: ppIRStmt(stmt); vpanic("iselStmt(ppc)"); } static void iselNext ( ISelEnv* env, IRExpr* next, IRJumpKind jk, Int offsIP ) { if (vex_traceflags & VEX_TRACE_VCODE) { vex_printf( "\n-- PUT(%d) = ", offsIP); ppIRExpr( next ); vex_printf( "; exit-"); ppIRJumpKind(jk); vex_printf( "\n"); } PPCCondCode always = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); if (next->tag == Iex_Const) { IRConst* cdst = next->Iex.Const.con; vassert(cdst->tag == (env->mode64 ? Ico_U64 :Ico_U32)); if (jk == Ijk_Boring || jk == Ijk_Call) { PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64)); if (env->chainingAllowed) { Bool toFastEP = env->mode64 ? (((Addr64)cdst->Ico.U64) > (Addr64)env->max_ga) : (((Addr32)cdst->Ico.U32) > (Addr32)env->max_ga); if (0) vex_printf("%s", toFastEP ? "X" : "."); addInstr(env, PPCInstr_XDirect( env->mode64 ? (Addr64)cdst->Ico.U64 : (Addr64)cdst->Ico.U32, amCIA, always, toFastEP)); } else { HReg r = iselWordExpr_R(env, next); addInstr(env, PPCInstr_XAssisted(r, amCIA, always, Ijk_Boring)); } return; } } switch (jk) { case Ijk_Boring: case Ijk_Ret: case Ijk_Call: { HReg r = iselWordExpr_R(env, next); PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64)); if (env->chainingAllowed) { addInstr(env, PPCInstr_XIndir(r, amCIA, always)); } else { addInstr(env, PPCInstr_XAssisted(r, amCIA, always, Ijk_Boring)); } return; } default: break; } switch (jk) { case Ijk_ClientReq: case Ijk_EmFail: case Ijk_EmWarn: case Ijk_NoDecode: case Ijk_NoRedir: case Ijk_SigBUS: case Ijk_SigTRAP: case Ijk_Sys_syscall: case Ijk_TInval: { HReg r = iselWordExpr_R(env, next); PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64)); addInstr(env, PPCInstr_XAssisted(r, amCIA, always, jk)); return; } default: break; } vex_printf( "\n-- PUT(%d) = ", offsIP); ppIRExpr( next ); vex_printf( "; exit-"); ppIRJumpKind(jk); vex_printf( "\n"); vassert(0); } HInstrArray* iselSB_PPC ( IRSB* bb, VexArch arch_host, VexArchInfo* archinfo_host, VexAbiInfo* vbi, Int offs_Host_EvC_Counter, Int offs_Host_EvC_FailAddr, Bool chainingAllowed, Bool addProfInc, Addr64 max_ga ) { Int i, j; HReg hregLo, hregMedLo, hregMedHi, hregHi; ISelEnv* env; UInt hwcaps_host = archinfo_host->hwcaps; Bool mode64 = False; UInt mask32, mask64; PPCAMode *amCounter, *amFailAddr; vassert(arch_host == VexArchPPC32 || arch_host == VexArchPPC64); mode64 = arch_host == VexArchPPC64; if (!mode64) vassert(max_ga <= 0xFFFFFFFFULL); mask32 = VEX_HWCAPS_PPC32_F | VEX_HWCAPS_PPC32_V | VEX_HWCAPS_PPC32_FX | VEX_HWCAPS_PPC32_GX | VEX_HWCAPS_PPC32_VX | VEX_HWCAPS_PPC32_DFP; mask64 = VEX_HWCAPS_PPC64_V | VEX_HWCAPS_PPC64_FX | VEX_HWCAPS_PPC64_GX | VEX_HWCAPS_PPC64_VX | VEX_HWCAPS_PPC64_DFP; if (mode64) { vassert((hwcaps_host & mask32) == 0); } else { vassert((hwcaps_host & mask64) == 0); } env = LibVEX_Alloc(sizeof(ISelEnv)); env->vreg_ctr = 0; env->mode64 = mode64; env->code = newHInstrArray(); env->type_env = bb->tyenv; env->n_vregmap = bb->tyenv->types_used; env->vregmapLo = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); env->vregmapMedLo = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); if (mode64) { env->vregmapMedHi = NULL; env->vregmapHi = NULL; } else { env->vregmapMedHi = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); env->vregmapHi = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); } env->chainingAllowed = chainingAllowed; env->max_ga = max_ga; env->hwcaps = hwcaps_host; env->previous_rm = NULL; env->vbi = vbi; j = 0; for (i = 0; i < env->n_vregmap; i++) { hregLo = hregMedLo = hregMedHi = hregHi = INVALID_HREG; switch (bb->tyenv->types[i]) { case Ity_I1: case Ity_I8: case Ity_I16: case Ity_I32: if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); break; } else { hregLo = mkHReg(j++, HRcInt32, True); break; } case Ity_I64: if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); break; } else { hregLo = mkHReg(j++, HRcInt32, True); hregMedLo = mkHReg(j++, HRcInt32, True); break; } case Ity_I128: if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); hregMedLo = mkHReg(j++, HRcInt64, True); break; } else { hregLo = mkHReg(j++, HRcInt32, True); hregMedLo = mkHReg(j++, HRcInt32, True); hregMedHi = mkHReg(j++, HRcInt32, True); hregHi = mkHReg(j++, HRcInt32, True); break; } case Ity_F32: case Ity_F64: hregLo = mkHReg(j++, HRcFlt64, True); break; case Ity_V128: hregLo = mkHReg(j++, HRcVec128, True); break; case Ity_D64: hregLo = mkHReg(j++, HRcFlt64, True); break; case Ity_D128: hregLo = mkHReg(j++, HRcFlt64, True); hregMedLo = mkHReg(j++, HRcFlt64, True); break; default: ppIRType(bb->tyenv->types[i]); vpanic("iselBB(ppc): IRTemp type"); } env->vregmapLo[i] = hregLo; env->vregmapMedLo[i] = hregMedLo; if (!mode64) { env->vregmapMedHi[i] = hregMedHi; env->vregmapHi[i] = hregHi; } } env->vreg_ctr = j; amCounter = PPCAMode_IR(offs_Host_EvC_Counter, hregPPC_GPR31(mode64)); amFailAddr = PPCAMode_IR(offs_Host_EvC_FailAddr, hregPPC_GPR31(mode64)); addInstr(env, PPCInstr_EvCheck(amCounter, amFailAddr)); if (addProfInc) { addInstr(env, PPCInstr_ProfInc()); } for (i = 0; i < bb->stmts_used; i++) iselStmt(env, bb->stmts[i]); iselNext(env, bb->next, bb->jumpkind, bb->offsIP); env->code->n_vregs = env->vreg_ctr; return env->code; }
qtekfun/htcDesire820Kernel
external/valgrind/main/VEX/priv/host_ppc_isel.c
C
gpl-2.0
151,543
/* * Implementation of the security services. * * Authors : Stephen Smalley, <sds@epoch.ncsc.mil> * James Morris <jmorris@redhat.com> * * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com> * * Support for enhanced MLS infrastructure. * Support for context based audit filters. * * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com> * * Added conditional policy language extensions * * Updated: Hewlett-Packard <paul@paul-moore.com> * * Added support for NetLabel * Added support for the policy capability bitmap * * Updated: Chad Sellers <csellers@tresys.com> * * Added validation of kernel classes and permissions * * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com> * * Added support for bounds domain and audit messaged on masked permissions * * Updated: Guido Trentalancia <guido@trentalancia.com> * * Added support for runtime switching of the policy type * * Copyright (C) 2008, 2009 NEC Corporation * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P. * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc. * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.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, version 2. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/spinlock.h> #include <linux/rcupdate.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/sched.h> #include <linux/audit.h> #include <linux/mutex.h> #include <linux/selinux.h> #include <linux/flex_array.h> #include <linux/vmalloc.h> #include <net/netlabel.h> #include "flask.h" #include "avc.h" #include "avc_ss.h" #include "security.h" #include "context.h" #include "policydb.h" #include "sidtab.h" #include "services.h" #include "conditional.h" #include "mls.h" #include "objsec.h" #include "netlabel.h" #include "xfrm.h" #include "ebitmap.h" #include "audit.h" int selinux_policycap_netpeer; int selinux_policycap_openperm; static DEFINE_RWLOCK(policy_rwlock); static struct sidtab sidtab; struct policydb policydb; int ss_initialized; /* * The largest sequence number that has been used when * providing an access decision to the access vector cache. * The sequence number only changes when a policy change * occurs. */ static u32 latest_granting; /* Forward declaration. */ static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len); static void context_struct_compute_av(struct context *scontext, struct context *tcontext, u16 tclass, struct av_decision *avd); struct selinux_mapping { u16 value; /* policy value */ unsigned num_perms; u32 perms[sizeof(u32) * 8]; }; static struct selinux_mapping *current_mapping; static u16 current_mapping_size; static int selinux_set_mapping(struct policydb *pol, struct security_class_mapping *map, struct selinux_mapping **out_map_p, u16 *out_map_size) { struct selinux_mapping *out_map = NULL; size_t size = sizeof(struct selinux_mapping); u16 i, j; unsigned k; bool print_unknown_handle = false; /* Find number of classes in the input mapping */ if (!map) return -EINVAL; i = 0; while (map[i].name) i++; /* Allocate space for the class records, plus one for class zero */ out_map = kcalloc(++i, size, GFP_ATOMIC); if (!out_map) return -ENOMEM; /* Store the raw class and permission values */ j = 0; while (map[j].name) { struct security_class_mapping *p_in = map + (j++); struct selinux_mapping *p_out = out_map + j; /* An empty class string skips ahead */ if (!strcmp(p_in->name, "")) { p_out->num_perms = 0; continue; } p_out->value = string_to_security_class(pol, p_in->name); if (!p_out->value) { printk(KERN_INFO "SELinux: Class %s not defined in policy.\n", p_in->name); if (pol->reject_unknown) goto err; p_out->num_perms = 0; print_unknown_handle = true; continue; } k = 0; while (p_in->perms && p_in->perms[k]) { /* An empty permission string skips ahead */ if (!*p_in->perms[k]) { k++; continue; } p_out->perms[k] = string_to_av_perm(pol, p_out->value, p_in->perms[k]); if (!p_out->perms[k]) { printk(KERN_INFO "SELinux: Permission %s in class %s not defined in policy.\n", p_in->perms[k], p_in->name); if (pol->reject_unknown) goto err; print_unknown_handle = true; } k++; } p_out->num_perms = k; } if (print_unknown_handle) printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n", pol->allow_unknown ? "allowed" : "denied"); *out_map_p = out_map; *out_map_size = i; return 0; err: kfree(out_map); return -EINVAL; } /* * Get real, policy values from mapped values */ static u16 unmap_class(u16 tclass) { if (tclass < current_mapping_size) return current_mapping[tclass].value; return tclass; } /* * Get kernel value for class from its policy value */ static u16 map_class(u16 pol_value) { u16 i; for (i = 1; i < current_mapping_size; i++) { if (current_mapping[i].value == pol_value) return i; } return SECCLASS_NULL; } static void map_decision(u16 tclass, struct av_decision *avd, int allow_unknown) { if (tclass < current_mapping_size) { unsigned i, n = current_mapping[tclass].num_perms; u32 result; for (i = 0, result = 0; i < n; i++) { if (avd->allowed & current_mapping[tclass].perms[i]) result |= 1<<i; if (allow_unknown && !current_mapping[tclass].perms[i]) result |= 1<<i; } avd->allowed = result; for (i = 0, result = 0; i < n; i++) if (avd->auditallow & current_mapping[tclass].perms[i]) result |= 1<<i; avd->auditallow = result; for (i = 0, result = 0; i < n; i++) { if (avd->auditdeny & current_mapping[tclass].perms[i]) result |= 1<<i; if (!allow_unknown && !current_mapping[tclass].perms[i]) result |= 1<<i; } /* * In case the kernel has a bug and requests a permission * between num_perms and the maximum permission number, we * should audit that denial */ for (; i < (sizeof(u32)*8); i++) result |= 1<<i; avd->auditdeny = result; } } int security_mls_enabled(void) { return policydb.mls_enabled; } /* * Return the boolean value of a constraint expression * when it is applied to the specified source and target * security contexts. * * xcontext is a special beast... It is used by the validatetrans rules * only. For these rules, scontext is the context before the transition, * tcontext is the context after the transition, and xcontext is the context * of the process performing the transition. All other callers of * constraint_expr_eval should pass in NULL for xcontext. */ static int constraint_expr_eval(struct context *scontext, struct context *tcontext, struct context *xcontext, struct constraint_expr *cexpr) { u32 val1, val2; struct context *c; struct role_datum *r1, *r2; struct mls_level *l1, *l2; struct constraint_expr *e; int s[CEXPR_MAXDEPTH]; int sp = -1; for (e = cexpr; e; e = e->next) { switch (e->expr_type) { case CEXPR_NOT: BUG_ON(sp < 0); s[sp] = !s[sp]; break; case CEXPR_AND: BUG_ON(sp < 1); sp--; s[sp] &= s[sp + 1]; break; case CEXPR_OR: BUG_ON(sp < 1); sp--; s[sp] |= s[sp + 1]; break; case CEXPR_ATTR: if (sp == (CEXPR_MAXDEPTH - 1)) return 0; switch (e->attr) { case CEXPR_USER: val1 = scontext->user; val2 = tcontext->user; break; case CEXPR_TYPE: val1 = scontext->type; val2 = tcontext->type; break; case CEXPR_ROLE: val1 = scontext->role; val2 = tcontext->role; r1 = policydb.role_val_to_struct[val1 - 1]; r2 = policydb.role_val_to_struct[val2 - 1]; switch (e->op) { case CEXPR_DOM: s[++sp] = ebitmap_get_bit(&r1->dominates, val2 - 1); continue; case CEXPR_DOMBY: s[++sp] = ebitmap_get_bit(&r2->dominates, val1 - 1); continue; case CEXPR_INCOMP: s[++sp] = (!ebitmap_get_bit(&r1->dominates, val2 - 1) && !ebitmap_get_bit(&r2->dominates, val1 - 1)); continue; default: break; } break; case CEXPR_L1L2: l1 = &(scontext->range.level[0]); l2 = &(tcontext->range.level[0]); goto mls_ops; case CEXPR_L1H2: l1 = &(scontext->range.level[0]); l2 = &(tcontext->range.level[1]); goto mls_ops; case CEXPR_H1L2: l1 = &(scontext->range.level[1]); l2 = &(tcontext->range.level[0]); goto mls_ops; case CEXPR_H1H2: l1 = &(scontext->range.level[1]); l2 = &(tcontext->range.level[1]); goto mls_ops; case CEXPR_L1H1: l1 = &(scontext->range.level[0]); l2 = &(scontext->range.level[1]); goto mls_ops; case CEXPR_L2H2: l1 = &(tcontext->range.level[0]); l2 = &(tcontext->range.level[1]); goto mls_ops; mls_ops: switch (e->op) { case CEXPR_EQ: s[++sp] = mls_level_eq(l1, l2); continue; case CEXPR_NEQ: s[++sp] = !mls_level_eq(l1, l2); continue; case CEXPR_DOM: s[++sp] = mls_level_dom(l1, l2); continue; case CEXPR_DOMBY: s[++sp] = mls_level_dom(l2, l1); continue; case CEXPR_INCOMP: s[++sp] = mls_level_incomp(l2, l1); continue; default: BUG(); return 0; } break; default: BUG(); return 0; } switch (e->op) { case CEXPR_EQ: s[++sp] = (val1 == val2); break; case CEXPR_NEQ: s[++sp] = (val1 != val2); break; default: BUG(); return 0; } break; case CEXPR_NAMES: if (sp == (CEXPR_MAXDEPTH-1)) return 0; c = scontext; if (e->attr & CEXPR_TARGET) c = tcontext; else if (e->attr & CEXPR_XTARGET) { c = xcontext; if (!c) { BUG(); return 0; } } if (e->attr & CEXPR_USER) val1 = c->user; else if (e->attr & CEXPR_ROLE) val1 = c->role; else if (e->attr & CEXPR_TYPE) val1 = c->type; else { BUG(); return 0; } switch (e->op) { case CEXPR_EQ: s[++sp] = ebitmap_get_bit(&e->names, val1 - 1); break; case CEXPR_NEQ: s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1); break; default: BUG(); return 0; } break; default: BUG(); return 0; } } BUG_ON(sp != 0); return s[0]; } /* * security_dump_masked_av - dumps masked permissions during * security_compute_av due to RBAC, MLS/Constraint and Type bounds. */ static int dump_masked_av_helper(void *k, void *d, void *args) { struct perm_datum *pdatum = d; char **permission_names = args; BUG_ON(pdatum->value < 1 || pdatum->value > 32); permission_names[pdatum->value - 1] = (char *)k; return 0; } static void security_dump_masked_av(struct context *scontext, struct context *tcontext, u16 tclass, u32 permissions, const char *reason) { struct common_datum *common_dat; struct class_datum *tclass_dat; struct audit_buffer *ab; char *tclass_name; char *scontext_name = NULL; char *tcontext_name = NULL; char *permission_names[32]; int index; u32 length; bool need_comma = false; if (!permissions) return; tclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1); tclass_dat = policydb.class_val_to_struct[tclass - 1]; common_dat = tclass_dat->comdatum; /* init permission_names */ if (common_dat && hashtab_map(common_dat->permissions.table, dump_masked_av_helper, permission_names) < 0) goto out; if (hashtab_map(tclass_dat->permissions.table, dump_masked_av_helper, permission_names) < 0) goto out; /* get scontext/tcontext in text form */ if (context_struct_to_string(scontext, &scontext_name, &length) < 0) goto out; if (context_struct_to_string(tcontext, &tcontext_name, &length) < 0) goto out; /* audit a message */ ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR); if (!ab) goto out; audit_log_format(ab, "op=security_compute_av reason=%s " "scontext=%s tcontext=%s tclass=%s perms=", reason, scontext_name, tcontext_name, tclass_name); for (index = 0; index < 32; index++) { u32 mask = (1 << index); if ((mask & permissions) == 0) continue; audit_log_format(ab, "%s%s", need_comma ? "," : "", permission_names[index] ? permission_names[index] : "????"); need_comma = true; } audit_log_end(ab); out: /* release scontext/tcontext */ kfree(tcontext_name); kfree(scontext_name); return; } /* * security_boundary_permission - drops violated permissions * on boundary constraint. */ static void type_attribute_bounds_av(struct context *scontext, struct context *tcontext, u16 tclass, struct av_decision *avd) { struct context lo_scontext; struct context lo_tcontext; struct av_decision lo_avd; struct type_datum *source; struct type_datum *target; u32 masked = 0; source = flex_array_get_ptr(policydb.type_val_to_struct_array, scontext->type - 1); BUG_ON(!source); target = flex_array_get_ptr(policydb.type_val_to_struct_array, tcontext->type - 1); BUG_ON(!target); if (source->bounds) { memset(&lo_avd, 0, sizeof(lo_avd)); memcpy(&lo_scontext, scontext, sizeof(lo_scontext)); lo_scontext.type = source->bounds; context_struct_compute_av(&lo_scontext, tcontext, tclass, &lo_avd); if ((lo_avd.allowed & avd->allowed) == avd->allowed) return; /* no masked permission */ masked = ~lo_avd.allowed & avd->allowed; } if (target->bounds) { memset(&lo_avd, 0, sizeof(lo_avd)); memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext)); lo_tcontext.type = target->bounds; context_struct_compute_av(scontext, &lo_tcontext, tclass, &lo_avd); if ((lo_avd.allowed & avd->allowed) == avd->allowed) return; /* no masked permission */ masked = ~lo_avd.allowed & avd->allowed; } if (source->bounds && target->bounds) { memset(&lo_avd, 0, sizeof(lo_avd)); /* * lo_scontext and lo_tcontext are already * set up. */ context_struct_compute_av(&lo_scontext, &lo_tcontext, tclass, &lo_avd); if ((lo_avd.allowed & avd->allowed) == avd->allowed) return; /* no masked permission */ masked = ~lo_avd.allowed & avd->allowed; } if (masked) { /* mask violated permissions */ avd->allowed &= ~masked; /* audit masked permissions */ security_dump_masked_av(scontext, tcontext, tclass, masked, "bounds"); } } /* * Compute access vectors based on a context structure pair for * the permissions in a particular class. */ static void context_struct_compute_av(struct context *scontext, struct context *tcontext, u16 tclass, struct av_decision *avd) { struct constraint_node *constraint; struct role_allow *ra; struct avtab_key avkey; struct avtab_node *node; struct class_datum *tclass_datum; struct ebitmap *sattr, *tattr; struct ebitmap_node *snode, *tnode; unsigned int i, j; avd->allowed = 0; avd->auditallow = 0; avd->auditdeny = 0xffffffff; if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) { if (printk_ratelimit()) printk(KERN_WARNING "SELinux: Invalid class %hu\n", tclass); return; } tclass_datum = policydb.class_val_to_struct[tclass - 1]; /* * If a specific type enforcement rule was defined for * this permission check, then use it. */ avkey.target_class = tclass; avkey.specified = AVTAB_AV; sattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1); BUG_ON(!sattr); tattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1); BUG_ON(!tattr); ebitmap_for_each_positive_bit(sattr, snode, i) { ebitmap_for_each_positive_bit(tattr, tnode, j) { avkey.source_type = i + 1; avkey.target_type = j + 1; for (node = avtab_search_node(&policydb.te_avtab, &avkey); node; node = avtab_search_node_next(node, avkey.specified)) { if (node->key.specified == AVTAB_ALLOWED) avd->allowed |= node->datum.data; else if (node->key.specified == AVTAB_AUDITALLOW) avd->auditallow |= node->datum.data; else if (node->key.specified == AVTAB_AUDITDENY) avd->auditdeny &= node->datum.data; } /* Check conditional av table for additional permissions */ cond_compute_av(&policydb.te_cond_avtab, &avkey, avd); } } /* * Remove any permissions prohibited by a constraint (this includes * the MLS policy). */ constraint = tclass_datum->constraints; while (constraint) { if ((constraint->permissions & (avd->allowed)) && !constraint_expr_eval(scontext, tcontext, NULL, constraint->expr)) { avd->allowed &= ~(constraint->permissions); } constraint = constraint->next; } /* * If checking process transition permission and the * role is changing, then check the (current_role, new_role) * pair. */ if (tclass == policydb.process_class && (avd->allowed & policydb.process_trans_perms) && scontext->role != tcontext->role) { for (ra = policydb.role_allow; ra; ra = ra->next) { if (scontext->role == ra->role && tcontext->role == ra->new_role) break; } if (!ra) avd->allowed &= ~policydb.process_trans_perms; } /* * If the given source and target types have boundary * constraint, lazy checks have to mask any violated * permission and notice it to userspace via audit. */ type_attribute_bounds_av(scontext, tcontext, tclass, avd); } static int security_validtrans_handle_fail(struct context *ocontext, struct context *ncontext, struct context *tcontext, u16 tclass) { char *o = NULL, *n = NULL, *t = NULL; u32 olen, nlen, tlen; if (context_struct_to_string(ocontext, &o, &olen)) goto out; if (context_struct_to_string(ncontext, &n, &nlen)) goto out; if (context_struct_to_string(tcontext, &t, &tlen)) goto out; audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "security_validate_transition: denied for" " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s", o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1)); out: kfree(o); kfree(n); kfree(t); #ifdef CONFIG_ALWAYS_ENFORCE selinux_enforcing = 1; #endif if (!selinux_enforcing) return 0; return -EPERM; } int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid, u16 orig_tclass) { struct context *ocontext; struct context *ncontext; struct context *tcontext; struct class_datum *tclass_datum; struct constraint_node *constraint; u16 tclass; int rc = 0; if (!ss_initialized) return 0; read_lock(&policy_rwlock); tclass = unmap_class(orig_tclass); if (!tclass || tclass > policydb.p_classes.nprim) { printk(KERN_ERR "SELinux: %s: unrecognized class %d\n", __func__, tclass); rc = -EINVAL; goto out; } tclass_datum = policydb.class_val_to_struct[tclass - 1]; ocontext = sidtab_search(&sidtab, oldsid); if (!ocontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, oldsid); rc = -EINVAL; goto out; } ncontext = sidtab_search(&sidtab, newsid); if (!ncontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, newsid); rc = -EINVAL; goto out; } tcontext = sidtab_search(&sidtab, tasksid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tasksid); rc = -EINVAL; goto out; } constraint = tclass_datum->validatetrans; while (constraint) { if (!constraint_expr_eval(ocontext, ncontext, tcontext, constraint->expr)) { rc = security_validtrans_handle_fail(ocontext, ncontext, tcontext, tclass); goto out; } constraint = constraint->next; } out: read_unlock(&policy_rwlock); return rc; } /* * security_bounded_transition - check whether the given * transition is directed to bounded, or not. * It returns 0, if @newsid is bounded by @oldsid. * Otherwise, it returns error code. * * @oldsid : current security identifier * @newsid : destinated security identifier */ int security_bounded_transition(u32 old_sid, u32 new_sid) { struct context *old_context, *new_context; struct type_datum *type; int index; int rc; read_lock(&policy_rwlock); rc = -EINVAL; old_context = sidtab_search(&sidtab, old_sid); if (!old_context) { printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n", __func__, old_sid); goto out; } rc = -EINVAL; new_context = sidtab_search(&sidtab, new_sid); if (!new_context) { printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n", __func__, new_sid); goto out; } rc = 0; /* type/domain unchanged */ if (old_context->type == new_context->type) goto out; index = new_context->type; while (true) { type = flex_array_get_ptr(policydb.type_val_to_struct_array, index - 1); BUG_ON(!type); /* not bounded anymore */ rc = -EPERM; if (!type->bounds) break; /* @newsid is bounded by @oldsid */ rc = 0; if (type->bounds == old_context->type) break; index = type->bounds; } if (rc) { char *old_name = NULL; char *new_name = NULL; u32 length; if (!context_struct_to_string(old_context, &old_name, &length) && !context_struct_to_string(new_context, &new_name, &length)) { audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "op=security_bounded_transition " "result=denied " "oldcontext=%s newcontext=%s", old_name, new_name); } kfree(new_name); kfree(old_name); } out: read_unlock(&policy_rwlock); return rc; } static void avd_init(struct av_decision *avd) { avd->allowed = 0; avd->auditallow = 0; avd->auditdeny = 0xffffffff; avd->seqno = latest_granting; avd->flags = 0; } /** * security_compute_av - Compute access vector decisions. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @avd: access vector decisions * * Compute a set of access vector decisions based on the * SID pair (@ssid, @tsid) for the permissions in @tclass. */ void security_compute_av(u32 ssid, u32 tsid, u16 orig_tclass, struct av_decision *avd) { u16 tclass; struct context *scontext = NULL, *tcontext = NULL; read_lock(&policy_rwlock); avd_init(avd); if (!ss_initialized) goto allow; scontext = sidtab_search(&sidtab, ssid); if (!scontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, ssid); goto out; } /* permissive domain? */ if (ebitmap_get_bit(&policydb.permissive_map, scontext->type)) avd->flags |= AVD_FLAGS_PERMISSIVE; tcontext = sidtab_search(&sidtab, tsid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tsid); goto out; } tclass = unmap_class(orig_tclass); if (unlikely(orig_tclass && !tclass)) { if (policydb.allow_unknown) goto allow; goto out; } context_struct_compute_av(scontext, tcontext, tclass, avd); map_decision(orig_tclass, avd, policydb.allow_unknown); out: read_unlock(&policy_rwlock); return; allow: avd->allowed = 0xffffffff; goto out; } void security_compute_av_user(u32 ssid, u32 tsid, u16 tclass, struct av_decision *avd) { struct context *scontext = NULL, *tcontext = NULL; read_lock(&policy_rwlock); avd_init(avd); if (!ss_initialized) goto allow; scontext = sidtab_search(&sidtab, ssid); if (!scontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, ssid); goto out; } /* permissive domain? */ if (ebitmap_get_bit(&policydb.permissive_map, scontext->type)) avd->flags |= AVD_FLAGS_PERMISSIVE; tcontext = sidtab_search(&sidtab, tsid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tsid); goto out; } if (unlikely(!tclass)) { if (policydb.allow_unknown) goto allow; goto out; } context_struct_compute_av(scontext, tcontext, tclass, avd); out: read_unlock(&policy_rwlock); return; allow: avd->allowed = 0xffffffff; goto out; } /* * Write the security context string representation of * the context structure `context' into a dynamically * allocated string of the correct size. Set `*scontext' * to point to this string and set `*scontext_len' to * the length of the string. */ static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len) { char *scontextp; if (scontext) *scontext = NULL; *scontext_len = 0; if (context->len) { *scontext_len = context->len; if (scontext) { *scontext = kstrdup(context->str, GFP_ATOMIC); if (!(*scontext)) return -ENOMEM; } return 0; } /* Compute the size of the context. */ *scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1; *scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1; *scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1; *scontext_len += mls_compute_context_len(context); if (!scontext) return 0; /* Allocate space for the context; caller must free this space. */ scontextp = kmalloc(*scontext_len, GFP_ATOMIC); if (!scontextp) return -ENOMEM; *scontext = scontextp; /* * Copy the user name, role name and type name into the context. */ sprintf(scontextp, "%s:%s:%s", sym_name(&policydb, SYM_USERS, context->user - 1), sym_name(&policydb, SYM_ROLES, context->role - 1), sym_name(&policydb, SYM_TYPES, context->type - 1)); scontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)); mls_sid_to_context(context, &scontextp); *scontextp = 0; return 0; } #include "initial_sid_to_string.h" const char *security_get_initial_sid_context(u32 sid) { if (unlikely(sid > SECINITSID_NUM)) return NULL; return initial_sid_to_string[sid]; } static int security_sid_to_context_core(u32 sid, char **scontext, u32 *scontext_len, int force) { struct context *context; int rc = 0; if (scontext) *scontext = NULL; *scontext_len = 0; if (!ss_initialized) { if (sid <= SECINITSID_NUM) { char *scontextp; *scontext_len = strlen(initial_sid_to_string[sid]) + 1; if (!scontext) goto out; scontextp = kmalloc(*scontext_len, GFP_ATOMIC); if (!scontextp) { rc = -ENOMEM; goto out; } strcpy(scontextp, initial_sid_to_string[sid]); *scontext = scontextp; goto out; } printk(KERN_ERR "SELinux: %s: called before initial " "load_policy on unknown SID %d\n", __func__, sid); rc = -EINVAL; goto out; } read_lock(&policy_rwlock); if (force) context = sidtab_search_force(&sidtab, sid); else context = sidtab_search(&sidtab, sid); if (!context) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, sid); rc = -EINVAL; goto out_unlock; } rc = context_struct_to_string(context, scontext, scontext_len); out_unlock: read_unlock(&policy_rwlock); out: return rc; } /** * security_sid_to_context - Obtain a context for a given SID. * @sid: security identifier, SID * @scontext: security context * @scontext_len: length in bytes * * Write the string representation of the context associated with @sid * into a dynamically allocated string of the correct size. Set @scontext * to point to this string and set @scontext_len to the length of the string. */ int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len) { return security_sid_to_context_core(sid, scontext, scontext_len, 0); } int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len) { return security_sid_to_context_core(sid, scontext, scontext_len, 1); } /* * Caveat: Mutates scontext. */ static int string_to_context_struct(struct policydb *pol, struct sidtab *sidtabp, char *scontext, u32 scontext_len, struct context *ctx, u32 def_sid) { struct role_datum *role; struct type_datum *typdatum; struct user_datum *usrdatum; char *scontextp, *p, oldc; int rc = 0; context_init(ctx); /* Parse the security context. */ rc = -EINVAL; scontextp = (char *) scontext; /* Extract the user. */ p = scontextp; while (*p && *p != ':') p++; if (*p == 0) goto out; *p++ = 0; usrdatum = hashtab_search(pol->p_users.table, scontextp); if (!usrdatum) goto out; ctx->user = usrdatum->value; /* Extract role. */ scontextp = p; while (*p && *p != ':') p++; if (*p == 0) goto out; *p++ = 0; role = hashtab_search(pol->p_roles.table, scontextp); if (!role) goto out; ctx->role = role->value; /* Extract type. */ scontextp = p; while (*p && *p != ':') p++; oldc = *p; *p++ = 0; typdatum = hashtab_search(pol->p_types.table, scontextp); if (!typdatum || typdatum->attribute) goto out; ctx->type = typdatum->value; rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid); if (rc) goto out; rc = -EINVAL; if ((p - scontext) < scontext_len) goto out; /* Check the validity of the new context. */ if (!policydb_context_isvalid(pol, ctx)) goto out; rc = 0; out: if (rc) context_destroy(ctx); return rc; } static int security_context_to_sid_core(const char *scontext, u32 scontext_len, u32 *sid, u32 def_sid, gfp_t gfp_flags, int force) { char *scontext2, *str = NULL; struct context context; int rc = 0; /* An empty security context is never valid. */ if (!scontext_len) return -EINVAL; /* An empty security context is never valid. */ if (!scontext_len) return -EINVAL; if (!ss_initialized) { int i; for (i = 1; i < SECINITSID_NUM; i++) { if (!strcmp(initial_sid_to_string[i], scontext)) { *sid = i; return 0; } } *sid = SECINITSID_KERNEL; return 0; } *sid = SECSID_NULL; /* Copy the string so that we can modify the copy as we parse it. */ scontext2 = kmalloc(scontext_len + 1, gfp_flags); if (!scontext2) return -ENOMEM; memcpy(scontext2, scontext, scontext_len); scontext2[scontext_len] = 0; if (force) { /* Save another copy for storing in uninterpreted form */ rc = -ENOMEM; str = kstrdup(scontext2, gfp_flags); if (!str) goto out; } read_lock(&policy_rwlock); rc = string_to_context_struct(&policydb, &sidtab, scontext2, scontext_len, &context, def_sid); if (rc == -EINVAL && force) { context.str = str; context.len = scontext_len; str = NULL; } else if (rc) goto out_unlock; rc = sidtab_context_to_sid(&sidtab, &context, sid); context_destroy(&context); out_unlock: read_unlock(&policy_rwlock); out: kfree(scontext2); kfree(str); return rc; } /** * security_context_to_sid - Obtain a SID for a given security context. * @scontext: security context * @scontext_len: length in bytes * @sid: security identifier, SID * * Obtains a SID associated with the security context that * has the string representation specified by @scontext. * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient * memory is available, or 0 on success. */ int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid) { return security_context_to_sid_core(scontext, scontext_len, sid, SECSID_NULL, GFP_KERNEL, 0); } /** * security_context_to_sid_default - Obtain a SID for a given security context, * falling back to specified default if needed. * * @scontext: security context * @scontext_len: length in bytes * @sid: security identifier, SID * @def_sid: default SID to assign on error * * Obtains a SID associated with the security context that * has the string representation specified by @scontext. * The default SID is passed to the MLS layer to be used to allow * kernel labeling of the MLS field if the MLS field is not present * (for upgrading to MLS without full relabel). * Implicitly forces adding of the context even if it cannot be mapped yet. * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient * memory is available, or 0 on success. */ int security_context_to_sid_default(const char *scontext, u32 scontext_len, u32 *sid, u32 def_sid, gfp_t gfp_flags) { return security_context_to_sid_core(scontext, scontext_len, sid, def_sid, gfp_flags, 1); } int security_context_to_sid_force(const char *scontext, u32 scontext_len, u32 *sid) { return security_context_to_sid_core(scontext, scontext_len, sid, SECSID_NULL, GFP_KERNEL, 1); } static int compute_sid_handle_invalid_context( struct context *scontext, struct context *tcontext, u16 tclass, struct context *newcontext) { char *s = NULL, *t = NULL, *n = NULL; u32 slen, tlen, nlen; if (context_struct_to_string(scontext, &s, &slen)) goto out; if (context_struct_to_string(tcontext, &t, &tlen)) goto out; if (context_struct_to_string(newcontext, &n, &nlen)) goto out; audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "security_compute_sid: invalid context %s" " for scontext=%s" " tcontext=%s" " tclass=%s", n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1)); out: kfree(s); kfree(t); kfree(n); #ifdef CONFIG_ALWAYS_ENFORCE selinux_enforcing = 1; #endif if (!selinux_enforcing) return 0; return -EACCES; } static void filename_compute_type(struct policydb *p, struct context *newcontext, u32 stype, u32 ttype, u16 tclass, const char *objname) { struct filename_trans ft; struct filename_trans_datum *otype; /* * Most filename trans rules are going to live in specific directories * like /dev or /var/run. This bitmap will quickly skip rule searches * if the ttype does not contain any rules. */ if (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype)) return; ft.stype = stype; ft.ttype = ttype; ft.tclass = tclass; ft.name = objname; otype = hashtab_search(p->filename_trans, &ft); if (otype) newcontext->type = otype->otype; } static int security_compute_sid(u32 ssid, u32 tsid, u16 orig_tclass, u32 specified, const char *objname, u32 *out_sid, bool kern) { struct class_datum *cladatum = NULL; struct context *scontext = NULL, *tcontext = NULL, newcontext; struct role_trans *roletr = NULL; struct avtab_key avkey; struct avtab_datum *avdatum; struct avtab_node *node; u16 tclass; int rc = 0; bool sock; if (!ss_initialized) { switch (orig_tclass) { case SECCLASS_PROCESS: /* kernel value */ *out_sid = ssid; break; default: *out_sid = tsid; break; } goto out; } context_init(&newcontext); read_lock(&policy_rwlock); if (kern) { tclass = unmap_class(orig_tclass); sock = security_is_socket_class(orig_tclass); } else { tclass = orig_tclass; sock = security_is_socket_class(map_class(tclass)); } scontext = sidtab_search(&sidtab, ssid); if (!scontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, ssid); rc = -EINVAL; goto out_unlock; } tcontext = sidtab_search(&sidtab, tsid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tsid); rc = -EINVAL; goto out_unlock; } if (tclass && tclass <= policydb.p_classes.nprim) cladatum = policydb.class_val_to_struct[tclass - 1]; /* Set the user identity. */ switch (specified) { case AVTAB_TRANSITION: case AVTAB_CHANGE: if (cladatum && cladatum->default_user == DEFAULT_TARGET) { newcontext.user = tcontext->user; } else { /* notice this gets both DEFAULT_SOURCE and unset */ /* Use the process user identity. */ newcontext.user = scontext->user; } break; case AVTAB_MEMBER: /* Use the related object owner. */ newcontext.user = tcontext->user; break; } /* Set the role to default values. */ if (cladatum && cladatum->default_role == DEFAULT_SOURCE) { newcontext.role = scontext->role; } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) { newcontext.role = tcontext->role; } else { if ((tclass == policydb.process_class) || (sock == true)) newcontext.role = scontext->role; else newcontext.role = OBJECT_R_VAL; } /* Set the type to default values. */ if (cladatum && cladatum->default_type == DEFAULT_SOURCE) { newcontext.type = scontext->type; } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) { newcontext.type = tcontext->type; } else { if ((tclass == policydb.process_class) || (sock == true)) { /* Use the type of process. */ newcontext.type = scontext->type; } else { /* Use the type of the related object. */ newcontext.type = tcontext->type; } } /* Look for a type transition/member/change rule. */ avkey.source_type = scontext->type; avkey.target_type = tcontext->type; avkey.target_class = tclass; avkey.specified = specified; avdatum = avtab_search(&policydb.te_avtab, &avkey); /* If no permanent rule, also check for enabled conditional rules */ if (!avdatum) { node = avtab_search_node(&policydb.te_cond_avtab, &avkey); for (; node; node = avtab_search_node_next(node, specified)) { if (node->key.specified & AVTAB_ENABLED) { avdatum = &node->datum; break; } } } if (avdatum) { /* Use the type from the type transition/member/change rule. */ newcontext.type = avdatum->data; } /* if we have a objname this is a file trans check so check those rules */ if (objname) filename_compute_type(&policydb, &newcontext, scontext->type, tcontext->type, tclass, objname); /* Check for class-specific changes. */ if (specified & AVTAB_TRANSITION) { /* Look for a role transition rule. */ for (roletr = policydb.role_tr; roletr; roletr = roletr->next) { if ((roletr->role == scontext->role) && (roletr->type == tcontext->type) && (roletr->tclass == tclass)) { /* Use the role transition rule. */ newcontext.role = roletr->new_role; break; } } } /* Set the MLS attributes. This is done last because it may allocate memory. */ rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext, sock); if (rc) goto out_unlock; /* Check the validity of the context. */ if (!policydb_context_isvalid(&policydb, &newcontext)) { rc = compute_sid_handle_invalid_context(scontext, tcontext, tclass, &newcontext); if (rc) goto out_unlock; } /* Obtain the sid for the context. */ rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid); out_unlock: read_unlock(&policy_rwlock); context_destroy(&newcontext); out: return rc; } /** * security_transition_sid - Compute the SID for a new subject/object. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @out_sid: security identifier for new subject/object * * Compute a SID to use for labeling a new subject or object in the * class @tclass based on a SID pair (@ssid, @tsid). * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM * if insufficient memory is available, or %0 if the new SID was * computed successfully. */ int security_transition_sid(u32 ssid, u32 tsid, u16 tclass, const struct qstr *qstr, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, qstr ? qstr->name : NULL, out_sid, true); } int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass, const char *objname, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, objname, out_sid, false); } /** * security_member_sid - Compute the SID for member selection. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @out_sid: security identifier for selected member * * Compute a SID to use when selecting a member of a polyinstantiated * object of class @tclass based on a SID pair (@ssid, @tsid). * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM * if insufficient memory is available, or %0 if the SID was * computed successfully. */ int security_member_sid(u32 ssid, u32 tsid, u16 tclass, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL, out_sid, false); } /** * security_change_sid - Compute the SID for object relabeling. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @out_sid: security identifier for selected member * * Compute a SID to use for relabeling an object of class @tclass * based on a SID pair (@ssid, @tsid). * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM * if insufficient memory is available, or %0 if the SID was * computed successfully. */ int security_change_sid(u32 ssid, u32 tsid, u16 tclass, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL, out_sid, false); } /* Clone the SID into the new SID table. */ static int clone_sid(u32 sid, struct context *context, void *arg) { struct sidtab *s = arg; if (sid > SECINITSID_NUM) return sidtab_insert(s, sid, context); else return 0; } static inline int convert_context_handle_invalid_context(struct context *context) { char *s; u32 len; #ifdef CONFIG_ALWAYS_ENFORCE selinux_enforcing = 1; #endif if (selinux_enforcing) return -EINVAL; if (!context_struct_to_string(context, &s, &len)) { printk(KERN_WARNING "SELinux: Context %s would be invalid if enforcing\n", s); kfree(s); } return 0; } struct convert_context_args { struct policydb *oldp; struct policydb *newp; }; /* * Convert the values in the security context * structure `c' from the values specified * in the policy `p->oldp' to the values specified * in the policy `p->newp'. Verify that the * context is valid under the new policy. */ static int convert_context(u32 key, struct context *c, void *p) { struct convert_context_args *args; struct context oldc; struct ocontext *oc; struct mls_range *range; struct role_datum *role; struct type_datum *typdatum; struct user_datum *usrdatum; char *s; u32 len; int rc = 0; if (key <= SECINITSID_NUM) goto out; args = p; if (c->str) { struct context ctx; rc = -ENOMEM; s = kstrdup(c->str, GFP_KERNEL); if (!s) goto out; rc = string_to_context_struct(args->newp, NULL, s, c->len, &ctx, SECSID_NULL); kfree(s); if (!rc) { printk(KERN_INFO "SELinux: Context %s became valid (mapped).\n", c->str); /* Replace string with mapped representation. */ kfree(c->str); memcpy(c, &ctx, sizeof(*c)); goto out; } else if (rc == -EINVAL) { /* Retain string representation for later mapping. */ rc = 0; goto out; } else { /* Other error condition, e.g. ENOMEM. */ printk(KERN_ERR "SELinux: Unable to map context %s, rc = %d.\n", c->str, -rc); goto out; } } rc = context_cpy(&oldc, c); if (rc) goto out; /* Convert the user. */ rc = -EINVAL; usrdatum = hashtab_search(args->newp->p_users.table, sym_name(args->oldp, SYM_USERS, c->user - 1)); if (!usrdatum) goto bad; c->user = usrdatum->value; /* Convert the role. */ rc = -EINVAL; role = hashtab_search(args->newp->p_roles.table, sym_name(args->oldp, SYM_ROLES, c->role - 1)); if (!role) goto bad; c->role = role->value; /* Convert the type. */ rc = -EINVAL; typdatum = hashtab_search(args->newp->p_types.table, sym_name(args->oldp, SYM_TYPES, c->type - 1)); if (!typdatum) goto bad; c->type = typdatum->value; /* Convert the MLS fields if dealing with MLS policies */ if (args->oldp->mls_enabled && args->newp->mls_enabled) { rc = mls_convert_context(args->oldp, args->newp, c); if (rc) goto bad; } else if (args->oldp->mls_enabled && !args->newp->mls_enabled) { /* * Switching between MLS and non-MLS policy: * free any storage used by the MLS fields in the * context for all existing entries in the sidtab. */ mls_context_destroy(c); } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) { /* * Switching between non-MLS and MLS policy: * ensure that the MLS fields of the context for all * existing entries in the sidtab are filled in with a * suitable default value, likely taken from one of the * initial SIDs. */ oc = args->newp->ocontexts[OCON_ISID]; while (oc && oc->sid[0] != SECINITSID_UNLABELED) oc = oc->next; rc = -EINVAL; if (!oc) { printk(KERN_ERR "SELinux: unable to look up" " the initial SIDs list\n"); goto bad; } range = &oc->context[0].range; rc = mls_range_set(c, range); if (rc) goto bad; } /* Check the validity of the new context. */ if (!policydb_context_isvalid(args->newp, c)) { rc = convert_context_handle_invalid_context(&oldc); if (rc) goto bad; } context_destroy(&oldc); rc = 0; out: return rc; bad: /* Map old representation to string and save it. */ rc = context_struct_to_string(&oldc, &s, &len); if (rc) return rc; context_destroy(&oldc); context_destroy(c); c->str = s; c->len = len; printk(KERN_INFO "SELinux: Context %s became invalid (unmapped).\n", c->str); rc = 0; goto out; } static void security_load_policycaps(void) { selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps, POLICYDB_CAPABILITY_NETPEER); selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps, POLICYDB_CAPABILITY_OPENPERM); } static int security_preserve_bools(struct policydb *p); /** * security_load_policy - Load a security policy configuration. * @data: binary policy data * @len: length of data in bytes * * Load a new set of security policy configuration data, * validate it and convert the SID table as necessary. * This function will flush the access vector cache after * loading the new policy. */ int security_load_policy(void *data, size_t len) { struct policydb oldpolicydb, newpolicydb; struct sidtab oldsidtab, newsidtab; struct selinux_mapping *oldmap, *map = NULL; struct convert_context_args args; u32 seqno; u16 map_size; int rc = 0; struct policy_file file = { data, len }, *fp = &file; if (!ss_initialized) { avtab_cache_init(); rc = policydb_read(&policydb, fp); if (rc) { avtab_cache_destroy(); return rc; } policydb.len = len; rc = selinux_set_mapping(&policydb, secclass_map, &current_mapping, &current_mapping_size); if (rc) { policydb_destroy(&policydb); avtab_cache_destroy(); return rc; } rc = policydb_load_isids(&policydb, &sidtab); if (rc) { policydb_destroy(&policydb); avtab_cache_destroy(); return rc; } security_load_policycaps(); ss_initialized = 1; seqno = ++latest_granting; selinux_complete_init(); avc_ss_reset(seqno); selnl_notify_policyload(seqno); selinux_status_update_policyload(seqno); selinux_netlbl_cache_invalidate(); selinux_xfrm_notify_policyload(); return 0; } #if 0 sidtab_hash_eval(&sidtab, "sids"); #endif rc = policydb_read(&newpolicydb, fp); if (rc) return rc; newpolicydb.len = len; /* If switching between different policy types, log MLS status */ if (policydb.mls_enabled && !newpolicydb.mls_enabled) printk(KERN_INFO "SELinux: Disabling MLS support...\n"); else if (!policydb.mls_enabled && newpolicydb.mls_enabled) printk(KERN_INFO "SELinux: Enabling MLS support...\n"); rc = policydb_load_isids(&newpolicydb, &newsidtab); if (rc) { printk(KERN_ERR "SELinux: unable to load the initial SIDs\n"); policydb_destroy(&newpolicydb); return rc; } rc = selinux_set_mapping(&newpolicydb, secclass_map, &map, &map_size); if (rc) goto err; rc = security_preserve_bools(&newpolicydb); if (rc) { printk(KERN_ERR "SELinux: unable to preserve booleans\n"); goto err; } /* Clone the SID table. */ sidtab_shutdown(&sidtab); rc = sidtab_map(&sidtab, clone_sid, &newsidtab); if (rc) goto err; /* * Convert the internal representations of contexts * in the new SID table. */ args.oldp = &policydb; args.newp = &newpolicydb; rc = sidtab_map(&newsidtab, convert_context, &args); if (rc) { printk(KERN_ERR "SELinux: unable to convert the internal" " representation of contexts in the new SID" " table\n"); goto err; } /* Save the old policydb and SID table to free later. */ memcpy(&oldpolicydb, &policydb, sizeof policydb); sidtab_set(&oldsidtab, &sidtab); /* Install the new policydb and SID table. */ write_lock_irq(&policy_rwlock); memcpy(&policydb, &newpolicydb, sizeof policydb); sidtab_set(&sidtab, &newsidtab); security_load_policycaps(); oldmap = current_mapping; current_mapping = map; current_mapping_size = map_size; seqno = ++latest_granting; write_unlock_irq(&policy_rwlock); /* Free the old policydb and SID table. */ policydb_destroy(&oldpolicydb); sidtab_destroy(&oldsidtab); kfree(oldmap); avc_ss_reset(seqno); selnl_notify_policyload(seqno); selinux_status_update_policyload(seqno); selinux_netlbl_cache_invalidate(); selinux_xfrm_notify_policyload(); return 0; err: kfree(map); sidtab_destroy(&newsidtab); policydb_destroy(&newpolicydb); return rc; } size_t security_policydb_len(void) { size_t len; read_lock(&policy_rwlock); len = policydb.len; read_unlock(&policy_rwlock); return len; } /** * security_port_sid - Obtain the SID for a port. * @protocol: protocol number * @port: port number * @out_sid: security identifier */ int security_port_sid(u8 protocol, u16 port, u32 *out_sid) { struct ocontext *c; int rc = 0; read_lock(&policy_rwlock); c = policydb.ocontexts[OCON_PORT]; while (c) { if (c->u.port.protocol == protocol && c->u.port.low_port <= port && c->u.port.high_port >= port) break; c = c->next; } if (c) { if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *out_sid = c->sid[0]; } else { *out_sid = SECINITSID_PORT; } out: read_unlock(&policy_rwlock); return rc; } /** * security_netif_sid - Obtain the SID for a network interface. * @name: interface name * @if_sid: interface SID */ int security_netif_sid(char *name, u32 *if_sid) { int rc = 0; struct ocontext *c; read_lock(&policy_rwlock); c = policydb.ocontexts[OCON_NETIF]; while (c) { if (strcmp(name, c->u.name) == 0) break; c = c->next; } if (c) { if (!c->sid[0] || !c->sid[1]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; rc = sidtab_context_to_sid(&sidtab, &c->context[1], &c->sid[1]); if (rc) goto out; } *if_sid = c->sid[0]; } else *if_sid = SECINITSID_NETIF; out: read_unlock(&policy_rwlock); return rc; } static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask) { int i, fail = 0; for (i = 0; i < 4; i++) if (addr[i] != (input[i] & mask[i])) { fail = 1; break; } return !fail; } /** * security_node_sid - Obtain the SID for a node (host). * @domain: communication domain aka address family * @addrp: address * @addrlen: address length in bytes * @out_sid: security identifier */ int security_node_sid(u16 domain, void *addrp, u32 addrlen, u32 *out_sid) { int rc; struct ocontext *c; read_lock(&policy_rwlock); switch (domain) { case AF_INET: { u32 addr; rc = -EINVAL; if (addrlen != sizeof(u32)) goto out; addr = *((u32 *)addrp); c = policydb.ocontexts[OCON_NODE]; while (c) { if (c->u.node.addr == (addr & c->u.node.mask)) break; c = c->next; } break; } case AF_INET6: rc = -EINVAL; if (addrlen != sizeof(u64) * 2) goto out; c = policydb.ocontexts[OCON_NODE6]; while (c) { if (match_ipv6_addrmask(addrp, c->u.node6.addr, c->u.node6.mask)) break; c = c->next; } break; default: rc = 0; *out_sid = SECINITSID_NODE; goto out; } if (c) { if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *out_sid = c->sid[0]; } else { *out_sid = SECINITSID_NODE; } rc = 0; out: read_unlock(&policy_rwlock); return rc; } #define SIDS_NEL 25 /** * security_get_user_sids - Obtain reachable SIDs for a user. * @fromsid: starting SID * @username: username * @sids: array of reachable SIDs for user * @nel: number of elements in @sids * * Generate the set of SIDs for legal security contexts * for a given user that can be reached by @fromsid. * Set *@sids to point to a dynamically allocated * array containing the set of SIDs. Set *@nel to the * number of elements in the array. */ int security_get_user_sids(u32 fromsid, char *username, u32 **sids, u32 *nel) { struct context *fromcon, usercon; u32 *mysids = NULL, *mysids2, sid; u32 mynel = 0, maxnel = SIDS_NEL; struct user_datum *user; struct role_datum *role; struct ebitmap_node *rnode, *tnode; int rc = 0, i, j; *sids = NULL; *nel = 0; if (!ss_initialized) goto out; read_lock(&policy_rwlock); context_init(&usercon); rc = -EINVAL; fromcon = sidtab_search(&sidtab, fromsid); if (!fromcon) goto out_unlock; rc = -EINVAL; user = hashtab_search(policydb.p_users.table, username); if (!user) goto out_unlock; usercon.user = user->value; rc = -ENOMEM; mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC); if (!mysids) goto out_unlock; ebitmap_for_each_positive_bit(&user->roles, rnode, i) { role = policydb.role_val_to_struct[i]; usercon.role = i + 1; ebitmap_for_each_positive_bit(&role->types, tnode, j) { usercon.type = j + 1; if (mls_setup_user_range(fromcon, user, &usercon)) continue; rc = sidtab_context_to_sid(&sidtab, &usercon, &sid); if (rc) goto out_unlock; if (mynel < maxnel) { mysids[mynel++] = sid; } else { rc = -ENOMEM; maxnel += SIDS_NEL; mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC); if (!mysids2) goto out_unlock; memcpy(mysids2, mysids, mynel * sizeof(*mysids2)); kfree(mysids); mysids = mysids2; mysids[mynel++] = sid; } } } rc = 0; out_unlock: read_unlock(&policy_rwlock); if (rc || !mynel) { kfree(mysids); goto out; } rc = -ENOMEM; mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL); if (!mysids2) { kfree(mysids); goto out; } for (i = 0, j = 0; i < mynel; i++) { struct av_decision dummy_avd; rc = avc_has_perm_noaudit(fromsid, mysids[i], SECCLASS_PROCESS, /* kernel value */ PROCESS__TRANSITION, AVC_STRICT, &dummy_avd); if (!rc) mysids2[j++] = mysids[i]; cond_resched(); } rc = 0; kfree(mysids); *sids = mysids2; *nel = j; out: return rc; } /** * security_genfs_sid - Obtain a SID for a file in a filesystem * @fstype: filesystem type * @path: path from root of mount * @sclass: file security class * @sid: SID for path * * Obtain a SID to use for a file in a filesystem that * cannot support xattr or use a fixed labeling behavior like * transition SIDs or task SIDs. */ int security_genfs_sid(const char *fstype, char *path, u16 orig_sclass, u32 *sid) { int len; u16 sclass; struct genfs *genfs; struct ocontext *c; int rc, cmp = 0; while (path[0] == '/' && path[1] == '/') path++; read_lock(&policy_rwlock); sclass = unmap_class(orig_sclass); *sid = SECINITSID_UNLABELED; for (genfs = policydb.genfs; genfs; genfs = genfs->next) { cmp = strcmp(fstype, genfs->fstype); if (cmp <= 0) break; } rc = -ENOENT; if (!genfs || cmp) goto out; for (c = genfs->head; c; c = c->next) { len = strlen(c->u.name); if ((!c->v.sclass || sclass == c->v.sclass) && (strncmp(c->u.name, path, len) == 0)) break; } rc = -ENOENT; if (!c) goto out; if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *sid = c->sid[0]; rc = 0; out: read_unlock(&policy_rwlock); return rc; } /** * security_fs_use - Determine how to handle labeling for a filesystem. * @fstype: filesystem type * @behavior: labeling behavior * @sid: SID for filesystem (superblock) */ int security_fs_use( const char *fstype, unsigned int *behavior, u32 *sid) { int rc = 0; struct ocontext *c; read_lock(&policy_rwlock); c = policydb.ocontexts[OCON_FSUSE]; while (c) { if (strcmp(fstype, c->u.name) == 0) break; c = c->next; } if (c) { *behavior = c->v.behavior; if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *sid = c->sid[0]; } else { rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid); if (rc) { *behavior = SECURITY_FS_USE_NONE; rc = 0; } else { *behavior = SECURITY_FS_USE_GENFS; } } out: read_unlock(&policy_rwlock); return rc; } int security_get_bools(int *len, char ***names, int **values) { int i, rc; read_lock(&policy_rwlock); *names = NULL; *values = NULL; rc = 0; *len = policydb.p_bools.nprim; if (!*len) goto out; rc = -ENOMEM; *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC); if (!*names) goto err; rc = -ENOMEM; *values = kcalloc(*len, sizeof(int), GFP_ATOMIC); if (!*values) goto err; for (i = 0; i < *len; i++) { size_t name_len; (*values)[i] = policydb.bool_val_to_struct[i]->state; name_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1; rc = -ENOMEM; (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC); if (!(*names)[i]) goto err; strncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len); (*names)[i][name_len - 1] = 0; } rc = 0; out: read_unlock(&policy_rwlock); return rc; err: if (*names) { for (i = 0; i < *len; i++) kfree((*names)[i]); } kfree(*values); goto out; } int security_set_bools(int len, int *values) { int i, rc; int lenp, seqno = 0; struct cond_node *cur; write_lock_irq(&policy_rwlock); rc = -EFAULT; lenp = policydb.p_bools.nprim; if (len != lenp) goto out; for (i = 0; i < len; i++) { if (!!values[i] != policydb.bool_val_to_struct[i]->state) { audit_log(current->audit_context, GFP_ATOMIC, AUDIT_MAC_CONFIG_CHANGE, "bool=%s val=%d old_val=%d auid=%u ses=%u", sym_name(&policydb, SYM_BOOLS, i), !!values[i], policydb.bool_val_to_struct[i]->state, from_kuid(&init_user_ns, audit_get_loginuid(current)), audit_get_sessionid(current)); } if (values[i]) policydb.bool_val_to_struct[i]->state = 1; else policydb.bool_val_to_struct[i]->state = 0; } for (cur = policydb.cond_list; cur; cur = cur->next) { rc = evaluate_cond_node(&policydb, cur); if (rc) goto out; } seqno = ++latest_granting; rc = 0; out: write_unlock_irq(&policy_rwlock); if (!rc) { avc_ss_reset(seqno); selnl_notify_policyload(seqno); selinux_status_update_policyload(seqno); selinux_xfrm_notify_policyload(); } return rc; } int security_get_bool_value(int bool) { int rc; int len; read_lock(&policy_rwlock); rc = -EFAULT; len = policydb.p_bools.nprim; if (bool >= len) goto out; rc = policydb.bool_val_to_struct[bool]->state; out: read_unlock(&policy_rwlock); return rc; } static int security_preserve_bools(struct policydb *p) { int rc, nbools = 0, *bvalues = NULL, i; char **bnames = NULL; struct cond_bool_datum *booldatum; struct cond_node *cur; rc = security_get_bools(&nbools, &bnames, &bvalues); if (rc) goto out; for (i = 0; i < nbools; i++) { booldatum = hashtab_search(p->p_bools.table, bnames[i]); if (booldatum) booldatum->state = bvalues[i]; } for (cur = p->cond_list; cur; cur = cur->next) { rc = evaluate_cond_node(p, cur); if (rc) goto out; } out: if (bnames) { for (i = 0; i < nbools; i++) kfree(bnames[i]); } kfree(bnames); kfree(bvalues); return rc; } /* * security_sid_mls_copy() - computes a new sid based on the given * sid and the mls portion of mls_sid. */ int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid) { struct context *context1; struct context *context2; struct context newcon; char *s; u32 len; int rc; rc = 0; if (!ss_initialized || !policydb.mls_enabled) { *new_sid = sid; goto out; } context_init(&newcon); read_lock(&policy_rwlock); rc = -EINVAL; context1 = sidtab_search(&sidtab, sid); if (!context1) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, sid); goto out_unlock; } rc = -EINVAL; context2 = sidtab_search(&sidtab, mls_sid); if (!context2) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, mls_sid); goto out_unlock; } newcon.user = context1->user; newcon.role = context1->role; newcon.type = context1->type; rc = mls_context_cpy(&newcon, context2); if (rc) goto out_unlock; /* Check the validity of the new context. */ if (!policydb_context_isvalid(&policydb, &newcon)) { rc = convert_context_handle_invalid_context(&newcon); if (rc) { if (!context_struct_to_string(&newcon, &s, &len)) { audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "security_sid_mls_copy: invalid context %s", s); kfree(s); } goto out_unlock; } } rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid); out_unlock: read_unlock(&policy_rwlock); context_destroy(&newcon); out: return rc; } /** * security_net_peersid_resolve - Compare and resolve two network peer SIDs * @nlbl_sid: NetLabel SID * @nlbl_type: NetLabel labeling protocol type * @xfrm_sid: XFRM SID * * Description: * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be * resolved into a single SID it is returned via @peer_sid and the function * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function * returns a negative value. A table summarizing the behavior is below: * * | function return | @sid * ------------------------------+-----------------+----------------- * no peer labels | 0 | SECSID_NULL * single peer label | 0 | <peer_label> * multiple, consistent labels | 0 | <peer_label> * multiple, inconsistent labels | -<errno> | SECSID_NULL * */ int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type, u32 xfrm_sid, u32 *peer_sid) { int rc; struct context *nlbl_ctx; struct context *xfrm_ctx; *peer_sid = SECSID_NULL; /* handle the common (which also happens to be the set of easy) cases * right away, these two if statements catch everything involving a * single or absent peer SID/label */ if (xfrm_sid == SECSID_NULL) { *peer_sid = nlbl_sid; return 0; } /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label * is present */ if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) { *peer_sid = xfrm_sid; return 0; } /* we don't need to check ss_initialized here since the only way both * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the * security server was initialized and ss_initialized was true */ if (!policydb.mls_enabled) return 0; read_lock(&policy_rwlock); rc = -EINVAL; nlbl_ctx = sidtab_search(&sidtab, nlbl_sid); if (!nlbl_ctx) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, nlbl_sid); goto out; } rc = -EINVAL; xfrm_ctx = sidtab_search(&sidtab, xfrm_sid); if (!xfrm_ctx) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, xfrm_sid); goto out; } rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES); if (rc) goto out; /* at present NetLabel SIDs/labels really only carry MLS * information so if the MLS portion of the NetLabel SID * matches the MLS portion of the labeled XFRM SID/label * then pass along the XFRM SID as it is the most * expressive */ *peer_sid = xfrm_sid; out: read_unlock(&policy_rwlock); return rc; } static int get_classes_callback(void *k, void *d, void *args) { struct class_datum *datum = d; char *name = k, **classes = args; int value = datum->value - 1; classes[value] = kstrdup(name, GFP_ATOMIC); if (!classes[value]) return -ENOMEM; return 0; } int security_get_classes(char ***classes, int *nclasses) { int rc; read_lock(&policy_rwlock); rc = -ENOMEM; *nclasses = policydb.p_classes.nprim; *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC); if (!*classes) goto out; rc = hashtab_map(policydb.p_classes.table, get_classes_callback, *classes); if (rc) { int i; for (i = 0; i < *nclasses; i++) kfree((*classes)[i]); kfree(*classes); } out: read_unlock(&policy_rwlock); return rc; } static int get_permissions_callback(void *k, void *d, void *args) { struct perm_datum *datum = d; char *name = k, **perms = args; int value = datum->value - 1; perms[value] = kstrdup(name, GFP_ATOMIC); if (!perms[value]) return -ENOMEM; return 0; } int security_get_permissions(char *class, char ***perms, int *nperms) { int rc, i; struct class_datum *match; read_lock(&policy_rwlock); rc = -EINVAL; match = hashtab_search(policydb.p_classes.table, class); if (!match) { printk(KERN_ERR "SELinux: %s: unrecognized class %s\n", __func__, class); goto out; } rc = -ENOMEM; *nperms = match->permissions.nprim; *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC); if (!*perms) goto out; if (match->comdatum) { rc = hashtab_map(match->comdatum->permissions.table, get_permissions_callback, *perms); if (rc) goto err; } rc = hashtab_map(match->permissions.table, get_permissions_callback, *perms); if (rc) goto err; out: read_unlock(&policy_rwlock); return rc; err: read_unlock(&policy_rwlock); for (i = 0; i < *nperms; i++) kfree((*perms)[i]); kfree(*perms); return rc; } int security_get_reject_unknown(void) { return policydb.reject_unknown; } int security_get_allow_unknown(void) { return policydb.allow_unknown; } /** * security_policycap_supported - Check for a specific policy capability * @req_cap: capability * * Description: * This function queries the currently loaded policy to see if it supports the * capability specified by @req_cap. Returns true (1) if the capability is * supported, false (0) if it isn't supported. * */ int security_policycap_supported(unsigned int req_cap) { int rc; read_lock(&policy_rwlock); rc = ebitmap_get_bit(&policydb.policycaps, req_cap); read_unlock(&policy_rwlock); return rc; } struct selinux_audit_rule { u32 au_seqno; struct context au_ctxt; }; void selinux_audit_rule_free(void *vrule) { struct selinux_audit_rule *rule = vrule; if (rule) { context_destroy(&rule->au_ctxt); kfree(rule); } } int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule) { struct selinux_audit_rule *tmprule; struct role_datum *roledatum; struct type_datum *typedatum; struct user_datum *userdatum; struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule; int rc = 0; #ifdef CONFIG_TIMA_RKP_RO_CRED if ((rc = security_integrity_current())) return rc; #endif *rule = NULL; if (!ss_initialized) return -EOPNOTSUPP; switch (field) { case AUDIT_SUBJ_USER: case AUDIT_SUBJ_ROLE: case AUDIT_SUBJ_TYPE: case AUDIT_OBJ_USER: case AUDIT_OBJ_ROLE: case AUDIT_OBJ_TYPE: /* only 'equals' and 'not equals' fit user, role, and type */ if (op != Audit_equal && op != Audit_not_equal) return -EINVAL; break; case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: /* we do not allow a range, indicated by the presence of '-' */ if (strchr(rulestr, '-')) return -EINVAL; break; default: /* only the above fields are valid */ return -EINVAL; } tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL); if (!tmprule) return -ENOMEM; context_init(&tmprule->au_ctxt); read_lock(&policy_rwlock); tmprule->au_seqno = latest_granting; switch (field) { case AUDIT_SUBJ_USER: case AUDIT_OBJ_USER: rc = -EINVAL; userdatum = hashtab_search(policydb.p_users.table, rulestr); if (!userdatum) goto out; tmprule->au_ctxt.user = userdatum->value; break; case AUDIT_SUBJ_ROLE: case AUDIT_OBJ_ROLE: rc = -EINVAL; roledatum = hashtab_search(policydb.p_roles.table, rulestr); if (!roledatum) goto out; tmprule->au_ctxt.role = roledatum->value; break; case AUDIT_SUBJ_TYPE: case AUDIT_OBJ_TYPE: rc = -EINVAL; typedatum = hashtab_search(policydb.p_types.table, rulestr); if (!typedatum) goto out; tmprule->au_ctxt.type = typedatum->value; break; case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC); if (rc) goto out; break; } rc = 0; out: read_unlock(&policy_rwlock); if (rc) { selinux_audit_rule_free(tmprule); tmprule = NULL; } *rule = tmprule; return rc; } /* Check to see if the rule contains any selinux fields */ int selinux_audit_rule_known(struct audit_krule *rule) { int i; #ifdef CONFIG_TIMA_RKP_RO_CRED int rc; if ((rc = security_integrity_current())) return rc; #endif for (i = 0; i < rule->field_count; i++) { struct audit_field *f = &rule->fields[i]; switch (f->type) { case AUDIT_SUBJ_USER: case AUDIT_SUBJ_ROLE: case AUDIT_SUBJ_TYPE: case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_USER: case AUDIT_OBJ_ROLE: case AUDIT_OBJ_TYPE: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: return 1; } } return 0; } int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule, struct audit_context *actx) { struct context *ctxt; struct mls_level *level; struct selinux_audit_rule *rule = vrule; int match = 0; #ifdef CONFIG_TIMA_RKP_RO_CRED int rc; if ((rc = security_integrity_current())) return rc; #endif if (!rule) { audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, "selinux_audit_rule_match: missing rule\n"); return -ENOENT; } read_lock(&policy_rwlock); if (rule->au_seqno < latest_granting) { audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, "selinux_audit_rule_match: stale rule\n"); match = -ESTALE; goto out; } ctxt = sidtab_search(&sidtab, sid); if (!ctxt) { audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, "selinux_audit_rule_match: unrecognized SID %d\n", sid); match = -ENOENT; goto out; } /* a field/op pair that is not caught here will simply fall through without a match */ switch (field) { case AUDIT_SUBJ_USER: case AUDIT_OBJ_USER: switch (op) { case Audit_equal: match = (ctxt->user == rule->au_ctxt.user); break; case Audit_not_equal: match = (ctxt->user != rule->au_ctxt.user); break; } break; case AUDIT_SUBJ_ROLE: case AUDIT_OBJ_ROLE: switch (op) { case Audit_equal: match = (ctxt->role == rule->au_ctxt.role); break; case Audit_not_equal: match = (ctxt->role != rule->au_ctxt.role); break; } break; case AUDIT_SUBJ_TYPE: case AUDIT_OBJ_TYPE: switch (op) { case Audit_equal: match = (ctxt->type == rule->au_ctxt.type); break; case Audit_not_equal: match = (ctxt->type != rule->au_ctxt.type); break; } break; case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: level = ((field == AUDIT_SUBJ_SEN || field == AUDIT_OBJ_LEV_LOW) ? &ctxt->range.level[0] : &ctxt->range.level[1]); switch (op) { case Audit_equal: match = mls_level_eq(&rule->au_ctxt.range.level[0], level); break; case Audit_not_equal: match = !mls_level_eq(&rule->au_ctxt.range.level[0], level); break; case Audit_lt: match = (mls_level_dom(&rule->au_ctxt.range.level[0], level) && !mls_level_eq(&rule->au_ctxt.range.level[0], level)); break; case Audit_le: match = mls_level_dom(&rule->au_ctxt.range.level[0], level); break; case Audit_gt: match = (mls_level_dom(level, &rule->au_ctxt.range.level[0]) && !mls_level_eq(level, &rule->au_ctxt.range.level[0])); break; case Audit_ge: match = mls_level_dom(level, &rule->au_ctxt.range.level[0]); break; } } out: read_unlock(&policy_rwlock); return match; } static int (*aurule_callback)(void) = audit_update_lsm_rules; static int aurule_avc_callback(u32 event) { int err = 0; if (event == AVC_CALLBACK_RESET && aurule_callback) err = aurule_callback(); return err; } static int __init aurule_init(void) { int err; err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET); if (err) panic("avc_add_callback() failed, error %d\n", err); return err; } __initcall(aurule_init); #ifdef CONFIG_NETLABEL /** * security_netlbl_cache_add - Add an entry to the NetLabel cache * @secattr: the NetLabel packet security attributes * @sid: the SELinux SID * * Description: * Attempt to cache the context in @ctx, which was derived from the packet in * @skb, in the NetLabel subsystem cache. This function assumes @secattr has * already been initialized. * */ static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr, u32 sid) { u32 *sid_cache; sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC); if (sid_cache == NULL) return; secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC); if (secattr->cache == NULL) { kfree(sid_cache); return; } *sid_cache = sid; secattr->cache->free = kfree; secattr->cache->data = sid_cache; secattr->flags |= NETLBL_SECATTR_CACHE; } /** * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID * @secattr: the NetLabel packet security attributes * @sid: the SELinux SID * * Description: * Convert the given NetLabel security attributes in @secattr into a * SELinux SID. If the @secattr field does not contain a full SELinux * SID/context then use SECINITSID_NETMSG as the foundation. If possible the * 'cache' field of @secattr is set and the CACHE flag is set; this is to * allow the @secattr to be used by NetLabel to cache the secattr to SID * conversion for future lookups. Returns zero on success, negative values on * failure. * */ int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr, u32 *sid) { int rc; struct context *ctx; struct context ctx_new; if (!ss_initialized) { *sid = SECSID_NULL; return 0; } read_lock(&policy_rwlock); if (secattr->flags & NETLBL_SECATTR_CACHE) *sid = *(u32 *)secattr->cache->data; else if (secattr->flags & NETLBL_SECATTR_SECID) *sid = secattr->attr.secid; else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) { rc = -EIDRM; ctx = sidtab_search(&sidtab, SECINITSID_NETMSG); if (ctx == NULL) goto out; context_init(&ctx_new); ctx_new.user = ctx->user; ctx_new.role = ctx->role; ctx_new.type = ctx->type; mls_import_netlbl_lvl(&ctx_new, secattr); if (secattr->flags & NETLBL_SECATTR_MLS_CAT) { rc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat, secattr->attr.mls.cat); if (rc) goto out; memcpy(&ctx_new.range.level[1].cat, &ctx_new.range.level[0].cat, sizeof(ctx_new.range.level[0].cat)); } rc = -EIDRM; if (!mls_context_isvalid(&policydb, &ctx_new)) goto out_free; rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid); if (rc) goto out_free; security_netlbl_cache_add(secattr, *sid); ebitmap_destroy(&ctx_new.range.level[0].cat); } else *sid = SECSID_NULL; read_unlock(&policy_rwlock); return 0; out_free: ebitmap_destroy(&ctx_new.range.level[0].cat); out: read_unlock(&policy_rwlock); return rc; } /** * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr * @sid: the SELinux SID * @secattr: the NetLabel packet security attributes * * Description: * Convert the given SELinux SID in @sid into a NetLabel security attribute. * Returns zero on success, negative values on failure. * */ int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr) { int rc; struct context *ctx; if (!ss_initialized) return 0; read_lock(&policy_rwlock); rc = -ENOENT; ctx = sidtab_search(&sidtab, sid); if (ctx == NULL) goto out; rc = -ENOMEM; secattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1), GFP_ATOMIC); if (secattr->domain == NULL) goto out; secattr->attr.secid = sid; secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID; mls_export_netlbl_lvl(ctx, secattr); rc = mls_export_netlbl_cat(ctx, secattr); out: read_unlock(&policy_rwlock); return rc; } #endif /* CONFIG_NETLABEL */ /** * security_read_policy - read the policy. * @data: binary policy data * @len: length of data in bytes * */ int security_read_policy(void **data, size_t *len) { int rc; struct policy_file fp; if (!ss_initialized) return -EINVAL; *len = security_policydb_len(); *data = vmalloc_user(*len); if (!*data) return -ENOMEM; fp.data = *data; fp.len = *len; read_lock(&policy_rwlock); rc = policydb_write(&policydb, &fp); read_unlock(&policy_rwlock); if (rc) return rc; *len = (unsigned long)fp.data - (unsigned long)*data; return 0; }
bju2000/android_kernel_samsung_slteskt
security/selinux/ss/services.c
C
gpl-2.0
77,340
/* * linux/arch/arm/mm/flush.c * * Copyright (C) 1995-2002 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/mm.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <asm/cacheflush.h> #include <asm/cachetype.h> #include <asm/highmem.h> #include <asm/smp_plat.h> #include <asm/tlbflush.h> #include "mm.h" #ifdef CONFIG_CPU_CACHE_VIPT static void flush_pfn_alias(unsigned long pfn, unsigned long vaddr) { unsigned long to = FLUSH_ALIAS_START + (CACHE_COLOUR(vaddr) << PAGE_SHIFT); const int zero = 0; set_top_pte(to, pfn_pte(pfn, PAGE_KERNEL)); asm( "mcrr p15, 0, %1, %0, c14\n" " mcr p15, 0, %2, c7, c10, 4" : : "r" (to), "r" (to + PAGE_SIZE - L1_CACHE_BYTES), "r" (zero) : "cc"); } static void flush_icache_alias(unsigned long pfn, unsigned long vaddr, unsigned long len) { unsigned long va = FLUSH_ALIAS_START + (CACHE_COLOUR(vaddr) << PAGE_SHIFT); unsigned long offset = vaddr & (PAGE_SIZE - 1); unsigned long to; set_top_pte(va, pfn_pte(pfn, PAGE_KERNEL)); to = va + offset; flush_icache_range(to, to + len); } void flush_cache_mm(struct mm_struct *mm) { if (cache_is_vivt()) { vivt_flush_cache_mm(mm); return; } if (cache_is_vipt_aliasing()) { asm( "mcr p15, 0, %0, c7, c14, 0\n" " mcr p15, 0, %0, c7, c10, 4" : : "r" (0) : "cc"); } } void flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { if (cache_is_vivt()) { vivt_flush_cache_range(vma, start, end); return; } if (cache_is_vipt_aliasing()) { asm( "mcr p15, 0, %0, c7, c14, 0\n" " mcr p15, 0, %0, c7, c10, 4" : : "r" (0) : "cc"); } if (vma->vm_flags & VM_EXEC) __flush_icache_all(); } void flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr, unsigned long pfn) { if (cache_is_vivt()) { vivt_flush_cache_page(vma, user_addr, pfn); return; } if (cache_is_vipt_aliasing()) { flush_pfn_alias(pfn, user_addr); __flush_icache_all(); } if (vma->vm_flags & VM_EXEC && icache_is_vivt_asid_tagged()) __flush_icache_all(); } #else #define flush_pfn_alias(pfn,vaddr) do { } while (0) #define flush_icache_alias(pfn,vaddr,len) do { } while (0) #endif static void flush_ptrace_access_other(void *args) { __flush_icache_all(); } static void flush_ptrace_access(struct vm_area_struct *vma, struct page *page, unsigned long uaddr, void *kaddr, unsigned long len) { if (cache_is_vivt()) { if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(vma->vm_mm))) { unsigned long addr = (unsigned long)kaddr; __cpuc_coherent_kern_range(addr, addr + len); } return; } if (cache_is_vipt_aliasing()) { flush_pfn_alias(page_to_pfn(page), uaddr); __flush_icache_all(); return; } /* VIPT non-aliasing D-cache */ if (vma->vm_flags & VM_EXEC) { unsigned long addr = (unsigned long)kaddr; if (icache_is_vipt_aliasing()) flush_icache_alias(page_to_pfn(page), uaddr, len); else __cpuc_coherent_kern_range(addr, addr + len); if (cache_ops_need_broadcast()) smp_call_function(flush_ptrace_access_other, NULL, 1); } } /* * Copy user data from/to a page which is mapped into a different * processes address space. Really, we want to allow our "user * space" model to handle this. * * Note that this code needs to run on the current CPU. */ void copy_to_user_page(struct vm_area_struct *vma, struct page *page, unsigned long uaddr, void *dst, const void *src, unsigned long len) { #ifdef CONFIG_SMP preempt_disable(); #endif memcpy(dst, src, len); flush_ptrace_access(vma, page, uaddr, dst, len); #ifdef CONFIG_SMP preempt_enable(); #endif } void __flush_dcache_page(struct address_space *mapping, struct page *page) { /* * Writeback any data associated with the kernel mapping of this * page. This ensures that data in the physical page is mutually * coherent with the kernels mapping. */ if (!PageHighMem(page)) { __cpuc_flush_dcache_area(page_address(page), PAGE_SIZE); } else { void *addr = kmap_high_get(page); if (addr) { __cpuc_flush_dcache_area(addr, PAGE_SIZE); kunmap_high(page); } else if (cache_is_vipt()) { /* unmapped pages might still be cached */ addr = kmap_atomic(page); __cpuc_flush_dcache_area(addr, PAGE_SIZE); kunmap_atomic(addr); } } /* * If this is a page cache page, and we have an aliasing VIPT cache, * we only need to do one flush - which would be at the relevant * userspace colour, which is congruent with page->index. */ if (mapping && cache_is_vipt_aliasing()) flush_pfn_alias(page_to_pfn(page), page->index << PAGE_CACHE_SHIFT); } static void __flush_dcache_aliases(struct address_space *mapping, struct page *page) { struct mm_struct *mm = current->active_mm; struct vm_area_struct *mpnt; struct prio_tree_iter iter; pgoff_t pgoff; /* * There are possible user space mappings of this page: * - VIVT cache: we need to also write back and invalidate all user * data in the current VM view associated with this page. * - aliasing VIPT: we only need to find one mapping of this page. */ pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT); flush_dcache_mmap_lock(mapping); vma_prio_tree_foreach(mpnt, &iter, &mapping->i_mmap, pgoff, pgoff) { unsigned long offset; /* * If this VMA is not in our MM, we can ignore it. */ if (mpnt->vm_mm != mm) continue; if (!(mpnt->vm_flags & VM_MAYSHARE)) continue; offset = (pgoff - mpnt->vm_pgoff) << PAGE_SHIFT; flush_cache_page(mpnt, mpnt->vm_start + offset, page_to_pfn(page)); } flush_dcache_mmap_unlock(mapping); } #if __LINUX_ARM_ARCH__ >= 6 void __sync_icache_dcache(pte_t pteval) { unsigned long pfn; struct page *page; struct address_space *mapping; if (!pte_present_user(pteval)) return; if (cache_is_vipt_nonaliasing() && !pte_exec(pteval)) /* only flush non-aliasing VIPT caches for exec mappings */ return; pfn = pte_pfn(pteval); if (!pfn_valid(pfn)) return; page = pfn_to_page(pfn); if (cache_is_vipt_aliasing()) mapping = page_mapping(page); else mapping = NULL; if (!test_and_set_bit(PG_dcache_clean, &page->flags)) __flush_dcache_page(mapping, page); if (pte_exec(pteval)) __flush_icache_all(); } #endif /* * Ensure cache coherency between kernel mapping and userspace mapping * of this page. * * We have three cases to consider: * - VIPT non-aliasing cache: fully coherent so nothing required. * - VIVT: fully aliasing, so we need to handle every alias in our * current VM view. * - VIPT aliasing: need to handle one alias in our current VM view. * * If we need to handle aliasing: * If the page only exists in the page cache and there are no user * space mappings, we can be lazy and remember that we may have dirty * kernel cache lines for later. Otherwise, we assume we have * aliasing mappings. * * Note that we disable the lazy flush for SMP configurations where * the cache maintenance operations are not automatically broadcasted. */ void flush_dcache_page(struct page *page) { struct address_space *mapping; /* * The zero page is never written to, so never has any dirty * cache lines, and therefore never needs to be flushed. */ if (page == ZERO_PAGE(0)) return; mapping = page_mapping(page); if (!cache_ops_need_broadcast() && mapping && !mapping_mapped(mapping)) clear_bit(PG_dcache_clean, &page->flags); else { __flush_dcache_page(mapping, page); if (mapping && cache_is_vivt()) __flush_dcache_aliases(mapping, page); else if (mapping) __flush_icache_all(); set_bit(PG_dcache_clean, &page->flags); } } EXPORT_SYMBOL(flush_dcache_page); /* * Flush an anonymous page so that users of get_user_pages() * can safely access the data. The expected sequence is: * * get_user_pages() * -> flush_anon_page * memcpy() to/from page * if written to page, flush_dcache_page() */ void __flush_anon_page(struct vm_area_struct *vma, struct page *page, unsigned long vmaddr) { unsigned long pfn; /* VIPT non-aliasing caches need do nothing */ if (cache_is_vipt_nonaliasing()) return; /* * Write back and invalidate userspace mapping. */ pfn = page_to_pfn(page); if (cache_is_vivt()) { flush_cache_page(vma, vmaddr, pfn); } else { /* * For aliasing VIPT, we can flush an alias of the * userspace address only. */ flush_pfn_alias(pfn, vmaddr); __flush_icache_all(); } /* * Invalidate kernel mapping. No data should be contained * in this mapping of the page. FIXME: this is overkill * since we actually ask for a write-back and invalidate. */ __cpuc_flush_dcache_area(page_address(page), PAGE_SIZE); }
Jackeagle/android_kernel_sony_c2305
arch/arm/mm/flush.c
C
gpl-2.0
9,199
/* * Copyright (c) 2011-2012, 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. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <mach/rpm-regulator.h> #include <mach/msm_bus_board.h> #include <mach/msm_bus.h> #include "mach/socinfo.h" #include "acpuclock.h" #include "acpuclock-krait.h" #ifdef CONFIG_PERFLOCK #include <mach/perflock.h> #endif static struct hfpll_data hfpll_data __initdata = { .mode_offset = 0x00, .l_offset = 0x08, .m_offset = 0x0C, .n_offset = 0x10, .config_offset = 0x04, .config_val = 0x7845C665, .has_droop_ctl = true, .droop_offset = 0x14, .droop_val = 0x0108C000, .low_vdd_l_max = 22, .nom_vdd_l_max = 42, .vdd[HFPLL_VDD_NONE] = 0, .vdd[HFPLL_VDD_LOW] = 945000, .vdd[HFPLL_VDD_NOM] = 1050000, .vdd[HFPLL_VDD_HIGH] = 1150000, }; static struct scalable scalable[] __initdata = { [CPU0] = { .hfpll_phys_base = 0x00903200, .aux_clk_sel_phys = 0x02088014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x4501, .vreg[VREG_CORE] = { "krait0", 1350000 }, .vreg[VREG_MEM] = { "krait0_mem", 1150000 }, .vreg[VREG_DIG] = { "krait0_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait0_hfpll", 1800000 }, }, [CPU1] = { .hfpll_phys_base = 0x00903240, .aux_clk_sel_phys = 0x02098014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x5501, .vreg[VREG_CORE] = { "krait1", 1350000 }, .vreg[VREG_MEM] = { "krait1_mem", 1150000 }, .vreg[VREG_DIG] = { "krait1_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait1_hfpll", 1800000 }, }, [CPU2] = { .hfpll_phys_base = 0x00903280, .aux_clk_sel_phys = 0x020A8014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x6501, .vreg[VREG_CORE] = { "krait2", 1350000 }, .vreg[VREG_MEM] = { "krait2_mem", 1150000 }, .vreg[VREG_DIG] = { "krait2_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait2_hfpll", 1800000 }, }, [CPU3] = { .hfpll_phys_base = 0x009032C0, .aux_clk_sel_phys = 0x020B8014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x7501, .vreg[VREG_CORE] = { "krait3", 1350000 }, .vreg[VREG_MEM] = { "krait3_mem", 1150000 }, .vreg[VREG_DIG] = { "krait3_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait3_hfpll", 1800000 }, }, [L2] = { .hfpll_phys_base = 0x00903300, .aux_clk_sel_phys = 0x02011028, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x0500, .vreg[VREG_HFPLL_A] = { "l2_hfpll", 1800000 }, }, }; static struct msm_bus_paths bw_level_tbl[] __initdata = { [0] = BW_MBPS(640), [1] = BW_MBPS(1064), [2] = BW_MBPS(1600), [3] = BW_MBPS(2128), [4] = BW_MBPS(3200), [5] = BW_MBPS(4264), }; static struct msm_bus_scale_pdata bus_scale_data __initdata = { .usecase = bw_level_tbl, .num_usecases = ARRAY_SIZE(bw_level_tbl), .active_only = 1, .name = "acpuclk-8064", }; static struct l2_level l2_freq_tbl[] __initdata = { [0] = { { 378000, HFPLL, 2, 0x1C }, 950000, 1050000, 1 }, [0] = { { 384000, PLL_8, 0, 0x00 }, 950000, 1050000, 1 }, [1] = { { 432000, HFPLL, 2, 0x20 }, 1050000, 1050000, 2 }, [2] = { { 486000, HFPLL, 2, 0x24 }, 1050000, 1050000, 2 }, [3] = { { 540000, HFPLL, 2, 0x28 }, 1050000, 1050000, 2 }, [4] = { { 594000, HFPLL, 1, 0x16 }, 1050000, 1050000, 2 }, [5] = { { 648000, HFPLL, 1, 0x18 }, 1050000, 1050000, 4 }, [6] = { { 702000, HFPLL, 1, 0x1A }, 1150000, 1150000, 4 }, [7] = { { 756000, HFPLL, 1, 0x1C }, 1150000, 1150000, 4 }, [8] = { { 810000, HFPLL, 1, 0x1E }, 1150000, 1150000, 4 }, [9] = { { 864000, HFPLL, 1, 0x20 }, 1150000, 1150000, 4 }, [10] = { { 918000, HFPLL, 1, 0x22 }, 1150000, 1150000, 5 }, [11] = { { 972000, HFPLL, 1, 0x24 }, 1150000, 1150000, 5 }, [12] = { { 1134000, HFPLL, 1, 0x2A }, 1150000, 1150000, 5 }, [13] = { { 1242000, HFPLL, 1, 0x2E }, 1150000, 1150000, 5 }, [14] = { { 1296000, HFPLL, 1, 0x30 }, 1150000, 1150000, 5 }, [15] = { { 1350000, HFPLL, 1, 0x32 }, 1150000, 1150000, 5 }, [16] = { { 1404000, HFPLL, 1, 0x34 }, 1150000, 1150000, 5 }, [17] = { { 1458000, HFPLL, 1, 0x36 }, 1150000, 1150000, 5 }, { } }; static struct acpu_level tbl_slow[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 975000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 975000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 1000000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 1000000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 1025000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 1025000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 1075000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1075000 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1100000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1100000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1125000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1125000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1175000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1175000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1200000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1200000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1225000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1225000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1237500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1237500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1250000 }, { 0, { 0 } } }; static struct acpu_level tbl_nom[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 925000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 975000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 975000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 1025000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1025000 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1050000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1050000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1075000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1075000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1125000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1125000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1150000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1150000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1175000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1175000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1187500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1187500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1200000 }, { 0, { 0 } } }; static struct acpu_level tbl_fast[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 850000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 975000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 975000 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1000000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1000000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1025000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1025000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1075000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1075000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1100000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1100000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1125000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1125000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1137500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1137500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 0, { 0 } } }; static struct acpu_level tbl_faster[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 850000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 962500 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 962500 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 975000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 975000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1000000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1000000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1050000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1050000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1075000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1075000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1100000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1100000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1112500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1112500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1125000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS0_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 962500 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1000000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1025000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1037500 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1075000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1087500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1125000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1150000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1175000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1150000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1175000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1175000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1200000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS1_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 962500 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 975000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1000000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1012500 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1037500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1050000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1087500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1112500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1150000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1150000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1175000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1175000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1200000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS2_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 925000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 937500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 950000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 975000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1000000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1012500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1037500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1075000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1100000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1125000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1150000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1150000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1175000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS3_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 900000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 925000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 950000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 975000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 987500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1000000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1037500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1062500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1100000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1125000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS4_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 950000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 962500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 975000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1000000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1037500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1075000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1100000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS5_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 987500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1012500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1050000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1075000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS6_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 975000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1000000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1025000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1050000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1100000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1125000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS0_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 950000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 962500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 975000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1000000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1025000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1037500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1062500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1100000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1125000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1175000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1225000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1287500 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS1_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 925000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 937500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 950000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 975000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1000000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1012500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1037500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1075000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1100000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1137500 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1187500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1250000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS2_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 912500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 925000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 950000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 975000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 987500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1012500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1050000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1075000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1112500 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1162500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1212500 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS3_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 900000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 912500 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 937500 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 962500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 975000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1000000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1025000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1050000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1087500 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1137500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1175000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS4_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 950000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 962500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 975000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1000000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1037500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1075000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1112500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1150000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS5_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 987500 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1012500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1050000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1087500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1125000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS6_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 975000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1000000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1025000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1062500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1100000 }, { 0, { 0 } } }; static struct pvs_table pvs_tables[NUM_SPEED_BINS][NUM_PVS] __initdata = { [0][PVS_SLOW] = {tbl_slow, sizeof(tbl_slow), 0 }, [0][PVS_NOMINAL] = {tbl_nom, sizeof(tbl_nom), 25000 }, [0][PVS_FAST] = {tbl_fast, sizeof(tbl_fast), 25000 }, [0][PVS_FASTER] = {tbl_faster, sizeof(tbl_faster), 25000 }, [1][0] = { tbl_PVS0_1700MHz, sizeof(tbl_PVS0_1700MHz), 0 }, [1][1] = { tbl_PVS1_1700MHz, sizeof(tbl_PVS1_1700MHz), 25000 }, [1][2] = { tbl_PVS2_1700MHz, sizeof(tbl_PVS2_1700MHz), 25000 }, [1][3] = { tbl_PVS3_1700MHz, sizeof(tbl_PVS3_1700MHz), 25000 }, [1][4] = { tbl_PVS4_1700MHz, sizeof(tbl_PVS4_1700MHz), 25000 }, [1][5] = { tbl_PVS5_1700MHz, sizeof(tbl_PVS5_1700MHz), 25000 }, [1][6] = { tbl_PVS6_1700MHz, sizeof(tbl_PVS6_1700MHz), 25000 }, [2][0] = { tbl_PVS0_2000MHz, sizeof(tbl_PVS0_2000MHz), 0 }, [2][1] = { tbl_PVS1_2000MHz, sizeof(tbl_PVS1_2000MHz), 25000 }, [2][2] = { tbl_PVS2_2000MHz, sizeof(tbl_PVS2_2000MHz), 25000 }, [2][3] = { tbl_PVS3_2000MHz, sizeof(tbl_PVS3_2000MHz), 25000 }, [2][4] = { tbl_PVS4_2000MHz, sizeof(tbl_PVS4_2000MHz), 25000 }, [2][5] = { tbl_PVS5_2000MHz, sizeof(tbl_PVS5_2000MHz), 25000 }, [2][6] = { tbl_PVS6_2000MHz, sizeof(tbl_PVS6_2000MHz), 25000 }, }; static struct acpuclk_krait_params acpuclk_8064_params __initdata = { .scalable = scalable, .scalable_size = sizeof(scalable), .hfpll_data = &hfpll_data, .pvs_tables = pvs_tables, .l2_freq_tbl = l2_freq_tbl, .l2_freq_tbl_size = sizeof(l2_freq_tbl), .bus_scale = &bus_scale_data, .pte_efuse_phys = 0x007000C0, .stby_khz = 384000, }; static int __init acpuclk_8064_probe(struct platform_device *pdev) { int ret; if (cpu_is_apq8064ab() || SOCINFO_VERSION_MAJOR(socinfo_get_version()) == 2) { acpuclk_8064_params.hfpll_data->low_vdd_l_max = 37; acpuclk_8064_params.hfpll_data->nom_vdd_l_max = 74; } ret = acpuclk_krait_init(&pdev->dev, &acpuclk_8064_params); return ret; } static struct platform_driver acpuclk_8064_driver = { .driver = { .name = "acpuclk-8064", .owner = THIS_MODULE, }, }; static int __init acpuclk_8064_init(void) { return platform_driver_probe(&acpuclk_8064_driver, acpuclk_8064_probe); } device_initcall(acpuclk_8064_init);
GruesomeWolf/Slippery_Sloth
arch/arm/mach-msm/acpuclock-8064.c
C
gpl-2.0
28,898
#include <stdio.h> #include <stdlib.h> #include <string.h> /* memset */ #include <libwzd-core/wzd_structs.h> #include <libwzd-core/wzd_crc32.h> #define C1 0x12345678 #define C2 0x9abcdef0 int main(int argc, char *argv[]) { unsigned long c1 = C1; unsigned long crc = 0x0; char input1[1024]; const char * file1 = "file_crc.txt"; const unsigned long crc_ref = 0xEB2FAFAF; /* cksfv file_crc.txt */ char * srcdir = NULL; unsigned long c2 = C2; if (argc > 1) { srcdir = argv[1]; } else { srcdir = getenv("srcdir"); if (srcdir == NULL) { fprintf(stderr, "Environment variable $srcdir not found, aborting\n"); return 1; } } snprintf(input1,sizeof(input1)-1,"%s/%s",srcdir,file1); if ( calc_crc32(input1,&crc,0,(unsigned long)-1) ) { fprintf(stderr, "calc_crc32 failed\n"); return 1; } if ( crc != crc_ref ) { fprintf(stderr, "calc_crc32 returned crap\n"); return 1; } if (c1 != C1) { fprintf(stderr, "c1 nuked !\n"); return -1; } if (c2 != C2) { fprintf(stderr, "c2 nuked !\n"); return -1; } return 0; }
mathgl67/wzdftpd
tests/test_wzd_crc32.c
C
gpl-2.0
1,106
#ifdef CONFIG_COMPAT #include <linux/compat.h> /* for compat_old_sigset_t */ #endif #include <linux/sched.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/errno.h> #include <linux/wait.h> #include <linux/ptrace.h> #include <linux/tracehook.h> #include <linux/unistd.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/binfmts.h> #include <linux/bitops.h> #include <asm/uaccess.h> #include <asm/ptrace.h> #include <asm/pgtable.h> #include <asm/fpumacro.h> #include <asm/uctx.h> #include <asm/siginfo.h> #include <asm/visasm.h> #include "entry.h" #include "systbls.h" #define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP))) /* {set, get}context() needed for 64-bit SparcLinux userland. */ asmlinkage void sparc64_set_context(struct pt_regs *regs) { struct ucontext __user *ucp = (struct ucontext __user *) regs->u_regs[UREG_I0]; mc_gregset_t __user *grp; unsigned long pc, npc, tstate; unsigned long fp, i7; unsigned char fenab; int err; flush_user_windows(); if (get_thread_wsaved() || (((unsigned long)ucp) & (sizeof(unsigned long)-1)) || (!__access_ok(ucp, sizeof(*ucp)))) goto do_sigsegv; grp = &ucp->uc_mcontext.mc_gregs; err = __get_user(pc, &((*grp)[MC_PC])); err |= __get_user(npc, &((*grp)[MC_NPC])); if (err || ((pc | npc) & 3)) goto do_sigsegv; if (regs->u_regs[UREG_I1]) { sigset_t set; if (_NSIG_WORDS == 1) { if (__get_user(set.sig[0], &ucp->uc_sigmask.sig[0])) goto do_sigsegv; } else { if (__copy_from_user(&set, &ucp->uc_sigmask, sizeof(sigset_t))) goto do_sigsegv; } sigdelsetmask(&set, ~_BLOCKABLE); spin_lock_irq(&current->sighand->siglock); current->blocked = set; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); } if (test_thread_flag(TIF_32BIT)) { pc &= 0xffffffff; npc &= 0xffffffff; } regs->tpc = pc; regs->tnpc = npc; err |= __get_user(regs->y, &((*grp)[MC_Y])); err |= __get_user(tstate, &((*grp)[MC_TSTATE])); regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC); regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC)); err |= __get_user(regs->u_regs[UREG_G1], (&(*grp)[MC_G1])); err |= __get_user(regs->u_regs[UREG_G2], (&(*grp)[MC_G2])); err |= __get_user(regs->u_regs[UREG_G3], (&(*grp)[MC_G3])); err |= __get_user(regs->u_regs[UREG_G4], (&(*grp)[MC_G4])); err |= __get_user(regs->u_regs[UREG_G5], (&(*grp)[MC_G5])); err |= __get_user(regs->u_regs[UREG_G6], (&(*grp)[MC_G6])); /* Skip %g7 as that's the thread register in userspace. */ err |= __get_user(regs->u_regs[UREG_I0], (&(*grp)[MC_O0])); err |= __get_user(regs->u_regs[UREG_I1], (&(*grp)[MC_O1])); err |= __get_user(regs->u_regs[UREG_I2], (&(*grp)[MC_O2])); err |= __get_user(regs->u_regs[UREG_I3], (&(*grp)[MC_O3])); err |= __get_user(regs->u_regs[UREG_I4], (&(*grp)[MC_O4])); err |= __get_user(regs->u_regs[UREG_I5], (&(*grp)[MC_O5])); err |= __get_user(regs->u_regs[UREG_I6], (&(*grp)[MC_O6])); err |= __get_user(regs->u_regs[UREG_I7], (&(*grp)[MC_O7])); err |= __get_user(fp, &(ucp->uc_mcontext.mc_fp)); err |= __get_user(i7, &(ucp->uc_mcontext.mc_i7)); err |= __put_user(fp, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6]))); err |= __put_user(i7, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7]))); err |= __get_user(fenab, &(ucp->uc_mcontext.mc_fpregs.mcfpu_enab)); if (fenab) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; fprs_write(0); err |= __get_user(fprs, &(ucp->uc_mcontext.mc_fpregs.mcfpu_fprs)); if (fprs & FPRS_DL) err |= copy_from_user(fpregs, &(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs), (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_from_user(fpregs+16, ((unsigned long __user *)&(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs))+16, (sizeof(unsigned int) * 32)); err |= __get_user(current_thread_info()->xfsr[0], &(ucp->uc_mcontext.mc_fpregs.mcfpu_fsr)); err |= __get_user(current_thread_info()->gsr[0], &(ucp->uc_mcontext.mc_fpregs.mcfpu_gsr)); regs->tstate &= ~TSTATE_PEF; } if (err) goto do_sigsegv; return; do_sigsegv: force_sig(SIGSEGV, current); } asmlinkage void sparc64_get_context(struct pt_regs *regs) { struct ucontext __user *ucp = (struct ucontext __user *) regs->u_regs[UREG_I0]; mc_gregset_t __user *grp; mcontext_t __user *mcp; unsigned long fp, i7; unsigned char fenab; int err; synchronize_user_stack(); if (get_thread_wsaved() || clear_user(ucp, sizeof(*ucp))) goto do_sigsegv; #if 1 fenab = 0; /* IMO get_context is like any other system call, thus modifies FPU state -jj */ #else fenab = (current_thread_info()->fpsaved[0] & FPRS_FEF); #endif mcp = &ucp->uc_mcontext; grp = &mcp->mc_gregs; /* Skip over the trap instruction, first. */ if (test_thread_flag(TIF_32BIT)) { regs->tpc = (regs->tnpc & 0xffffffff); regs->tnpc = (regs->tnpc + 4) & 0xffffffff; } else { regs->tpc = regs->tnpc; regs->tnpc += 4; } err = 0; if (_NSIG_WORDS == 1) err |= __put_user(current->blocked.sig[0], (unsigned long __user *)&ucp->uc_sigmask); else err |= __copy_to_user(&ucp->uc_sigmask, &current->blocked, sizeof(sigset_t)); err |= __put_user(regs->tstate, &((*grp)[MC_TSTATE])); err |= __put_user(regs->tpc, &((*grp)[MC_PC])); err |= __put_user(regs->tnpc, &((*grp)[MC_NPC])); err |= __put_user(regs->y, &((*grp)[MC_Y])); err |= __put_user(regs->u_regs[UREG_G1], &((*grp)[MC_G1])); err |= __put_user(regs->u_regs[UREG_G2], &((*grp)[MC_G2])); err |= __put_user(regs->u_regs[UREG_G3], &((*grp)[MC_G3])); err |= __put_user(regs->u_regs[UREG_G4], &((*grp)[MC_G4])); err |= __put_user(regs->u_regs[UREG_G5], &((*grp)[MC_G5])); err |= __put_user(regs->u_regs[UREG_G6], &((*grp)[MC_G6])); err |= __put_user(regs->u_regs[UREG_G7], &((*grp)[MC_G7])); err |= __put_user(regs->u_regs[UREG_I0], &((*grp)[MC_O0])); err |= __put_user(regs->u_regs[UREG_I1], &((*grp)[MC_O1])); err |= __put_user(regs->u_regs[UREG_I2], &((*grp)[MC_O2])); err |= __put_user(regs->u_regs[UREG_I3], &((*grp)[MC_O3])); err |= __put_user(regs->u_regs[UREG_I4], &((*grp)[MC_O4])); err |= __put_user(regs->u_regs[UREG_I5], &((*grp)[MC_O5])); err |= __put_user(regs->u_regs[UREG_I6], &((*grp)[MC_O6])); err |= __put_user(regs->u_regs[UREG_I7], &((*grp)[MC_O7])); err |= __get_user(fp, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6]))); err |= __get_user(i7, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7]))); err |= __put_user(fp, &(mcp->mc_fp)); err |= __put_user(i7, &(mcp->mc_i7)); err |= __put_user(fenab, &(mcp->mc_fpregs.mcfpu_enab)); if (fenab) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; fprs = current_thread_info()->fpsaved[0]; if (fprs & FPRS_DL) err |= copy_to_user(&(mcp->mc_fpregs.mcfpu_fregs), fpregs, (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_to_user( ((unsigned long __user *)&(mcp->mc_fpregs.mcfpu_fregs))+16, fpregs+16, (sizeof(unsigned int) * 32)); err |= __put_user(current_thread_info()->xfsr[0], &(mcp->mc_fpregs.mcfpu_fsr)); err |= __put_user(current_thread_info()->gsr[0], &(mcp->mc_fpregs.mcfpu_gsr)); err |= __put_user(fprs, &(mcp->mc_fpregs.mcfpu_fprs)); } if (err) goto do_sigsegv; return; do_sigsegv: force_sig(SIGSEGV, current); } struct rt_signal_frame { struct sparc_stackf ss; siginfo_t info; struct pt_regs regs; __siginfo_fpu_t __user *fpu_save; stack_t stack; sigset_t mask; __siginfo_fpu_t fpu_state; }; static long _sigpause_common(old_sigset_t set) { set &= _BLOCKABLE; spin_lock_irq(&current->sighand->siglock); current->saved_sigmask = current->blocked; siginitset(&current->blocked, set); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); current->state = TASK_INTERRUPTIBLE; schedule(); set_restore_sigmask(); return -ERESTARTNOHAND; } asmlinkage long sys_sigpause(unsigned int set) { return _sigpause_common(set); } asmlinkage long sys_sigsuspend(old_sigset_t set) { return _sigpause_common(set); } static inline int restore_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; int err; err = __get_user(fprs, &fpu->si_fprs); fprs_write(0); regs->tstate &= ~TSTATE_PEF; if (fprs & FPRS_DL) err |= copy_from_user(fpregs, &fpu->si_float_regs[0], (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_from_user(fpregs+16, &fpu->si_float_regs[32], (sizeof(unsigned int) * 32)); err |= __get_user(current_thread_info()->xfsr[0], &fpu->si_fsr); err |= __get_user(current_thread_info()->gsr[0], &fpu->si_gsr); current_thread_info()->fpsaved[0] |= fprs; return err; } void do_rt_sigreturn(struct pt_regs *regs) { struct rt_signal_frame __user *sf; unsigned long tpc, tnpc, tstate; __siginfo_fpu_t __user *fpu_save; sigset_t set; int err; /* Always make any pending restarted system calls return -EINTR */ current_thread_info()->restart_block.fn = do_no_restart_syscall; synchronize_user_stack (); sf = (struct rt_signal_frame __user *) (regs->u_regs [UREG_FP] + STACK_BIAS); /* 1. Make sure we are not getting garbage from the user */ if (((unsigned long) sf) & 3) goto segv; err = get_user(tpc, &sf->regs.tpc); err |= __get_user(tnpc, &sf->regs.tnpc); if (test_thread_flag(TIF_32BIT)) { tpc &= 0xffffffff; tnpc &= 0xffffffff; } err |= ((tpc | tnpc) & 3); /* 2. Restore the state */ err |= __get_user(regs->y, &sf->regs.y); err |= __get_user(tstate, &sf->regs.tstate); err |= copy_from_user(regs->u_regs, sf->regs.u_regs, sizeof(regs->u_regs)); /* User can only change condition codes and %asi in %tstate. */ regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC); regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC)); err |= __get_user(fpu_save, &sf->fpu_save); if (fpu_save) err |= restore_fpu_state(regs, &sf->fpu_state); err |= __copy_from_user(&set, &sf->mask, sizeof(sigset_t)); err |= do_sigaltstack(&sf->stack, NULL, (unsigned long)sf); if (err) goto segv; regs->tpc = tpc; regs->tnpc = tnpc; /* Prevent syscall restart. */ pt_regs_clear_syscall(regs); sigdelsetmask(&set, ~_BLOCKABLE); spin_lock_irq(&current->sighand->siglock); current->blocked = set; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); return; segv: force_sig(SIGSEGV, current); } /* Checks if the fp is valid */ static int invalid_frame_pointer(void __user *fp, int fplen) { if (((unsigned long) fp) & 15) return 1; return 0; } static inline int save_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; int err = 0; fprs = current_thread_info()->fpsaved[0]; if (fprs & FPRS_DL) err |= copy_to_user(&fpu->si_float_regs[0], fpregs, (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_to_user(&fpu->si_float_regs[32], fpregs+16, (sizeof(unsigned int) * 32)); err |= __put_user(current_thread_info()->xfsr[0], &fpu->si_fsr); err |= __put_user(current_thread_info()->gsr[0], &fpu->si_gsr); err |= __put_user(fprs, &fpu->si_fprs); return err; } static inline void __user *get_sigframe(struct k_sigaction *ka, struct pt_regs *regs, unsigned long framesize) { unsigned long sp = regs->u_regs[UREG_FP] + STACK_BIAS; /* * If we are on the alternate signal stack and would overflow it, don't. * Return an always-bogus address instead so we will die with SIGSEGV. */ if (on_sig_stack(sp) && !likely(on_sig_stack(sp - framesize))) return (void __user *) -1L; /* This is the X/Open sanctioned signal stack switching. */ if (ka->sa.sa_flags & SA_ONSTACK) { if (sas_ss_flags(sp) == 0) sp = current->sas_ss_sp + current->sas_ss_size; } sp -= framesize; /* Always align the stack frame. This handles two cases. First, * sigaltstack need not be mindful of platform specific stack * alignment. Second, if we took this signal because the stack * is not aligned properly, we'd like to take the signal cleanly * and report that. */ sp &= ~15UL; return (void __user *) sp; } static inline void setup_rt_frame(struct k_sigaction *ka, struct pt_regs *regs, int signo, sigset_t *oldset, siginfo_t *info) { struct rt_signal_frame __user *sf; int sigframe_size, err; /* 1. Make sure everything is clean */ synchronize_user_stack(); save_and_clear_fpu(); sigframe_size = sizeof(struct rt_signal_frame); if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) sigframe_size -= sizeof(__siginfo_fpu_t); sf = (struct rt_signal_frame __user *) get_sigframe(ka, regs, sigframe_size); if (invalid_frame_pointer (sf, sigframe_size)) goto sigill; if (get_thread_wsaved() != 0) goto sigill; /* 2. Save the current process state */ err = copy_to_user(&sf->regs, regs, sizeof (*regs)); if (current_thread_info()->fpsaved[0] & FPRS_FEF) { err |= save_fpu_state(regs, &sf->fpu_state); err |= __put_user((u64)&sf->fpu_state, &sf->fpu_save); } else { err |= __put_user(0, &sf->fpu_save); } /* Setup sigaltstack */ err |= __put_user(current->sas_ss_sp, &sf->stack.ss_sp); err |= __put_user(sas_ss_flags(regs->u_regs[UREG_FP]), &sf->stack.ss_flags); err |= __put_user(current->sas_ss_size, &sf->stack.ss_size); err |= copy_to_user(&sf->mask, oldset, sizeof(sigset_t)); err |= copy_in_user((u64 __user *)sf, (u64 __user *)(regs->u_regs[UREG_FP]+STACK_BIAS), sizeof(struct reg_window)); if (info) err |= copy_siginfo_to_user(&sf->info, info); else { err |= __put_user(signo, &sf->info.si_signo); err |= __put_user(SI_NOINFO, &sf->info.si_code); } if (err) goto sigsegv; /* 3. signal handler back-trampoline and parameters */ regs->u_regs[UREG_FP] = ((unsigned long) sf) - STACK_BIAS; regs->u_regs[UREG_I0] = signo; regs->u_regs[UREG_I1] = (unsigned long) &sf->info; /* The sigcontext is passed in this way because of how it * is defined in GLIBC's /usr/include/bits/sigcontext.h * for sparc64. It includes the 128 bytes of siginfo_t. */ regs->u_regs[UREG_I2] = (unsigned long) &sf->info; /* 5. signal handler */ regs->tpc = (unsigned long) ka->sa.sa_handler; regs->tnpc = (regs->tpc + 4); if (test_thread_flag(TIF_32BIT)) { regs->tpc &= 0xffffffff; regs->tnpc &= 0xffffffff; } /* 4. return to kernel instructions */ regs->u_regs[UREG_I7] = (unsigned long)ka->ka_restorer; return; sigill: do_exit(SIGILL); sigsegv: force_sigsegv(signo, current); } static inline void handle_signal(unsigned long signr, struct k_sigaction *ka, siginfo_t *info, sigset_t *oldset, struct pt_regs *regs) { setup_rt_frame(ka, regs, signr, oldset, (ka->sa.sa_flags & SA_SIGINFO) ? info : NULL); spin_lock_irq(&current->sighand->siglock); sigorsets(&current->blocked,&current->blocked,&ka->sa.sa_mask); if (!(ka->sa.sa_flags & SA_NOMASK)) sigaddset(&current->blocked,signr); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); } static inline void syscall_restart(unsigned long orig_i0, struct pt_regs *regs, struct sigaction *sa) { switch (regs->u_regs[UREG_I0]) { case ERESTART_RESTARTBLOCK: case ERESTARTNOHAND: no_system_call_restart: regs->u_regs[UREG_I0] = EINTR; regs->tstate |= (TSTATE_ICARRY|TSTATE_XCARRY); break; case ERESTARTSYS: if (!(sa->sa_flags & SA_RESTART)) goto no_system_call_restart; /* fallthrough */ case ERESTARTNOINTR: regs->u_regs[UREG_I0] = orig_i0; regs->tpc -= 4; regs->tnpc -= 4; } } static void do_signal(struct pt_regs *regs, unsigned long orig_i0) { struct k_sigaction ka; int restart_syscall; sigset_t *oldset; siginfo_t info; int signr; if (pt_regs_is_syscall(regs) && (regs->tstate & (TSTATE_XCARRY | TSTATE_ICARRY))) { restart_syscall = 1; } else restart_syscall = 0; if (current_thread_info()->status & TS_RESTORE_SIGMASK) oldset = &current->saved_sigmask; else oldset = &current->blocked; #ifdef CONFIG_COMPAT if (test_thread_flag(TIF_32BIT)) { extern void do_signal32(sigset_t *, struct pt_regs *, int restart_syscall, unsigned long orig_i0); do_signal32(oldset, regs, restart_syscall, orig_i0); return; } #endif signr = get_signal_to_deliver(&info, &ka, regs, NULL); /* If the debugger messes with the program counter, it clears * the software "in syscall" bit, directing us to not perform * a syscall restart. */ if (restart_syscall && !pt_regs_is_syscall(regs)) restart_syscall = 0; if (signr > 0) { if (restart_syscall) syscall_restart(orig_i0, regs, &ka.sa); handle_signal(signr, &ka, &info, oldset, regs); /* A signal was successfully delivered; the saved * sigmask will have been stored in the signal frame, * and will be restored by sigreturn, so we can simply * clear the TS_RESTORE_SIGMASK flag. */ current_thread_info()->status &= ~TS_RESTORE_SIGMASK; tracehook_signal_handler(signr, &info, &ka, regs, 0); return; } if (restart_syscall && (regs->u_regs[UREG_I0] == ERESTARTNOHAND || regs->u_regs[UREG_I0] == ERESTARTSYS || regs->u_regs[UREG_I0] == ERESTARTNOINTR)) { /* replay the system call when we are done */ regs->u_regs[UREG_I0] = orig_i0; regs->tpc -= 4; regs->tnpc -= 4; } if (restart_syscall && regs->u_regs[UREG_I0] == ERESTART_RESTARTBLOCK) { regs->u_regs[UREG_G1] = __NR_restart_syscall; regs->tpc -= 4; regs->tnpc -= 4; } /* If there's no signal to deliver, we just put the saved sigmask * back */ if (current_thread_info()->status & TS_RESTORE_SIGMASK) { current_thread_info()->status &= ~TS_RESTORE_SIGMASK; sigprocmask(SIG_SETMASK, &current->saved_sigmask, NULL); } } void do_notify_resume(struct pt_regs *regs, unsigned long orig_i0, unsigned long thread_info_flags) { if (thread_info_flags & _TIF_SIGPENDING) do_signal(regs, orig_i0); if (thread_info_flags & _TIF_NOTIFY_RESUME) { clear_thread_flag(TIF_NOTIFY_RESUME); tracehook_notify_resume(regs); if (current->replacement_session_keyring) key_replace_session_keyring(); } }
luckasfb/OT_903D-kernel-2.6.35.7
kernel/arch/sparc/kernel/signal_64.c
C
gpl-2.0
18,267
/* * symlink.c * * Symlink methods. * * Author: Steve Longerbeam <stevel@mvista.com, or source@mvista.com> * * 2003 (c) MontaVista Software, Inc. * Copyright 2003 Sony Corporation * Copyright 2003 Matsushita Electric Industrial Co., Ltd. * * This software is being distributed under the terms of the GNU General Public * License version 2. Some or all of the technology encompassed by this * software may be subject to one or more patents pending as of the date of * this notice. No additional patent license will be required for GPL * implementations of the technology. If you want to create a non-GPL * implementation of the technology encompassed by this software, please * contact legal@mvista.com for details including licensing terms and fees. * * This file is licensed under the terms of the GNU General Public License * version 2. This program is licensed "as is" without any warranty of any * kind, whether express or implied. */ #include <linux/fs.h> #include <linux/pram_fs.h> int pram_block_symlink(struct inode *inode, const char *symname, int len) { struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; unsigned long flags; int err; err = pram_alloc_blocks (inode, 0, 1); if (err) return err; block = pram_find_data_block(inode, 0); blockp = pram_get_block(sb, block); pram_lock_block(sb, blockp); memcpy(blockp, symname, len); blockp[len] = '\0'; pram_unlock_block(sb, blockp); return 0; } static int pram_readlink(struct dentry *dentry, char *buffer, int buflen) { struct inode * inode = dentry->d_inode; struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; block = pram_find_data_block(inode, 0); blockp = pram_get_block(sb, block); return vfs_readlink(dentry, buffer, buflen, blockp); } static int pram_follow_link(struct dentry *dentry, struct nameidata *nd) { struct inode * inode = dentry->d_inode; struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; block = pram_find_data_block(inode, 0); blockp = pram_get_block(sb, block); return vfs_follow_link(nd, blockp); } struct inode_operations pram_symlink_inode_operations = { readlink: pram_readlink, follow_link: pram_follow_link, };
robacklin/celinux
fs/pramfs/symlink.c
C
gpl-2.0
2,227
/* * ux_text.c - Unix interface, text functions * * This file is part of Frotz. * * Frotz 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. * * Frotz 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 */ #define __UNIX_PORT_FILE #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef USE_NCURSES_H #include <ncurses.h> #else #include <curses.h> #endif #include "ux_frotz.h" /* When color_enabled is FALSE, we still minimally keep track of colors by * setting current_color to A_REVERSE if the game reads the default * foreground and background colors and swaps them. If we don't do this, * Strange Results can happen when playing certain V6 games when * color_enabled is FALSE. */ bool color_enabled = FALSE; /* int current_color = 0; */ static char latin1_to_ascii[] = " ! c L >o<Y | S '' C a << not- R _ " "^0 +/-^2 ^3 ' my P . , ^1 o >> 1/41/23/4? " "A A A A Ae A AE C E E E E I I I I " "Th N O O O O Oe * O U U U Ue Y Th ss " "a a a a ae a ae c e e e e i i i i " "th n o o o o oe : o u u u ue y th y "; /* * os_font_data * * Return true if the given font is available. The font can be * * TEXT_FONT * PICTURE_FONT * GRAPHICS_FONT * FIXED_WIDTH_FONT * * The font size should be stored in "height" and "width". If * the given font is unavailable then these values must _not_ * be changed. * */ int os_font_data (int font, int *height, int *width) { if (font == TEXT_FONT) { *height = 1; *width = 1; return 1; /* Truth in advertising */ } return 0; }/* os_font_data */ #ifdef COLOR_SUPPORT /* * unix_convert * * Converts frotz's (and Infocom's) color values to ncurses color values. * */ static int unix_convert(int color) { switch(color) { case BLACK_COLOUR: return COLOR_BLACK; case RED_COLOUR: return COLOR_RED; case GREEN_COLOUR: return COLOR_GREEN; case YELLOW_COLOUR: return COLOR_YELLOW; case BLUE_COLOUR: return COLOR_BLUE; case MAGENTA_COLOUR: return COLOR_MAGENTA; case CYAN_COLOUR: return COLOR_CYAN; case WHITE_COLOUR: return COLOR_WHITE; } return 0; } #endif /* * os_set_colour * * Set the foreground and background colours which can be: * * DEFAULT_COLOUR * BLACK_COLOUR * RED_COLOUR * GREEN_COLOUR * YELLOW_COLOUR * BLUE_COLOUR * MAGENTA_COLOUR * CYAN_COLOUR * WHITE_COLOUR * * MS-DOS 320 columns MCGA mode only: * * GREY_COLOUR * * Amiga only: * * LIGHTGREY_COLOUR * MEDIUMGREY_COLOUR * DARKGREY_COLOUR * * There may be more colours in the range from 16 to 255; see the * remarks on os_peek_colour. * */ void os_set_colour (int new_foreground, int new_background) { if (new_foreground == 1) new_foreground = z_header.h_default_foreground; if (new_background == 1) new_background = z_header.h_default_background; if (u_setup.color_enabled) { #ifdef COLOR_SUPPORT static int colorspace[10][10]; static int n_colors = 0; if (!colorspace[new_foreground][new_background]) { init_pair(++n_colors, unix_convert(new_foreground), unix_convert(new_background)); colorspace[new_foreground][new_background] = n_colors; } u_setup.current_color = COLOR_PAIR(colorspace[new_foreground][new_background]); #endif } else u_setup.current_color = (((new_foreground == z_header.h_default_background) && (new_background == z_header.h_default_foreground)) ? A_REVERSE : 0); os_set_text_style(u_setup.current_text_style); }/* os_set_colour */ /* * os_set_text_style * * Set the current text style. Following flags can be set: * * REVERSE_STYLE * BOLDFACE_STYLE * EMPHASIS_STYLE (aka underline aka italics) * FIXED_WIDTH_STYLE * */ void os_set_text_style (int new_style) { int temp = 0; u_setup.current_text_style = new_style; if (new_style & REVERSE_STYLE) temp |= A_REVERSE; if (new_style & BOLDFACE_STYLE) temp |= A_BOLD; if (new_style & EMPHASIS_STYLE) temp |= A_UNDERLINE; attrset(temp ^ u_setup.current_color); }/* os_set_text_style */ /* * os_set_font * * Set the font for text output. The interpreter takes care not to * choose fonts which aren't supported by the interface. * */ void os_set_font (int new_font) { /* Not implemented */ }/* os_set_font */ /* * os_display_char * * Display a character of the current font using the current colours and * text style. The cursor moves to the next position. Printable codes are * all ASCII values from 32 to 126, ISO Latin-1 characters from 160 to * 255, ZC_GAP (gap between two sentences) and ZC_INDENT (paragraph * indentation). The screen should not be scrolled after printing to the * bottom right corner. * */ void os_display_char (zchar c) { if (c >= ZC_LATIN1_MIN) { if (u_setup.plain_ascii) { char *ptr = latin1_to_ascii + 3 * (c - ZC_LATIN1_MIN); char c1 = *ptr++; char c2 = *ptr++; char c3 = *ptr++; addch(c1); if (c2 != ' ') addch(c2); if (c3 != ' ') addch(c3); } else addch(c); return; } if (c >= ZC_ASCII_MIN && c <= ZC_ASCII_MAX) { addch(c); return; } if (c == ZC_INDENT) { addch(' '); addch(' '); addch(' '); return; } if (c == ZC_GAP) { addch(' '); addch(' '); return; } }/* os_display_char */ /* * os_display_string * * Pass a string of characters to os_display_char. * */ void os_display_string (const zchar *s) { zchar c; while ((c = (unsigned char) *s++) != 0) /* Is this superfluous given it's also done in screen_word()? */ if (c == ZC_NEW_FONT || c == ZC_NEW_STYLE) { int arg = (unsigned char) *s++; if (c == ZC_NEW_FONT) os_set_font (arg); if (c == ZC_NEW_STYLE) os_set_text_style (arg); } else os_display_char (c); }/* os_display_string */ /* * os_char_width * * Return the width of the character in screen units. * */ int os_char_width (zchar c) { if (c >= ZC_LATIN1_MIN && u_setup.plain_ascii) { int width = 0; const char *ptr = latin1_to_ascii + 3 * (c - ZC_LATIN1_MIN); char c1 = *ptr++; char c2 = *ptr++; char c3 = *ptr++; /* Why, oh, why did you declare variables that way??? */ if (c1 == c1) /* let's avoid confusing the compiler (and me) */ width++; if (c2 != ' ') width++; if (c3 != ' ') width++; return width; } return 1; }/* os_char_width*/ /* * os_string_width * * Calculate the length of a word in screen units. Apart from letters, * the word may contain special codes: * * NEW_STYLE - next character is a new text style * NEW_FONT - next character is a new font * */ int os_string_width (const zchar *s) { int width = 0; zchar c; while ((c = *s++) != 0) if (c == ZC_NEW_STYLE || c == ZC_NEW_FONT) { s++; /* No effect */ } else width += os_char_width(c); return width; }/* os_string_width */ /* * os_set_cursor * * Place the text cursor at the given coordinates. Top left is (1,1). * */ void os_set_cursor (int y, int x) { /* Curses thinks the top left is (0,0) */ move(--y, --x); }/* os_set_cursor */ /* * os_more_prompt * * Display a MORE prompt, wait for a keypress and remove the MORE * prompt from the screen. * */ void os_more_prompt (void) { int saved_style, saved_x, saved_y; /* Save some useful information */ saved_style = u_setup.current_text_style; getyx(stdscr, saved_y, saved_x); os_set_text_style(0); addstr("[MORE]"); os_read_key(0, TRUE); move(saved_y, saved_x); addstr(" "); move(saved_y, saved_x); os_set_text_style(saved_style); }/* os_more_prompt */
holzman/frotz
src/curses/ux_text.c
C
gpl-2.0
8,410
/* Copyright (C) 2005 Michael K. McCarty & Fritz Bronner 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 */ /** \file future.c This is responsible for Future Mission planning screen. * */ #include <Buzz_inc.h> #include <externs.h> #include <assert.h> #include <logging.h> //Used to read steps from missStep.dat FILE* MSteps; char missStep[1024]; static inline char B_Mis(char x) {return missStep[x]-0x30;} /*missStep.dat is plain text, with: Mission Number (2 first bytes of each line) A Coded letter, each drawing a different line (1105-1127 for all possible letters) Numbers following each letter, which are the parameters of the function Each line must finish with a Z, so the game stops reading Any other char is ignored, but it's easier to read for a human that way */ LOG_DEFAULT_CATEGORY(future) char status[5],lck[5],F1,F2,F3,F4,FMen,F5,Pad; char JointFlag,MarFlag,JupFlag,SatFlag,MisType; GXHEADER vh; struct StepInfo { i16 x_cor; i16 y_cor; } StepBub[MAXBUB]; struct Parameter { char A; /**< DOCKING */ char B; /**< EVA */ char C; /**< LEM */ char D; /**< JOINT */ char E; /**< MANNED/UNMANNED/Duration 0==unmanned 1-6==duration */ char X; /**< the type of mission for assign crew and hardware */ char Z; /**< A duration mission only */ } V[62]; extern int Bub_Count; extern struct mStr Mis; extern struct MisEval Mev[60]; extern int SEG; void Load_FUT_BUT(void) { FILE *fin; unsigned i; fin=sOpen("NFUTBUT.BUT","rb",0); i=fread(screen,1,MAX_X*MAX_Y,fin); fclose(fin); RLED_img((char *)screen,(char *)vh.vptr,(unsigned)i,vh.w,vh.h); return; } void DrawFuture(char plr,int mis,char pad) { int i,j; FILE *fin; unsigned sz; strcpy(IKEY,"k011");strcpy(IDT,"i011"); JointFlag=0; // initialize joint flag F1=F2=F3=F4=FMen=F5=0; for (i=0;i<5;i++) lck[i]=status[i]=0; FadeOut(2,pal,10,0,0); Load_FUT_BUT(); fin=sOpen("FMIN.IMG","rb",0); fread(&pal[0],768,1,fin); sz=fread(screen,1,MAX_X*MAX_Y,fin); fclose(fin); RLED_img((char *)screen,(char *)vhptr.vptr,sz,vhptr.w,vhptr.h); gxClearDisplay(0,0); gr_sync (); if (pad==2) JointFlag=0; // third pad automatic no joint mission else if (Data->P[plr].LaunchFacility[pad+1] == 1) { if (Data->P[plr].Future[pad+1].MissionCode==0) JointFlag=1; // if no mission then set joint flag else if (Data->P[plr].Future[pad+1].part==1) // check if the part of that second mission is set { JointFlag=1; Data->P[plr].Future[pad+1].MissionCode=0; // clear mission Data->P[plr].Future[pad+1].part=0; }; }; if (pad==1 || pad==0) { if (Data->P[plr].LaunchFacility[pad+1]==1) JointFlag=1; } i=Data->Year;j=Data->Season; TRACE3("--- Setting i=Year (%d), j=Season (%d)", i, j); if ((i==60 && j==0) || (i==62 && j==0) || (i==64 && j==0) || (i==66 && j==0) || (i==69 && j==1) || (i==71 && j==1) || (i==73 && j==1)) { gxVirtualVirtual(&vhptr,1,2,12,11,&vhptr,198,153,gxSET); /* Mars */ MarFlag=1; } else MarFlag=0; if ((i==60 || i==64 || i==68 || i==72 || i==73 || i==77)) { gxVirtualVirtual(&vhptr,14,2,64,54,&vhptr,214,130,gxSET); /* Jup */ JupFlag=1; } else JupFlag=0; if (i==61 || i==66 || i==72) { gxVirtualVirtual(&vhptr,66,2,114,53,&vhptr,266,135,gxSET); /* Sat */ SatFlag=1; } else SatFlag=0; RectFill(1,1,318,21,3);RectFill(317,22,318,198,3);RectFill(1,197,316,198,3); RectFill(1,22,2,196,3);OutBox(0,0,319,199);InBox(3,3,30,19); InBox(3,22,316,196); IOBox(242,3,315,19); ShBox(5,24,183,47); ShBox(5,24,201,47); //name box ShBox(5,74,41,82); // RESET ShBox(5,49,53,72); //dur/man ShBox(43,74,53,82); // lock ShBox(80,74,90,82); ShBox(117,74,127,82); ShBox(154,74,164,82); ShBox(191,74,201,82); ShBox(5,84,16,130); //arrows up ShBox(5,132,16,146); //middle box ShBox(5,148,16,194); // down ShBox(203,24,238,31); // new right boxes RectFill(206,36,235,44,7); ShBox(203,33,238,47); InBox(205,35,236,45); UPArrow(8,95);DNArrow(8,157); gxVirtualDisplay(&vh,140,5,5,132,15,146,0); Toggle(5,1);draw_Pie(0);OutBox(5,49,53,72); Toggle(1,1);TogBox(55,49,0); Toggle(2,1);TogBox(92,49,0); Toggle(3,1);TogBox(129,49,0); FMen=F1=F2=F3=F4=F5=0; for (i=1;i<4;i++){ if (status[i]!=0) { Toggle(i,1); } }; if (JointFlag==0) { F4=2;lck[4]=1; Toggle(4,1); InBox(191,74,201,82); PlaceRX(5); TogBox(166,49,1); } else { F4=0; lck[4]=0; status[4]=0; Toggle(4,1); OutBox(191,74,201,82); ClearRX(5); TogBox(166,49,0); }; gr_sync (); Missions(plr,8,37,mis,1); GetMinus(plr); grSetColor(5); /* lines of text are 1:8,30 2:8,37 3:8,44 */ switch(pad) { // These used to say Pad 1, 2, 3 -Leon case 0: PrintAt(8,30,"PAD A:");break; case 1: PrintAt(8,30,"PAD B:");break; case 2: PrintAt(8,30,"PAD C:");break; default:break; }; grSetColor(1); PrintAt(9,80,"RESET"); PrintAt(256,13,"CONTINUE"); grSetColor(11); if (Data->Season==0) PrintAt(200,9,"SPRING"); else PrintAt(205,9,"FALL"); PrintAt(206,16,"19"); DispNum(0,0,Data->Year); grSetColor(1); FlagSm(plr,4,4); DispBig(40,5,"FUTURE MISSIONS",0,-1); FadeIn(2,pal,10,0,0); return; } void ClearDisplay(void) { gxVirtualDisplay(&vhptr,202,48,202,48,241,82,0); gxVirtualDisplay(&vhptr,17,83,17,83,241,195,0); gxVirtualDisplay(&vhptr,242,23,242,23,315,195,0); grSetColor(1); return; } int GetMinus(char plr) { char i;int u; i=PrestMin(plr); RectFill(206,36,235,44,7); if (i<3) u=1; //ok else if (i<9) u=10; //caution else u=19; //danger gxVirtualDisplay(&vh,203,u,203,24,238,31,0); grSetColor(11); if (i>0) PrintAt(210,42,"-"); else grMoveTo(210,42); DispNum(0,0,i); grSetColor(1); return 0; } void SetParameters(void) { int i; FILE *fin; fin=sOpen("MISSION.DAT","rb",0); for (i=0;i<62;i++) { fread(&Mis,sizeof Mis,1,fin); V[i].A=Mis.Doc; V[i].B=Mis.EVA; V[i].C=Mis.LM; V[i].D=Mis.Jt; V[i].E=Mis.Days; V[i].X=Mis.mCrew; V[i].Z=Mis.Dur; } fclose(fin); return; } void DrawLocks(void) { int i; for (i=0;i<5;i++) if (lck[i]==1) PlaceRX(i+1); else ClearRX(i+1); return; } /** set the toggles??? * * \param wh the button * \param i in or out */ void Toggle(int wh,int i) { TRACE3("->Toggle(wh %d, i %d)", wh, i); switch(wh) { case 1:if (i==1) gxVirtualDisplay(&vh,1,21,55,49,89,81,0);else gxVirtualDisplay(&vh,1,56,55,49,89,81,0); break; case 2:if(i==1) gxVirtualDisplay(&vh,38,21,92,49,127,81,0);else gxVirtualDisplay(&vh,38,56,92,49,127,81,0); break; case 3:if(i==1) gxVirtualDisplay(&vh,75,21,129,49,163,81,0);else gxVirtualDisplay(&vh,75,56,129,49,163,81,0); break; case 4:if(i==1) gxVirtualDisplay(&vh,112,21,166,49,200,81,0);else gxVirtualDisplay(&vh,112,56,166,49,200,81,0); break; case 5:if (i==1) gxVirtualDisplay(&vh,153,1,5,49,52,71,0); else gxVirtualDisplay(&vh,153,26,5,49,52,71,0); break; default:break; } TRACE1("<-Toggle()"); return; } void TogBox(int x,int y,int st) { TRACE4("->TogBox(x %d, y %d, st %d)", x, y, st); char sta[2][2]={{2,4},{4,2}}; grSetColor(sta[st][0]); grMoveTo(0+x,y+32);grLineTo(0+x,y+0);grLineTo(34+x,y+0); grSetColor(sta[st][1]); grMoveTo(x+0,y+33);grLineTo(23+x,y+33);grLineTo(23+x,y+23); grLineTo(x+35,y+23);grLineTo(x+35,y+0); TRACE1("<-TogBox()"); return; } void PianoKey(int X) { TRACE2("->PianoKey(X %d)", X); int t; if (F1==0) { if (V[X].A==1) {Toggle(1,1);status[1]=1;} else {Toggle(1,0);PlaceRX(1);status[1]=0;}} if (F2==0) { if (V[X].B==1) {Toggle(2,1);status[2]=1;} else {Toggle(2,0);PlaceRX(2);status[2]=0;}} if (F3==0) { if (V[X].C==1) {Toggle(3,1);status[3]=1;} else {Toggle(3,0);PlaceRX(3);status[3]=0;}} if (F4==0) { if (V[X].D==1) {Toggle(4,0);status[4]=1;} else {Toggle(4,1);status[4]=0; }} if (F5==-1 || (F5==0 && V[X].E==0)) { Toggle(5,0); status[0]=0; } else { Toggle(5,1); t=(F5==0) ? V[X].E : F5; assert(0 <= t); draw_Pie(t); status[0]=t; } DrawLocks(); TRACE1("<-PianoKey()"); return; } /** draw a piechart * * The piechart is indicating the number of astronauts on this mission. * * \param s something of an offset... */ void draw_Pie(int s) { int off; if (s==0) off=1; else off=s*20; gxVirtualDisplay(&vh,off,1,7,51,25,69,0); return; } void PlaceRX(int s) { switch(s) { case 1: RectFill(44,75,52,81,8);break; case 2: RectFill(81,75,89,81,8);break; case 3: RectFill(118,75,126,81,8);break; case 4: RectFill(155,75,163,81,8);break; case 5: RectFill(192,75,200,81,8);break; default:break; } return; } void ClearRX(int s) { switch(s) { case 1: RectFill(44,75,52,81,3);break; case 2: RectFill(81,75,89,81,3);break; case 3: RectFill(118,75,126,81,3);break; case 4: RectFill(155,75,163,81,3);break; case 5: RectFill(192,75,200,81,3);break; default:break; } return; } int UpSearchRout(int num,char plr) { int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1; orig=num; if (num >= 56+plr) num=0; else num++; while (found==0) { c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1; if (F1==V[num].A) c1=1; /* condition one is true */ if (F1==0 && V[num].A==1) c1=1; if (F1==2 && V[num].A==0) c1=1; if (F2==V[num].B) c2=1; /* condition two is true */ if (F2==0 && V[num].B==1) c2=1; if (F2==2 && V[num].B==0) c2=1; if (F3==V[num].C) c3=1; /* condition three is true */ if (F3==0 && V[num].C==1) c3=1; if (F3==2 && V[num].C==0) c3=1; if (F4==V[num].D) c4=1; /* condition four is true */ if (F4==0 && V[num].D==1) c4=1; if (F4==2 && V[num].D==0) c4=1; if (num==0) c5=1; else { if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1; if (F5==0) c5=1; if (F5>1 && V[num].Z==1) c5=1; if (F5==V[num].E) c5=1; }; if ((num==32 || num==36) && F5==2) c5=0; // planet check if (num==10 && MarFlag==0) c6=0; if (num==12 && JupFlag==0) c7=0; if (num==13 && SatFlag==0) c8=0; if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1; if (num==orig) return(0); if (found==0) { if (num==56+plr) num=0; else ++num; } }; /* end while */ return(num); } int DownSearchRout(int num,char plr) { int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1; orig=num; if (num<=0) num=56+plr; else --num; while (found==0) { c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1; if (F1==V[num].A) c1=1; if (F1==0 && V[num].A==1) c1=1; /* condition one is true */ if (F1==2 && V[num].A==0) c1=1; if (F2==V[num].B) c2=1; /* condition two is true */ if (F2==0 && V[num].B==1) c2=1; /* condition one is true */ if (F2==2 && V[num].B==0) c2=1; if (F3==V[num].C) c3=1; /* condition three is true */ if (F3==0 && V[num].C==1) c3=1; /* condition one is true */ if (F3==2 && V[num].C==0) c3=1; if (F4==V[num].D) c4=1; /* condition four is true */ if (F4==0 && V[num].D==1) c4=1; /* condition one is true */ if (F4==2 && V[num].D==0) c4=1; if (num==0) c5=1; else { if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1; // locked on zero duration if (F5==0) c5=1; // nothing set if (F5>1 && V[num].Z==1) c5=1; // set duration with duration mission if (F5==V[num].E) c5=1; // the duration is equal to what is preset }; if ((num==32 || num==36) && F5==2) c5=0; // planet check if (num==10 && MarFlag==0) c6=0; if (num==12 && JupFlag==0) c7=0; if (num==13 && SatFlag==0) c8=0; if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1; if (num==orig) return(0); if (found==0) { if (num==0) num=56+plr; else --num; } }; /* end while */ return(num); } void Future(char plr) { /** \todo the whole Future()-function is 500 >lines and unreadable */ TRACE1("->Future(plr)"); int MisNum = 0, DuraType = 0, MaxDur = 6, i, ii; int setting = -1, prev_setting = -1; int Ok, NewType; GXHEADER local, local2; GV(&local, 166, 9); GV(&local2, 177, 197); GV(&vh,240,90); /* global variable */ begfut: MisNum = FutureCheck(plr, 0); if (MisNum == 5) { DV(&local); DV(&local2); DV(&vh); return; } F1 = F2 = F3 = F4 = FMen = F5 = 0; // memset(buffer, 0x00, 20000); for (i = 0; i < 5; i++) lck[i] = status[i] = 0; SetParameters(); strcpy(IDT, "i011"); Pad = MisNum; DuraType = FMen = MisType = 0; ClrFut(plr, MisNum); DrawFuture(plr, MisType, MisNum); begfut_noredraw: // for (i=0;i<5;i++) ClearRX(i+1); while (1) { GetMouse(); if (mousebuttons == 0) break; } while (1) { GetMouse(); prev_setting = setting; setting = -1; if (key == '-' && SEG > 1) SEG--; if (key == '+' && SEG < 500) SEG++; if (key >= 65 && key < Bub_Count + 65) setting = key - 65; for (ii = 0; ii < Bub_Count; ii++) { if (x >= StepBub[ii].x_cor && x <= StepBub[ii].x_cor + 7 && y >= StepBub[ii].y_cor && y <= StepBub[ii].y_cor + 7) setting = ii; } if (setting >= 0) { if (prev_setting < 0) gxGetImage(&local, 18, 186, 183, 194, 0); if (prev_setting != setting) { ShBox(18, 186, 183, 194); grSetColor(1); MisStep(21, 192, Mev[setting].loc); } } else if (setting < 0 && prev_setting >= 0) { gxPutImage(&local, gxSET, 18, 186, 0); } if (Mis.Dur <= V[MisType].E && ((x >= 244 && y >= 5 && x <= 313 && y <= 17 && mousebuttons > 0) || key == K_ENTER)) { InBox(244, 5, 313, 17); WaitForMouseUp(); if (key > 0) delay(300); key = 0; OutBox(244, 5, 313, 17); gxGetImage(&local2, 74, 3, 250, 199, 0); NewType = V[MisType].X; Data->P[plr].Future[MisNum].Duration = DuraType; Ok = HardCrewAssign(plr, Pad, MisType, NewType); gxPutImage(&local2, gxSET, 74, 3, 0); // DV(&local2); if (Ok == 1) { Data->P[plr].Future[MisNum].Duration = DuraType; goto begfut; // return to loop } else { ClrFut(plr, MisNum); // DuraType = FMen = MisType = 0; key = 0; goto begfut_noredraw; // DrawFuture(plr, MisType, MisNum); } key = 0; }; // continue if ((((x >= 5 && y >= 49 && x <= 53 && y <= 72) || (x >= 43 && y >= 74 && x <= 53 && y <= 82)) && mousebuttons > 0) || (key == '!' || key == '1')) { if ((x >= 43 && y >= 74 && x <= 53 && y <= 82) || key == '!') { lck[0] = abs(lck[0] - 1); if (lck[0] == 1) InBox(43, 74, 53, 82); else OutBox(43, 74, 53, 82); if (lck[0] == 1) F5 = (status[0] == 0) ? -1 : status[0]; if (lck[0] == 1) PlaceRX(1); else ClearRX(1); if (lck[0] == 0) { F5 = 0; status[0] = 0; } while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[0] != 1) { InBox(5, 49, 53, 72); if (DuraType == MaxDur) DuraType = 0; else DuraType++; Data->P[plr].Future[MisNum].Duration = DuraType; if (DuraType == 0) Toggle(5, 0); else if (DuraType == 1) Toggle(5, 1); if (DuraType != 0) draw_Pie(DuraType); status[0] = DuraType; while (1) { GetMouse(); if (mousebuttons == 0) break; } grSetColor(34); OutBox(5, 49, 53, 72); }; key = 0; /* Duration */ }; if ((x >= 5 && y >= 74 && x <= 41 && y <= 82 && mousebuttons > 0) || (key == K_ESCAPE)) { InBox(5, 74, 41, 82); while (1) { GetMouse(); if (mousebuttons == 0) break; } MisType = 0; if (DuraType != 0) Toggle(5, 0); FMen = DuraType = F1 = F2 = F3 = F4 = F5 = 0; for (i = 1; i < 4; i++) if (status[i] != 0) Toggle(i, 1); if (JointFlag == 0) { F4 = 2; lck[4] = 1; Toggle(4, 1); InBox(191, 74, 201, 82); PlaceRX(5); TogBox(166, 49, 1); } else { F4 = 0; lck[4] = 0; status[4] = 0; Toggle(4, 1); OutBox(191, 74, 201, 82); ClearRX(5); TogBox(166, 49, 0); }; for (i = 0; i < 4; i++) { lck[i] = status[i] = 0; } OutBox(5, 49, 53, 72); OutBox(43, 74, 53, 82); TogBox(55, 49, 0); OutBox(80, 74, 90, 82); TogBox(92, 49, 0); OutBox(117, 74, 127, 82); TogBox(129, 49, 0); OutBox(154, 74, 164, 82); ClrFut(plr, MisNum); Data->P[plr].Future[MisNum].Duration = 0; Missions(plr, 8, 37, MisType, 1); GetMinus(plr); OutBox(5, 74, 41, 82); key = 0; /* Reset */ }; if ((x >= 55 && y >= 49 && x <= 90 && y <= 82 && mousebuttons > 0) || (key == '2' || key == '@')) { if ((x >= 80 && y >= 74 && x <= 90 && y <= 82) || (key == '@')) { if (lck[1] == 0) InBox(80, 74, 90, 82); else OutBox(80, 74, 90, 82); lck[1] = abs(lck[1] - 1); if (lck[1] == 1) PlaceRX(2); else ClearRX(2); if ((status[1] == 0) && (lck[1] == 1)) F1 = 2; else if ((status[1] == 1) && (lck[1] == 1)) F1 = 1; else F1 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[1] != 1) { TogBox(55, 49, 1); if (status[1] == 0) Toggle(1, 1); else Toggle(1, 0); status[1] = abs(status[1] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(55, 49, 0); }; /* Docking */ key = 0; }; if ((x >= 92 && y >= 49 && x <= 127 && y <= 82 && mousebuttons > 0) || (key == '3' || key == '#')) { if ((x >= 117 && y >= 74 && x <= 127 && y <= 82) || (key == '#')) { if (lck[2] == 0) InBox(117, 74, 127, 82); else OutBox(117, 74, 127, 82); lck[2] = abs(lck[2] - 1); if (lck[2] == 1) PlaceRX(3); else ClearRX(3); if ((status[2] == 0) && (lck[2] == 1)) F2 = 2; else if ((status[2] == 1) && (lck[2] == 1)) F2 = 1; else F2 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[2] != 1) { TogBox(92, 49, 1); if (status[2] == 0) Toggle(2, 1); else { Toggle(2, 0); }; status[2] = abs(status[2] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(92, 49, 0); }; /* EVA */ key = 0; }; if ((x >= 129 && y >= 49 && x <= 164 && y <= 82 && mousebuttons > 0) || (key == '4' || key == '$')) { if ((x >= 154 && y >= 74 && x <= 164 && y <= 82) || (key == '$')) { if (lck[3] == 0) InBox(154, 74, 164, 82); else OutBox(154, 74, 164, 82); lck[3] = abs(lck[3] - 1); // F3=lck[3]; if (lck[3] == 1) PlaceRX(4); else ClearRX(4); if ((status[3] == 0) && (lck[3] == 1)) F3 = 2; else if ((status[3] == 1) && (lck[3] == 1)) F3 = 1; else F3 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[3] != 1) { TogBox(129, 49, 1); if (status[3] == 0) Toggle(3, 1); else { Toggle(3, 0); }; status[3] = abs(status[3] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(129, 49, 0); }; /* LEM */ key = 0; }; if (((x >= 166 && y >= 49 && x <= 201 && y <= 82 && mousebuttons > 0) || (key == '5' || key == '%')) && (JointFlag == 1)) { if ((x > 191 && y >= 74 && x <= 201 && y <= 82) || (key == '%')) { if (lck[4] == 0) InBox(191, 74, 201, 82); else OutBox(191, 74, 201, 82); lck[4] = abs(lck[4] - 1); if (lck[4] == 1) PlaceRX(5); else ClearRX(5); if ((status[4] == 0) && (lck[4] == 1)) F4 = 2; else if ((status[4] == 1) && (lck[4] == 1)) F4 = 1; else F4 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[4] != 1) { TogBox(166, 49, 1); status[4] = abs(status[4] - 1); if (status[4] == 0) { Toggle(4, 1); } else { Toggle(4, 0); } while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(166, 49, 0); }; /* Joint Launch */ key = 0; }; if ((x >= 5 && y >= 84 && x <= 16 && y <= 130 && mousebuttons > 0) || (key == UP_ARROW)) { InBox(5, 84, 16, 130); for (i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } } while (mousebuttons == 1 || key == UP_ARROW) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 84, 16, 130); key = 0; /* Mission Type plus */ }; if ((x >= 5 && y >= 132 && x < 16 && y <= 146 && mousebuttons > 0) || (key == K_SPACE)) { InBox(5, 132, 16, 146); WaitForMouseUp(); delay(50); MisType = Data->P[plr].Future[MisNum].MissionCode; assert(0 <= MisType); if (MisType != 0){ Missions(plr, 8, 37, MisType, 1); } else{ Missions(plr, 8, 37, MisType, 3); } OutBox(5, 132, 16, 146); key = 0; } if ((x >= 5 && y >= 148 && x <= 16 && y <= 194 && mousebuttons > 0) || (key == DN_ARROW)) { InBox(5, 148, 16, 194); for (i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } key = 0; } while (mousebuttons == 1 || key == DN_ARROW) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 148, 16, 194); key = 0; /* Mission Type minus */ }; } // while TRACE1("<-Future()"); } /** draws the bubble on the screen, * starts with upper left coor * * \param x x-coord of the upper left corner of the bubble * \param y y-coord of the upper left corner of the bubble */ void Bd(int x,int y) { int x1,y1,x2,y2; x1=x-2; y1=y; x2=x-1; y2=y-1; RectFill(x1,y1,x1+8,y1+4,21); RectFill(x2,y2,x2+6,y2+6,21); grSetColor(1); grMoveTo(x,y+4); /** \note references Bub_Count to determine the number of the character to draw in the bubble */ DispChr(65+Bub_Count); StepBub[Bub_Count].x_cor=x1; StepBub[Bub_Count].y_cor=y1; ++Bub_Count; return; } /** Print the duration of a mission * * \param x duration code * * \todo Link this at whatever place the duration is actually defined */ void DurPri(int x) { grSetColor(5); switch(x) { case -1:PrintAt(112,30,"NO DURATION");break; case 0:PrintAt(112,30,"NO DURATION");break; case 1:PrintAt(112,30,"1 - 2 DAYS");break; case 2:PrintAt(112,30,"3 - 5 DAYS");break; case 3:PrintAt(112,30,"6 - 7 DAYS");break; case 4:PrintAt(112,30,"8 - 12 DAYS");break; case 5:PrintAt(112,30,"13 - 16 DAYS");break; case 6:PrintAt(112,30,"17 - 20 DAYS");break; default:break; }; return; } void MissionName(int val,int xx,int yy,int len) { TRACE5("->MissionName(val %d, xx %d, yy %d, len %d)", val, xx, yy, len); int i,j=0; GetMisType(val); grMoveTo(xx,yy); for (i=0;i<50;i++) { if (j>len && Mis.Name[i]==' ') {yy+=7;j=0;grMoveTo(xx,yy);} else DispChr(Mis.Name[i]); j++;if (Mis.Name[i]=='\0') break; }; TRACE1("<-MissionName"); return; } /** Missions() will draw the future missions among other things * * \param plr Player * \param X screen coord for mission name string * \param Y screen coord for mission name string * \param val mission number * \param bub if set to 0 or 3 the function will not draw stuff */ void Missions(char plr,int X,int Y,int val,char bub) { TRACE5("->Missions(plr, X %d, Y %d, val %d, bub %c)", X, Y, val, bub); if (bub==1 || bub==3) { PianoKey(val); Bub_Count=0; // set the initial bub_count ClearDisplay(); RectFill(6,31,182,46,3); RectFill(80,25,175,30,3);grSetColor(5); PrintAt(55,30,"TYPE: ");DispNum(0,0,val); grSetColor(5); if (V[val].E>0) { if (F5 > V[val].E && Mis.Dur==1) DurPri(F5); else DurPri(V[val].E);} else DurPri(F5); } else grSetColor(1); MissionName(val,X,Y,24); if (bub==3) GetMinus(plr); if (bub==0 || bub==3) {return;} MSteps=sOpen("missSteps.dat","r",FT_DATA); if (fgets(missStep, 1024, MSteps) == NULL) memset (missStep, 0, sizeof missStep); while (!feof(MSteps)&&((missStep[0]-0x30)*10+(missStep[1]-0x30))!=val) { if (fgets(missStep, 1024, MSteps) == NULL) break; } fclose(MSteps); int n; for (n=2;missStep[n]!='Z';n++) switch (missStep[n]) { case 'A': Draw_IJ (B_Mis(++n)); break; case 'B': Draw_IJV (B_Mis(++n)); break; case 'C': OrbOut (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'D': LefEarth (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'E': OrbIn (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'F': OrbMid (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'G': LefOrb (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'H': Draw_LowS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6)); n+=6; break; case 'I': Fly_By (); break; case 'J': VenMarMerc (B_Mis(++n)); break; case 'K': Draw_PQR (); break; case 'L': Draw_PST (); break; case 'M': Draw_GH (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'N': Q_Patch (); break; case 'O': RghtMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'P': DrawLunPas (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'Q': DrawLefMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'R': DrawSTUV (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'S': Draw_HighS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'T': DrawMoon (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6),B_Mis(n+7)); n+=7; break; case 'U': LefGap (B_Mis(++n)); break; case 'V': S_Patch (B_Mis(++n)); break; case 'W': DrawZ (); break; default : break; } gr_sync (); MissionCodes(plr,MisType,Pad); TRACE1("<-Missions()"); } // end function missions #ifdef DEAD_CODE /** Draws stuff about choosing a program and having < 2 groups available * * \deprecated This function appears to be deprecated. */ char FutBad(void) { char i; grSetColor(0); ShBox(84,41,232,128); InBox(91,47,225,103); IOBox(91,107,225,123); grSetColor(1); PrintAt(150,117,"EXIT"); grSetColor(11); PrintAt(96,60,"YOU HAVE SELECTED A"); PrintAt(96,70,"PROGRAM WITH LESS THAN"); PrintAt(96,80,"TWO GROUPS AVAILABLE."); WaitForMouseUp(); i=0; while(i==0) { GetMouse(); if (mousebuttons!=0) { if (x>=93 && y>=109 && x<=223 && y<=121) { InBox(93,109,223,123);i=3; delay(50); }; }; }; /* End while */ return (i); } #endif /* vim: set noet ts=4 sw=4 tw=77: */
raceintospace/raceintospace-cvs
future.c
C
gpl-2.0
27,931
// Copyright (C) 1999-2000 Id Software, Inc. // #include "ui_local.h" /********************************************************************************* SPECIFY SERVER *********************************************************************************/ #define MAX_LISTBOXITEMS 128 #define MAX_LISTBOXWIDTH 40 #define MAX_LEAGUENAME 80 #define SPECIFYLEAGUE_FRAMEL "menu/art/frame2_l" #define SPECIFYLEAGUE_FRAMER "menu/art/frame1_r" #define SPECIFYLEAGUE_BACK0 "menu/art/back_0" #define SPECIFYLEAGUE_BACK1 "menu/art/back_1" #define SPECIFYLEAGUE_ARROWS0 "menu/art/arrows_vert_0" #define SPECIFYLEAGUE_UP "menu/art/arrows_vert_top" #define SPECIFYLEAGUE_DOWN "menu/art/arrows_vert_bot" #define GLOBALRANKINGS_LOGO "menu/art/gr/grlogo" #define GLOBALRANKINGS_LETTERS "menu/art/gr/grletters" #define ID_SPECIFYLEAGUENAME 100 #define ID_SPECIFYLEAGUELIST 101 #define ID_SPECIFYLEAGUEUP 102 #define ID_SPECIFYLEAGUEDOWN 103 #define ID_SPECIFYLEAGUEBACK 104 static char* specifyleague_artlist[] = { SPECIFYLEAGUE_FRAMEL, SPECIFYLEAGUE_FRAMER, SPECIFYLEAGUE_ARROWS0, SPECIFYLEAGUE_UP, SPECIFYLEAGUE_DOWN, SPECIFYLEAGUE_BACK0, SPECIFYLEAGUE_BACK1, GLOBALRANKINGS_LOGO, GLOBALRANKINGS_LETTERS, NULL }; static char playername[80]; typedef struct { menuframework_s menu; menutext_s banner; menubitmap_s framel; menubitmap_s framer; menufield_s rankname; menulist_s list; menubitmap_s arrows; menubitmap_s up; menubitmap_s down; menubitmap_s back; menubitmap_s grlogo; menubitmap_s grletters; } specifyleague_t; static specifyleague_t s_specifyleague; typedef struct { char buff[MAX_LISTBOXWIDTH]; char leaguename[MAX_LEAGUENAME]; } table_t; table_t league_table[MAX_LISTBOXITEMS]; char *leaguename_items[MAX_LISTBOXITEMS]; static void SpecifyLeague_GetList() { int count = 0; int i; /* The Player Name has changed. We need to perform another search */ Q_strncpyz( playername, s_specifyleague.rankname.field.buffer, sizeof(playername) ); count = trap_CL_UI_RankGetLeauges( playername ); for(i = 0; i < count; i++) { char s[MAX_LEAGUENAME]; const char *var; var = va( "leaguename%i", i+1 ); trap_Cvar_VariableStringBuffer( var, s, sizeof(s) ); Q_strncpyz(league_table[i].leaguename, s, sizeof(league_table[i].leaguename) ); Q_strncpyz(league_table[i].buff, league_table[i].leaguename, sizeof(league_table[i].buff) ); } s_specifyleague.list.numitems = count; } /* ================= SpecifyLeague_Event ================= */ static void SpecifyLeague_Event( void* ptr, int event ) { int id; id = ((menucommon_s*)ptr)->id; //if( event != QM_ACTIVATED && id != ID_SPECIFYLEAGUELIST ) { // return; //} switch (id) { case ID_SPECIFYLEAGUELIST: if( event == QM_GOTFOCUS ) { //ArenaServers_UpdatePicture(); } break; case ID_SPECIFYLEAGUEUP: if( event == QM_ACTIVATED ) ScrollList_Key( &s_specifyleague.list, K_UPARROW ); break; case ID_SPECIFYLEAGUEDOWN: if( event == QM_ACTIVATED ) ScrollList_Key( &s_specifyleague.list, K_DOWNARROW ); break; case ID_SPECIFYLEAGUENAME: if( (event == QM_LOSTFOCUS) && (Q_strncmp(playername, s_specifyleague.rankname.field.buffer, strlen(s_specifyleague.rankname.field.buffer)) != 0)) { SpecifyLeague_GetList(); } break; case ID_SPECIFYLEAGUEBACK: if( event == QM_ACTIVATED ) { trap_Cvar_Set( "sv_leagueName", league_table[s_specifyleague.list.curvalue].leaguename); UI_PopMenu(); } break; } } /* ================= SpecifyLeague_MenuInit ================= */ void SpecifyLeague_MenuInit( void ) { int i; // zero set all our globals memset( &s_specifyleague, 0 ,sizeof(specifyleague_t) ); SpecifyLeague_Cache(); s_specifyleague.menu.wrapAround = qtrue; s_specifyleague.menu.fullscreen = qtrue; s_specifyleague.banner.generic.type = MTYPE_BTEXT; s_specifyleague.banner.generic.x = 320; s_specifyleague.banner.generic.y = 16; s_specifyleague.banner.string = "CHOOSE LEAGUE"; s_specifyleague.banner.color = color_white; s_specifyleague.banner.style = UI_CENTER; s_specifyleague.framel.generic.type = MTYPE_BITMAP; s_specifyleague.framel.generic.name = SPECIFYLEAGUE_FRAMEL; s_specifyleague.framel.generic.flags = QMF_INACTIVE; s_specifyleague.framel.generic.x = 0; s_specifyleague.framel.generic.y = 78; s_specifyleague.framel.width = 256; s_specifyleague.framel.height = 334; s_specifyleague.framer.generic.type = MTYPE_BITMAP; s_specifyleague.framer.generic.name = SPECIFYLEAGUE_FRAMER; s_specifyleague.framer.generic.flags = QMF_INACTIVE; s_specifyleague.framer.generic.x = 376; s_specifyleague.framer.generic.y = 76; s_specifyleague.framer.width = 256; s_specifyleague.framer.height = 334; s_specifyleague.grlogo.generic.type = MTYPE_BITMAP; s_specifyleague.grlogo.generic.name = GLOBALRANKINGS_LOGO; s_specifyleague.grlogo.generic.flags = QMF_INACTIVE; s_specifyleague.grlogo.generic.x = 0; s_specifyleague.grlogo.generic.y = 0; s_specifyleague.grlogo.width = 64; s_specifyleague.grlogo.height = 128; s_specifyleague.rankname.generic.type = MTYPE_FIELD; s_specifyleague.rankname.generic.name = "Player Name:"; s_specifyleague.rankname.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT; s_specifyleague.rankname.generic.callback = SpecifyLeague_Event; s_specifyleague.rankname.generic.id = ID_SPECIFYLEAGUENAME; s_specifyleague.rankname.generic.x = 226; s_specifyleague.rankname.generic.y = 128; s_specifyleague.rankname.field.widthInChars = 32; s_specifyleague.rankname.field.maxchars = 80; s_specifyleague.list.generic.type = MTYPE_SCROLLLIST; s_specifyleague.list.generic.flags = QMF_HIGHLIGHT_IF_FOCUS; s_specifyleague.list.generic.id = ID_SPECIFYLEAGUELIST; s_specifyleague.list.generic.callback = SpecifyLeague_Event; s_specifyleague.list.generic.x = 160; s_specifyleague.list.generic.y = 200; s_specifyleague.list.width = MAX_LISTBOXWIDTH; s_specifyleague.list.height = 8; s_specifyleague.list.itemnames = (const char **)leaguename_items; s_specifyleague.list.numitems = 0; for( i = 0; i < MAX_LISTBOXITEMS; i++ ) { league_table[i].buff[0] = 0; league_table[i].leaguename[0] = 0; leaguename_items[i] = league_table[i].buff; } s_specifyleague.arrows.generic.type = MTYPE_BITMAP; s_specifyleague.arrows.generic.name = SPECIFYLEAGUE_ARROWS0; s_specifyleague.arrows.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE; s_specifyleague.arrows.generic.callback = SpecifyLeague_Event; s_specifyleague.arrows.generic.x = 512; s_specifyleague.arrows.generic.y = 240-64+16; s_specifyleague.arrows.width = 64; s_specifyleague.arrows.height = 128; s_specifyleague.up.generic.type = MTYPE_BITMAP; s_specifyleague.up.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY; s_specifyleague.up.generic.callback = SpecifyLeague_Event; s_specifyleague.up.generic.id = ID_SPECIFYLEAGUEUP; s_specifyleague.up.generic.x = 512; s_specifyleague.up.generic.y = 240-64+16; s_specifyleague.up.width = 64; s_specifyleague.up.height = 64; s_specifyleague.up.focuspic = SPECIFYLEAGUE_UP; s_specifyleague.down.generic.type = MTYPE_BITMAP; s_specifyleague.down.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY; s_specifyleague.down.generic.callback = SpecifyLeague_Event; s_specifyleague.down.generic.id = ID_SPECIFYLEAGUEDOWN; s_specifyleague.down.generic.x = 512; s_specifyleague.down.generic.y = 240+16; s_specifyleague.down.width = 64; s_specifyleague.down.height = 64; s_specifyleague.down.focuspic = SPECIFYLEAGUE_DOWN; s_specifyleague.back.generic.type = MTYPE_BITMAP; s_specifyleague.back.generic.name = SPECIFYLEAGUE_BACK0; s_specifyleague.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; s_specifyleague.back.generic.callback = SpecifyLeague_Event; s_specifyleague.back.generic.id = ID_SPECIFYLEAGUEBACK; s_specifyleague.back.generic.x = 0; s_specifyleague.back.generic.y = 480-64; s_specifyleague.back.width = 128; s_specifyleague.back.height = 64; s_specifyleague.back.focuspic = SPECIFYLEAGUE_BACK1; Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.banner ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framel ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framer ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.grlogo ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.rankname ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.list ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.arrows ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.up ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.down ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.back ); // initialize any menu variables Q_strncpyz( s_specifyleague.rankname.field.buffer, UI_Cvar_VariableString("name"), sizeof(s_specifyleague.rankname.field.buffer) ); Q_strncpyz( playername, UI_Cvar_VariableString("name"), sizeof(playername) ); SpecifyLeague_GetList(); } /* ================= SpecifyLeague_Cache ================= */ void SpecifyLeague_Cache( void ) { int i; // touch all our pics for (i=0; ;i++) { if (!specifyleague_artlist[i]) break; trap_R_RegisterShaderNoMip(specifyleague_artlist[i]); } } /* ================= UI_SpecifyLeagueMenu ================= */ void UI_SpecifyLeagueMenu( void ) { SpecifyLeague_MenuInit(); UI_PushMenu( &s_specifyleague.menu ); }
tectronics/battle-of-the-sexes
reference/bots_q3_127/code/q3_ui/ui_specifyleague.c
C
gpl-2.0
9,959
/* * Copyright (c) 2002-2009 BalaBit IT Ltd, Budapest, Hungary * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * Note that this permission is granted for only version 2 of the GPL. * * As an additional exemption you are allowed to compile & link against the * OpenSSL libraries as published by the OpenSSL project. See the file * COPYING for details. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "gprocess.h" #include "misc.h" #include "messages.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <time.h> #include <sys/resource.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <signal.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pwd.h> #include <grp.h> #if ENABLE_LINUX_CAPS # include <sys/capability.h> # include <sys/prctl.h> #endif /* * NOTES: * * * pidfile is created and removed by the daemon (e.g. the child) itself, * the parent does not touch that * * * we communicate with the user using stderr (using fprintf) as long as it * is available and using syslog() afterwards * * * there are 3 processes involved in safe_background mode (e.g. auto-restart) * - startup process which was started by the user (zorpctl) * - supervisor process which automatically restarts the daemon when it exits abnormally * - daemon processes which perform the actual task at hand * * The startup process delivers the result of the first startup to its * caller, if we can deliver a failure in this case then restarts will not * be performed (e.g. if the first startup fails, the daemon will not be * restarted even if auto-restart was enabled). After the first successful * start, the startup process exits (delivering that startup was * successful) and the supervisor process wait()s for the daemon processes * to exit. If they exit prematurely (e.g. they crash) they will be * restarted, if the startup is not successful in this case the restart * will be attempted again just as if they crashed. * * The processes communicate with two pairs of pipes, startup_result_pipe * is used to indicate success/failure to the startup process, * init_result_pipe (as in "initialization") is used to deliver success * reports from the daemon to the supervisor. */ typedef enum { G_PK_STARTUP, G_PK_SUPERVISOR, G_PK_DAEMON, } GProcessKind; #define G_PROCESS_FD_LIMIT_RESERVE 64 #define G_PROCESS_FAILURE_NOTIFICATION PATH_PREFIX "/sbin/syslog-ng-failure" /* pipe used to deliver the initialization result to the calling process */ static gint startup_result_pipe[2] = { -1, -1 }; /* pipe used to deliver initialization result to the supervisor */ static gint init_result_pipe[2] = { -1, -1 }; static GProcessKind process_kind = G_PK_STARTUP; static gboolean stderr_present = TRUE; /* global variables */ static struct { GProcessMode mode; const gchar *name; const gchar *user; gint uid; const gchar *group; gint gid; const gchar *chroot_dir; const gchar *pidfile; const gchar *pidfile_dir; const gchar *cwd; const gchar *caps; gint argc; gchar **argv; gchar *argv_start; size_t argv_env_len; gchar *argv_orig; gboolean core; gint fd_limit_min; gint check_period; gboolean (*check_fn)(void); } process_opts = { .mode = G_PM_SAFE_BACKGROUND, .argc = 0, .argv = NULL, .argv_start = NULL, .argv_env_len = 0, #ifdef __CYGWIN__ .fd_limit_min = 256, #else .fd_limit_min = 4096, #endif .check_period = -1, .check_fn = NULL, .uid = -1, .gid = -1 }; #if ENABLE_LINUX_CAPS /** * g_process_cap_modify: * @capability: capability to turn off or on * @onoff: specifies whether the capability should be enabled or disabled * * This function modifies the current permitted set of capabilities by * enabling or disabling the capability specified in @capability. * * Returns: whether the operation was successful. **/ gboolean g_process_cap_modify(int capability, int onoff) { cap_t caps; if (!process_opts.caps) return TRUE; caps = cap_get_proc(); if (!caps) return FALSE; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &capability, onoff) == -1) { msg_error("Error managing capability set, cap_set_flag returned an error", evt_tag_errno("error", errno), NULL); cap_free(caps); return FALSE; } if (cap_set_proc(caps) == -1) { gchar *cap_text; cap_text = cap_to_text(caps, NULL); msg_error("Error managing capability set, cap_set_proc returned an error", evt_tag_str("caps", cap_text), evt_tag_errno("error", errno), NULL); cap_free(cap_text); cap_free(caps); return FALSE; } cap_free(caps); return TRUE; } /** * g_process_cap_save: * * Save the set of current capabilities and return it. The caller might * restore the saved set of capabilities by using cap_restore(). * * Returns: the current set of capabilities **/ cap_t g_process_cap_save(void) { if (!process_opts.caps) return NULL; return cap_get_proc(); } /** * cap_restore: * @r: capability set saved by cap_save() * * Restore the set of current capabilities specified by @r. * * Returns: whether the operation was successful. **/ void g_process_cap_restore(cap_t r) { gboolean rc; if (!process_opts.caps) return; rc = cap_set_proc(r) != -1; cap_free(r); if (!rc) { gchar *cap_text; cap_text = cap_to_text(r, NULL); msg_error("Error managing capability set, cap_set_proc returned an error", evt_tag_str("caps", cap_text), evt_tag_errno("error", errno), NULL); cap_free(cap_text); return; } return; } #endif /** * g_process_set_mode: * @mode: an element from ZProcessMode * * This function should be called by the daemon to set the processing mode * as specified by @mode. **/ void g_process_set_mode(GProcessMode mode) { process_opts.mode = mode; } /** * g_process_set_name: * @name: the name of the process to be reported as program name * * This function should be called by the daemon to set the program name * which is present in various error message and might influence the PID * file if not overridden by g_process_set_pidfile(). **/ void g_process_set_name(const gchar *name) { process_opts.name = name; } /** * g_process_set_user: * @user: the name of the user the process should switch to during startup * * This function should be called by the daemon to set the user name. **/ void g_process_set_user(const gchar *user) { if (!process_opts.user) process_opts.user = user; } /** * g_process_set_group: * @group: the name of the group the process should switch to during startup * * This function should be called by the daemon to set the group name. **/ void g_process_set_group(const gchar *group) { if (!process_opts.group) process_opts.group = group; } /** * g_process_set_chroot: * @chroot_dir: the name of the chroot directory the process should switch to during startup * * This function should be called by the daemon to set the chroot directory **/ void g_process_set_chroot(const gchar *chroot_dir) { if (!process_opts.chroot_dir) process_opts.chroot_dir = chroot_dir; } /** * g_process_set_pidfile: * @pidfile: the name of the complete pid file with full path * * This function should be called by the daemon to set the PID file name to * store the pid of the process. This value will be used as the pidfile * directly, neither name nor pidfile_dir influences the pidfile location if * this is set. **/ void g_process_set_pidfile(const gchar *pidfile) { if (!process_opts.pidfile) process_opts.pidfile = pidfile; } /** * g_process_set_pidfile_dir: * @pidfile_dir: name of the pidfile directory * * This function should be called by the daemon to set the PID file * directory. This value is not used if set_pidfile() was called. **/ void g_process_set_pidfile_dir(const gchar *pidfile_dir) { if (!process_opts.pidfile_dir) process_opts.pidfile_dir = pidfile_dir; } /** * g_process_set_working_dir: * @working_dir: name of the working directory * * This function should be called by the daemon to set the working * directory. The process will change its current directory to this value or * to pidfile_dir if it is unset. **/ void g_process_set_working_dir(const gchar *cwd) { if (!process_opts.cwd) process_opts.cwd = cwd; } /** * g_process_set_caps: * @caps: capability specification in text form * * This function should be called by the daemon to set the initial * capability set. The process will change its capabilities to this value * during startup, provided it has enough permissions to do so. **/ void g_process_set_caps(const gchar *caps) { if (!process_opts.caps) process_opts.caps = caps; } /** * g_process_set_argv_space: * @argc: Original argc, as received by the main function in it's first parameter * @argv: Original argv, as received by the main function in it's second parameter * * This function should be called by the daemon if it wants to enable * process title manipulation in the supervisor process. **/ void g_process_set_argv_space(gint argc, gchar **argv) { extern char **environ; gchar *lastargv = NULL; gchar **envp = environ; gint i; if (process_opts.argv) return; process_opts.argv = argv; process_opts.argc = argc; for (i = 0; envp[i] != NULL; i++) ; environ = g_new(char *, i + 1); /* * Find the last argv string or environment variable within * our process memory area. */ for (i = 0; i < process_opts.argc; i++) { if (lastargv == NULL || lastargv + 1 == process_opts.argv[i]) lastargv = process_opts.argv[i] + strlen(process_opts.argv[i]); } for (i = 0; envp[i] != NULL; i++) { if (lastargv + 1 == envp[i]) lastargv = envp[i] + strlen(envp[i]); } process_opts.argv_start = process_opts.argv[0]; process_opts.argv_env_len = lastargv - process_opts.argv[0] - 1; process_opts.argv_orig = malloc(sizeof(gchar) * process_opts.argv_env_len); memcpy(process_opts.argv_orig, process_opts.argv_start, process_opts.argv_env_len); /* * Copy environment * XXX - will truncate env on strdup fail */ for (i = 0; envp[i] != NULL; i++) environ[i] = g_strdup(envp[i]); environ[i] = NULL; } /** * g_process_set_check: * @check_period: check period in seconds * @check_fn: checker function * * Installs a checker function that is called at the specified rate. * The checked process is allowed to run as long as this function * returns TRUE. */ void g_process_set_check(gint check_period, gboolean (*check_fn)(void)) { process_opts.check_period = check_period; process_opts.check_fn = check_fn; } /** * g_process_message: * @fmt: format string * @...: arguments to @fmt * * This function sends a message to the client preferring to use the stderr * channel as long as it is available and switching to using syslog() if it * isn't. Generally the stderr channell will be available in the startup * process and in the beginning of the first startup in the * supervisor/daemon processes. Later on the stderr fd will be closed and we * have to fall back to using the system log. **/ void g_process_message(const gchar *fmt, ...) { gchar buf[2048]; va_list ap; va_start(ap, fmt); g_vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (stderr_present) fprintf(stderr, "%s: %s\n", process_opts.name, buf); else { gchar name[32]; g_snprintf(name, sizeof(name), "%s/%s", process_kind == G_PK_SUPERVISOR ? "supervise" : "daemon", process_opts.name); openlog(name, LOG_PID, LOG_DAEMON); syslog(LOG_CRIT, "%s\n", buf); closelog(); } } /** * g_process_detach_tty: * * This function is called from g_process_start() to detach from the * controlling tty. **/ static void g_process_detach_tty(void) { if (process_opts.mode != G_PM_FOREGROUND) { /* detach ourselves from the tty when not staying in the foreground */ if (isatty(STDIN_FILENO)) { #ifdef TIOCNOTTY ioctl(STDIN_FILENO, TIOCNOTTY, 0); #endif setsid(); } } } /** * g_process_change_limits: * * Set fd limit. * **/ static void g_process_change_limits(void) { struct rlimit limit; limit.rlim_cur = limit.rlim_max = process_opts.fd_limit_min; if (setrlimit(RLIMIT_NOFILE, &limit) < 0) g_process_message("Error setting file number limit; limit='%d'; error='%s'", process_opts.fd_limit_min, g_strerror(errno)); } /** * g_process_detach_stdio: * * Use /dev/null as input/output/error. This function is idempotent, can be * called any number of times without harm. **/ static void g_process_detach_stdio(void) { gint devnull_fd; if (process_opts.mode != G_PM_FOREGROUND && stderr_present) { devnull_fd = open("/dev/null", O_RDONLY); if (devnull_fd >= 0) { dup2(devnull_fd, STDIN_FILENO); close(devnull_fd); } devnull_fd = open("/dev/null", O_WRONLY); if (devnull_fd >= 0) { dup2(devnull_fd, STDOUT_FILENO); dup2(devnull_fd, STDERR_FILENO); close(devnull_fd); } stderr_present = FALSE; } } /** * g_process_enable_core: * * Enable core file dumping by setting PR_DUMPABLE and changing the core * file limit to infinity. **/ static void g_process_enable_core(void) { struct rlimit limit; if (process_opts.core) { #if ENABLE_LINUX_CAPS if (!prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) { gint rc; rc = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); if (rc < 0) g_process_message("Cannot set process to be dumpable; error='%s'", g_strerror(errno)); } #endif limit.rlim_cur = limit.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &limit) < 0) g_process_message("Error setting core limit to infinity; error='%s'", g_strerror(errno)); } } /** * g_process_format_pidfile_name: * @buf: buffer to store the pidfile name * @buflen: size of @buf * * Format the pid file name according to the settings specified by the * process. **/ static const gchar * g_process_format_pidfile_name(gchar *buf, gsize buflen) { const gchar *pidfile = process_opts.pidfile; if (pidfile == NULL) { g_snprintf(buf, buflen, "%s/%s.pid", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, process_opts.name); pidfile = buf; } else if (pidfile[0] != '/') { /* complete path to pidfile not specified, assume it is a relative path to pidfile_dir */ g_snprintf(buf, buflen, "%s/%s", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, pidfile); pidfile = buf; } return pidfile; } /** * g_process_write_pidfile: * @pid: pid to write into the pidfile * * Write the pid to the pidfile. **/ static void g_process_write_pidfile(pid_t pid) { gchar buf[256]; const gchar *pidfile; FILE *fd; pidfile = g_process_format_pidfile_name(buf, sizeof(buf)); fd = fopen(pidfile, "w"); if (fd != NULL) { fprintf(fd, "%d\n", (int) pid); fclose(fd); } else { g_process_message("Error creating pid file; file='%s', error='%s'", pidfile, g_strerror(errno)); } } /** * g_process_remove_pidfile: * * Remove the pidfile. **/ static void g_process_remove_pidfile(void) { gchar buf[256]; const gchar *pidfile; pidfile = g_process_format_pidfile_name(buf, sizeof(buf)); if (unlink(pidfile) < 0) { g_process_message("Error removing pid file; file='%s', error='%s'", pidfile, g_strerror(errno)); } } /** * g_process_change_root: * * Change the current root to the value specified by the user, causes the * startup process to fail if this function returns FALSE. (e.g. the user * specified a chroot but we could not change to that directory) * * Returns: TRUE to indicate success **/ static gboolean g_process_change_root(void) { if (process_opts.chroot_dir) { if (chroot(process_opts.chroot_dir) < 0) { g_process_message("Error in chroot(); chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno)); return FALSE; } if (chdir("/") < 0) { g_process_message("Error in chdir() after chroot; chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno)); return FALSE; } } return TRUE; } /** * g_process_change_user: * * Change the current user/group/groups to the value specified by the user. * causes the startup process to fail if this function returns FALSE. (e.g. * the user requested the uid/gid to change we could not change to that uid) * * Returns: TRUE to indicate success **/ static gboolean g_process_change_user(void) { #if ENABLE_LINUX_CAPS if (process_opts.caps) prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0); #endif if (process_opts.gid >= 0) { if (setgid((gid_t) process_opts.gid) < 0) { g_process_message("Error in setgid(); group='%s', gid='%d', error='%s'", process_opts.group, process_opts.gid, g_strerror(errno)); if (getuid() == 0) return FALSE; } if (process_opts.user && initgroups(process_opts.user, (gid_t) process_opts.gid) < 0) { g_process_message("Error in initgroups(); user='%s', error='%s'", process_opts.user, g_strerror(errno)); if (getuid() == 0) return FALSE; } } if (process_opts.uid >= 0) { if (setuid((uid_t) process_opts.uid) < 0) { g_process_message("Error in setuid(); user='%s', uid='%d', error='%s'", process_opts.user, process_opts.uid, g_strerror(errno)); if (getuid() == 0) return FALSE; } } return TRUE; } #if ENABLE_LINUX_CAPS /** * g_process_change_caps: * * Change the current capset to the value specified by the user. causes the * startup process to fail if this function returns FALSE, but we only do * this if the capset cannot be parsed, otherwise a failure changing the * capabilities will not result in failure * * Returns: TRUE to indicate success **/ static gboolean g_process_change_caps(void) { if (process_opts.caps) { cap_t cap = cap_from_text(process_opts.caps); if (cap == NULL) { g_process_message("Error parsing capabilities: %s", process_opts.caps); process_opts.caps = NULL; return FALSE; } else { if (cap_set_proc(cap) == -1) { g_process_message("Error setting capabilities, capability management disabled; error='%s'", g_strerror(errno)); process_opts.caps = NULL; } cap_free(cap); } } return TRUE; } #else static gboolean g_process_change_caps(void) { return TRUE; } #endif static void g_process_resolve_names(void) { if (process_opts.user && !resolve_user(process_opts.user, &process_opts.uid)) { g_process_message("Error resolving user; user='%s'", process_opts.user); process_opts.uid = -1; } if (process_opts.group && !resolve_group(process_opts.group, &process_opts.gid)) { g_process_message("Error resolving group; group='%s'", process_opts.group); process_opts.gid = -1; } } /** * g_process_change_dir: * * Change the current working directory to the value specified by the user * and verify that the daemon would be able to dump core to that directory * if that is requested. **/ static void g_process_change_dir(void) { const gchar *cwd = NULL; if (process_opts.mode != G_PM_FOREGROUND) { if (process_opts.cwd) cwd = process_opts.cwd; else if (process_opts.pidfile_dir) cwd = process_opts.pidfile_dir; if (!cwd) cwd = PATH_PIDFILEDIR; if (cwd) chdir(cwd); } /* this check is here to avoid having to change directory early in the startup process */ if ((process_opts.core) && access(".", W_OK) < 0) { gchar buf[256]; getcwd(buf, sizeof(buf)); g_process_message("Unable to write to current directory, core dumps will not be generated; dir='%s', error='%s'", buf, g_strerror(errno)); } } /** * g_process_send_result: * @ret_num: exit code of the process * * This function is called to notify our parent process (which is the same * executable process but separated with a fork()) about the result of the * process startup phase. Specifying ret_num == 0 means that everything was * dandy, all other values mean that the initialization failed and the * parent should exit using ret_num as the exit code. The function behaves * differently depending on which process it was called from, determined by * the value of the process_kind global variable. In the daemon process it * writes to init_result_pipe, in the startup process it writes to the * startup_result_pipe. * * This function can only be called once, further invocations will do nothing. **/ static void g_process_send_result(guint ret_num) { gchar buf[10]; guint buf_len; gint *fd; if (process_kind == G_PK_SUPERVISOR) fd = &startup_result_pipe[1]; else if (process_kind == G_PK_DAEMON) fd = &init_result_pipe[1]; else g_assert_not_reached(); if (*fd != -1) { buf_len = g_snprintf(buf, sizeof(buf), "%d\n", ret_num); write(*fd, buf, buf_len); close(*fd); *fd = -1; } } /** * g_process_recv_result: * * Retrieves an exit code value from one of the result pipes depending on * which process the function was called from. This function can be called * only once, further invocations will return non-zero result code. **/ static gint g_process_recv_result(void) { gchar ret_buf[6]; gint ret_num = 1; gint *fd; /* FIXME: use a timer */ if (process_kind == G_PK_SUPERVISOR) fd = &init_result_pipe[0]; else if (process_kind == G_PK_STARTUP) fd = &startup_result_pipe[0]; else g_assert_not_reached(); if (*fd != -1) { memset(ret_buf, 0, sizeof(ret_buf)); if (read(*fd, ret_buf, sizeof(ret_buf)) > 0) { ret_num = atoi(ret_buf); } else { /* the process probably crashed without telling a proper exit code */ ret_num = 1; } close(*fd); *fd = -1; } return ret_num; } /** * g_process_perform_startup: * * This function is the startup process, never returns, the startup process exits here. **/ static void g_process_perform_startup(void) { /* startup process */ exit(g_process_recv_result()); } #define SPT_PADCHAR '\0' static void g_process_setproctitle(const gchar* proc_title) { size_t len; g_assert(process_opts.argv_start != NULL); len = g_strlcpy(process_opts.argv_start, proc_title, process_opts.argv_env_len); for (; len < process_opts.argv_env_len; ++len) process_opts.argv_start[len] = SPT_PADCHAR; } #define PROC_TITLE_SPACE 1024 /** * g_process_perform_supervise: * * Supervise process, returns only in the context of the daemon process, the * supervisor process exits here. **/ static void g_process_perform_supervise(void) { pid_t pid; gboolean first = TRUE, exited = FALSE; gchar proc_title[PROC_TITLE_SPACE]; g_snprintf(proc_title, PROC_TITLE_SPACE, "supervising %s", process_opts.name); g_process_setproctitle(proc_title); while (1) { if (pipe(init_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); g_process_startup_failed(1, TRUE); } /* fork off a child process */ if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); g_process_startup_failed(1, TRUE); } else if (pid != 0) { gint rc; gboolean deadlock = FALSE; /* this is the supervisor process */ /* shut down init_result_pipe write side */ close(init_result_pipe[1]); init_result_pipe[1] = -1; rc = g_process_recv_result(); if (first) { /* first time encounter, we have a chance to report back, do it */ g_process_send_result(rc); if (rc != 0) break; g_process_detach_stdio(); } first = FALSE; if (rc != 0) { gint i = 0; /* initialization failed in daemon, it will probably exit soon, wait and restart */ while (i < 6 && waitpid(pid, &rc, WNOHANG) == 0) { if (i > 3) kill(pid, i > 4 ? SIGKILL : SIGTERM); sleep(1); i++; } if (i == 6) g_process_message("Initialization failed but the daemon did not exit, even when forced to, trying to recover; pid='%d'", pid); continue; } if (process_opts.check_fn && (process_opts.check_period >= 0)) { gint i = 1; while (!(exited = waitpid(pid, &rc, WNOHANG))) { if (i >= process_opts.check_period) { if (!process_opts.check_fn()) break; i = 0; } sleep(1); i++; } if (!exited) { gint j = 0; g_process_message("Daemon deadlock detected, killing process;"); deadlock = TRUE; while (j < 6 && waitpid(pid, &rc, WNOHANG) == 0) { if (j > 3) kill(pid, j > 4 ? SIGKILL : SIGABRT); sleep(1); j++; } if (j == 6) g_process_message("The daemon did not exit after deadlock, even when forced to, trying to recover; pid='%d'", pid); } } else { waitpid(pid, &rc, 0); } if (deadlock || WIFSIGNALED(rc) || (WIFEXITED(rc) && WEXITSTATUS(rc) != 0)) { gchar argbuf[64]; if (!access(G_PROCESS_FAILURE_NOTIFICATION, R_OK | X_OK)) { const gchar *notify_reason; pid_t npid = fork(); gint nrc; switch (npid) { case -1: g_process_message("Could not fork for external notification; reason='%s'", strerror(errno)); break; case 0: switch(fork()) { case -1: g_process_message("Could not fork for external notification; reason='%s'", strerror(errno)); exit(1); break; case 0: if (deadlock) { notify_reason = "deadlock detected"; argbuf[0] = 0; } else { snprintf(argbuf, sizeof(argbuf), "%d", WIFSIGNALED(rc) ? WTERMSIG(rc) : WEXITSTATUS(rc)); if (WIFSIGNALED(rc)) notify_reason = "signalled"; else notify_reason = "non-zero exit code"; } execlp(G_PROCESS_FAILURE_NOTIFICATION, G_PROCESS_FAILURE_NOTIFICATION, SAFE_STRING(process_opts.name), SAFE_STRING(process_opts.chroot_dir), SAFE_STRING(process_opts.pidfile_dir), SAFE_STRING(process_opts.pidfile), SAFE_STRING(process_opts.cwd), SAFE_STRING(process_opts.caps), notify_reason, argbuf, (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) ? "restarting" : "not-restarting", (gchar*) NULL); g_process_message("Could not execute external notification; reason='%s'", strerror(errno)); break; default: exit(0); break; } /* child process */ default: waitpid(npid, &nrc, 0); break; } } if (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) { g_process_message("Daemon exited due to a deadlock/signal/failure, restarting; exitcode='%d'", rc); sleep(1); } else { g_process_message("Daemon was killed, not restarting; exitcode='%d'", rc); break; } } else { g_process_message("Daemon exited gracefully, not restarting; exitcode='%d'", rc); break; } } else { /* this is the daemon process, thus we should return to the caller of g_process_start() */ /* shut down init_result_pipe read side */ process_kind = G_PK_DAEMON; close(init_result_pipe[0]); init_result_pipe[0] = -1; memcpy(process_opts.argv_start, process_opts.argv_orig, process_opts.argv_env_len); return; } } exit(0); } /** * g_process_start: * * Start the process as directed by the options set by various * g_process_set_*() functions. **/ void g_process_start(void) { pid_t pid; g_process_detach_tty(); g_process_change_limits(); g_process_resolve_names(); if (process_opts.mode == G_PM_BACKGROUND) { /* no supervisor, sends result to startup process directly */ if (pipe(init_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); exit(1); } if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); exit(1); } else if (pid != 0) { /* shut down init_result_pipe write side */ close(init_result_pipe[1]); /* connect startup_result_pipe with init_result_pipe */ startup_result_pipe[0] = init_result_pipe[0]; init_result_pipe[0] = -1; g_process_perform_startup(); /* NOTE: never returns */ g_assert_not_reached(); } process_kind = G_PK_DAEMON; /* shut down init_result_pipe read side */ close(init_result_pipe[0]); init_result_pipe[0] = -1; } else if (process_opts.mode == G_PM_SAFE_BACKGROUND) { /* full blown startup/supervisor/daemon */ if (pipe(startup_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); exit(1); } /* first fork off supervisor process */ if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); exit(1); } else if (pid != 0) { /* this is the startup process */ /* shut down startup_result_pipe write side */ close(startup_result_pipe[1]); startup_result_pipe[1] = -1; /* NOTE: never returns */ g_process_perform_startup(); g_assert_not_reached(); } /* this is the supervisor process */ /* shut down startup_result_pipe read side */ close(startup_result_pipe[0]); startup_result_pipe[0] = -1; process_kind = G_PK_SUPERVISOR; g_process_perform_supervise(); /* we only return in the daamon process here */ } else if (process_opts.mode == G_PM_FOREGROUND) { process_kind = G_PK_DAEMON; } else { g_assert_not_reached(); } /* daemon process, we should return to the caller to perform work */ setsid(); /* NOTE: we need to signal the parent in case of errors from this point. * This is accomplished by writing the appropriate exit code to * init_result_pipe, the easiest way doing so is calling g_process_startup_failed. * */ if (!g_process_change_root() || !g_process_change_user() || !g_process_change_caps()) { g_process_startup_failed(1, TRUE); } g_process_enable_core(); g_process_change_dir(); } /** * g_process_startup_failed: * @ret_num: exit code * @may_exit: whether to exit the process * * This is a public API function to be called by the user code when * initialization failed. **/ void g_process_startup_failed(guint ret_num, gboolean may_exit) { if (process_kind != G_PK_STARTUP) g_process_send_result(ret_num); if (may_exit) { exit(ret_num); } else { g_process_detach_stdio(); } } /** * g_process_startup_ok: * * This is a public API function to be called by the user code when * initialization was successful, we can report back to the user. **/ void g_process_startup_ok(void) { g_process_write_pidfile(getpid()); g_process_send_result(0); g_process_detach_stdio(); } /** * g_process_finish: * * This is a public API function to be called by the user code when the * daemon exits after properly initialized (e.g. when it terminates because * of SIGTERM). This function currently only removes the PID file. **/ void g_process_finish(void) { g_process_remove_pidfile(); } static gboolean g_process_process_mode_arg(const gchar *option_name G_GNUC_UNUSED, const gchar *value, gpointer data G_GNUC_UNUSED, GError **error) { if (strcmp(value, "foreground") == 0) { process_opts.mode = G_PM_FOREGROUND; } else if (strcmp(value, "background") == 0) { process_opts.mode = G_PM_BACKGROUND; } else if (strcmp(value, "safe-background") == 0) { process_opts.mode = G_PM_SAFE_BACKGROUND; } else { g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Error parsing process-mode argument"); return FALSE; } return TRUE; } static GOptionEntry g_process_option_entries[] = { { "foreground", 'F', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &process_opts.mode, "Do not go into the background after initialization", NULL }, { "process-mode", 0, 0, G_OPTION_ARG_CALLBACK, g_process_process_mode_arg , "Set process running mode", "<foreground|background|safe-background>" }, { "user", 'u', 0, G_OPTION_ARG_STRING, &process_opts.user, "Set the user to run as", "<user>" }, { "uid", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &process_opts.user, NULL, NULL }, { "group", 'g', 0, G_OPTION_ARG_STRING, &process_opts.group, "Set the group to run as", "<group>" }, { "gid", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &process_opts.group, NULL, NULL }, { "chroot", 'C', 0, G_OPTION_ARG_STRING, &process_opts.chroot_dir, "Chroot to this directory", "<dir>" }, { "caps", 0, 0, G_OPTION_ARG_STRING, &process_opts.caps, "Set default capability set", "<capspec>" }, { "no-caps", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &process_opts.caps, "Disable managing Linux capabilities", NULL }, { "pidfile", 'p', 0, G_OPTION_ARG_STRING, &process_opts.pidfile, "Set path to pid file", "<pidfile>" }, { "enable-core", 0, 0, G_OPTION_ARG_NONE, &process_opts.core, "Enable dumping core files", NULL }, { "fd-limit", 0, 0, G_OPTION_ARG_INT, &process_opts.fd_limit_min, "The minimum required number of fds", NULL }, { NULL, 0, 0, 0, NULL, NULL, NULL }, }; void g_process_add_option_group(GOptionContext *ctx) { GOptionGroup *group; group = g_option_group_new("process", "Process options", "Process options", NULL, NULL); g_option_group_add_entries(group, g_process_option_entries); g_option_context_add_group(ctx, group); }
ystk/debian-syslog-ng
src/gprocess.c
C
gpl-2.0
37,305
/* * PROJECT: Boot Loader * LICENSE: BSD - See COPYING.ARM in the top level directory * FILE: boot/armllb/hw/versatile/hwclcd.c * PURPOSE: LLB CLCD Routines for Versatile * PROGRAMMERS: ReactOS Portable Systems Group */ #include "precomp.h" #define LCDTIMING0_PPL(x) ((((x) / 16 - 1) & 0x3f) << 2) #define LCDTIMING1_LPP(x) (((x) & 0x3ff) - 1) #define LCDCONTROL_LCDPWR (1 << 11) #define LCDCONTROL_LCDEN (1) #define LCDCONTROL_LCDBPP(x) (((x) & 7) << 1) #define LCDCONTROL_LCDTFT (1 << 5) #define PL110_LCDTIMING0 (PVOID)0x10120000 #define PL110_LCDTIMING1 (PVOID)0x10120004 #define PL110_LCDTIMING2 (PVOID)0x10120008 #define PL110_LCDUPBASE (PVOID)0x10120010 #define PL110_LCDLPBASE (PVOID)0x10120014 #define PL110_LCDCONTROL (PVOID)0x10120018 PUSHORT LlbHwVideoBuffer; VOID NTAPI LlbHwVersaClcdInitialize(VOID) { /* Set framebuffer address */ WRITE_REGISTER_ULONG(PL110_LCDUPBASE, (ULONG)LlbHwGetFrameBuffer()); WRITE_REGISTER_ULONG(PL110_LCDLPBASE, (ULONG)LlbHwGetFrameBuffer()); /* Initialize timings to 720x400 */ WRITE_REGISTER_ULONG(PL110_LCDTIMING0, LCDTIMING0_PPL(LlbHwGetScreenWidth())); WRITE_REGISTER_ULONG(PL110_LCDTIMING1, LCDTIMING1_LPP(LlbHwGetScreenHeight())); /* Enable the TFT/LCD Display */ WRITE_REGISTER_ULONG(PL110_LCDCONTROL, LCDCONTROL_LCDEN | LCDCONTROL_LCDTFT | LCDCONTROL_LCDPWR | LCDCONTROL_LCDBPP(4)); } ULONG NTAPI LlbHwGetScreenWidth(VOID) { return 720; } ULONG NTAPI LlbHwGetScreenHeight(VOID) { return 400; } PVOID NTAPI LlbHwGetFrameBuffer(VOID) { return (PVOID)0x000A0000; } ULONG NTAPI LlbHwVideoCreateColor(IN ULONG Red, IN ULONG Green, IN ULONG Blue) { return (((Blue >> 3) << 11)| ((Green >> 2) << 5)| ((Red >> 3) << 0)); } /* EOF */
GreenteaOS/Kernel
third-party/reactos/boot/armllb/hw/versatile/hwclcd.c
C
gpl-2.0
1,933
/* * Copyright (C) 2011 ST-Ericsson SA. * Copyright (C) 2009 Motorola, Inc. * * License Terms: GNU General Public License v2 * * Simple driver for National Semiconductor LM3530 Backlight driver chip * * Author: Shreshtha Kumar SAHU <shreshthakumar.sahu@stericsson.com> * based on leds-lm3530.c by Dan Murphy <D.Murphy@motorola.com> */ #include <linux/i2c.h> #include <linux/leds.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/led-lm3530.h> #include <linux/types.h> #include <linux/regulator/consumer.h> #include <linux/module.h> #define LM3530_LED_DEV "lcd-backlight" #define LM3530_NAME "lm3530-led" #define LM3530_GEN_CONFIG 0x10 #define LM3530_ALS_CONFIG 0x20 #define LM3530_BRT_RAMP_RATE 0x30 #define LM3530_ALS_IMP_SELECT 0x41 #define LM3530_BRT_CTRL_REG 0xA0 #define LM3530_ALS_ZB0_REG 0x60 #define LM3530_ALS_ZB1_REG 0x61 #define LM3530_ALS_ZB2_REG 0x62 #define LM3530_ALS_ZB3_REG 0x63 #define LM3530_ALS_Z0T_REG 0x70 #define LM3530_ALS_Z1T_REG 0x71 #define LM3530_ALS_Z2T_REG 0x72 #define LM3530_ALS_Z3T_REG 0x73 #define LM3530_ALS_Z4T_REG 0x74 #define LM3530_REG_MAX 14 /* General Control Register */ #define LM3530_EN_I2C_SHIFT (0) #define LM3530_RAMP_LAW_SHIFT (1) #define LM3530_MAX_CURR_SHIFT (2) #define LM3530_EN_PWM_SHIFT (5) #define LM3530_PWM_POL_SHIFT (6) #define LM3530_EN_PWM_SIMPLE_SHIFT (7) #define LM3530_ENABLE_I2C (1 << LM3530_EN_I2C_SHIFT) #define LM3530_ENABLE_PWM (1 << LM3530_EN_PWM_SHIFT) #define LM3530_POL_LOW (1 << LM3530_PWM_POL_SHIFT) #define LM3530_ENABLE_PWM_SIMPLE (1 << LM3530_EN_PWM_SIMPLE_SHIFT) /* ALS Config Register Options */ #define LM3530_ALS_AVG_TIME_SHIFT (0) #define LM3530_EN_ALS_SHIFT (3) #define LM3530_ALS_SEL_SHIFT (5) #define LM3530_ENABLE_ALS (3 << LM3530_EN_ALS_SHIFT) /* Brightness Ramp Rate Register */ #define LM3530_BRT_RAMP_FALL_SHIFT (0) #define LM3530_BRT_RAMP_RISE_SHIFT (3) /* ALS Resistor Select */ #define LM3530_ALS1_IMP_SHIFT (0) #define LM3530_ALS2_IMP_SHIFT (4) /* Zone Boundary Register defaults */ #define LM3530_ALS_ZB_MAX (4) #define LM3530_ALS_WINDOW_mV (1000) #define LM3530_ALS_OFFSET_mV (4) /* Zone Target Register defaults */ #define LM3530_DEF_ZT_0 (0x7F) #define LM3530_DEF_ZT_1 (0x66) #define LM3530_DEF_ZT_2 (0x4C) #define LM3530_DEF_ZT_3 (0x33) #define LM3530_DEF_ZT_4 (0x19) /* 7 bits are used for the brightness : LM3530_BRT_CTRL_REG */ #define MAX_BRIGHTNESS (127) struct lm3530_mode_map { const char *mode; enum lm3530_mode mode_val; }; static struct lm3530_mode_map mode_map[] = { { "man", LM3530_BL_MODE_MANUAL }, { "als", LM3530_BL_MODE_ALS }, { "pwm", LM3530_BL_MODE_PWM }, }; /** * struct lm3530_data * @led_dev: led class device * @client: i2c client * @pdata: LM3530 platform data * @mode: mode of operation - manual, ALS, PWM * @regulator: regulator * @brighness: previous brightness value * @enable: regulator is enabled */ struct lm3530_data { struct led_classdev led_dev; struct i2c_client *client; struct lm3530_platform_data *pdata; enum lm3530_mode mode; struct regulator *regulator; enum led_brightness brightness; bool enable; }; static const u8 lm3530_reg[LM3530_REG_MAX] = { LM3530_GEN_CONFIG, LM3530_ALS_CONFIG, LM3530_BRT_RAMP_RATE, LM3530_ALS_IMP_SELECT, LM3530_BRT_CTRL_REG, LM3530_ALS_ZB0_REG, LM3530_ALS_ZB1_REG, LM3530_ALS_ZB2_REG, LM3530_ALS_ZB3_REG, LM3530_ALS_Z0T_REG, LM3530_ALS_Z1T_REG, LM3530_ALS_Z2T_REG, LM3530_ALS_Z3T_REG, LM3530_ALS_Z4T_REG, }; static int lm3530_get_mode_from_str(const char *str) { int i; for (i = 0; i < ARRAY_SIZE(mode_map); i++) if (sysfs_streq(str, mode_map[i].mode)) return mode_map[i].mode_val; return -1; } static int lm3530_init_registers(struct lm3530_data *drvdata) { int ret = 0; int i; u8 gen_config; u8 als_config = 0; u8 brt_ramp; u8 als_imp_sel = 0; u8 brightness; u8 reg_val[LM3530_REG_MAX]; u8 zones[LM3530_ALS_ZB_MAX]; u32 als_vmin, als_vmax, als_vstep; struct lm3530_platform_data *pdata = drvdata->pdata; struct i2c_client *client = drvdata->client; struct lm3530_pwm_data *pwm = &pdata->pwm_data; gen_config = (pdata->brt_ramp_law << LM3530_RAMP_LAW_SHIFT) | ((pdata->max_current & 7) << LM3530_MAX_CURR_SHIFT); switch (drvdata->mode) { case LM3530_BL_MODE_MANUAL: case LM3530_BL_MODE_ALS: gen_config |= LM3530_ENABLE_I2C; break; case LM3530_BL_MODE_PWM: gen_config |= LM3530_ENABLE_PWM | LM3530_ENABLE_PWM_SIMPLE | (pdata->pwm_pol_hi << LM3530_PWM_POL_SHIFT); break; } if (drvdata->mode == LM3530_BL_MODE_ALS) { if (pdata->als_vmax == 0) { pdata->als_vmin = 0; pdata->als_vmax = LM3530_ALS_WINDOW_mV; } als_vmin = pdata->als_vmin; als_vmax = pdata->als_vmax; if ((als_vmax - als_vmin) > LM3530_ALS_WINDOW_mV) pdata->als_vmax = als_vmax = als_vmin + LM3530_ALS_WINDOW_mV; /* n zone boundary makes n+1 zones */ als_vstep = (als_vmax - als_vmin) / (LM3530_ALS_ZB_MAX + 1); for (i = 0; i < LM3530_ALS_ZB_MAX; i++) zones[i] = (((als_vmin + LM3530_ALS_OFFSET_mV) + als_vstep + (i * als_vstep)) * LED_FULL) / 1000; als_config = (pdata->als_avrg_time << LM3530_ALS_AVG_TIME_SHIFT) | (LM3530_ENABLE_ALS) | (pdata->als_input_mode << LM3530_ALS_SEL_SHIFT); als_imp_sel = (pdata->als1_resistor_sel << LM3530_ALS1_IMP_SHIFT) | (pdata->als2_resistor_sel << LM3530_ALS2_IMP_SHIFT); } brt_ramp = (pdata->brt_ramp_fall << LM3530_BRT_RAMP_FALL_SHIFT) | (pdata->brt_ramp_rise << LM3530_BRT_RAMP_RISE_SHIFT); if (drvdata->brightness) brightness = drvdata->brightness; else brightness = drvdata->brightness = pdata->brt_val; if (brightness > drvdata->led_dev.max_brightness) brightness = drvdata->led_dev.max_brightness; reg_val[0] = gen_config; /* LM3530_GEN_CONFIG */ reg_val[1] = als_config; /* LM3530_ALS_CONFIG */ reg_val[2] = brt_ramp; /* LM3530_BRT_RAMP_RATE */ reg_val[3] = als_imp_sel; /* LM3530_ALS_IMP_SELECT */ reg_val[4] = brightness; /* LM3530_BRT_CTRL_REG */ reg_val[5] = zones[0]; /* LM3530_ALS_ZB0_REG */ reg_val[6] = zones[1]; /* LM3530_ALS_ZB1_REG */ reg_val[7] = zones[2]; /* LM3530_ALS_ZB2_REG */ reg_val[8] = zones[3]; /* LM3530_ALS_ZB3_REG */ reg_val[9] = LM3530_DEF_ZT_0; /* LM3530_ALS_Z0T_REG */ reg_val[10] = LM3530_DEF_ZT_1; /* LM3530_ALS_Z1T_REG */ reg_val[11] = LM3530_DEF_ZT_2; /* LM3530_ALS_Z2T_REG */ reg_val[12] = LM3530_DEF_ZT_3; /* LM3530_ALS_Z3T_REG */ reg_val[13] = LM3530_DEF_ZT_4; /* LM3530_ALS_Z4T_REG */ if (!drvdata->enable) { ret = regulator_enable(drvdata->regulator); if (ret) { dev_err(&drvdata->client->dev, "Enable regulator failed\n"); return ret; } drvdata->enable = true; } for (i = 0; i < LM3530_REG_MAX; i++) { /* do not update brightness register when pwm mode */ if (lm3530_reg[i] == LM3530_BRT_CTRL_REG && drvdata->mode == LM3530_BL_MODE_PWM) { if (pwm->pwm_set_intensity) pwm->pwm_set_intensity(reg_val[i], drvdata->led_dev.max_brightness); continue; } ret = i2c_smbus_write_byte_data(client, lm3530_reg[i], reg_val[i]); if (ret) break; } return ret; } static void lm3530_brightness_set(struct led_classdev *led_cdev, enum led_brightness brt_val) { int err; struct lm3530_data *drvdata = container_of(led_cdev, struct lm3530_data, led_dev); struct lm3530_platform_data *pdata = drvdata->pdata; struct lm3530_pwm_data *pwm = &pdata->pwm_data; u8 max_brightness = led_cdev->max_brightness; switch (drvdata->mode) { case LM3530_BL_MODE_MANUAL: if (!drvdata->enable) { err = lm3530_init_registers(drvdata); if (err) { dev_err(&drvdata->client->dev, "Register Init failed: %d\n", err); break; } } /* set the brightness in brightness control register*/ err = i2c_smbus_write_byte_data(drvdata->client, LM3530_BRT_CTRL_REG, brt_val); if (err) dev_err(&drvdata->client->dev, "Unable to set brightness: %d\n", err); else drvdata->brightness = brt_val; if (brt_val == 0) { err = regulator_disable(drvdata->regulator); if (err) dev_err(&drvdata->client->dev, "Disable regulator failed\n"); drvdata->enable = false; } break; case LM3530_BL_MODE_ALS: break; case LM3530_BL_MODE_PWM: if (pwm->pwm_set_intensity) pwm->pwm_set_intensity(brt_val, max_brightness); break; default: break; } } static ssize_t lm3530_mode_get(struct device *dev, struct device_attribute *attr, char *buf) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct lm3530_data *drvdata; int i, len = 0; drvdata = container_of(led_cdev, struct lm3530_data, led_dev); for (i = 0; i < ARRAY_SIZE(mode_map); i++) if (drvdata->mode == mode_map[i].mode_val) len += sprintf(buf + len, "[%s] ", mode_map[i].mode); else len += sprintf(buf + len, "%s ", mode_map[i].mode); len += sprintf(buf + len, "\n"); return len; } static ssize_t lm3530_mode_set(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct lm3530_data *drvdata; struct lm3530_pwm_data *pwm; u8 max_brightness; int mode, err; drvdata = container_of(led_cdev, struct lm3530_data, led_dev); pwm = &drvdata->pdata->pwm_data; max_brightness = led_cdev->max_brightness; mode = lm3530_get_mode_from_str(buf); if (mode < 0) { dev_err(dev, "Invalid mode\n"); return -EINVAL; } drvdata->mode = mode; /* set pwm to low if unnecessary */ if (mode != LM3530_BL_MODE_PWM && pwm->pwm_set_intensity) pwm->pwm_set_intensity(0, max_brightness); err = lm3530_init_registers(drvdata); if (err) { dev_err(dev, "Setting %s Mode failed :%d\n", buf, err); return err; } return sizeof(drvdata->mode); } static DEVICE_ATTR(mode, 0644, lm3530_mode_get, lm3530_mode_set); static int __devinit lm3530_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct lm3530_platform_data *pdata = client->dev.platform_data; struct lm3530_data *drvdata; int err = 0; if (pdata == NULL) { dev_err(&client->dev, "platform data required\n"); err = -ENODEV; goto err_out; } /* BL mode */ if (pdata->mode > LM3530_BL_MODE_PWM) { dev_err(&client->dev, "Illegal Mode request\n"); err = -EINVAL; goto err_out; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "I2C_FUNC_I2C not supported\n"); err = -EIO; goto err_out; } drvdata = kzalloc(sizeof(struct lm3530_data), GFP_KERNEL); if (drvdata == NULL) { err = -ENOMEM; goto err_out; } drvdata->mode = pdata->mode; drvdata->client = client; drvdata->pdata = pdata; drvdata->brightness = LED_OFF; drvdata->enable = false; drvdata->led_dev.name = LM3530_LED_DEV; drvdata->led_dev.brightness_set = lm3530_brightness_set; drvdata->led_dev.max_brightness = MAX_BRIGHTNESS; i2c_set_clientdata(client, drvdata); drvdata->regulator = regulator_get(&client->dev, "vin"); if (IS_ERR(drvdata->regulator)) { dev_err(&client->dev, "regulator get failed\n"); err = PTR_ERR(drvdata->regulator); drvdata->regulator = NULL; goto err_regulator_get; } if (drvdata->pdata->brt_val) { err = lm3530_init_registers(drvdata); if (err < 0) { dev_err(&client->dev, "Register Init failed: %d\n", err); err = -ENODEV; goto err_reg_init; } } err = led_classdev_register(&client->dev, &drvdata->led_dev); if (err < 0) { dev_err(&client->dev, "Register led class failed: %d\n", err); err = -ENODEV; goto err_class_register; } err = device_create_file(drvdata->led_dev.dev, &dev_attr_mode); if (err < 0) { dev_err(&client->dev, "File device creation failed: %d\n", err); err = -ENODEV; goto err_create_file; } return 0; err_create_file: led_classdev_unregister(&drvdata->led_dev); err_class_register: err_reg_init: regulator_put(drvdata->regulator); err_regulator_get: kfree(drvdata); err_out: return err; } static int __devexit lm3530_remove(struct i2c_client *client) { struct lm3530_data *drvdata = i2c_get_clientdata(client); device_remove_file(drvdata->led_dev.dev, &dev_attr_mode); if (drvdata->enable) regulator_disable(drvdata->regulator); regulator_put(drvdata->regulator); led_classdev_unregister(&drvdata->led_dev); kfree(drvdata); return 0; } static const struct i2c_device_id lm3530_id[] = { {LM3530_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, lm3530_id); static struct i2c_driver lm3530_i2c_driver = { .probe = lm3530_probe, .remove = __devexit_p(lm3530_remove), .id_table = lm3530_id, .driver = { .name = LM3530_NAME, .owner = THIS_MODULE, }, }; module_i2c_driver(lm3530_i2c_driver); MODULE_DESCRIPTION("Back Light driver for LM3530"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Shreshtha Kumar SAHU <shreshthakumar.sahu@stericsson.com>");
Jackeagle/android_kernel_sony_c2305
drivers/leds/leds-lm3530.c
C
gpl-2.0
13,280
/*****************************************************************************/ /* */ /* Ittiam 802.11 MAC SOFTWARE */ /* */ /* ITTIAM SYSTEMS PVT LTD, BANGALORE */ /* COPYRIGHT(C) 2005 */ /* */ /* This program is proprietary to Ittiam Systems Private Limited and */ /* is protected under Indian Copyright Law as an unpublished work. Its use */ /* and disclosure is limited by the terms and conditions of a license */ /* agreement. It may not be copied or otherwise reproduced or disclosed to */ /* persons outside the licensee's organization except in accordance with the*/ /* terms and conditions of such an agreement. All copies and */ /* reproductions shall be the property of Ittiam Systems Private Limited and*/ /* must bear this notice in its entirety. */ /* */ /*****************************************************************************/ /*****************************************************************************/ /* */ /* File Name : common.c */ /* */ /* Description : This file contains the functions used by both AP/STA */ /* modes in MAC. */ /* */ /* List of Functions : set_dscr_fn */ /* get_dscr_fn */ /* */ /* Issues / Problems : None */ /* */ /*****************************************************************************/ /*****************************************************************************/ /* File Includes */ /*****************************************************************************/ #include "common.h" #include "mh.h" #include "csl_linux.h" #include "trout_share_mem.h" #ifdef MAC_HW_UNIT_TEST_MODE #include "mh_test.h" #endif /* MAC_HW_UNIT_TEST_MODE */ /*****************************************************************************/ /* Global Variables */ /*****************************************************************************/ UWORD32 g_calib_cnt = DEFAULT_CALIB_COUNT; extern UWORD32 g_done_wifi_suspend; #ifdef DEBUG_MODE mac_stats_t g_mac_stats = {0}; reset_stats_t g_reset_stats = {0}; UWORD8 g_enable_debug_print = 1; UWORD8 g_11n_print_stats = 0; #endif /* DEBUG_MODE */ #ifdef MEM_DEBUG_MODE mem_stats_t g_mem_stats = {0}; #endif /* MEM_DEBUG_MODE */ #ifdef MAC_HW_UNIT_TEST_MODE #endif /* MAC_HW_UNIT_TEST_MODE */ #ifdef DSCR_MACROS_NOT_DEFINED /*****************************************************************************/ /* */ /* Function Name : set_dscr_fn */ /* */ /* Description : This function modifies the packet descriptor with the */ /* new specified value. The descriptor field to be modified */ /* is specified by the descriptor offset and width */ /* */ /* Inputs : 1) Offset of the descriptor field */ /* 2) Width of the descriptor field */ /* 3) Pointer to the packet descriptor to be modified */ /* 4) The new value for the descriptor field */ /* */ /* Globals : None */ /* */ /* Processing : Modifies the specified descriptor with the supplied */ /* value. */ /* */ /* Outputs : None */ /* Returns : None */ /* Issues : None */ /* */ /*****************************************************************************/ void set_dscr_fn(UWORD8 offset, UWORD16 width, UWORD32 *ptr, UWORD32 value) { UWORD32 mask_inverse = 0; UWORD32 mask = 0; UWORD32 temp = 0; UWORD32 shift_offset = 32 - width - offset; #ifdef DEBUG_MODE if((width + offset) > 32) { /* Signal Erroneous input */ } #endif /* DEBUG_MODE */ /* Calculate the inverse of the Mask */ if(width < 32) mask_inverse = ((1 << width) - 1) << shift_offset; else mask_inverse = 0xFFFFFFFF; /* Generate the mask */ mask = ~mask_inverse; /* Read the descriptor word in little endian format */ temp = convert_to_le(*ptr); /* Updating the value of the descriptor field with the help of masks */ temp = ((value << shift_offset) & mask_inverse) | (temp & mask); /* Swap the byte order in the word if required for endian-ness change */ *ptr = convert_to_le(temp); } /*****************************************************************************/ /* */ /* Function Name : get_dscr_fn */ /* */ /* Description : This function reads a word32 location to extract a */ /* specified descriptor field.of specified width. */ /* */ /* Inputs : 1) Offset of the descriptor field in the 32 bit boundary */ /* 2) Width of the desired descriptor field */ /* 3) Pointer to the word32 location of the field */ /* */ /* Globals : None */ /* */ /* Processing : Reads the descriptor for the specific field and returns */ /* the value. */ /* */ /* Outputs : None */ /* */ /* Returns : Descriptor field value */ /* */ /* Issues : None */ /* */ /*****************************************************************************/ UWORD32 get_dscr_fn(UWORD8 offset, UWORD16 width, UWORD32 *ptr) { UWORD32 mask = 0; UWORD32 temp = 0; UWORD32 value = 0; UWORD32 shift_offset = 32 - width - offset; #ifdef DEBUG_MODE if((width + offset) > 32) { /* Signal Erroneous input */ } #endif /* DEBUG_MODE */ /* Calculate the Mask */ if(width < 32) mask = ((1 << width) - 1) << shift_offset; else mask = 0xFFFFFFFF; /* Swap the byte order in the word if required for endian-ness change */ temp = convert_to_le(*ptr); /* Obtain the value of the descriptor field with the help of masks */ value = (temp & mask) >> shift_offset; return value; } #endif /* DSCR_MACROS_NOT_DEFINED */ #ifdef MWLAN /*****************************************************************************/ /* */ /* Function Name : itm_memset */ /* */ /* Description : This function sets the specified number of bytes in the */ /* buffer to the required value. The functionality is */ /* similar to the standard memset function. The new */ /* implementation was required due to the bug seen when */ /* using memset function across the bridge on MWLAN. */ /* */ /* Inputs : 1) Pointer to the buffer. */ /* 2) Value of character to set */ /* 3) Number of characters to set. */ /* */ /* Globals : None */ /* */ /* Processing : */ /* */ /* Outputs : None */ /* */ /* Returns : Pointer to the buffer */ /* */ /* Issues : None */ /* */ /*****************************************************************************/ void *itm_memset(void *buff, UWORD8 val, UWORD32 num) { UWORD8 *cbuff = (UWORD8 *)buff; if(num < 20) while(num--) *cbuff++ = val; else { UWORD32 *wbuff = NULL; UWORD32 wval = val; UWORD32 temp = 0; temp = (UWORD32)cbuff & 0x3; /* Unaligned buffer */ num -= temp; while(temp--) *cbuff++ = val; /* Word transfers */ wval += (wval << 8) + (wval << 16) + (wval << 24); wbuff = (UWORD32 *)cbuff; while(num > 3) { *wbuff++ = wval; num -= 4; } /* Unaligned length */ cbuff = (UWORD8 *)wbuff; while(num--) *cbuff++ = val; } return buff; } #endif /* MWLAN */ /*****************************************************************************/ /* */ /* Function Name : calibrate_delay_loop */ /* */ /* Description : This function calibrates the delay loop counter using */ /* MAC H/w TSF Timer . */ /* */ /* Inputs : None */ /* */ /* Globals : g_calib_cnt */ /* */ /* Processing : MAC H/w version register is read a fixed number of times */ /* to introduce delay in S/w. This function calibrates this */ /* delay mechanism. It updates the global variable */ /* (g_calib_cnt) which holds the number of times the */ /* version register should be read to introduce a delay of */ /* 10us. */ /* */ /* Outputs : None */ /* Returns : None */ /* Issues : None */ /* */ /*****************************************************************************/ void calibrate_delay_loop(void) { UWORD32 i = 0; UWORD32 entry_time = 0; UWORD32 exit_time = 0; BOOL_T pa_enabled = BFALSE; BOOL_T tbtt_mask = BFALSE; UWORD32 tsf_ctrl_bkup = 0; UWORD32 calib_thresh = 0; TROUT_FUNC_ENTER; /* Backup the registers which will be used for the calibration process */ pa_enabled = is_machw_enabled(); tbtt_mask = is_machw_tbtt_int_masked(); tsf_ctrl_bkup = get_machw_tsf_ctrl(); critical_section_start(); /* PA is disabled but TBTT Interrupts can still come. Mask it. */ disable_machw_phy_and_pa(); mask_machw_tbtt_int(); set_machw_tsf_start(); set_machw_tsf_beacon_tx_suspend_enable(); /* Initialize Calibration Parameters */ calib_thresh = 1000; entry_time = get_machw_tsf_timer_lo(); for(i = 0; i < calib_thresh; i++) { GET_TIME(); //modified by chengwg. } exit_time = get_machw_tsf_timer_lo(); /* Restore the Backed-up registers */ if(pa_enabled == BTRUE) enable_machw_phy_and_pa(); if(tbtt_mask == BFALSE) unmask_machw_tbtt_int(); set_machw_tsf_ctrl(tsf_ctrl_bkup); critical_section_end(); /* The Delay Calibration Count is computed to provide a delay of 10us */ if(exit_time > entry_time) g_calib_cnt = ((calib_thresh+2)*10)/(exit_time-entry_time) + 1; TROUT_DBG4("Delay Calibration: Cnt=%d Delay=%d Calib_Cnt=%d\n",calib_thresh+2, (exit_time-entry_time), g_calib_cnt); TROUT_FUNC_EXIT; } #ifdef COMBO_SCAN void calibrate_delay_loop_plus(void) { UWORD32 i = 0; UWORD32 entry_time = 0; UWORD32 exit_time = 0; BOOL_T pa_enabled = BFALSE; BOOL_T tbtt_mask = BFALSE; UWORD32 tsf_ctrl_bkup = 0; UWORD32 calib_thresh = 0; TROUT_FUNC_ENTER; /* Backup the registers which will be used for the calibration process */ pa_enabled = is_machw_enabled(); tbtt_mask = is_machw_tbtt_int_masked(); tsf_ctrl_bkup = get_machw_tsf_ctrl(); critical_section_start(); /* PA is disabled but TBTT Interrupts can still come. Mask it. */ disable_machw_phy_and_pa(); mask_machw_tbtt_int(); set_machw_tsf_start(); set_machw_tsf_beacon_tx_suspend_enable(); /* Initialize Calibration Parameters */ calib_thresh = 1000; entry_time = get_machw_tsf_timer_lo(); for(i = 0; i < calib_thresh; i++) { GET_TIME(); //modified by chengwg. } exit_time = get_machw_tsf_timer_lo(); /* Restore the Backed-up registers */ if(pa_enabled == BTRUE) enable_machw_phy_and_pa(); if(tbtt_mask == BFALSE) unmask_machw_tbtt_int(); set_machw_tsf_ctrl(tsf_ctrl_bkup); critical_section_end(); /* The Delay Calibration Count is computed to provide a delay of 10us */ //if(exit_time > entry_time) //g_calib_cnt = ((calib_thresh+2)*10)/(exit_time-entry_time) + 1; //TROUT_DBG4("Delay Calibration: Cnt=%d Delay=%d Calib_Cnt=%d\n",calib_thresh+2, //(exit_time-entry_time), g_calib_cnt); TROUT_FUNC_EXIT; } #endif /*****************************************************************************/ /* */ /* Function Name : add_calib_delay */ /* */ /* Description : This function provides a minimum S/w delay of the */ /* required time specified in units of 10us */ /* */ /* Inputs : 1) The required delay in units of 10us. i.e. Input 10 */ /* will provide a delay of 100us */ /* */ /* Globals : g_calib_cnt */ /* */ /* Processing : The MAC H/w version number is read continuously for a */ /* precomputed number of times to provide the required */ /* delay. */ /* */ /* Outputs : None */ /* */ /* Returns : None */ /* */ /* Issues : None */ /* */ /*****************************************************************************/ void add_calib_delay(UWORD32 delay) { UWORD32 i = 0; // UWORD32 j = 0; UWORD32 delay_thresh = g_calib_cnt * delay; for(i = 0; i < delay_thresh; i++) //j += get_machw_pa_ver(); //j += (*(volatile UWORD32 *)HOST_DELAY_FOR_TROUT_PHY); //add by chengq. GET_TIME(); } #ifdef DEBUG_MODE void print_ba_debug_stats(void) { UWORD32 idx = 0; PRINTK("BA Frames Rxd = %d\n\r", g_mac_stats.babarxd); PRINTK("BAR Frames successfully Txd = %d\n\r", g_mac_stats.babartxd); PRINTK("BAR Frames Rxd = %d\n\r", g_mac_stats.babarrxd); PRINTK("Data Frames retransmitted = %d\n\r", g_mac_stats.badatretx); PRINTK("Times Window is moved = %d\n\r", g_mac_stats.bawinmove); PRINTK("BAR Tx-Failures = %d\n\r", g_mac_stats.babarfail); PRINTK("Data Tx-Failures = %d\n\r", g_mac_stats.badatfail); PRINTK("Missing Buffers = %d\n\r", g_mac_stats.babufmiss); PRINTK("Frames deleted during Buffer cleanup = %d\n\r", g_mac_stats.badatclnup); PRINTK("Pending Frames discarded = %d\n\r", g_mac_stats.bapenddrop); PRINTK("Frames Txd from the Pending Q = %d\n\r", g_mac_stats.bapendingtxwlantxd); PRINTK("Stale BA frames received = %d\n\r", g_mac_stats.baoldbarxd); PRINTK("Stale BA frames received = %d\n\r", g_mac_stats.baoldbarrxd); PRINTK("Frames received out of window and hence droped = %d\n\r",g_mac_stats.barxdatoutwin); PRINTK("Re-queue failures = %d\n\r", g_mac_stats.bartrqfail); PRINTK("Number of blocks Qed = %d\n\r", g_mac_stats.banumblks); PRINTK("Number of Frames Qed = %d\n\r", g_mac_stats.banumqed); PRINTK("Number of times the pending Q was empty while enqueing = %d\n\r",g_mac_stats.baemptyQ); PRINTK("Num of times grp=%d\n\r", g_mac_stats.num_buffto); PRINTK("ba_num_dq=%d\n\r", g_mac_stats.ba_num_dq); PRINTK("ba_num_dqed=%d\n\r", g_mac_stats.ba_num_dqed); PRINTK("batxfba=%d\n\r", g_mac_stats.batxfba); for(idx = 0; idx < 10; idx++) PRINTK("batemp[%d] = %d\n\r", idx, g_mac_stats.batemp[idx]); } UWORD8 print_mem_stats(void) { UWORD8 print_flag = 0; #ifdef MEM_DEBUG_MODE print_flag |= printe("nosizeallocexc", g_mem_stats.nosizeallocexc); print_flag |= printe("nofreeallocexc", g_mem_stats.nofreeallocexc); print_flag |= printe("reallocexc", g_mem_stats.reallocexc); print_flag |= printe("corruptallocexc", g_mem_stats.corruptallocexc); print_flag |= printe("nullfreeexc", g_mem_stats.nullfreeexc); print_flag |= printe("oobfreeexc", g_mem_stats.oobfreeexc); print_flag |= printe("refreeexc", g_mem_stats.refreeexc); print_flag |= printe("corruptfreeexc", g_mem_stats.corruptfreeexc); print_flag |= printe("invalidfreeexc", g_mem_stats.invalidfreeexc); print_flag |= printe("excessfreeexc", g_mem_stats.excessfreeexc); print_flag |= printe("nulladdexc", g_mem_stats.nulladdexc); print_flag |= printe("oobaddexc", g_mem_stats.oobaddexc); print_flag |= printe("freeaddexc", g_mem_stats.freeaddexc); print_flag |= printe("invalidaddexc", g_mem_stats.invalidaddexc); print_flag |= printe("excessaddexc", g_mem_stats.excessaddexc); print_flag |= printe("nofreeDscrallocexc[0]", g_mem_stats.nofreeDscrallocexc[0]); print_flag |= printe("nofreeDscrallocexc[1]", g_mem_stats.nofreeDscrallocexc[1]); print_flag |= printe("nofreePktallocexc[0]", g_mem_stats.nofreePktallocexc[0]); print_flag |= printe("nofreePktallocexc[1]", g_mem_stats.nofreePktallocexc[1]); print_flag |= printe("nofreePktallocexc[2]", g_mem_stats.nofreePktallocexc[2]); print_flag |= printe("nofreePktallocexc[3]", g_mem_stats.nofreePktallocexc[3]); print_flag |= printe("nofreePktallocexc[4]", g_mem_stats.nofreePktallocexc[4]); print_flag |= printe("nofreeLocalallocexc[0]", g_mem_stats.nofreeLocalallocexc[0]); print_flag |= printe("nofreeLocalallocexc[1]", g_mem_stats.nofreeLocalallocexc[1]); print_flag |= printe("nofreeLocalallocexc[2]", g_mem_stats.nofreeLocalallocexc[2]); print_flag |= printe("nofreeLocalallocexc[3]", g_mem_stats.nofreeLocalallocexc[3]); print_flag |= printe("nofreeLocalallocexc[4]", g_mem_stats.nofreeLocalallocexc[4]); print_flag |= printe("nofreeLocalallocexc[5]", g_mem_stats.nofreeLocalallocexc[5]); print_flag |= printe("nofreeLocalallocexc[6]", g_mem_stats.nofreeLocalallocexc[6]); print_flag |= printe("nofreeLocalallocexc[7]", g_mem_stats.nofreeLocalallocexc[7]); print_flag |= printe("nofreeEventallocexc", g_mem_stats.nofreeEventallocexc); /* Print the size of the maximum Shared memory used and reset it after that */ PRINTK("Max Scratch Memory Utilized = %d", get_max_scratch_mem_usage()); reset_scratch_mem_usage(); #endif /* MEM_DEBUG_MODE */ return print_flag; } void print_debug_stats(void) { UWORD8 i = 0; #ifdef MEM_DEBUG_MODE PRINTK("Memory Statistics\n\r"); PRINTK("sdalloc = %d\n\r",g_mem_stats.sdalloc); PRINTK("sdfree = %d\n\r",g_mem_stats.sdfree); PRINTK("sdtotalfree = %d\n\r",g_mem_stats.sdtotalfree); PRINTK("spalloc = %d\n\r",g_mem_stats.spalloc); PRINTK("spfree = %d\n\r",g_mem_stats.spfree); PRINTK("sptotalfree = %d\n\r",g_mem_stats.sptotalfree); PRINTK("lalloc = %d\n\r",g_mem_stats.lalloc); PRINTK("lfree = %d\n\r",g_mem_stats.lfree); PRINTK("ltotalfree = %d\n\r",g_mem_stats.ltotalfree); PRINTK("ealloc = %d\n\r",g_mem_stats.ealloc); PRINTK("efree = %d\n\r",g_mem_stats.efree); PRINTK("etotalfree = %d\n\r",g_mem_stats.etotalfree); PRINTK("nosizeallocexc = %d\n\r",g_mem_stats.nosizeallocexc); PRINTK("nofreeallocexc = %d\n\r",g_mem_stats.nofreeallocexc); PRINTK("reallocexc = %d\n\r",g_mem_stats.reallocexc); PRINTK("corruptallocexc = %d\n\r",g_mem_stats.corruptallocexc); PRINTK("nullfreeexc = %d\n\r",g_mem_stats.nullfreeexc); PRINTK("oobfreeexc = %d\n\r",g_mem_stats.oobfreeexc); PRINTK("refreeexc = %d\n\r",g_mem_stats.refreeexc); PRINTK("corruptfreeexc = %d\n\r",g_mem_stats.corruptfreeexc); PRINTK("invalidfreeexc = %d\n\r",g_mem_stats.invalidfreeexc); PRINTK("excessfreeexc = %d\n\r",g_mem_stats.excessfreeexc); PRINTK("nulladdexc = %d\n\r",g_mem_stats.nulladdexc); PRINTK("oobaddexc = %d\n\r",g_mem_stats.oobaddexc); PRINTK("freeaddexc = %d\n\r",g_mem_stats.freeaddexc); PRINTK("invalidaddexc = %d\n\r",g_mem_stats.invalidaddexc); PRINTK("excessaddexc = %d\n\r",g_mem_stats.excessaddexc); PRINTK("nofreeDscrallocexc[0] = %d\n\r",g_mem_stats.nofreeDscrallocexc[0]); PRINTK("nofreeDscrallocexc[1] = %d\n\r",g_mem_stats.nofreeDscrallocexc[1]); for(i = 0; i < 5; i++) PRINTK("nofreePktallocexc[%d] = %d\n\r",i, g_mem_stats.nofreePktallocexc[i]); for(i = 0; i < 8; i++) PRINTK("nofreeLocalallocexc[%d] = %d\n\r",i, g_mem_stats.nofreeLocalallocexc[i]); PRINTK("nofreeEventallocexc = %d\n\r", g_mem_stats.nofreeEventallocexc); #endif /* MEM_DEBUG_MODE */ PRINTK("\nMAC Statistics\n\r"); #ifndef MAC_HW_UNIT_TEST_MODE PRINTK("itbtt = %d\n\r",g_mac_stats.itbtt); PRINTK("itxc = %d\n\r",g_mac_stats.itxc); PRINTK("irxc = %d\n\r",g_mac_stats.irxc); PRINTK("ihprxc = %d\n\r",g_mac_stats.ihprxc); PRINTK("ierr = %d\n\r",g_mac_stats.ierr); PRINTK("ideauth = %d\n\r",g_mac_stats.ideauth); PRINTK("icapend = %d\n\r",g_mac_stats.icapend); PRINTK("enpmsdu = %d\n\r",g_mac_stats.enpmsdu); PRINTK("erxqemp = %d\n\r",g_mac_stats.erxqemp); PRINTK("etxsus1machang = %d\n\r",g_mac_stats.etxsus1machang); PRINTK("etxsus1phyhang = %d\n\r",g_mac_stats.etxsus1phyhang); PRINTK("etxsus3 = %d\n\r",g_mac_stats.etxsus3); PRINTK("ebus = %d\n\r",g_mac_stats.ebus); PRINTK("ebwrsig = %d\n\r",g_mac_stats.ebwrsig); PRINTK("emsaddr = %d\n\r",g_mac_stats.emsaddr); PRINTK("etxfifo = %d\n\r",g_mac_stats.etxfifo); PRINTK("erxfifo = %d\n\r",g_mac_stats.erxfifo); PRINTK("ehprxfifo = %d\n\r",g_mac_stats.ehprxfifo); PRINTK("etxqempt = %d\n\r",g_mac_stats.etxqempt); PRINTK("edmanoerr = %d\n\r",g_mac_stats.edmanoerr); PRINTK("etxcenr = %d\n\r",g_mac_stats.etxcenr); PRINTK("erxcenr = %d\n\r",g_mac_stats.erxcenr); PRINTK("esgaf = %d\n\r",g_mac_stats.esgaf); PRINTK("eother = %d\n\r",g_mac_stats.eother); PRINTK("qatxp = %d\n\r",g_mac_stats.qatxp); PRINTK("qdtxp = %d\n\r",g_mac_stats.qdtxp); #else /* MAC_HW_UNIT_TEST_MODE */ PRINTK("rxci = %d\n\r",g_test_stats.rxci); PRINTK("hprxci = %d\n\r",g_test_stats.hprxci); PRINTK("txci = %d\n\r",g_test_stats.txci); PRINTK("tbtti = %d\n\r",g_test_stats.tbtti); PRINTK("erri = %d\n\r",g_test_stats.erri); PRINTK("capei = %d\n\r",g_test_stats.capei); PRINTK("uki = %d\n\r",g_test_stats.uki); PRINTK("err.enpmsdu = %d\n\r",g_test_stats.exp.enpmsdu); PRINTK("err.erxqemp = %d\n\r",g_test_stats.exp.erxqemp); PRINTK("err.emsaddr = %d\n\r",g_test_stats.exp.emsaddr); PRINTK("err.etxsus1machang = %d\n\r",g_test_stats.exp.etxsus1machang); PRINTK("err.etxsus1phyhang = %d\n\r",g_test_stats.exp.etxsus1phyhang); PRINTK("err.etxsus3 = %d\n\r",g_test_stats.exp.etxsus3); PRINTK("err.ebus = %d\n\r",g_test_stats.exp.ebus); PRINTK("err.ebwrsig = %d\n\r",g_test_stats.exp.ebwrsig); PRINTK("err.etxqempt = %d\n\r",g_test_stats.exp.etxqempt); PRINTK("err.edmanoerr = %d\n\r",g_test_stats.exp.edmanoerr); PRINTK("err.etxcenr = %d\n\r",g_test_stats.exp.etxcenr); PRINTK("err.erxcenr = %d\n\r",g_test_stats.exp.erxcenr); PRINTK("err.esgaf = %d\n\r",g_test_stats.exp.esgaf); PRINTK("err.etxfifo = %d\n\r",g_test_stats.exp.etxfifo); PRINTK("err.erxfifo = %d\n\r",g_test_stats.exp.erxfifo); PRINTK("err.eother = %d\n\r",g_test_stats.exp.eother); #endif /* MAC_HW_UNIT_TEST_MODE */ } void print_build_flags(void) { #ifdef ETHERNET_HOST PRINTK("ETHERNET_HOST\n\r"); #endif /* ETHERNET_HOST */ #ifdef GENERIC_HOST PRINTK("GENERIC_HOST\n\r"); #endif /* GENERIC_HOST */ #ifdef PHY_802_11n PRINTK("PHY_802_11n\n\r"); #endif /* PHY_802_11n */ #ifdef GENERIC_PHY PRINTK("GENERIC_PHY\n\r"); #endif /* GENERIC_PHY */ #ifdef ITTIAM_PHY PRINTK("ITTIAM_PHY\n\r"); #endif /* ITTIAM_PHY */ #ifdef BSS_ACCESS_POINT_MODE PRINTK("BSS_ACCESS_POINT_MODE\n\r"); #endif /* BSS_ACCESS_POINT_MODE */ #ifdef IBSS_BSS_STATION_MODE PRINTK("IBSS_BSS_STATION_MODE\n\r"); #endif /* IBSS_BSS_STATION_MODE */ #ifdef MAC_HW_UNIT_TEST_MODE PRINTK("MAC_HW_UNIT_TEST_MODE \n\r"); #endif /* MAC_HW_UNIT_TEST_MODE */ #ifdef MAC_802_11I PRINTK("MAC_802_11I \n\r"); #endif /* MAC_802_11I */ #ifdef SUPP_11I PRINTK("SUPP_11I \n\r"); #endif /* SUPP_11I */ #ifdef MAC_WMM PRINTK("MAC_WMM \n\r"); #endif /* MAC_WMM */ #ifdef MAC_802_11N PRINTK("MAC_802_11N \n\r"); #endif /* MAC_802_11N */ #ifdef MAC_802_1X PRINTK("MAC_802_1X \n\r"); #endif /* MAC_802_1X */ #ifdef MAC_802_11H PRINTK("MAC_802_11H \n\r"); #endif /* MAC_802_11H */ #ifdef GENERIC_RF PRINTK("GENERIC_RF\n\r"); #endif /* GENERIC_RF */ #ifdef RF_MAXIM_ITTIAM PRINTK("RF_MAXIM_ITTIAM \n\r"); #endif /* RF_MAXIM_ITTIAM */ // 20120709 caisf masked, merged ittiam mac v1.2 code #if 0 #ifdef RF_AIROHA_ITTIAM PRINTK("RF_AIROHA_ITTIAM \n\r"); #endif /* RF_AIROHA_ITTIAM */ #endif #ifdef MAX2829 PRINTK("MAX2829 \n\r"); #endif /* MAX2829 */ // 20120709 caisf masked, merged ittiam mac v1.2 code #if 0 #ifdef MAX2830_32 PRINTK("MAX2830_32 \n\r"); #endif /* MAX2830_32 */ #ifdef AL2236 PRINTK("AL2236 \n\r"); #endif /* AL2236 */ #ifdef AL7230 PRINTK("AL7230 \n\r"); #endif /* AL7230 */ #endif #ifdef MWLAN PRINTK("MWLAN \n\r"); #endif /* MWLAN */ #ifdef OS_LINUX_CSL_TYPE PRINTK("OS_LINUX_CSL_TYPE \n\r"); #endif /* OS_LINUX_CSL_TYPE */ #ifdef DEBUG_MODE PRINTK("DEBUG_MODE \n\r"); #endif /* DEBUG_MODE */ #ifdef USE_PROCESSOR_DMA PRINTK("USE_PROCESSOR_DMA \n\r"); #endif /* USE_PROCESSOR_DMA */ #ifdef EDCA_DEMO_KLUDGE PRINTK("EDCA_DEMO_KLUDGE \n\r"); #endif /* EDCA_DEMO_KLUDGE */ #ifdef LOCALMEM_TX_DSCR PRINTK("LOCALMEM_TX_DSCR \n\r"); #endif /* LOCALMEM_TX_DSCR */ #ifdef AUTORATE_FEATURE PRINTK("AUTORATE_FEATURE \n\r"); #endif /* AUTORATE_FEATURE */ #ifdef DISABLE_MACHW_DEFRAG PRINTK("DISABLE_MACHW_DEFRAG \n\r"); #endif /* DISABLE_MACHW_DEFRAG */ #ifdef DISABLE_MACHW_DEAGGR PRINTK("DISABLE_MACHW_DEAGGR \n\r"); #endif /* DISABLE_MACHW_DEAGGR */ #ifdef PHY_TEST_MAX_PKT_RX PRINTK("PHY_TEST_MAX_PKT_RX \n\r"); #endif /* PHY_TEST_MAX_PKT_RX */ #ifdef DEFAULT_SME PRINTK("DEFAULT_SME \n\r"); #endif /* DEFAULT_SME */ #ifdef NO_ACTION_RESET PRINTK("NO_ACTION_RESET \n\r"); #endif /* NO_ACTION_RESET */ #ifdef LITTLE_ENDIAN PRINTK("LITTLE_ENDIAN \n\r"); #endif /* LITTLE_ENDIAN */ #ifdef DSCR_MACROS_NOT_DEFINED PRINTK("DSCR_MACROS_NOT_DEFINED \n\r"); #endif /* DSCR_MACROS_NOT_DEFINED */ #ifdef PHY_CONTINUOUS_TX_MODE PRINTK("PHY_CONTINUOUS_TX_MODE \n\r"); #endif /* PHY_CONTINUOUS_TX_MODE */ #ifdef HANDLE_ERROR_INTR PRINTK("HANDLE_ERROR_INTR \n\r"); #endif /* HANDLE_ERROR_INTR */ #ifdef MEM_DEBUG_MODE PRINTK("MEM_DEBUG_MODE \n\r"); #endif /* MEM_DEBUG_MODE */ #ifdef MEM_STRUCT_SIZES_INIT PRINTK("MEM_STRUCT_SIZES_INIT \n\r"); #endif /* MEM_STRUCT_SIZES_INIT */ #ifdef TX_ABORT_FEATURE PRINTK("TX_ABORT_FEATURE \n\r"); #endif /* TX_ABORT_FEATURE */ } #endif /* DEBUG_MODE */ /*chenq add itm trace*/ /*flag of ShareMemInfo*/ int g_debug_print_tx_pkt_on = 0; int g_debug_print_rx_ptk_on = 0; int g_debug_print_tx_buf_on = 0; int g_debug_print_rx_buf_on = 0; int g_debug_buf_use_info_start = 0; /*flag of MacTxRxStatistics*/ int g_debug_txrx_reg_info_start = 0; int g_debug_txrx_frame_info_start = 0; int g_debug_rx_size_info_start = 0; int g_debug_isr_info_start = 0; /*flag of SpiSdioDmaState*/ int g_debug_print_spisdio_bus_on = 0; int g_debug_print_dma_do_on = 0; int g_debug_spisdiodma_isr_info_start = 0; /*flag of MacFsmMibState*/ int g_debug_print_fsm_on = 0; int g_debug_print_assoc_on = 0; int g_debug_print_Enc_auth_on = 0; int g_debug_print_wps_on = 0; int g_debug_print_ps_on = 0;//PowerSave int g_debug_print_wd_on = 0;//WiFi-Direct int g_debug_print_txrx_path_on = 0; /*flag of Host6820Info*/ //no add void Reset_itm_trace_flag(void) { /*flag of ShareMemInfo*/ g_debug_print_tx_pkt_on = 0; g_debug_print_rx_ptk_on = 0; g_debug_print_tx_buf_on = 0; g_debug_print_rx_buf_on = 0; g_debug_buf_use_info_start = 0; /*flag of MacTxRxStatistics*/ g_debug_txrx_reg_info_start = 0; g_debug_txrx_frame_info_start = 0; g_debug_rx_size_info_start = 0; g_debug_isr_info_start = 0; /*flag of SpiSdioDmaState*/ g_debug_print_spisdio_bus_on = 0; g_debug_print_dma_do_on = 0; g_debug_spisdiodma_isr_info_start = 0; /*flag of MacFsmMibState*/ g_debug_print_fsm_on = 0; g_debug_print_assoc_on = 0; g_debug_print_Enc_auth_on = 0; g_debug_print_wps_on = 0; g_debug_print_ps_on = 0;//PowerSave g_debug_print_wd_on = 0;//WiFi-Direct g_debug_print_txrx_path_on = 0; /*flag of Host6820Info*/ //no add } void ShareMemInfo(int type,int flag,int value,char * reserved2ext) { if(type == itm_debug_plog_sharemem_tx_pkt) { g_debug_print_tx_pkt_on = value; } else if(type == itm_debug_plog_sharemem_rx_ptk) { g_debug_print_rx_ptk_on = value; } else if(type == itm_debug_plog_sharemem_tx_buf) { g_debug_print_tx_buf_on = value; } else if(type == itm_debug_plog_sharemem_rx_buf) { g_debug_print_rx_buf_on = value; } else if(type == itm_debug_plog_sharemem_buf_use) { if(flag == counter_start) { g_debug_buf_use_info_start = counter_start; } else if( ( flag == counter_end ) && ( g_debug_buf_use_info_start == counter_end ) ) { /*printk("already in counter_end stat\n");*/ } else if( flag == counter_end ) { g_debug_buf_use_info_start = counter_end; } } } void MacTxRxStatistics(int type,int flag,char * reserved2ext) { if(type == itm_debug_plog_mactxrx_reg) { if(flag == counter_start) { g_debug_txrx_reg_info_start = counter_start; } else if( ( flag == counter_end ) && ( g_debug_txrx_reg_info_start == counter_end ) ) { /*printk("already in counter_end stat\n");*/ } else if( flag == counter_end ) { g_debug_txrx_reg_info_start = counter_end; } } else if(type == itm_debug_plog_mactxrx_frame) { if(flag == counter_start) { g_debug_txrx_frame_info_start = counter_start; } else if( ( flag == counter_end ) && ( g_debug_txrx_frame_info_start == counter_end ) ) { /*printk("already in counter_end stat\n");*/ } else if( flag == counter_end ) { g_debug_txrx_frame_info_start = counter_end; } } else if(type == itm_debug_plog_mactxrx_rx_size) { if(flag == counter_start) { g_debug_rx_size_info_start = counter_start; } else if( ( flag == counter_end ) && ( g_debug_rx_size_info_start == counter_end ) ) { /*printk("already in counter_end stat\n");*/ } else if( flag == counter_end ) { g_debug_rx_size_info_start = counter_end; } } else if(type == itm_debug_plog_mactxrx_isr) { if(flag == counter_start) { g_debug_isr_info_start = counter_start; } else if( ( flag == counter_end ) && ( g_debug_isr_info_start == counter_end ) ) { /*printk("already in counter_end stat\n");*/ } else if( flag == counter_end ) { g_debug_isr_info_start = counter_end; } } } void SpiSdioDmaState(int type,int flag,int value,char * reserved2ext) { if(type == itm_debug_plog_spisdiodma_spisdio) { g_debug_print_spisdio_bus_on = value; } else if(type == itm_debug_plog_spisdiodma_dma) { g_debug_print_dma_do_on = value; } else if(type == itm_debug_plog_spisdiodma_isr) { if(flag == counter_start) { g_debug_spisdiodma_isr_info_start = counter_start; } else if( ( flag == counter_end ) && ( g_debug_spisdiodma_isr_info_start == counter_end ) ) { /*printk("already in counter_end stat\n");*/ } else if( flag == counter_end ) { g_debug_spisdiodma_isr_info_start = counter_end; } } } void MacFsmMibState(int type,int value,char * reserved2ext) { if(type == itm_debug_plog_macfsm_mib_fsm) { g_debug_print_fsm_on = value; } else if(type == itm_debug_plog_macfsm_mib_assoc) { g_debug_print_assoc_on = value; } else if(type == itm_debug_plog_macfsm_mib_Enc_auth) { g_debug_print_Enc_auth_on = value; } else if(type == itm_debug_plog_macfsm_mib_wps) { g_debug_print_wps_on = value; } else if(type == itm_debug_plog_macfsm_mib_ps)//PowerSave { g_debug_print_ps_on = value;//PowerSave } else if(type == itm_debug_plog_macfsm_mib_wd)//WiFi-Direct { g_debug_print_wd_on = value;//WiFi-Direct } else if(type == itm_debug_plog_macfsm_mib_txrx_path) { g_debug_print_txrx_path_on = value; } else if(type == itm_debug_plog_macfsm_mib_mibapp) { /*print ...*/ } else if(type == itm_debug_plog_macfsm_mib_mibprtcl) { /*print ...*/ } else if(type == itm_debug_plog_macfsm_mib_mibmac) { /*print ...*/ } } void Host6820Info(int type,char * reserved2ext) { } /*chenq add end*/ #ifdef TROUT_WIFI_POWER_SLEEP_ENABLE /* * Notify co-processor to handle Power Management event * through interrupt. * Author: Keguang * Date: 20130321 */ inline void notify_cp_with_handshake(uint msg, uint retry) { uint i = retry; uint count = host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) + 1; //#ifdef POWERSAVE_DEBUG pr_info("rSYSREG_POWER_CTRL: %x\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL)); //#endif host_write_trout_reg((UWORD32)msg, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*load message*/ host_write_trout_reg((UWORD32)0x1, (UWORD32)rSYSREG_GEN_ISR_2_ARM7); /*interrupt CP*/ /*pr_info("command done!\n");*/ /*wait for CP*/ while((host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) != count) && i--) { msleep(10); //#ifdef POWERSAVE_DEBUG pr_info("Done! rSYSREG_POWER_CTRL: %x\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL)); //#endif } pr_info("!!! rSYSREG_POWER_CTRL: %x, retry %d, i %d\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL), retry, i); host_write_trout_reg(0x0, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*clear message*/ if(msg == PS_MSG_WIFI_SUSPEND_MAGIC) g_done_wifi_suspend = 1; else if(msg == PS_MSG_WIFI_RESUME_MAGIC) g_done_wifi_suspend = 0; } EXPORT_SYMBOL(notify_cp_with_handshake); extern int prepare_null_frame_for_cp(UWORD8 psm, BOOL_T is_qos, UWORD8 priority); void check_and_retransmit(void) { uint which_frame = 0; uint sta = 0; uint vs; uint retry = 0; unsigned char tmp[200]; uint *pw = (uint *)&tmp[0]; which_frame = root_host_read_trout_reg((UWORD32)rSYSREG_HOST2ARM_INFO1); if(which_frame) sta = BEACON_MEM_BEGIN; else sta = BEACON_MEM_BEGIN + 200; root_host_read_trout_ram((void *)tmp, (void *)sta, TX_DSCR_LEN); if(((tmp[3] >> 5) & 0x3) == 0x3){ goto retx; } if((tmp[20] & 0x3) != 0x3){ printk("SF0-CASUED\n"); goto retx; } /* arrive here, means the last frame ARM7 sent was success(AP acked) do nothing*/ return; retx: tmp[3] &= 0x9F; tmp[3] |= 0x20; tmp[20] &= 0xFC; vs = root_host_read_trout_reg((UWORD32)rMAC_TSF_TIMER_LO); vs = (vs >> 10) & 0xFFFF; pw[3] &= 0xFFFF0000; pw[3] |= vs; printk("RE-TX\n"); root_host_write_trout_ram((void *)sta, (void *)tmp, TX_DSCR_LEN); root_host_write_trout_reg((UWORD32)sta, (UWORD32)rMAC_EDCA_PRI_HP_Q_PTR); msleep(20); return; } /*for internal use only*/ inline void root_notify_cp_with_handshake(uint msg, uint retry) { uint i = retry; uint count = root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) + 1; #ifdef POWERSAVE_DEBUG pr_info("rSYSREG_POWER_CTRL: %x\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL)); /*pr_info("command %x\n", msg);*/ #endif root_host_write_trout_reg((UWORD32)msg, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*load message*/ root_host_write_trout_reg((UWORD32)0x1, (UWORD32)rSYSREG_GEN_ISR_2_ARM7); /*interrupt CP*/ /*pr_info("command done!\n");*/ if((msg & 0xFFFF) == PS_MSG_ARM7_EBEA_KC_MAGIC){ printk("EBEA.......\n"); msleep(75); check_and_retransmit(); } /*wait for CP*/ while((root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) != count) && i--) { msleep(10); #ifdef POWERSAVE_DEBUG pr_info("Done! rSYSREG_POWER_CTRL: %x\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL)); /*pr_info("expected %x, SYSREG_INFO1_FROM_ARM = %x\n", count, root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM));*/ #endif } pr_info("@@@ rSYSREG_POWER_CTRL: %x, retry %d, i %d\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL), retry, i); root_host_write_trout_reg(0x0, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*clear message*/ if(msg == PS_MSG_WIFI_SUSPEND_MAGIC) g_done_wifi_suspend = 1; else if(msg == PS_MSG_WIFI_RESUME_MAGIC) g_done_wifi_suspend = 0; } #endif
abgoyal/zen_u105_kernel
drivers/net/wireless/trout/mac/src/Common/common.c
C
gpl-2.0
42,309
/* * Asterisk -- An open source telephony toolkit. * * Copyright (C) 2005-2006, Kevin P. Fleming * * Kevin P. Fleming <kpfleming@digium.com> * * See http://www.asterisk.org for more information about * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. */ /*! \file * * \brief Background DNS update manager * * \author Kevin P. Fleming <kpfleming@digium.com> * * \bug There is a minor race condition. In the event that an IP address * of a dnsmgr managed host changes, there is the potential for the consumer * of that address to access the in_addr data at the same time that the dnsmgr * thread is in the middle of updating it to the new address. */ #include "asterisk.h" ASTERISK_FILE_VERSION(__FILE__, "$Revision: 130752 $") #include "asterisk/_private.h" #include <regex.h> #include <signal.h> #include "asterisk/dnsmgr.h" #include "asterisk/linkedlists.h" #include "asterisk/utils.h" #include "asterisk/config.h" #include "asterisk/sched.h" #include "asterisk/cli.h" #include "asterisk/manager.h" static struct sched_context *sched; static int refresh_sched = -1; static pthread_t refresh_thread = AST_PTHREADT_NULL; struct ast_dnsmgr_entry { /*! where we will store the resulting address */ struct in_addr *result; /*! the last result, used to check if address has changed */ struct in_addr last; /*! Set to 1 if the entry changes */ int changed:1; ast_mutex_t lock; AST_RWLIST_ENTRY(ast_dnsmgr_entry) list; /*! just 1 here, but we use calloc to allocate the correct size */ char name[1]; }; static AST_RWLIST_HEAD_STATIC(entry_list, ast_dnsmgr_entry); AST_MUTEX_DEFINE_STATIC(refresh_lock); #define REFRESH_DEFAULT 300 static int enabled; static int refresh_interval; struct refresh_info { struct entry_list *entries; int verbose; unsigned int regex_present:1; regex_t filter; }; static struct refresh_info master_refresh_info = { .entries = &entry_list, .verbose = 0, }; struct ast_dnsmgr_entry *ast_dnsmgr_get(const char *name, struct in_addr *result) { struct ast_dnsmgr_entry *entry; if (!result || ast_strlen_zero(name) || !(entry = ast_calloc(1, sizeof(*entry) + strlen(name)))) return NULL; entry->result = result; ast_mutex_init(&entry->lock); strcpy(entry->name, name); memcpy(&entry->last, result, sizeof(entry->last)); AST_RWLIST_WRLOCK(&entry_list); AST_RWLIST_INSERT_HEAD(&entry_list, entry, list); AST_RWLIST_UNLOCK(&entry_list); return entry; } void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry) { if (!entry) return; AST_RWLIST_WRLOCK(&entry_list); AST_RWLIST_REMOVE(&entry_list, entry, list); AST_RWLIST_UNLOCK(&entry_list); ast_verb(4, "removing dns manager for '%s'\n", entry->name); ast_mutex_destroy(&entry->lock); ast_free(entry); } int ast_dnsmgr_lookup(const char *name, struct in_addr *result, struct ast_dnsmgr_entry **dnsmgr) { struct ast_hostent ahp; struct hostent *hp; if (ast_strlen_zero(name) || !result || !dnsmgr) return -1; if (*dnsmgr && !strcasecmp((*dnsmgr)->name, name)) return 0; ast_verb(4, "doing dnsmgr_lookup for '%s'\n", name); /* if it's actually an IP address and not a name, there's no need for a managed lookup */ if (inet_aton(name, result)) return 0; /* do a lookup now but add a manager so it will automagically get updated in the background */ if ((hp = ast_gethostbyname(name, &ahp))) memcpy(result, hp->h_addr, sizeof(result)); /* if dnsmgr is not enable don't bother adding an entry */ if (!enabled) return 0; ast_verb(3, "adding dns manager for '%s'\n", name); *dnsmgr = ast_dnsmgr_get(name, result); return !*dnsmgr; } /* * Refresh a dnsmgr entry */ static int dnsmgr_refresh(struct ast_dnsmgr_entry *entry, int verbose) { struct ast_hostent ahp; struct hostent *hp; char iabuf[INET_ADDRSTRLEN]; char iabuf2[INET_ADDRSTRLEN]; struct in_addr tmp; int changed = 0; ast_mutex_lock(&entry->lock); if (verbose) ast_verb(3, "refreshing '%s'\n", entry->name); if ((hp = ast_gethostbyname(entry->name, &ahp))) { /* check to see if it has changed, do callback if requested (where de callback is defined ????) */ memcpy(&tmp, hp->h_addr, sizeof(tmp)); if (tmp.s_addr != entry->last.s_addr) { ast_copy_string(iabuf, ast_inet_ntoa(entry->last), sizeof(iabuf)); ast_copy_string(iabuf2, ast_inet_ntoa(tmp), sizeof(iabuf2)); ast_log(LOG_NOTICE, "host '%s' changed from %s to %s\n", entry->name, iabuf, iabuf2); memcpy(entry->result, hp->h_addr, sizeof(entry->result)); memcpy(&entry->last, hp->h_addr, sizeof(entry->last)); changed = entry->changed = 1; } } ast_mutex_unlock(&entry->lock); return changed; } int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry) { return dnsmgr_refresh(entry, 0); } /* * Check if dnsmgr entry has changed from since last call to this function */ int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry) { int changed; ast_mutex_lock(&entry->lock); changed = entry->changed; entry->changed = 0; ast_mutex_unlock(&entry->lock); return changed; } static void *do_refresh(void *data) { for (;;) { pthread_testcancel(); usleep((ast_sched_wait(sched)*1000)); pthread_testcancel(); ast_sched_runq(sched); } return NULL; } static int refresh_list(const void *data) { struct refresh_info *info = (struct refresh_info *)data; struct ast_dnsmgr_entry *entry; /* if a refresh or reload is already in progress, exit now */ if (ast_mutex_trylock(&refresh_lock)) { if (info->verbose) ast_log(LOG_WARNING, "DNS Manager refresh already in progress.\n"); return -1; } ast_verb(3, "Refreshing DNS lookups.\n"); AST_RWLIST_RDLOCK(info->entries); AST_RWLIST_TRAVERSE(info->entries, entry, list) { if (info->regex_present && regexec(&info->filter, entry->name, 0, NULL, 0)) continue; dnsmgr_refresh(entry, info->verbose); } AST_RWLIST_UNLOCK(info->entries); ast_mutex_unlock(&refresh_lock); /* automatically reschedule based on the interval */ return refresh_interval * 1000; } void dnsmgr_start_refresh(void) { if (refresh_sched > -1) { AST_SCHED_DEL(sched, refresh_sched); refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1); } } static int do_reload(int loading); static char *handle_cli_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { switch (cmd) { case CLI_INIT: e->command = "dnsmgr reload"; e->usage = "Usage: dnsmgr reload\n" " Reloads the DNS manager configuration.\n"; return NULL; case CLI_GENERATE: return NULL; } if (a->argc > 2) return CLI_SHOWUSAGE; do_reload(0); return CLI_SUCCESS; } static char *handle_cli_refresh(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct refresh_info info = { .entries = &entry_list, .verbose = 1, }; switch (cmd) { case CLI_INIT: e->command = "dnsmgr refresh"; e->usage = "Usage: dnsmgr refresh [pattern]\n" " Peforms an immediate refresh of the managed DNS entries.\n" " Optional regular expression pattern is used to filter the entries to refresh.\n"; return NULL; case CLI_GENERATE: return NULL; } if (!enabled) { ast_cli(a->fd, "DNS Manager is disabled.\n"); return 0; } if (a->argc > 3) { return CLI_SHOWUSAGE; } if (a->argc == 3) { if (regcomp(&info.filter, a->argv[2], REG_EXTENDED | REG_NOSUB)) { return CLI_SHOWUSAGE; } else { info.regex_present = 1; } } refresh_list(&info); if (info.regex_present) { regfree(&info.filter); } return CLI_SUCCESS; } static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { int count = 0; struct ast_dnsmgr_entry *entry; switch (cmd) { case CLI_INIT: e->command = "dnsmgr status"; e->usage = "Usage: dnsmgr status\n" " Displays the DNS manager status.\n"; return NULL; case CLI_GENERATE: return NULL; } if (a->argc > 2) return CLI_SHOWUSAGE; ast_cli(a->fd, "DNS Manager: %s\n", enabled ? "enabled" : "disabled"); ast_cli(a->fd, "Refresh Interval: %d seconds\n", refresh_interval); AST_RWLIST_RDLOCK(&entry_list); AST_RWLIST_TRAVERSE(&entry_list, entry, list) count++; AST_RWLIST_UNLOCK(&entry_list); ast_cli(a->fd, "Number of entries: %d\n", count); return CLI_SUCCESS; } static struct ast_cli_entry cli_reload = AST_CLI_DEFINE(handle_cli_reload, "Reloads the DNS manager configuration"); static struct ast_cli_entry cli_refresh = AST_CLI_DEFINE(handle_cli_refresh, "Performs an immediate refresh"); static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the DNS manager status"); int dnsmgr_init(void) { if (!(sched = sched_context_create())) { ast_log(LOG_ERROR, "Unable to create schedule context.\n"); return -1; } ast_cli_register(&cli_reload); ast_cli_register(&cli_status); ast_cli_register(&cli_refresh); return do_reload(1); } int dnsmgr_reload(void) { return do_reload(0); } static int do_reload(int loading) { struct ast_config *config; struct ast_flags config_flags = { loading ? 0 : CONFIG_FLAG_FILEUNCHANGED }; const char *interval_value; const char *enabled_value; int interval; int was_enabled; int res = -1; if ((config = ast_config_load("dnsmgr.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) return 0; /* ensure that no refresh cycles run while the reload is in progress */ ast_mutex_lock(&refresh_lock); /* reset defaults in preparation for reading config file */ refresh_interval = REFRESH_DEFAULT; was_enabled = enabled; enabled = 0; AST_SCHED_DEL(sched, refresh_sched); if (config) { if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) { enabled = ast_true(enabled_value); } if ((interval_value = ast_variable_retrieve(config, "general", "refreshinterval"))) { if (sscanf(interval_value, "%d", &interval) < 1) ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", interval_value); else if (interval < 0) ast_log(LOG_WARNING, "Invalid refresh interval '%d' specified, using default\n", interval); else refresh_interval = interval; } ast_config_destroy(config); } if (enabled && refresh_interval) ast_log(LOG_NOTICE, "Managed DNS entries will be refreshed every %d seconds.\n", refresh_interval); /* if this reload enabled the manager, create the background thread if it does not exist */ if (enabled) { if (!was_enabled && (refresh_thread == AST_PTHREADT_NULL)) { if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) { ast_log(LOG_ERROR, "Unable to start refresh thread.\n"); } } /* make a background refresh happen right away */ refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1); res = 0; } /* if this reload disabled the manager and there is a background thread, kill it */ else if (!enabled && was_enabled && (refresh_thread != AST_PTHREADT_NULL)) { /* wake up the thread so it will exit */ pthread_cancel(refresh_thread); pthread_kill(refresh_thread, SIGURG); pthread_join(refresh_thread, NULL); refresh_thread = AST_PTHREADT_NULL; res = 0; } else res = 0; ast_mutex_unlock(&refresh_lock); manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: DNSmgr\r\nStatus: %s\r/nMessage: DNSmgr reload Requested\r\n", enabled ? "Enabled" : "Disabled"); return res; }
nicwolff/asterisk-agi-mp3
main/dnsmgr.c
C
gpl-2.0
11,631
/* pictool: ANSI C converter for Tibia's PIC files * (c) 2007-2009 Ivan Vucica * Part of OpenTibia project * * Although written in ANSI C, this makes use of #pragma pack(), * make sure your compiler supports packed structures, or else. * * 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. */ /* Headers */ #include <stdio.h> #include <stdlib.h> #include <SDL/SDL.h> #include <errno.h> #if !_MSC_VER #include <unistd.h> #endif #if !BAZEL_BUILD #include "../../sprdata.h" #else #include "sprdata.h" #endif #include "picfuncs.h" #pragma pack(1) typedef struct { uint32_t signature; uint16_t imgcount; } fileheader_t; typedef struct { uint8_t width, height; uint8_t unk1, unk2, unk3; /* FIXME (ivucica#4#) zerocoolz says this should be colorkey, according to http://otfans.net/showpost.php?p=840634&postcount=134 */ } picheader_t; #pragma pack() static int filesize (FILE* f) { int loc = ftell(f); int size = 0; fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, loc, SEEK_SET); return size; } int writesprite (FILE *f, SDL_Surface *s, int offx, int offy, uint16_t *datasize) { return writeSprData(f, s, offx, offy, datasize); } int readsprite (FILE *f, uint32_t sprloc, SDL_Surface *s, int offx, int offy) { int oldloc = ftell(f); int r; fseek(f, sprloc, SEEK_SET); r = readSprData(f, s, offx, offy); fseek(f, oldloc, SEEK_SET); return r; } int picdetails (const char* filename) { FILE *f; int i,j,k; fileheader_t fh; picheader_t ph; uint32_t sprloc; f = fopen(filename, "rb"); printf("information for %s\n", filename); if (!f) return -1; fread(&fh, sizeof(fh), 1, f); printf("signature %d\n", fh.signature); printf("imagecount %d\n", fh.imgcount); for(i = 0; i < fh.imgcount ; i++){ fread(&ph, sizeof(ph), 1, f); printf("img%d width %d height %d bg rgb #%02x%02x%02x\n", i, ph.width, ph.height, ph.unk1, ph.unk2, ph.unk3); for(j = 0; j<ph.height; j++){ for(k = 0; k < ph.width; k++){ fread(&sprloc, sizeof(sprloc), 1, f); printf("sprite img %d x %d y %d location %d\n", i,k,j,sprloc); } } } return 0; } int dumperror_stderr(char* txt, ...) { va_list vl; va_start(vl, txt); int r = vfprintf(stderr, txt, vl); va_end(vl); return r; } int (*pictool_dumperror)(char*,...) = dumperror_stderr; int writepic(const char* filename, int index, SDL_Surface *s){ FILE *fi, *fo; fileheader_t fh; picheader_t ph; uint32_t sprloc, sproffset; size_t continuationposi, continuationposo; uint16_t datasize; void *data; int i,j,k; fi = fopen(filename, "rb"); fo = fopen("__tmp__.pic","wb+"); if (!fi || !fo) return -1; fread(&fh, sizeof(fh), 1, fi); fwrite(&fh, sizeof(fh), 1, fo); sproffset = fh.imgcount * (sizeof(ph)+1)-2; for(i = 0; i < fh.imgcount; i++){ fread(&ph, sizeof(ph), 1, fi); if(i == index){ ph.width = s->w / 32; ph.height = s->h / 32; } sproffset += ph.width * ph.height * 4; fseek(fi, ph.width*ph.height*4, SEEK_CUR); } fseek(fi, sizeof(fh), SEEK_SET); for(i = 0; i < fh.imgcount; i++){ fread(&ph, sizeof(ph), 1, fi); if(i != index){ if(!ph.width || !ph.height){ fprintf(stderr, "pictool: width or height are 0\n"); return (10); } fwrite(&ph, sizeof(ph), 1, fo); for(j=0; j < ph.width * ph.height; j++){ fread(&sprloc, sizeof(sprloc), 1, fi); if(sproffset > 4000000){ dumperror_stderr("pictool: infinite loop\n"); exit(8); } if(sprloc > filesize(fi)){ dumperror_stderr("pictool: bad spr pointer\n"); exit(9); } fwrite(&sproffset, sizeof(sproffset), 1, fo); continuationposi = ftell(fi); continuationposo = ftell(fo); fseek(fi, sprloc, SEEK_SET); fseek(fo, sproffset, SEEK_SET); fread(&datasize, sizeof(datasize), 1, fi); fwrite(&datasize, sizeof(datasize), 1, fo); data = malloc(datasize+2); if(!data){ dumperror_stderr("pictool: allocation problem\n"); return (7); } fread(data, datasize+2, 1, fi); fwrite(data, datasize+2, 1, fo); free(data); fseek(fo, continuationposo, SEEK_SET); fseek(fi, continuationposi, SEEK_SET); sproffset += datasize+2; // 2 == space for datasize } fflush(fo); } else{ fseek(fi, ph.width*ph.height*4, SEEK_CUR); ph.width = s->w / 32; ph.height = s->h / 32; fwrite(&ph, sizeof(ph), 1, fo); for(j = 0; j < ph.height; j++){ for(k = 0; k < ph.width; k++){ /*printf("Placing %d %d on %d\n", j, k, sproffset);*/ fwrite(&sproffset, sizeof(sproffset), 1, fo); continuationposo = ftell(fo); fseek(fo, sproffset, SEEK_SET); writesprite(fo, s, k * 32, j*32, &datasize); /*printf("Its size is: %d\n", datasize);*/ fseek(fo, continuationposo, SEEK_SET); sproffset += datasize+2; } } fflush(fo); } } fclose(fo); fclose(fi); if(rename("__tmp__.pic", filename)){ if (errno == 17) {// file exists if(unlink(filename)) { if (errno != 2) return 93; } if(rename("__tmp__.pic", filename)){ return 92; } } else { return 92; } } return 0; } int readpic (const char* filename, int index, SDL_Surface **sr) { /* index >= -1; -1 means that we should print out details */ SDL_Surface *s=NULL; FILE *f; int i,j,k; fileheader_t fh; picheader_t ph; uint32_t sprloc; uint32_t magenta; f = fopen(filename, "rb"); if (!f) return -1; fread(&fh,sizeof(fh),1,f); for(i = 0; i < fh.imgcount && i <= index; i++){ fread(&ph, sizeof(ph), 1, f); if(i == index){ s = SDL_CreateRGBSurface(SDL_SWSURFACE, ph.width*32, ph.height*32, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000); if(!s){ printf("CreateRGBSurface failed: %s\n", SDL_GetError()); return -1; } magenta = SDL_MapRGB(s->format, 255, 0, 255); SDL_FillRect(s, NULL, magenta); /* FIXME (ivucica#4#) Above statement is potentially unportable to architectures with * different endianess. Lilliputtans would be happier if we took a look at SDL * docs and corrected this. */ for(j = 0; j < ph.height; j++){ for(k = 0; k < ph.width; k++){ fread(&sprloc, sizeof(sprloc), 1, f); dbgprintf(":: reading sprite at pos %d %d\n", j, k); if(readsprite(f, sprloc, s, k*32, j*32)){ /* TODO (ivucica#1#) cleanup sdl surface upon error */ return -1; } } } } else{ fseek(f, sizeof(sprloc)*ph.height*ph.width, SEEK_CUR); } } fclose(f); *sr = s; return 0; }
opentibia/yatc
tools/pictool/picfuncs.c
C
gpl-2.0
7,210
/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include <poll.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <stdint.h> #include <sys/ioctl.h> #include <crypto/cryptodev.h> #include "asynchelper.h" #include "testhelper.h" #ifdef ENABLE_ASYNC static int debug = 0; #define DATA_SIZE 8*1024 #define BLOCK_SIZE 16 #define KEY_SIZE 16 static int test_crypto(int cfd) { uint8_t plaintext_raw[DATA_SIZE + 63], *plaintext; uint8_t ciphertext_raw[DATA_SIZE + 63], *ciphertext; uint8_t iv[BLOCK_SIZE]; uint8_t key[KEY_SIZE]; struct session_op sess; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif struct crypt_op cryp; if (debug) printf("running %s\n", __func__); memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); memset(key, 0x33, sizeof(key)); memset(iv, 0x03, sizeof(iv)); /* Get crypto session for AES128 */ sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } if (debug) printf("%s: got the session\n", __func__); #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } plaintext = buf_align(plaintext_raw, siop.alignmask); ciphertext = buf_align(ciphertext_raw, siop.alignmask); #else plaintext = plaintext_raw; ciphertext = ciphertext_raw; #endif memset(plaintext, 0x15, DATA_SIZE); /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = DATA_SIZE; cryp.src = plaintext; cryp.dst = ciphertext; cryp.iv = iv; cryp.op = COP_ENCRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp), 0); DO_OR_DIE(do_async_fetch(cfd, &cryp), 0); if (debug) printf("%s: data encrypted\n", __func__); if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } if (debug) printf("%s: session finished\n", __func__); if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } if (debug) printf("%s: got new session\n", __func__); /* Decrypt data.encrypted to data.decrypted */ cryp.ses = sess.ses; cryp.len = DATA_SIZE; cryp.src = ciphertext; cryp.dst = ciphertext; cryp.iv = iv; cryp.op = COP_DECRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp), 0); DO_OR_DIE(do_async_fetch(cfd, &cryp), 0); if (debug) printf("%s: data encrypted\n", __func__); /* Verify the result */ if (memcmp(plaintext, ciphertext, DATA_SIZE) != 0) { fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); return 1; } else if (debug) printf("Test passed\n"); /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } static int test_aes(int cfd) { uint8_t plaintext1_raw[BLOCK_SIZE + 63], *plaintext1; uint8_t ciphertext1[BLOCK_SIZE] = { 0xdf, 0x55, 0x6a, 0x33, 0x43, 0x8d, 0xb8, 0x7b, 0xc4, 0x1b, 0x17, 0x52, 0xc5, 0x5e, 0x5e, 0x49 }; uint8_t iv1[BLOCK_SIZE]; uint8_t key1[KEY_SIZE] = { 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t plaintext2_data[BLOCK_SIZE] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00 }; uint8_t plaintext2_raw[BLOCK_SIZE + 63], *plaintext2; uint8_t ciphertext2[BLOCK_SIZE] = { 0xb7, 0x97, 0x2b, 0x39, 0x41, 0xc4, 0x4b, 0x90, 0xaf, 0xa7, 0xb2, 0x64, 0xbf, 0xba, 0x73, 0x87 }; uint8_t iv2[BLOCK_SIZE]; uint8_t key2[KEY_SIZE]; struct session_op sess1, sess2; #ifdef CIOCGSESSINFO struct session_info_op siop1, siop2; #endif struct crypt_op cryp1, cryp2; memset(&sess1, 0, sizeof(sess1)); memset(&sess2, 0, sizeof(sess2)); memset(&cryp1, 0, sizeof(cryp1)); memset(&cryp2, 0, sizeof(cryp2)); /* Get crypto session for AES128 */ sess1.cipher = CRYPTO_AES_CBC; sess1.keylen = KEY_SIZE; sess1.key = key1; if (ioctl(cfd, CIOCGSESSION, &sess1)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop1.ses = sess1.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop1)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } plaintext1 = buf_align(plaintext1_raw, siop1.alignmask); #else plaintext1 = plaintext1_raw; #endif memset(plaintext1, 0x0, BLOCK_SIZE); memset(iv1, 0x0, sizeof(iv1)); memset(key2, 0x0, sizeof(key2)); /* Get second crypto session for AES128 */ sess2.cipher = CRYPTO_AES_CBC; sess2.keylen = KEY_SIZE; sess2.key = key2; if (ioctl(cfd, CIOCGSESSION, &sess2)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop2.ses = sess2.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop2)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } plaintext2 = buf_align(plaintext2_raw, siop2.alignmask); #else plaintext2 = plaintext2_raw; #endif memcpy(plaintext2, plaintext2_data, BLOCK_SIZE); /* Encrypt data.in to data.encrypted */ cryp1.ses = sess1.ses; cryp1.len = BLOCK_SIZE; cryp1.src = plaintext1; cryp1.dst = plaintext1; cryp1.iv = iv1; cryp1.op = COP_ENCRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp1), 0); if (debug) printf("cryp1 written out\n"); memset(iv2, 0x0, sizeof(iv2)); /* Encrypt data.in to data.encrypted */ cryp2.ses = sess2.ses; cryp2.len = BLOCK_SIZE; cryp2.src = plaintext2; cryp2.dst = plaintext2; cryp2.iv = iv2; cryp2.op = COP_ENCRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp2), 0); if (debug) printf("cryp2 written out\n"); DO_OR_DIE(do_async_fetch(cfd, &cryp1), 0); DO_OR_DIE(do_async_fetch(cfd, &cryp2), 0); if (debug) printf("cryp1 + cryp2 successfully read\n"); /* Verify the result */ if (memcmp(plaintext1, ciphertext1, BLOCK_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", plaintext1[i]); } printf("ciphertext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", ciphertext1[i]); } printf("\n"); return 1; } else { if (debug) printf("result 1 passed\n"); } /* Test 2 */ /* Verify the result */ if (memcmp(plaintext2, ciphertext2, BLOCK_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", plaintext2[i]); } printf("ciphertext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", ciphertext2[i]); } printf("\n"); return 1; } else { if (debug) printf("result 2 passed\n"); } if (debug) printf("AES Test passed\n"); /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess1.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } if (ioctl(cfd, CIOCFSESSION, &sess2.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } int main(int argc, char** argv) { int fd = -1, cfd = -1; if (argc > 1) debug = 1; /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } /* Clone file descriptor */ if (ioctl(fd, CRIOGET, &cfd)) { perror("ioctl(CRIOGET)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_aes(cfd)) return 1; if (test_crypto(cfd)) return 1; /* Close cloned descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } /* Close the original descriptor */ if (close(fd)) { perror("close(fd)"); return 1; } return 0; } #else int main(int argc, char** argv) { return (0); } #endif
cryptodev-linux/cryptodev-linux
tests/async_cipher.c
C
gpl-2.0
7,773
/* * $Id: x2c.c,v 1.7 2009/06/02 09:40:53 bnv Exp $ * $Log: x2c.c,v $ * Revision 1.7 2009/06/02 09:40:53 bnv * MVS/CMS corrections * * Revision 1.6 2008/07/15 07:40:54 bnv * #include changed from <> to "" * * Revision 1.5 2008/07/14 13:08:16 bnv * MVS,CMS support * * Revision 1.4 2002/06/11 12:37:15 bnv * Added: CDECL * * Revision 1.3 2001/06/25 18:49:48 bnv * Header changed to Id * * Revision 1.2 1999/11/26 12:52:25 bnv * Changed: To use the new macros * * Revision 1.1 1998/07/02 17:20:58 bnv * Initial Version * */ #include <ctype.h> #include "lerror.h" #include "lstring.h" /* ------------------ Lx2c ------------------ */ void __CDECL Lx2c( const PLstr to, const PLstr from ) { int i,j,r; char *t,*f; L2STR(from); Lfx(to,LLEN(*from)/2+1); /* a rough estimation */ t = LSTR(*to); f = LSTR(*from); for (i=r=0; i<LLEN(*from); ) { for (; ISSPACE(f[i]) && (i<LLEN(*from)); i++) ;; /*skip spaces*/ for (j=i; ISXDIGIT(f[j]) && (j<LLEN(*from)); j++) ;; /* find hexdigits */ if ((i<LLEN(*from)) && (j==i)) { /* Ooops wrong character */ Lerror(ERR_INVALID_HEX_CONST,0); LZEROSTR(*to); /* return null when error occures */ return; } if ((j-i)&1) { t[r++] = HEXVAL(f[i]); i++; } for (; i<j; i+=2) t[r++] = (HEXVAL(f[i])<<4) | HEXVAL(f[i+1]); } LTYPE(*to) = LSTRING_TY; LLEN(*to) = r; } /* Lx2c */
vlachoudis/brexx
lstring/x2c.c
C
gpl-2.0
1,386
/* * This file is part of mpv. * * mpv 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. * * mpv 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 mpv. If not, see <http://www.gnu.org/licenses/>. */ /// \file /// \ingroup Config #include "config.h" #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <strings.h> #include <assert.h> #include <stdbool.h> #include "libmpv/client.h" #include "mpv_talloc.h" #include "m_config.h" #include "options/m_option.h" #include "common/msg.h" #include "common/msg_control.h" static const union m_option_value default_value; // Profiles allow to predefine some sets of options that can then // be applied later on with the internal -profile option. #define MAX_PROFILE_DEPTH 20 // Maximal include depth. #define MAX_RECURSION_DEPTH 8 struct m_profile { struct m_profile *next; char *name; char *desc; int num_opts; // Option/value pair array. char **opts; }; // In the file local case, this contains the old global value. struct m_opt_backup { struct m_opt_backup *next; struct m_config_option *co; void *backup; }; static int parse_include(struct m_config *config, struct bstr param, bool set, int flags) { if (param.len == 0) return M_OPT_MISSING_PARAM; if (!set) return 1; if (config->recursion_depth >= MAX_RECURSION_DEPTH) { MP_ERR(config, "Maximum 'include' nesting depth exceeded.\n"); return M_OPT_INVALID; } char *filename = bstrdup0(NULL, param); config->recursion_depth += 1; config->includefunc(config->includefunc_ctx, filename, flags); config->recursion_depth -= 1; talloc_free(filename); return 1; } static int parse_profile(struct m_config *config, const struct m_option *opt, struct bstr name, struct bstr param, bool set, int flags) { if (!bstrcmp0(param, "help")) { struct m_profile *p; if (!config->profiles) { MP_INFO(config, "No profiles have been defined.\n"); return M_OPT_EXIT - 1; } MP_INFO(config, "Available profiles:\n"); for (p = config->profiles; p; p = p->next) MP_INFO(config, "\t%s\t%s\n", p->name, p->desc ? p->desc : ""); MP_INFO(config, "\n"); return M_OPT_EXIT - 1; } char **list = NULL; int r = m_option_type_string_list.parse(config->log, opt, name, param, &list); if (r < 0) return r; if (!list || !list[0]) return M_OPT_INVALID; for (int i = 0; list[i]; i++) { if (set) r = m_config_set_profile(config, list[i], flags); if (r < 0) break; } m_option_free(opt, &list); return r; } static int show_profile(struct m_config *config, bstr param) { struct m_profile *p; if (!param.len) return M_OPT_MISSING_PARAM; if (!(p = m_config_get_profile(config, param))) { MP_ERR(config, "Unknown profile '%.*s'.\n", BSTR_P(param)); return M_OPT_EXIT - 1; } if (!config->profile_depth) MP_INFO(config, "Profile %s: %s\n", p->name, p->desc ? p->desc : ""); config->profile_depth++; for (int i = 0; i < p->num_opts; i++) { MP_INFO(config, "%*s%s=%s\n", config->profile_depth, "", p->opts[2 * i], p->opts[2 * i + 1]); if (config->profile_depth < MAX_PROFILE_DEPTH && !strcmp(p->opts[2*i], "profile")) { char *e, *list = p->opts[2 * i + 1]; while ((e = strchr(list, ','))) { int l = e - list; if (!l) continue; show_profile(config, (bstr){list, e - list}); list = e + 1; } if (list[0] != '\0') show_profile(config, bstr0(list)); } } config->profile_depth--; if (!config->profile_depth) MP_INFO(config, "\n"); return M_OPT_EXIT - 1; } static int list_options(struct m_config *config) { m_config_print_option_list(config); return M_OPT_EXIT; } // The memcpys are supposed to work around the strict aliasing violation, // that would result if we just dereferenced a void** (where the void** is // actually casted from struct some_type* ). The dummy struct type is in // theory needed, because void* and struct pointers could have different // representations, while pointers to different struct types don't. static void *substruct_read_ptr(const void *ptr) { struct mp_dummy_ *res; memcpy(&res, ptr, sizeof(res)); return res; } static void substruct_write_ptr(void *ptr, void *val) { struct mp_dummy_ *src = val; memcpy(ptr, &src, sizeof(src)); } static void add_options(struct m_config *config, const char *parent_name, void *optstruct, const void *optstruct_def, const struct m_option *defs); static void config_destroy(void *p) { struct m_config *config = p; m_config_restore_backups(config); for (int n = 0; n < config->num_opts; n++) m_option_free(config->opts[n].opt, config->opts[n].data); } struct m_config *m_config_new(void *talloc_ctx, struct mp_log *log, size_t size, const void *defaults, const struct m_option *options) { struct m_config *config = talloc(talloc_ctx, struct m_config); talloc_set_destructor(config, config_destroy); *config = (struct m_config) {.log = log, .size = size, .defaults = defaults, .options = options}; // size==0 means a dummy object is created if (size) { config->optstruct = talloc_zero_size(config, size); if (defaults) memcpy(config->optstruct, defaults, size); } if (options) add_options(config, "", config->optstruct, defaults, options); return config; } struct m_config *m_config_from_obj_desc(void *talloc_ctx, struct mp_log *log, struct m_obj_desc *desc) { return m_config_new(talloc_ctx, log, desc->priv_size, desc->priv_defaults, desc->options); } // Like m_config_from_obj_desc(), but don't allocate option struct. struct m_config *m_config_from_obj_desc_noalloc(void *talloc_ctx, struct mp_log *log, struct m_obj_desc *desc) { return m_config_new(talloc_ctx, log, 0, desc->priv_defaults, desc->options); } int m_config_set_obj_params(struct m_config *conf, char **args) { for (int n = 0; args && args[n * 2 + 0]; n++) { int r = m_config_set_option(conf, bstr0(args[n * 2 + 0]), bstr0(args[n * 2 + 1])); if (r < 0) return r; } return 0; } int m_config_apply_defaults(struct m_config *config, const char *name, struct m_obj_settings *defaults) { int r = 0; for (int n = 0; defaults && defaults[n].name; n++) { struct m_obj_settings *entry = &defaults[n]; if (name && strcmp(entry->name, name) == 0) { r = m_config_set_obj_params(config, entry->attribs); break; } } return r; } static void ensure_backup(struct m_config *config, struct m_config_option *co) { if (co->opt->type->flags & M_OPT_TYPE_HAS_CHILD) return; if (co->opt->flags & M_OPT_GLOBAL) return; if (!co->data) return; for (struct m_opt_backup *cur = config->backup_opts; cur; cur = cur->next) { if (cur->co->data == co->data) // comparing data ptr catches aliases return; } struct m_opt_backup *bc = talloc_ptrtype(NULL, bc); *bc = (struct m_opt_backup) { .co = co, .backup = talloc_zero_size(bc, co->opt->type->size), }; m_option_copy(co->opt, bc->backup, co->data); bc->next = config->backup_opts; config->backup_opts = bc; co->is_set_locally = true; } void m_config_restore_backups(struct m_config *config) { while (config->backup_opts) { struct m_opt_backup *bc = config->backup_opts; config->backup_opts = bc->next; m_option_copy(bc->co->opt, bc->co->data, bc->backup); m_option_free(bc->co->opt, bc->backup); bc->co->is_set_locally = false; talloc_free(bc); } } void m_config_backup_opt(struct m_config *config, const char *opt) { struct m_config_option *co = m_config_get_co(config, bstr0(opt)); if (co) { ensure_backup(config, co); } else { MP_ERR(config, "Option %s not found.\n", opt); } } void m_config_backup_all_opts(struct m_config *config) { for (int n = 0; n < config->num_opts; n++) ensure_backup(config, &config->opts[n]); } // Given an option --opt, add --no-opt (if applicable). static void add_negation_option(struct m_config *config, struct m_config_option *orig, const char *parent_name) { const struct m_option *opt = orig->opt; int value; if (opt->type == CONF_TYPE_FLAG) { value = 0; } else if (opt->type == CONF_TYPE_CHOICE) { // Find out whether there's a "no" choice. // m_option_parse() should be used for this, but it prints // unsilenceable error messages. struct m_opt_choice_alternatives *alt = opt->priv; for ( ; alt->name; alt++) { if (strcmp(alt->name, "no") == 0) break; } if (!alt->name) return; value = alt->value; } else { return; } struct m_option *no_opt = talloc_ptrtype(config, no_opt); *no_opt = (struct m_option) { .name = opt->name, .type = CONF_TYPE_STORE, .flags = opt->flags & (M_OPT_NOCFG | M_OPT_GLOBAL | M_OPT_PRE_PARSE), .offset = opt->offset, .max = value, }; // Add --no-sub-opt struct m_config_option co = *orig; co.name = talloc_asprintf(config, "no-%s", orig->name); co.opt = no_opt; co.is_generated = true; MP_TARRAY_APPEND(config, config->opts, config->num_opts, co); // Add --sub-no-opt (unfortunately needed for: "--sub=...:no-opt") if (parent_name[0]) { co.name = talloc_asprintf(config, "%s-no-%s", parent_name, opt->name); MP_TARRAY_APPEND(config, config->opts, config->num_opts, co); } } static void m_config_add_option(struct m_config *config, const char *parent_name, void *optstruct, const void *optstruct_def, const struct m_option *arg); static void add_options(struct m_config *config, const char *parent_name, void *optstruct, const void *optstruct_def, const struct m_option *defs) { for (int i = 0; defs && defs[i].name; i++) m_config_add_option(config, parent_name, optstruct, optstruct_def, &defs[i]); } // Initialize a field with a given value. In case this is dynamic data, it has // to be allocated and copied. src can alias dst, also can be NULL. static void init_opt_inplace(const struct m_option *opt, void *dst, const void *src) { union m_option_value temp = {0}; if (src) memcpy(&temp, src, opt->type->size); memset(dst, 0, opt->type->size); m_option_copy(opt, dst, &temp); } static void m_config_add_option(struct m_config *config, const char *parent_name, void *optstruct, const void *optstruct_def, const struct m_option *arg) { assert(config != NULL); assert(arg != NULL); struct m_config_option co = { .opt = arg, .name = arg->name, }; if (arg->offset >= 0) { if (optstruct) co.data = (char *)optstruct + arg->offset; if (optstruct_def) co.default_data = (char *)optstruct_def + arg->offset; } if (arg->defval) co.default_data = arg->defval; if (!co.default_data) co.default_data = &default_value; // Fill in the full name if (!co.name[0]) { co.name = parent_name; } else if (parent_name[0]) { co.name = talloc_asprintf(config, "%s-%s", parent_name, co.name); } // Option with children -> add them if (arg->type->flags & M_OPT_TYPE_HAS_CHILD) { const struct m_sub_options *subopts = arg->priv; void *new_optstruct = NULL; if (co.data) { new_optstruct = m_config_alloc_struct(config, subopts); substruct_write_ptr(co.data, new_optstruct); } const void *new_optstruct_def = substruct_read_ptr(co.default_data); if (!new_optstruct_def) new_optstruct_def = subopts->defaults; add_options(config, co.name, new_optstruct, new_optstruct_def, subopts->opts); } else { // Initialize options if (co.data && co.default_data) { if (arg->type->flags & M_OPT_TYPE_DYNAMIC) { // Would leak memory by overwriting *co.data repeatedly. for (int i = 0; i < config->num_opts; i++) { if (co.data == config->opts[i].data) assert(0); } } init_opt_inplace(arg, co.data, co.default_data); } } if (arg->name[0]) // no own name -> hidden MP_TARRAY_APPEND(config, config->opts, config->num_opts, co); add_negation_option(config, &co, parent_name); if (co.opt->type == &m_option_type_alias) { co.is_generated = true; // hide it const char *alias = (const char *)co.opt->priv; char no_alias[40]; snprintf(no_alias, sizeof(no_alias), "no-%s", alias); if (m_config_get_co(config, bstr0(no_alias))) { struct m_option *new = talloc_zero(config, struct m_option); new->name = talloc_asprintf(config, "no-%s", co.name); new->priv = talloc_strdup(config, no_alias); new->type = &m_option_type_alias; new->offset = -1; m_config_add_option(config, "", NULL, NULL, new); } } if (co.opt->type == &m_option_type_removed) co.is_generated = true; // hide it } struct m_config_option *m_config_get_co(const struct m_config *config, struct bstr name) { if (!name.len) return NULL; for (int n = 0; n < config->num_opts; n++) { struct m_config_option *co = &config->opts[n]; struct bstr coname = bstr0(co->name); bool matches = false; if ((co->opt->type->flags & M_OPT_TYPE_ALLOW_WILDCARD) && bstr_endswith0(coname, "*")) { coname.len--; if (bstrcmp(bstr_splice(name, 0, coname.len), coname) == 0) matches = true; } else if (bstrcmp(coname, name) == 0) matches = true; if (matches) { const char *prefix = config->is_toplevel ? "--" : ""; if (co->opt->type == &m_option_type_alias) { const char *alias = (const char *)co->opt->priv; if (!co->warning_was_printed) { MP_WARN(config, "Warning: option %s%s was replaced with " "%s%s and might be removed in the future.\n", prefix, co->name, prefix, alias); co->warning_was_printed = true; } return m_config_get_co(config, bstr0(alias)); } else if (co->opt->type == &m_option_type_removed) { if (!co->warning_was_printed) { char *msg = co->opt->priv; if (msg) { MP_FATAL(config, "Option %s%s was removed: %s\n", prefix, co->name, msg); } else { MP_FATAL(config, "Option %s%s was removed.\n", prefix, co->name); } co->warning_was_printed = true; } return NULL; } else if (co->opt->deprecation_message) { if (!co->warning_was_printed) { MP_WARN(config, "Warning: option %s%s is deprecated " "and might be removed in the future (%s).\n", prefix, co->name, co->opt->deprecation_message); co->warning_was_printed = true; } } return co; } } return NULL; } const char *m_config_get_positional_option(const struct m_config *config, int p) { int pos = 0; for (int n = 0; n < config->num_opts; n++) { struct m_config_option *co = &config->opts[n]; if (!co->is_generated) { if (pos == p) return co->name; pos++; } } return NULL; } // return: <0: M_OPT_ error, 0: skip, 1: check, 2: set static int handle_set_opt_flags(struct m_config *config, struct m_config_option *co, int flags) { int optflags = co->opt->flags; bool set = !(flags & M_SETOPT_CHECK_ONLY); if ((flags & M_SETOPT_PRE_PARSE_ONLY) && !(optflags & M_OPT_PRE_PARSE)) return 0; if ((flags & M_SETOPT_PRESERVE_CMDLINE) && co->is_set_from_cmdline) set = false; if ((flags & M_SETOPT_NO_FIXED) && (optflags & M_OPT_FIXED)) return M_OPT_INVALID; if ((flags & M_SETOPT_NO_PRE_PARSE) && (optflags & M_OPT_PRE_PARSE)) return M_OPT_INVALID; // Check if this option isn't forbidden in the current mode if ((flags & M_SETOPT_FROM_CONFIG_FILE) && (optflags & M_OPT_NOCFG)) { MP_ERR(config, "The %s option can't be used in a config file.\n", co->name); return M_OPT_INVALID; } if (flags & M_SETOPT_BACKUP) { if (optflags & M_OPT_GLOBAL) { MP_ERR(config, "The %s option is global and can't be set per-file.\n", co->name); return M_OPT_INVALID; } if (set) ensure_backup(config, co); } return set ? 2 : 1; } static void handle_on_set(struct m_config *config, struct m_config_option *co, int flags) { if (flags & M_SETOPT_FROM_CMDLINE) { co->is_set_from_cmdline = true; // Mark aliases too if (co->data) { for (int n = 0; n < config->num_opts; n++) { struct m_config_option *co2 = &config->opts[n]; if (co2->data == co->data) co2->is_set_from_cmdline = true; } } } if (config->global && (co->opt->flags & M_OPT_TERM)) mp_msg_update_msglevels(config->global); } // The type data points to is as in: m_config_get_co(config, name)->opt int m_config_set_option_raw(struct m_config *config, struct m_config_option *co, void *data, int flags) { if (!co) return M_OPT_UNKNOWN; // This affects some special options like "include", "profile". Maybe these // should work, or maybe not. For now they would require special code. if (!co->data) return M_OPT_UNKNOWN; int r = handle_set_opt_flags(config, co, flags); if (r <= 1) return r; m_option_copy(co->opt, co->data, data); handle_on_set(config, co, flags); return 0; } static int parse_subopts(struct m_config *config, char *name, char *prefix, struct bstr param, int flags); static int m_config_parse_option(struct m_config *config, struct bstr name, struct bstr param, int flags) { assert(config != NULL); struct m_config_option *co = m_config_get_co(config, name); if (!co) return M_OPT_UNKNOWN; // This is the only mandatory function assert(co->opt->type->parse); int r = handle_set_opt_flags(config, co, flags); if (r <= 0) return r; bool set = r == 2; if (set) { MP_VERBOSE(config, "Setting option '%.*s' = '%.*s' (flags = %d)\n", BSTR_P(name), BSTR_P(param), flags); } if (config->includefunc && bstr_equals0(name, "include")) return parse_include(config, param, set, flags); if (config->use_profiles && bstr_equals0(name, "profile")) return parse_profile(config, co->opt, name, param, set, flags); if (config->use_profiles && bstr_equals0(name, "show-profile")) return show_profile(config, param); if (bstr_equals0(name, "list-options")) return list_options(config); // Option with children are a bit different to parse if (co->opt->type->flags & M_OPT_TYPE_HAS_CHILD) { char prefix[110]; assert(strlen(co->name) < 100); sprintf(prefix, "%s-", co->name); return parse_subopts(config, (char *)co->name, prefix, param, flags); } r = m_option_parse(config->log, co->opt, name, param, set ? co->data : NULL); if (r >= 0 && set) handle_on_set(config, co, flags); return r; } static int parse_subopts(struct m_config *config, char *name, char *prefix, struct bstr param, int flags) { char **lst = NULL; // Split the argument into child options int r = m_option_type_subconfig.parse(config->log, NULL, bstr0(""), param, &lst); if (r < 0) return r; // Parse the child options for (int i = 0; lst && lst[2 * i]; i++) { // Build the full name char n[110]; if (snprintf(n, 110, "%s%s", prefix, lst[2 * i]) > 100) abort(); r = m_config_parse_option(config,bstr0(n), bstr0(lst[2 * i + 1]), flags); if (r < 0) { if (r > M_OPT_EXIT) { MP_ERR(config, "Error parsing suboption %s/%s (%s)\n", name, lst[2 * i], m_option_strerror(r)); r = M_OPT_INVALID; } break; } } talloc_free(lst); return r; } int m_config_parse_suboptions(struct m_config *config, char *name, char *subopts) { if (!subopts || !*subopts) return 0; int r = parse_subopts(config, name, "", bstr0(subopts), 0); if (r < 0 && r > M_OPT_EXIT) { MP_ERR(config, "Error parsing suboption %s (%s)\n", name, m_option_strerror(r)); r = M_OPT_INVALID; } return r; } int m_config_set_option_ext(struct m_config *config, struct bstr name, struct bstr param, int flags) { int r = m_config_parse_option(config, name, param, flags); if (r < 0 && r > M_OPT_EXIT) { MP_ERR(config, "Error parsing option %.*s (%s)\n", BSTR_P(name), m_option_strerror(r)); r = M_OPT_INVALID; } return r; } int m_config_set_option(struct m_config *config, struct bstr name, struct bstr param) { return m_config_set_option_ext(config, name, param, 0); } int m_config_set_option_node(struct m_config *config, bstr name, struct mpv_node *data, int flags) { struct m_config_option *co = m_config_get_co(config, name); if (!co) return M_OPT_UNKNOWN; int r; // Do this on an "empty" type to make setting the option strictly overwrite // the old value, as opposed to e.g. appending to lists. union m_option_value val = {0}; if (data->format == MPV_FORMAT_STRING) { bstr param = bstr0(data->u.string); r = m_option_parse(mp_null_log, co->opt, name, param, &val); } else { r = m_option_set_node(co->opt, &val, data); } if (r >= 0) r = m_config_set_option_raw(config, co, &val, flags); if (mp_msg_test(config->log, MSGL_V)) { char *s = m_option_type_node.print(NULL, data); MP_VERBOSE(config, "Setting option '%.*s' = %s (flags = %d) -> %d\n", BSTR_P(name), s ? s : "?", flags, r); talloc_free(s); } m_option_free(co->opt, &val); return r; } const struct m_option *m_config_get_option(const struct m_config *config, struct bstr name) { assert(config != NULL); struct m_config_option *co = m_config_get_co(config, name); return co ? co->opt : NULL; } int m_config_option_requires_param(struct m_config *config, bstr name) { const struct m_option *opt = m_config_get_option(config, name); if (opt) { if (bstr_endswith0(name, "-clr")) return 0; return m_option_required_params(opt); } return M_OPT_UNKNOWN; } static int sort_opt_compare(const void *pa, const void *pb) { const struct m_config_option *a = pa; const struct m_config_option *b = pb; return strcasecmp(a->name, b->name); } void m_config_print_option_list(const struct m_config *config) { char min[50], max[50]; int count = 0; const char *prefix = config->is_toplevel ? "--" : ""; struct m_config_option *sorted = talloc_memdup(NULL, config->opts, config->num_opts * sizeof(sorted[0])); if (config->is_toplevel) qsort(sorted, config->num_opts, sizeof(sorted[0]), sort_opt_compare); MP_INFO(config, "Options:\n\n"); for (int i = 0; i < config->num_opts; i++) { struct m_config_option *co = &sorted[i]; const struct m_option *opt = co->opt; if (opt->type->flags & M_OPT_TYPE_HAS_CHILD) continue; if (co->is_generated) continue; if (opt->type == &m_option_type_alias || opt->type == &m_option_type_removed) continue; MP_INFO(config, " %s%-30s", prefix, co->name); if (opt->type == &m_option_type_choice) { MP_INFO(config, " Choices:"); struct m_opt_choice_alternatives *alt = opt->priv; for (int n = 0; alt[n].name; n++) MP_INFO(config, " %s", alt[n].name); if (opt->flags & (M_OPT_MIN | M_OPT_MAX)) MP_INFO(config, " (or an integer)"); } else { MP_INFO(config, " %s", co->opt->type->name); } if (opt->flags & (M_OPT_MIN | M_OPT_MAX)) { snprintf(min, sizeof(min), "any"); snprintf(max, sizeof(max), "any"); if (opt->flags & M_OPT_MIN) snprintf(min, sizeof(min), "%.14g", opt->min); if (opt->flags & M_OPT_MAX) snprintf(max, sizeof(max), "%.14g", opt->max); MP_INFO(config, " (%s to %s)", min, max); } char *def = NULL; if (co->default_data) def = m_option_print(co->opt, co->default_data); if (def) { MP_INFO(config, " (default: %s)", def); talloc_free(def); } if (opt->flags & M_OPT_GLOBAL) MP_INFO(config, " [global]"); if (opt->flags & M_OPT_NOCFG) MP_INFO(config, " [nocfg]"); if (opt->flags & M_OPT_FILE) MP_INFO(config, " [file]"); MP_INFO(config, "\n"); count++; } MP_INFO(config, "\nTotal: %d options\n", count); talloc_free(sorted); } char **m_config_list_options(void *ta_parent, const struct m_config *config) { char **list = talloc_new(ta_parent); int count = 0; for (int i = 0; i < config->num_opts; i++) { struct m_config_option *co = &config->opts[i]; const struct m_option *opt = co->opt; if (opt->type->flags & M_OPT_TYPE_HAS_CHILD) continue; if (co->is_generated) continue; // For use with CONF_TYPE_STRING_LIST, it's important not to set list // as allocation parent. char *s = talloc_strdup(ta_parent, co->name); MP_TARRAY_APPEND(ta_parent, list, count, s); } MP_TARRAY_APPEND(ta_parent, list, count, NULL); return list; } struct m_profile *m_config_get_profile(const struct m_config *config, bstr name) { for (struct m_profile *p = config->profiles; p; p = p->next) { if (bstr_equals0(name, p->name)) return p; } return NULL; } struct m_profile *m_config_get_profile0(const struct m_config *config, char *name) { return m_config_get_profile(config, bstr0(name)); } struct m_profile *m_config_add_profile(struct m_config *config, char *name) { if (!name || !name[0] || strcmp(name, "default") == 0) return NULL; // never a real profile struct m_profile *p = m_config_get_profile0(config, name); if (p) return p; p = talloc_zero(config, struct m_profile); p->name = talloc_strdup(p, name); p->next = config->profiles; config->profiles = p; return p; } void m_profile_set_desc(struct m_profile *p, bstr desc) { talloc_free(p->desc); p->desc = bstrdup0(p, desc); } int m_config_set_profile_option(struct m_config *config, struct m_profile *p, bstr name, bstr val) { int i = m_config_set_option_ext(config, name, val, M_SETOPT_CHECK_ONLY | M_SETOPT_FROM_CONFIG_FILE); if (i < 0) return i; p->opts = talloc_realloc(p, p->opts, char *, 2 * (p->num_opts + 2)); p->opts[p->num_opts * 2] = bstrdup0(p, name); p->opts[p->num_opts * 2 + 1] = bstrdup0(p, val); p->num_opts++; p->opts[p->num_opts * 2] = p->opts[p->num_opts * 2 + 1] = NULL; return 1; } int m_config_set_profile(struct m_config *config, char *name, int flags) { struct m_profile *p = m_config_get_profile0(config, name); if (!p) { MP_WARN(config, "Unknown profile '%s'.\n", name); return M_OPT_INVALID; } if (config->profile_depth > MAX_PROFILE_DEPTH) { MP_WARN(config, "WARNING: Profile inclusion too deep.\n"); return M_OPT_UNKNOWN; } config->profile_depth++; for (int i = 0; i < p->num_opts; i++) { m_config_set_option_ext(config, bstr0(p->opts[2 * i]), bstr0(p->opts[2 * i + 1]), flags | M_SETOPT_FROM_CONFIG_FILE); } config->profile_depth--; return 0; } void *m_config_alloc_struct(void *talloc_ctx, const struct m_sub_options *subopts) { void *substruct = talloc_zero_size(talloc_ctx, subopts->size); if (subopts->defaults) memcpy(substruct, subopts->defaults, subopts->size); return substruct; } struct dtor_info { const struct m_sub_options *opts; void *ptr; }; static void free_substruct(void *ptr) { struct dtor_info *d = ptr; for (int n = 0; d->opts->opts && d->opts->opts[n].type; n++) { const struct m_option *opt = &d->opts->opts[n]; void *dst = (char *)d->ptr + opt->offset; m_option_free(opt, dst); } } // Passing ptr==NULL initializes it from proper defaults. void *m_sub_options_copy(void *talloc_ctx, const struct m_sub_options *opts, const void *ptr) { void *new = m_config_alloc_struct(talloc_ctx, opts); struct dtor_info *dtor = talloc_ptrtype(new, dtor); *dtor = (struct dtor_info){opts, new}; talloc_set_destructor(dtor, free_substruct); for (int n = 0; opts->opts && opts->opts[n].type; n++) { const struct m_option *opt = &opts->opts[n]; if (opt->offset < 0) continue; void *src = ptr ? (char *)ptr + opt->offset : NULL; void *dst = (char *)new + opt->offset; if (opt->type->flags & M_OPT_TYPE_HAS_CHILD) { // Specifying a default struct for a sub-option field in the // containing struct's default struct is not supported here. // (Out of laziness. Could possibly be supported.) assert(!substruct_read_ptr(dst)); const struct m_sub_options *subopts = opt->priv; const void *sub_src = NULL; if (src) sub_src = substruct_read_ptr(src); if (!sub_src) sub_src = subopts->defaults; void *sub_dst = m_sub_options_copy(new, subopts, sub_src); substruct_write_ptr(dst, sub_dst); } else { init_opt_inplace(opt, dst, src); } } return new; } struct m_config *m_config_dup(void *talloc_ctx, struct m_config *config) { struct m_config *new = m_config_new(talloc_ctx, config->log, config->size, config->defaults, config->options); assert(new->num_opts == config->num_opts); for (int n = 0; n < new->num_opts; n++) { assert(new->opts[n].opt->type == config->opts[n].opt->type); m_option_copy(new->opts[n].opt, new->opts[n].data, config->opts[n].data); } return new; }
Floens/mpv
options/m_config.c
C
gpl-2.0
33,574
#include <dfsch/lib/crypto.h> static void ecb_setup(dfsch_block_cipher_mode_context_t* cipher, uint8_t* iv, size_t iv_len){ if (iv_len != 0){ dfsch_error("ECB mode has no IV", NULL); } } static void ecb_encrypt(dfsch_block_cipher_mode_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->cipher->cipher->block_size; int i; for (i = 0; i < blocks; i++){ context->cipher->cipher->encrypt(context->cipher, in + (bsize * i), out + (bsize * i)); } } static void ecb_decrypt(dfsch_block_cipher_mode_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->cipher->cipher->block_size; int i; for (i = 0; i < blocks; i++){ context->cipher->cipher->decrypt(context->cipher, in + (bsize * i), out + (bsize * i)); } } dfsch_block_cipher_mode_t dfsch_crypto_ecb_mode = { .type = { .type = DFSCH_BLOCK_CIPHER_MODE_TYPE, .name = "crypto:ecb", .size = sizeof(dfsch_block_cipher_mode_context_t), }, .name = "ECB", .encrypt = ecb_encrypt, .decrypt = ecb_decrypt, .setup = ecb_setup }; static void memxor(uint8_t* dst, uint8_t* src, size_t count){ while (count){ *dst ^= *src; dst++; src++; count--; } } typedef struct cbc_context_t { dfsch_block_cipher_mode_context_t parent; uint8_t* iv; } cbc_context_t; static void cbc_setup(cbc_context_t* context, uint8_t* iv, size_t iv_len){ if (iv_len != context->parent.cipher->cipher->block_size){ dfsch_error("CBC IV length must be equal to block size", NULL); } context->iv = GC_MALLOC_ATOMIC(iv_len); memcpy(context->iv, iv, iv_len); } static void cbc_encrypt(cbc_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->parent.cipher->cipher->block_size; int i; for (i = 0; i < blocks; i++){ memxor(context->iv, in + (bsize * i), bsize); context->parent.cipher->cipher->encrypt(context->parent.cipher, context->iv, context->iv); memcpy(out + (bsize * i), context->iv, bsize); } } static void cbc_decrypt(cbc_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->parent.cipher->cipher->block_size; int i; uint8_t tmp[bsize]; for (i = 0; i < blocks; i++){ memcpy(tmp, in + (bsize * i), bsize); context->parent.cipher->cipher->decrypt(context->parent.cipher, in + (bsize * i), out + (bsize * i)); memxor(out + (bsize * i), context->iv, bsize); memcpy(context->iv, tmp, bsize); } } dfsch_block_cipher_mode_t dfsch_crypto_cbc_mode = { .type = { .type = DFSCH_BLOCK_CIPHER_MODE_TYPE, .name = "crypto:cbc", .size = sizeof(cbc_context_t), }, .name = "CBC", .encrypt = cbc_encrypt, .decrypt = cbc_decrypt, .setup = cbc_setup }; typedef struct cfb_context_t { dfsch_block_cipher_mode_context_t parent; uint8_t* iv; } cfb_context_t; static void cfb_setup(cfb_context_t* context, uint8_t* iv, size_t iv_len){ if (iv_len != context->parent.cipher->cipher->block_size){ dfsch_error("CFB IV length must be equal to block size", NULL); } context->iv = GC_MALLOC_ATOMIC(iv_len); memcpy(context->iv, iv, iv_len); } static void cfb_encrypt(cfb_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->parent.cipher->cipher->block_size; int i; for (i = 0; i < blocks; i++){ context->parent.cipher->cipher->encrypt(context->parent.cipher, context->iv, context->iv); memxor(context->iv, in + (bsize * i), bsize); memcpy(out + (bsize * i), context->iv, bsize); } } static void cfb_decrypt(cfb_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->parent.cipher->cipher->block_size; int i; uint8_t tmp[bsize]; for (i = 0; i < blocks; i++){ memcpy(tmp, in + (bsize * i), bsize); context->parent.cipher->cipher->encrypt(context->parent.cipher, context->iv, out + (bsize * i)); memxor(out + (bsize * i), tmp, bsize); memcpy(context->iv, tmp, bsize); } } dfsch_block_cipher_mode_t dfsch_crypto_cfb_mode = { .type = { .type = DFSCH_BLOCK_CIPHER_MODE_TYPE, .name = "crypto:cfb", .size = sizeof(cfb_context_t), }, .name = "CFB", .encrypt = cfb_encrypt, .decrypt = cfb_decrypt, .setup = cfb_setup }; typedef struct ofb_context_t { dfsch_block_cipher_mode_context_t parent; uint8_t* iv; } ofb_context_t; static void ofb_setup(ofb_context_t* context, uint8_t* iv, size_t iv_len){ if (iv_len != context->parent.cipher->cipher->block_size){ dfsch_error("OFB IV length must be equal to block size", NULL); } context->iv = GC_MALLOC_ATOMIC(iv_len); memcpy(context->iv, iv, iv_len); } static void ofb_operate(ofb_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->parent.cipher->cipher->block_size; int i; for (i = 0; i < blocks; i++){ context->parent.cipher->cipher->encrypt(context->parent.cipher, context->iv, context->iv); memcpy(out + (bsize * i), in + (bsize * i), bsize); memxor(out + (bsize * i), context->iv, bsize); } } dfsch_block_cipher_mode_t dfsch_crypto_ofb_mode = { .type = { .type = DFSCH_BLOCK_CIPHER_MODE_TYPE, .name = "crypto:ofb", .size = sizeof(ofb_context_t), }, .name = "OFB", .encrypt = ofb_operate, .decrypt = ofb_operate, .setup = ofb_setup }; /* This implementation of CTR mode comes from NIST recommendation, which is different in significant details from AES-CTR used by TLS and IPsec (which are even mutually different). CTR mode can use various additional data from underlying protocol, which unfortunately means that each protocol uses completely different method of construing CTR value */ typedef struct ctr_context_t { dfsch_block_cipher_mode_context_t parent; uint8_t* ctr; } ctr_context_t; static void ctr_setup(ctr_context_t* context, uint8_t* iv, size_t iv_len){ if (iv_len != context->parent.cipher->cipher->block_size){ dfsch_error("CTR IV length must be equal to block size", NULL); } context->ctr = GC_MALLOC_ATOMIC(iv_len); memcpy(context->ctr, iv, iv_len); } static void ctr_operate(ctr_context_t* context, uint8_t* in, uint8_t* out, size_t blocks){ size_t bsize = context->parent.cipher->cipher->block_size; int i; int j; uint8_t tmp[bsize]; for (i = 0; i < blocks; i++){ context->parent.cipher->cipher->encrypt(context->parent.cipher, context->ctr, tmp); memcpy(out + (bsize * i), in + (bsize * i), bsize); memxor(out + (bsize * i), tmp, bsize); /* Increment counter, little endian */ for (j = 0; j < bsize; j++){ context->ctr[j]++; if (context->ctr[j] != 0){ break; } } } } dfsch_block_cipher_mode_t dfsch_crypto_ctr_mode = { .type = { .type = DFSCH_BLOCK_CIPHER_MODE_TYPE, .name = "crypto:ctr", .size = sizeof(ctr_context_t), }, .name = "CTR", .encrypt = ctr_operate, .decrypt = ctr_operate, .setup = ctr_setup }; typedef struct block_stream_mode_t { dfsch_stream_cipher_t parent; dfsch_block_cipher_t* cipher; } block_stream_mode_t; dfsch_type_t dfsch_block_stream_mode_type = { .type = DFSCH_META_TYPE, .superclass = DFSCH_STREAM_CIPHER_TYPE, .name = "block-stream-mode", .size = sizeof(block_stream_mode_t), }; typedef struct block_stream_context_t { block_stream_mode_t* mode; dfsch_block_cipher_context_t* cipher; uint8_t* next_input; uint8_t* last_output; size_t output_offset; size_t output_size; } block_stream_context_t; static void bs_ofb_setup(block_stream_context_t* ctx, uint8_t *key, size_t keylen, uint8_t *nonce, size_t nonce_len){ if (nonce_len != ctx->mode->cipher->block_size){ dfsch_error("Nonce for OFB mode must be same size as cipher's block", NULL); } ctx->cipher = dfsch_setup_block_cipher(ctx->mode->cipher, key, keylen); ctx->next_input = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size); ctx->last_output = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size); ctx->output_offset = ctx->mode->cipher->block_size; ctx->output_size = ctx->mode->cipher->block_size; memcpy(ctx->next_input, nonce, ctx->output_size); } static void bs_ofb_encrypt_bytes(block_stream_context_t* ctx, uint8_t* out, size_t outlen){ while (outlen){ if (ctx->output_offset >= ctx->output_size){ ctx->cipher->cipher->encrypt(ctx->cipher, ctx->next_input, ctx->last_output); memcpy(ctx->next_input, ctx->last_output, ctx->output_size); ctx->output_offset = 0; } *out ^= ctx->last_output[ctx->output_offset]; ctx->output_offset++; out++; outlen--; } } dfsch_stream_cipher_t* dfsch_make_ofb_cipher(dfsch_block_cipher_t* cipher){ block_stream_mode_t* bs = dfsch_make_object(DFSCH_BLOCK_STREAM_MODE_TYPE); bs->parent.name = dfsch_saprintf("%s in OFB mode", cipher->name); bs->parent.type.name = dfsch_saprintf("%s-ofb", cipher->type.name); bs->parent.type.size = sizeof(block_stream_context_t); bs->parent.setup = bs_ofb_setup; bs->parent.encrypt_bytes = bs_ofb_encrypt_bytes; return bs; } static void bs_ctr_setup(block_stream_context_t* ctx, uint8_t *key, size_t keylen, uint8_t *nonce, size_t nonce_len){ if (nonce_len != ctx->mode->cipher->block_size){ dfsch_error("Nonce for OFB mode must be same size as cipher's block", NULL); } ctx->cipher = dfsch_setup_block_cipher(ctx->mode->cipher, key, keylen); ctx->next_input = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size); ctx->last_output = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size); ctx->output_offset = ctx->mode->cipher->block_size; ctx->output_size = ctx->mode->cipher->block_size; memcpy(ctx->next_input, nonce, ctx->output_size); } static void bs_ctr_encrypt_bytes(block_stream_context_t* ctx, uint8_t* out, size_t outlen){ int i; while (outlen){ if (ctx->output_offset >= ctx->output_size){ ctx->cipher->cipher->encrypt(ctx->cipher, ctx->next_input, ctx->last_output); for (i = 0; i < ctx->output_size; i++){ ctx->next_input[i]++; if (ctx->next_input[i] != 0){ break; } } ctx->output_offset = 0; } *out ^= ctx->last_output[ctx->output_offset]; ctx->output_offset++; out++; outlen--; } } dfsch_stream_cipher_t* dfsch_make_ctr_cipher(dfsch_block_cipher_t* cipher){ block_stream_mode_t* bs = dfsch_make_object(DFSCH_BLOCK_STREAM_MODE_TYPE); bs->parent.name = dfsch_saprintf("%s in CTR mode", cipher->name); bs->parent.type.name = dfsch_saprintf("%s-ctr", cipher->type.name); bs->parent.type.size = sizeof(block_stream_context_t); bs->parent.setup = bs_ctr_setup; bs->parent.encrypt_bytes = bs_ctr_encrypt_bytes; return bs; }
adh/dfsch
lib/crypto/modes.c
C
gpl-2.0
12,669
/* * arch/arm/mach-tegra/tegra3_dvfs.c * * Copyright (C) 2010-2011 NVIDIA Corporation. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/string.h> #include <linux/module.h> #include <linux/clk.h> #include <linux/kobject.h> #include <linux/err.h> #include "clock.h" #include "dvfs.h" #include "fuse.h" #include "board.h" #include "tegra3_emc.h" static bool tegra_dvfs_cpu_disabled; static bool tegra_dvfs_core_disabled; static struct dvfs *cpu_dvfs; static const int cpu_millivolts[MAX_DVFS_FREQS] = { 750, 800, 825, 850, 875, 900, 950, 975, 1000, 1025, 1050, 1100, 1200, 1275, 1275, 1275, 1300, 1325}; //750, 800, 825, 850, 875, 912, 975, 1000, 1025, 1050, 1075, 1100, 1150, 1200, 1212, 1225, 1250, 1300}; static const unsigned int cpu_cold_offs_mhz[MAX_DVFS_FREQS] = { 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50}; static const int core_millivolts[MAX_DVFS_FREQS] = { 900, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350}; #define KHZ 1000 #define MHZ 1000000 /* VDD_CPU >= (VDD_CORE - cpu_below_core) */ /* VDD_CORE >= min_level(VDD_CPU), see tegra3_get_core_floor_mv() below */ #define VDD_CPU_BELOW_VDD_CORE 300 static int cpu_below_core = VDD_CPU_BELOW_VDD_CORE; #define VDD_SAFE_STEP 100 static struct dvfs_rail tegra3_dvfs_rail_vdd_cpu = { .reg_id = "vdd_cpu", .max_millivolts = 1300, .min_millivolts = 750, .step = VDD_SAFE_STEP, .jmp_to_zero = true, }; static struct dvfs_rail tegra3_dvfs_rail_vdd_core = { .reg_id = "vdd_core", .max_millivolts = 1350, .min_millivolts = 900, .step = VDD_SAFE_STEP, }; static struct dvfs_rail *tegra3_dvfs_rails[] = { &tegra3_dvfs_rail_vdd_cpu, &tegra3_dvfs_rail_vdd_core, }; static int tegra3_get_core_floor_mv(int cpu_mv) { if (cpu_mv < 800) return 950; if (cpu_mv < 900) return 1000; if (cpu_mv < 1000) return 1100; if ((tegra_cpu_speedo_id() < 2) || (tegra_cpu_speedo_id() == 4) || (tegra_cpu_speedo_id() == 7) || (tegra_cpu_speedo_id() == 8)) return 1200; if (cpu_mv < 1100) return 1200; if (cpu_mv <= 1250) return 1300; BUG(); } /* vdd_core must be >= min_level as a function of vdd_cpu */ static int tegra3_dvfs_rel_vdd_cpu_vdd_core(struct dvfs_rail *vdd_cpu, struct dvfs_rail *vdd_core) { int core_floor = max(vdd_cpu->new_millivolts, vdd_cpu->millivolts); core_floor = tegra3_get_core_floor_mv(core_floor); return max(vdd_core->new_millivolts, core_floor); } /* vdd_cpu must be >= (vdd_core - cpu_below_core) */ static int tegra3_dvfs_rel_vdd_core_vdd_cpu(struct dvfs_rail *vdd_core, struct dvfs_rail *vdd_cpu) { int cpu_floor; if (vdd_cpu->new_millivolts == 0) return 0; /* If G CPU is off, core relations can be ignored */ cpu_floor = max(vdd_core->new_millivolts, vdd_core->millivolts) - cpu_below_core; return max(vdd_cpu->new_millivolts, cpu_floor); } static struct dvfs_relationship tegra3_dvfs_relationships[] = { { .from = &tegra3_dvfs_rail_vdd_cpu, .to = &tegra3_dvfs_rail_vdd_core, .solve = tegra3_dvfs_rel_vdd_cpu_vdd_core, .solved_at_nominal = true, }, { .from = &tegra3_dvfs_rail_vdd_core, .to = &tegra3_dvfs_rail_vdd_cpu, .solve = tegra3_dvfs_rel_vdd_core_vdd_cpu, }, }; #define CPU_DVFS(_clk_name, _speedo_id, _process_id, _mult, _freqs...) \ { \ .clk_name = _clk_name, \ .speedo_id = _speedo_id, \ .process_id = _process_id, \ .freqs = {_freqs}, \ .freqs_mult = _mult, \ .millivolts = cpu_millivolts, \ .auto_dvfs = true, \ .dvfs_rail = &tegra3_dvfs_rail_vdd_cpu, \ } static struct dvfs cpu_dvfs_table[] = { /* Cpu voltages (mV): 800, 825, 850, 875, 900, 912, 975, 1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1212, 1237 */ CPU_DVFS("cpu_g", 0, 0, MHZ, 1, 1, 684, 684, 817, 817, 1026, 1102, 1149, 1187, 1225, 1282, 1300), CPU_DVFS("cpu_g", 0, 1, MHZ, 1, 1, 807, 807, 948, 948, 1117, 1171, 1206, 1300), CPU_DVFS("cpu_g", 0, 2, MHZ, 1, 1, 883, 883, 1039, 1039, 1178, 1206, 1300), CPU_DVFS("cpu_g", 0, 3, MHZ, 1, 1, 931, 931, 1102, 1102, 1216, 1300), CPU_DVFS("cpu_g", 1, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1280, 1300), CPU_DVFS("cpu_g", 1, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1300), CPU_DVFS("cpu_g", 1, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1300), CPU_DVFS("cpu_g", 1, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1300), CPU_DVFS("cpu_g", 2, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1400), CPU_DVFS("cpu_g", 2, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1350, 1400), CPU_DVFS("cpu_g", 2, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1300, 1350, 1400), CPU_DVFS("cpu_g", 3, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1400), CPU_DVFS("cpu_g", 3, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1350, 1400), CPU_DVFS("cpu_g", 3, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1300, 1350, 1400), CPU_DVFS("cpu_g", 7, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1240, 1280, 1320, 1480, 1500, 1600), CPU_DVFS("cpu_g", 7, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1480, 1500, 1600), CPU_DVFS("cpu_g", 7, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1480, 1500, 1600), CPU_DVFS("cpu_g", 7, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1480, 1500, 1600), CPU_DVFS("cpu_g", 5, 2, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1540, 1600, 1650, 1700), CPU_DVFS("cpu_g", 5, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700), CPU_DVFS("cpu_g", 5, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700), CPU_DVFS("cpu_g", 6, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700), CPU_DVFS("cpu_g", 6, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700), CPU_DVFS("cpu_g", 4, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1240, 1280, 1320, 1360, 1600), CPU_DVFS("cpu_g", 4, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1360, 1500, 1600), CPU_DVFS("cpu_g", 4, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1340, 1480, 1600), CPU_DVFS("cpu_g", 4, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1270, 1300, 1340, 1480, 1600), CPU_DVFS("cpu_g", 4, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1300, 1340, 1480, 1600), CPU_DVFS("cpu_g", 8, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1280, 1300), CPU_DVFS("cpu_g", 8, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1300), CPU_DVFS("cpu_g", 8, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1300), CPU_DVFS("cpu_g", 8, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1300), CPU_DVFS("cpu_g", 8, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1300), CPU_DVFS("cpu_g", 9, -1, MHZ, 1, 1, 1, 1, 1, 900, 900, 900, 900, 900, 900, 900, 900, 900), CPU_DVFS("cpu_g", 10, -1, MHZ, 1, 1, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900), CPU_DVFS("cpu_g", 11, -1, MHZ, 1, 1, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600), CPU_DVFS("cpu_g", 12, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700), CPU_DVFS("cpu_g", 12, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700), CPU_DVFS("cpu_g", 13, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700), CPU_DVFS("cpu_g", 13, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700), /* * "Safe entry" to be used when no match for chip speedo, process * corner is found (just to boot at low rate); must be the last one */ CPU_DVFS("cpu_g", -1, -1, MHZ, 1, 1, 216, 216, 300), }; #define CORE_DVFS(_clk_name, _speedo_id, _auto, _mult, _freqs...) \ { \ .clk_name = _clk_name, \ .speedo_id = _speedo_id, \ .process_id = -1, \ .freqs = {_freqs}, \ .freqs_mult = _mult, \ .millivolts = core_millivolts, \ .auto_dvfs = _auto, \ .dvfs_rail = &tegra3_dvfs_rail_vdd_core, \ } static struct dvfs core_dvfs_table[] = { /* Core voltages (mV): 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350 */ /* Clock limits for internal blocks, PLLs */ CORE_DVFS("cpu_lp", 0, 1, KHZ, 1, 294000, 342000, 427000, 475000, 500000, 500000, 500000, 500000), CORE_DVFS("cpu_lp", 1, 1, KHZ, 204000, 294000, 342000, 427000, 475000, 500000, 500000, 500000, 500000), CORE_DVFS("cpu_lp", 2, 1, KHZ, 204000, 295000, 370000, 428000, 475000, 513000, 579000, 620000, 620000), CORE_DVFS("cpu_lp", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 450000, 450000, 450000), CORE_DVFS("emc", 0, 1, KHZ, 1, 266500, 266500, 266500, 266500, 533000, 533000, 533000, 533000), CORE_DVFS("emc", 1, 1, KHZ, 102000, 408000, 408000, 408000, 416000, 750000, 750000, 750000, 750000), CORE_DVFS("emc", 2, 1, KHZ, 102000, 408000, 408000, 408000, 416000, 750000, 750000, 800000, 900000), CORE_DVFS("emc", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 625000, 625000, 625000), CORE_DVFS("sbus", 0, 1, KHZ, 1, 136000, 164000, 191000, 216000, 216000, 216000, 216000, 216000), CORE_DVFS("sbus", 1, 1, KHZ, 51000, 205000, 205000, 227000, 227000, 267000, 267000, 267000, 267000), CORE_DVFS("sbus", 2, 1, KHZ, 51000, 205000, 205000, 227000, 227000, 267000, 334000, 334000, 334000), CORE_DVFS("sbus", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 378000, 378000, 378000), CORE_DVFS("vi", 0, 1, KHZ, 1, 216000, 285000, 300000, 300000, 300000, 300000, 300000, 300000), CORE_DVFS("vi", 1, 1, KHZ, 1, 216000, 267000, 300000, 371000, 409000, 409000, 409000, 409000), CORE_DVFS("vi", 2, 1, KHZ, 1, 219000, 267000, 300000, 371000, 409000, 425000, 425000, 425000), CORE_DVFS("vi", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 470000, 470000, 470000), CORE_DVFS("vde", 0, 1, KHZ, 1, 228000, 275000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("mpe", 0, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("2d", 0, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("epp", 0, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("3d", 0, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("3d2", 0, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("se", 0, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("vde", 1, 1, KHZ, 1, 228000, 275000, 332000, 380000, 416000, 484000, 520000, 666000), CORE_DVFS("mpe", 1, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 484000, 484000, 484000), CORE_DVFS("2d", 1, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 484000, 484000, 484000), CORE_DVFS("epp", 1, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 484000, 484000, 484000), CORE_DVFS("3d", 1, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 484000, 484000, 484000), CORE_DVFS("3d2", 1, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 484000, 484000, 484000), CORE_DVFS("se", 1, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 484000, 484000, 484000), CORE_DVFS("vde", 2, 1, KHZ, 1, 247000, 304000, 352000, 400000, 437000, 484000, 520000, 600000), CORE_DVFS("mpe", 2, 1, KHZ, 1, 247000, 304000, 361000, 408000, 446000, 484000, 520000, 600000), CORE_DVFS("2d", 2, 1, KHZ, 1, 267000, 304000, 361000, 408000, 446000, 484000, 520000, 600000), CORE_DVFS("epp", 2, 1, KHZ, 1, 267000, 304000, 361000, 408000, 446000, 484000, 520000, 600000), CORE_DVFS("3d", 2, 1, KHZ, 1, 247000, 304000, 361000, 408000, 446000, 484000, 520000, 600000), CORE_DVFS("3d2", 2, 1, KHZ, 1, 247000, 304000, 361000, 408000, 446000, 484000, 520000, 600000), CORE_DVFS("se", 2, 1, KHZ, 1, 267000, 304000, 361000, 408000, 446000, 484000, 520000, 600000), CORE_DVFS("vde", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000), CORE_DVFS("mpe", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000), CORE_DVFS("2d", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000), CORE_DVFS("epp", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000), CORE_DVFS("3d", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000), CORE_DVFS("3d2", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000), CORE_DVFS("se", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 625000, 625000, 625000), CORE_DVFS("host1x", 0, 1, KHZ, 1, 152000, 188000, 222000, 254000, 267000, 267000, 267000, 267000), CORE_DVFS("host1x", 1, 1, KHZ, 1, 152000, 188000, 222000, 254000, 267000, 267000, 267000, 267000), CORE_DVFS("host1x", 2, 1, KHZ, 1, 152000, 188000, 222000, 254000, 267000, 267000, 267000, 300000), CORE_DVFS("host1x", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 242000, 242000, 242000), CORE_DVFS("cbus", 0, 1, KHZ, 1, 228000, 275000, 332000, 380000, 416000, 416000, 416000, 416000), CORE_DVFS("cbus", 1, 1, KHZ, 1, 267000, 304000, 380000, 416000, 484000, 484000, 484000, 484000), CORE_DVFS("cbus", 2, 1, KHZ, 1, 247000, 304000, 352000, 400000, 437000, 484000, 520000, 600000), CORE_DVFS("cbus", 3, 1, KHZ, 1, 484000, 484000, 484000, 484000, 484000, 484000, 484000, 484000), CORE_DVFS("pll_c", -1, 1, KHZ, 533000, 667000, 667000, 800000, 800000, 1066000, 1066000, 1066000, 1200000), /* * PLLM dvfs is common across all speedo IDs with one special exception * for T30 and T33, rev A02+, provided PLLM usage is restricted. Both * common and restricted table are included, and table selection is * handled by is_pllm_dvfs() below. */ CORE_DVFS("pll_m", -1, 1, KHZ, 533000, 667000, 667000, 800000, 800000, 1066000, 1066000, 1066000, 1066000), #ifdef CONFIG_TEGRA_PLLM_RESTRICTED CORE_DVFS("pll_m", 2, 1, KHZ, 533000, 800000, 800000, 800000, 800000, 1066000, 1066000, 1066000, 1066000), #endif /* Core voltages (mV): 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350 */ /* Clock limits for I/O peripherals */ CORE_DVFS("mipi", 0, 1, KHZ, 1, 1, 1, 1, 1, 1, 1, 1, 1), CORE_DVFS("mipi", 1, 1, KHZ, 1, 1, 1, 1, 1, 60000, 60000, 60000, 60000), CORE_DVFS("mipi", 2, 1, KHZ, 1, 1, 1, 1, 1, 60000, 60000, 60000, 60000), CORE_DVFS("mipi", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 1, 1, 1), CORE_DVFS("fuse_burn", -1, 1, KHZ, 1, 1, 1, 1, 26000, 26000, 26000, 26000, 26000), CORE_DVFS("sdmmc1", -1, 1, KHZ, 104000, 104000, 104000, 104000, 104000, 208000, 208000, 208000, 208000), CORE_DVFS("sdmmc3", -1, 1, KHZ, 104000, 104000, 104000, 104000, 104000, 208000, 208000, 208000, 208000), CORE_DVFS("ndflash", -1, 1, KHZ, 1, 120000, 120000, 120000, 200000, 200000, 200000, 200000, 200000), CORE_DVFS("nor", 0, 1, KHZ, 1, 115000, 130000, 130000, 133000, 133000, 133000, 133000, 133000), CORE_DVFS("nor", 1, 1, KHZ, 1, 115000, 130000, 130000, 133000, 133000, 133000, 133000, 133000), CORE_DVFS("nor", 2, 1, KHZ, 1, 115000, 130000, 130000, 133000, 133000, 133000, 133000, 133000), CORE_DVFS("nor", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 108000, 108000, 108000), CORE_DVFS("sbc1", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000), CORE_DVFS("sbc2", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000), CORE_DVFS("sbc3", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000), CORE_DVFS("sbc4", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000), CORE_DVFS("sbc5", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000), CORE_DVFS("sbc6", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000), CORE_DVFS("usbd", -1, 1, KHZ, 1, 480000, 480000, 480000, 480000, 480000, 480000, 480000, 480000), CORE_DVFS("usb2", -1, 1, KHZ, 1, 480000, 480000, 480000, 480000, 480000, 480000, 480000, 480000), CORE_DVFS("usb3", -1, 1, KHZ, 1, 480000, 480000, 480000, 480000, 480000, 480000, 480000, 480000), CORE_DVFS("sata", -1, 1, KHZ, 1, 216000, 216000, 216000, 216000, 216000, 216000, 216000, 216000), CORE_DVFS("sata_oob", -1, 1, KHZ, 1, 216000, 216000, 216000, 216000, 216000, 216000, 216000, 216000), CORE_DVFS("pcie", -1, 1, KHZ, 1, 250000, 250000, 250000, 250000, 250000, 250000, 250000, 250000), CORE_DVFS("afi", -1, 1, KHZ, 1, 250000, 250000, 250000, 250000, 250000, 250000, 250000, 250000), CORE_DVFS("pll_e", -1, 1, KHZ, 1, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000), CORE_DVFS("tvdac", -1, 1, KHZ, 1, 220000, 220000, 220000, 220000, 220000, 220000, 220000, 220000), CORE_DVFS("tvo", -1, 1, KHZ, 1, 1, 297000, 297000, 297000, 297000, 297000, 297000, 297000), CORE_DVFS("cve", -1, 1, KHZ, 1, 1, 297000, 297000, 297000, 297000, 297000, 297000, 297000), CORE_DVFS("dsia", -1, 1, KHZ, 1, 275000, 275000, 275000, 275000, 275000, 275000, 275000, 275000), CORE_DVFS("dsib", -1, 1, KHZ, 1, 275000, 275000, 275000, 275000, 275000, 275000, 275000, 275000), CORE_DVFS("hdmi", -1, 1, KHZ, 1, 148500, 148500, 148500, 148500, 148500, 148500, 148500, 148500), /* * The clock rate for the display controllers that determines the * necessary core voltage depends on a divider that is internal * to the display block. Disable auto-dvfs on the display clocks, * and let the display driver call tegra_dvfs_set_rate manually */ CORE_DVFS("disp1", 0, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000), CORE_DVFS("disp1", 1, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000), CORE_DVFS("disp1", 2, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000), CORE_DVFS("disp1", 3, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000), CORE_DVFS("disp2", 0, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000), CORE_DVFS("disp2", 1, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000), CORE_DVFS("disp2", 2, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000), CORE_DVFS("disp2", 3, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000), CORE_DVFS("pwm", -1, 1, KHZ, 1, 408000, 408000, 408000, 408000, 408000, 408000, 408000, 408000), CORE_DVFS("spdif_out", -1, 1, KHZ, 1, 26000, 26000, 26000, 26000, 26000, 26000, 26000, 26000), }; int tegra_dvfs_disable_core_set(const char *arg, const struct kernel_param *kp) { int ret; ret = param_set_bool(arg, kp); if (ret) return ret; if (tegra_dvfs_core_disabled) tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_core); else tegra_dvfs_rail_enable(&tegra3_dvfs_rail_vdd_core); return 0; } int tegra_dvfs_disable_cpu_set(const char *arg, const struct kernel_param *kp) { int ret; ret = param_set_bool(arg, kp); if (ret) return ret; if (tegra_dvfs_cpu_disabled) tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_cpu); else tegra_dvfs_rail_enable(&tegra3_dvfs_rail_vdd_cpu); return 0; } int tegra_dvfs_disable_get(char *buffer, const struct kernel_param *kp) { return param_get_bool(buffer, kp); } static struct kernel_param_ops tegra_dvfs_disable_core_ops = { .set = tegra_dvfs_disable_core_set, .get = tegra_dvfs_disable_get, }; static struct kernel_param_ops tegra_dvfs_disable_cpu_ops = { .set = tegra_dvfs_disable_cpu_set, .get = tegra_dvfs_disable_get, }; module_param_cb(disable_core, &tegra_dvfs_disable_core_ops, &tegra_dvfs_core_disabled, 0644); module_param_cb(disable_cpu, &tegra_dvfs_disable_cpu_ops, &tegra_dvfs_cpu_disabled, 0644); static bool __init is_pllm_dvfs(struct clk *c, struct dvfs *d) { #ifdef CONFIG_TEGRA_PLLM_RESTRICTED /* Do not apply common PLLM dvfs table on T30, T33, T37 rev A02+ and do not apply restricted PLLM dvfs table for other SKUs/revs */ int cpu = tegra_cpu_speedo_id(); if (((cpu == 2) || (cpu == 5) || (cpu == 13)) == (d->speedo_id == -1)) return false; #endif /* Check if PLLM boot frequency can be applied to clock tree at minimum voltage. If yes, no need to enable dvfs on PLLM */ if (clk_get_rate_all_locked(c) <= d->freqs[0] * d->freqs_mult) return false; return true; } static void __init init_dvfs_one(struct dvfs *d, int nominal_mv_index) { int ret; struct clk *c = tegra_get_clock_by_name(d->clk_name); if (!c) { pr_debug("tegra3_dvfs: no clock found for %s\n", d->clk_name); return; } /* * Update max rate for auto-dvfs clocks, except EMC. * EMC is a special case, since EMC dvfs is board dependent: max rate * and EMC scaling frequencies are determined by tegra BCT (flashed * together with the image) and board specific EMC DFS table; we will * check the scaling ladder against nominal core voltage when the table * is loaded (and if on particular board the table is not loaded, EMC * scaling is disabled). */ if (!(c->flags & PERIPH_EMC_ENB) && d->auto_dvfs) { BUG_ON(!d->freqs[nominal_mv_index]); tegra_init_max_rate( c, d->freqs[nominal_mv_index] * d->freqs_mult); } d->max_millivolts = d->dvfs_rail->nominal_millivolts; /* * Check if we may skip enabling dvfs on PLLM. PLLM is a special case, * since its frequency never exceeds boot rate, and configuration with * restricted PLLM usage is possible. */ if (!(c->flags & PLLM) || is_pllm_dvfs(c, d)) { ret = tegra_enable_dvfs_on_clk(c, d); if (ret) pr_err("tegra3_dvfs: failed to enable dvfs on %s\n", c->name); } } static void __init init_dvfs_cold(struct dvfs *d, int nominal_mv_index) { int i; unsigned long offs; BUG_ON((nominal_mv_index == 0) || (nominal_mv_index > d->num_freqs)); for (i = 0; i < d->num_freqs; i++) { offs = cpu_cold_offs_mhz[i] * MHZ; if (i > nominal_mv_index) d->alt_freqs[i] = d->alt_freqs[i - 1]; else if (d->freqs[i] > offs) d->alt_freqs[i] = d->freqs[i] - offs; else { d->alt_freqs[i] = d->freqs[i]; pr_warn("tegra3_dvfs: cold offset %lu is too high for" " regular dvfs limit %lu\n", offs, d->freqs[i]); } if (i) BUG_ON(d->alt_freqs[i] < d->alt_freqs[i - 1]); } d->alt_freqs_state = ALT_FREQS_DISABLED; } static bool __init match_dvfs_one(struct dvfs *d, int speedo_id, int process_id) { if ((d->process_id != -1 && d->process_id != process_id) || (d->speedo_id != -1 && d->speedo_id != speedo_id)) { pr_debug("tegra3_dvfs: rejected %s speedo %d," " process %d\n", d->clk_name, d->speedo_id, d->process_id); return false; } return true; } static int __init get_cpu_nominal_mv_index( int speedo_id, int process_id, struct dvfs **cpu_dvfs) { int i, j, mv; struct dvfs *d; struct clk *c; /* * Find maximum cpu voltage that satisfies cpu_to_core dependency for * nominal core voltage ("solve from cpu to core at nominal"). Clip * result to the nominal cpu level for the chips with this speedo_id. */ mv = tegra3_dvfs_rail_vdd_core.nominal_millivolts; for (i = 0; i < MAX_DVFS_FREQS; i++) { if ((cpu_millivolts[i] == 0) || tegra3_get_core_floor_mv(cpu_millivolts[i]) > mv) break; } BUG_ON(i == 0); mv = cpu_millivolts[i - 1]; BUG_ON(mv < tegra3_dvfs_rail_vdd_cpu.min_millivolts); mv = min(mv, tegra_cpu_speedo_mv()); /* * Find matching cpu dvfs entry, and use it to determine index to the * final nominal voltage, that satisfies the following requirements: * - allows CPU to run at minimum of the maximum rates specified in * the dvfs entry and clock tree * - does not violate cpu_to_core dependency as determined above */ for (i = 0, j = 0; j < ARRAY_SIZE(cpu_dvfs_table); j++) { d = &cpu_dvfs_table[j]; if (match_dvfs_one(d, speedo_id, process_id)) { c = tegra_get_clock_by_name(d->clk_name); BUG_ON(!c); for (; i < MAX_DVFS_FREQS; i++) { if ((d->freqs[i] == 0) || (cpu_millivolts[i] == 0) || (mv < cpu_millivolts[i])) break; if (c->max_rate <= d->freqs[i]*d->freqs_mult) { i++; break; } } break; } } BUG_ON(i == 0); if (j == (ARRAY_SIZE(cpu_dvfs_table) - 1)) pr_err("tegra3_dvfs: WARNING!!!\n" "tegra3_dvfs: no cpu dvfs table found for chip speedo_id" " %d and process_id %d: set CPU rate limit at %lu\n" "tegra3_dvfs: WARNING!!!\n", speedo_id, process_id, d->freqs[i-1] * d->freqs_mult); *cpu_dvfs = d; return (i - 1); } static int __init get_core_nominal_mv_index(int speedo_id) { int i; int mv = tegra_core_speedo_mv(); int core_edp_limit = get_core_edp(); /* * Start with nominal level for the chips with this speedo_id. Then, * make sure core nominal voltage is below edp limit for the board * (if edp limit is set). */ if (core_edp_limit) mv = min(mv, core_edp_limit); /* Round nominal level down to the nearest core scaling step */ for (i = 0; i < MAX_DVFS_FREQS; i++) { if ((core_millivolts[i] == 0) || (mv < core_millivolts[i])) break; } if (i == 0) { pr_err("tegra3_dvfs: unable to adjust core dvfs table to" " nominal voltage %d\n", mv); return -ENOSYS; } return (i - 1); } void __init tegra_soc_init_dvfs(void) { int cpu_speedo_id = tegra_cpu_speedo_id(); int soc_speedo_id = tegra_soc_speedo_id(); int cpu_process_id = tegra_cpu_process_id(); int core_process_id = tegra_core_process_id(); int i; int core_nominal_mv_index; int cpu_nominal_mv_index; #ifndef CONFIG_TEGRA_CORE_DVFS tegra_dvfs_core_disabled = true; #endif #ifndef CONFIG_TEGRA_CPU_DVFS tegra_dvfs_cpu_disabled = true; #endif /* * Find nominal voltages for core (1st) and cpu rails before rail * init. Nominal voltage index in the scaling ladder will also be * used to determine max dvfs frequency for the respective domains. */ core_nominal_mv_index = get_core_nominal_mv_index(soc_speedo_id); if (core_nominal_mv_index < 0) { tegra3_dvfs_rail_vdd_core.disabled = true; tegra_dvfs_core_disabled = true; core_nominal_mv_index = 0; } tegra3_dvfs_rail_vdd_core.nominal_millivolts = core_millivolts[core_nominal_mv_index]; cpu_nominal_mv_index = get_cpu_nominal_mv_index( cpu_speedo_id, cpu_process_id, &cpu_dvfs); BUG_ON((cpu_nominal_mv_index < 0) || (!cpu_dvfs)); tegra3_dvfs_rail_vdd_cpu.nominal_millivolts = cpu_millivolts[cpu_nominal_mv_index]; /* Init rail structures and dependencies */ tegra_dvfs_init_rails(tegra3_dvfs_rails, ARRAY_SIZE(tegra3_dvfs_rails)); tegra_dvfs_add_relationships(tegra3_dvfs_relationships, ARRAY_SIZE(tegra3_dvfs_relationships)); /* Search core dvfs table for speedo/process matching entries and initialize dvfs-ed clocks */ for (i = 0; i < ARRAY_SIZE(core_dvfs_table); i++) { struct dvfs *d = &core_dvfs_table[i]; if (!match_dvfs_one(d, soc_speedo_id, core_process_id)) continue; init_dvfs_one(d, core_nominal_mv_index); } /* Initialize matching cpu dvfs entry already found when nominal voltage was determined */ init_dvfs_one(cpu_dvfs, cpu_nominal_mv_index); init_dvfs_cold(cpu_dvfs, cpu_nominal_mv_index); /* Finally disable dvfs on rails if necessary */ if (tegra_dvfs_core_disabled) tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_core); if (tegra_dvfs_cpu_disabled) tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_cpu); pr_info("tegra dvfs: VDD_CPU nominal %dmV, scaling %s\n", tegra3_dvfs_rail_vdd_cpu.nominal_millivolts, tegra_dvfs_cpu_disabled ? "disabled" : "enabled"); pr_info("tegra dvfs: VDD_CORE nominal %dmV, scaling %s\n", tegra3_dvfs_rail_vdd_core.nominal_millivolts, tegra_dvfs_core_disabled ? "disabled" : "enabled"); } void tegra_cpu_dvfs_alter(int edp_thermal_index, bool before_clk_update) { bool enable = !edp_thermal_index; if (enable != before_clk_update) { int ret = tegra_dvfs_alt_freqs_set(cpu_dvfs, enable); WARN_ONCE(ret, "tegra dvfs: failed to set CPU alternative" " frequency limits for cold temeperature\n"); } } int tegra_dvfs_rail_disable_prepare(struct dvfs_rail *rail) { int ret = 0; if (tegra_emc_get_dram_type() != DRAM_TYPE_DDR3) return ret; if (((&tegra3_dvfs_rail_vdd_core == rail) && (rail->nominal_millivolts > TEGRA_EMC_BRIDGE_MVOLTS_MIN)) || ((&tegra3_dvfs_rail_vdd_cpu == rail) && (tegra3_get_core_floor_mv(rail->nominal_millivolts) > TEGRA_EMC_BRIDGE_MVOLTS_MIN))) { struct clk *bridge = tegra_get_clock_by_name("bridge.emc"); BUG_ON(!bridge); ret = clk_enable(bridge); pr_info("%s: %s: %s bridge.emc\n", __func__, rail->reg_id, ret ? "failed to enable" : "enabled"); } return ret; } int tegra_dvfs_rail_post_enable(struct dvfs_rail *rail) { if (tegra_emc_get_dram_type() != DRAM_TYPE_DDR3) return 0; if (((&tegra3_dvfs_rail_vdd_core == rail) && (rail->nominal_millivolts > TEGRA_EMC_BRIDGE_MVOLTS_MIN)) || ((&tegra3_dvfs_rail_vdd_cpu == rail) && (tegra3_get_core_floor_mv(rail->nominal_millivolts) > TEGRA_EMC_BRIDGE_MVOLTS_MIN))) { struct clk *bridge = tegra_get_clock_by_name("bridge.emc"); BUG_ON(!bridge); clk_disable(bridge); pr_info("%s: %s: disabled bridge.emc\n", __func__, rail->reg_id); } return 0; } /* * sysfs and dvfs interfaces to cap tegra core domains frequencies */ static DEFINE_MUTEX(core_cap_lock); struct core_cap { int refcnt; int level; }; static struct core_cap tegra3_core_cap; static struct core_cap kdvfs_core_cap; static struct core_cap user_core_cap; static struct kobject *cap_kobj; /* Arranged in order required for enabling/lowering the cap */ static struct { const char *cap_name; struct clk *cap_clk; unsigned long freqs[MAX_DVFS_FREQS]; } core_cap_table[] = { { .cap_name = "cap.cbus" }, { .cap_name = "cap.sclk" }, { .cap_name = "cap.emc" }, }; static void core_cap_level_set(int level) { int i, j; for (j = 0; j < ARRAY_SIZE(core_millivolts); j++) { int v = core_millivolts[j]; if ((v == 0) || (level < v)) break; } j = (j == 0) ? 0 : j - 1; level = core_millivolts[j]; if (level < tegra3_core_cap.level) { for (i = 0; i < ARRAY_SIZE(core_cap_table); i++) if (core_cap_table[i].cap_clk) clk_set_rate(core_cap_table[i].cap_clk, core_cap_table[i].freqs[j]); } else if (level > tegra3_core_cap.level) { for (i = ARRAY_SIZE(core_cap_table) - 1; i >= 0; i--) if (core_cap_table[i].cap_clk) clk_set_rate(core_cap_table[i].cap_clk, core_cap_table[i].freqs[j]); } tegra3_core_cap.level = level; } static void core_cap_update(void) { int new_level = tegra3_dvfs_rail_vdd_core.max_millivolts; if (kdvfs_core_cap.refcnt) new_level = min(new_level, kdvfs_core_cap.level); if (user_core_cap.refcnt) new_level = min(new_level, user_core_cap.level); if (tegra3_core_cap.level != new_level) core_cap_level_set(new_level); } static void core_cap_enable(bool enable) { int i; if (enable) { tegra3_core_cap.refcnt++; if (tegra3_core_cap.refcnt == 1) for (i = 0; i < ARRAY_SIZE(core_cap_table); i++) if (core_cap_table[i].cap_clk) clk_enable(core_cap_table[i].cap_clk); } else if (tegra3_core_cap.refcnt) { tegra3_core_cap.refcnt--; if (tegra3_core_cap.refcnt == 0) for (i = ARRAY_SIZE(core_cap_table) - 1; i >= 0; i--) if (core_cap_table[i].cap_clk) clk_disable(core_cap_table[i].cap_clk); } core_cap_update(); } static ssize_t core_cap_state_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%d (%d)\n", tegra3_core_cap.refcnt ? 1 : 0, user_core_cap.refcnt ? 1 : 0); } static ssize_t core_cap_state_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int state; if (sscanf(buf, "%d", &state) != 1) return -1; mutex_lock(&core_cap_lock); if (state) { user_core_cap.refcnt++; if (user_core_cap.refcnt == 1) core_cap_enable(true); } else if (user_core_cap.refcnt) { user_core_cap.refcnt--; if (user_core_cap.refcnt == 0) core_cap_enable(false); } mutex_unlock(&core_cap_lock); return count; } static ssize_t core_cap_level_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%d (%d)\n", tegra3_core_cap.level, user_core_cap.level); } static ssize_t core_cap_level_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int level; if (sscanf(buf, "%d", &level) != 1) return -1; mutex_lock(&core_cap_lock); user_core_cap.level = level; core_cap_update(); mutex_unlock(&core_cap_lock); return count; } static struct kobj_attribute cap_state_attribute = __ATTR(core_cap_state, 0644, core_cap_state_show, core_cap_state_store); static struct kobj_attribute cap_level_attribute = __ATTR(core_cap_level, 0644, core_cap_level_show, core_cap_level_store); const struct attribute *cap_attributes[] = { &cap_state_attribute.attr, &cap_level_attribute.attr, NULL, }; void tegra_dvfs_core_cap_enable(bool enable) { mutex_lock(&core_cap_lock); if (enable) { kdvfs_core_cap.refcnt++; if (kdvfs_core_cap.refcnt == 1) core_cap_enable(true); } else if (kdvfs_core_cap.refcnt) { kdvfs_core_cap.refcnt--; if (kdvfs_core_cap.refcnt == 0) core_cap_enable(false); } mutex_unlock(&core_cap_lock); } void tegra_dvfs_core_cap_level_set(int level) { mutex_lock(&core_cap_lock); kdvfs_core_cap.level = level; core_cap_update(); mutex_unlock(&core_cap_lock); } static int __init init_core_cap_one(struct clk *c, unsigned long *freqs) { int i, v, next_v; unsigned long rate, next_rate = 0; for (i = 0; i < ARRAY_SIZE(core_millivolts); i++) { v = core_millivolts[i]; if (v == 0) break; for (;;) { rate = next_rate; next_rate = clk_round_rate(c, rate + 1000); if (IS_ERR_VALUE(next_rate)) { pr_debug("tegra3_dvfs: failed to round %s" " rate %lu", c->name, rate); return -EINVAL; } if (rate == next_rate) break; next_v = tegra_dvfs_predict_millivolts( c->parent, next_rate); if (IS_ERR_VALUE(next_rate)) { pr_debug("tegra3_dvfs: failed to predict %s mV" " for rate %lu", c->name, next_rate); return -EINVAL; } if (next_v > v) break; } if (rate == 0) { rate = next_rate; pr_warn("tegra3_dvfs: minimum %s rate %lu requires" " %d mV", c->name, rate, next_v); } freqs[i] = rate; next_rate = rate; } return 0; } static int __init tegra_dvfs_init_core_cap(void) { int i; struct clk *c = NULL; tegra3_core_cap.level = kdvfs_core_cap.level = user_core_cap.level = tegra3_dvfs_rail_vdd_core.max_millivolts; for (i = 0; i < ARRAY_SIZE(core_cap_table); i++) { c = tegra_get_clock_by_name(core_cap_table[i].cap_name); if (!c || !c->parent || init_core_cap_one(c, core_cap_table[i].freqs)) { pr_err("tegra3_dvfs: failed to initialize %s frequency" " table", core_cap_table[i].cap_name); continue; } core_cap_table[i].cap_clk = c; } cap_kobj = kobject_create_and_add("tegra_cap", kernel_kobj); if (!cap_kobj) { pr_err("tegra3_dvfs: failed to create sysfs cap object"); return 0; } if (sysfs_create_files(cap_kobj, cap_attributes)) { pr_err("tegra3_dvfs: failed to create sysfs cap interface"); return 0; } pr_info("tegra dvfs: tegra sysfs cap interface is initialized\n"); return 0; } late_initcall(tegra_dvfs_init_core_cap);
AndroidDeveloperAlliance/ZenKernel_Grouper
arch/arm/mach-tegra/tegra3_dvfs.c
C
gpl-2.0
37,574
/** * @file id_10361.c * @brief AOAPC I 10361 * @author chenxilinsidney * @version 1.0 * @date 2015-03-24 */ #include <stdio.h> #include <string.h> #define MAX_LINE_LENGTH 101 char line[2][MAX_LINE_LENGTH]; int main() { int num_case; scanf("%d\n", &num_case); while (num_case--) { gets(*line); gets(*(line+ 1)); int line_length_a = strlen(*line); int line_length_b = strlen(*(line + 1)); int line_index = 0; int char_position[4] = {0}; int position_index = 0; /* output first line */ while (line_index < line_length_a) { int character = line[0][line_index]; if (character != '<' && character != '>') putchar(character); else char_position[position_index++] = line_index; line_index++; } printf("\n"); /* output second line */ line[1][line_length_b - 3] = '\0'; printf("%s", line[1]); for (position_index = 2; position_index >= 0; position_index--) for (line_index = char_position[position_index] + 1; line_index < char_position[position_index + 1]; line_index++) putchar(line[0][line_index]); printf("%s", line[0] + char_position[3] + 1); printf("\n"); } return 0; }
chenxilinsidney/funnycprogram
acm/aoapc/id_10361.c
C
gpl-2.0
1,360
/* -*- mode: c -*- */ /* $Id$ */ /* Copyright (C) 2004-2013 Alexander Chernov <cher@ejudge.ru> */ /* * 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. */ #include "checker_internal.h" #include <errno.h> #include "l10n_impl.h" int checker_read_int( int ind, const char *name, int eof_error_flag, int *p_val) { int x; char sb[128], *db = 0, *vb = 0, *ep = 0; size_t ds = 0; if (!name) name = ""; vb = checker_read_buf_2(ind, name, eof_error_flag, sb, sizeof(sb), &db, &ds); if (!vb) return -1; if (!*vb) { fatal_read(ind, _("%s: no int32 value"), name); } errno = 0; x = strtol(vb, &ep, 10); if (*ep) { fatal_read(ind, _("%s: cannot parse int32 value"), name); } if (errno) { fatal_read(ind, _("%s: int32 value is out of range"), name); } *p_val = x; return 1; }
misty-fungus/ejudge-debian
checkers/read_int.c
C
gpl-2.0
1,296
/* Copyright (c) 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. */ #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <linux/msm_kgsl.h> #include <linux/regulator/machine.h> #include <mach/irqs.h> #include <mach/msm_iomap.h> #include <mach/board.h> #include <mach/dma.h> #include <mach/dal_axi.h> #include <asm/mach/flash.h> #include <asm/hardware/cache-l2x0.h> #include <asm/mach/mmc.h> #include <mach/rpc_hsusb.h> #include <mach/socinfo.h> #include "devices.h" #include "devices-msm7x2xa.h" #include "footswitch.h" #include "acpuclock.h" /* Address of GSBI blocks */ #define MSM_GSBI0_PHYS 0xA1200000 #define MSM_GSBI1_PHYS 0xA1300000 /* GSBI QUPe devices */ #define MSM_GSBI0_QUP_PHYS (MSM_GSBI0_PHYS + 0x80000) #define MSM_GSBI1_QUP_PHYS (MSM_GSBI1_PHYS + 0x80000) static struct resource gsbi0_qup_i2c_resources[] = { { .name = "qup_phys_addr", .start = MSM_GSBI0_QUP_PHYS, .end = MSM_GSBI0_QUP_PHYS + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .name = "gsbi_qup_i2c_addr", .start = MSM_GSBI0_PHYS, .end = MSM_GSBI0_PHYS + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .name = "qup_err_intr", .start = INT_PWB_I2C, .end = INT_PWB_I2C, .flags = IORESOURCE_IRQ, }, { .name = "i2c_clk", .start = 60, .end = 60, .flags = IORESOURCE_IO, }, { .name = "i2c_sda", .start = 61, .end = 61, .flags = IORESOURCE_IO, }, }; /* Use GSBI0 QUP for /dev/i2c-0 */ struct platform_device msm_gsbi0_qup_i2c_device = { .name = "qup_i2c", .id = MSM_GSBI0_QUP_I2C_BUS_ID, .num_resources = ARRAY_SIZE(gsbi0_qup_i2c_resources), .resource = gsbi0_qup_i2c_resources, }; static struct resource gsbi1_qup_i2c_resources[] = { { .name = "qup_phys_addr", .start = MSM_GSBI1_QUP_PHYS, .end = MSM_GSBI1_QUP_PHYS + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .name = "gsbi_qup_i2c_addr", .start = MSM_GSBI1_PHYS, .end = MSM_GSBI1_PHYS + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .name = "qup_err_intr", .start = INT_ARM11_DMA, .end = INT_ARM11_DMA, .flags = IORESOURCE_IRQ, }, { .name = "i2c_clk", .start = 131, .end = 131, .flags = IORESOURCE_IO, }, { .name = "i2c_sda", .start = 132, .end = 132, .flags = IORESOURCE_IO, }, }; /* Use GSBI1 QUP for /dev/i2c-1 */ struct platform_device msm_gsbi1_qup_i2c_device = { .name = "qup_i2c", .id = MSM_GSBI1_QUP_I2C_BUS_ID, .num_resources = ARRAY_SIZE(gsbi1_qup_i2c_resources), .resource = gsbi1_qup_i2c_resources, }; #define MSM_HSUSB_PHYS 0xA0800000 static struct resource resources_hsusb_otg[] = { { .start = MSM_HSUSB_PHYS, .end = MSM_HSUSB_PHYS + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_USB_HS, .end = INT_USB_HS, .flags = IORESOURCE_IRQ, }, }; static u64 dma_mask = 0xffffffffULL; struct platform_device msm_device_otg = { .name = "msm_otg", .id = -1, .num_resources = ARRAY_SIZE(resources_hsusb_otg), .resource = resources_hsusb_otg, .dev = { .dma_mask = &dma_mask, .coherent_dma_mask = 0xffffffffULL, }, }; static struct resource resources_gadget_peripheral[] = { { .start = MSM_HSUSB_PHYS, .end = MSM_HSUSB_PHYS + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_USB_HS, .end = INT_USB_HS, .flags = IORESOURCE_IRQ, }, }; struct platform_device msm_device_gadget_peripheral = { .name = "msm_hsusb", .id = -1, .num_resources = ARRAY_SIZE(resources_gadget_peripheral), .resource = resources_gadget_peripheral, .dev = { .dma_mask = &dma_mask, .coherent_dma_mask = 0xffffffffULL, }, }; static struct resource resources_hsusb_host[] = { { .start = MSM_HSUSB_PHYS, .end = MSM_HSUSB_PHYS + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_USB_HS, .end = INT_USB_HS, .flags = IORESOURCE_IRQ, }, }; struct platform_device msm_device_hsusb_host = { .name = "msm_hsusb_host", .id = 0, .num_resources = ARRAY_SIZE(resources_hsusb_host), .resource = resources_hsusb_host, .dev = { .dma_mask = &dma_mask, .coherent_dma_mask = 0xffffffffULL, }, }; static struct platform_device *msm_host_devices[] = { &msm_device_hsusb_host, }; int msm_add_host(unsigned int host, struct msm_usb_host_platform_data *plat) { struct platform_device *pdev; pdev = msm_host_devices[host]; if (!pdev) return -ENODEV; pdev->dev.platform_data = plat; return platform_device_register(pdev); } static struct resource msm_dmov_resource[] = { { .start = INT_ADM_AARM, .end = (resource_size_t)MSM_DMOV_BASE, .flags = IORESOURCE_IRQ, }, }; struct platform_device msm_device_dmov = { .name = "msm_dmov", .id = -1, .resource = msm_dmov_resource, .num_resources = ARRAY_SIZE(msm_dmov_resource), }; struct platform_device msm_device_smd = { .name = "msm_smd", .id = -1, }; static struct resource resources_uart1[] = { { .start = INT_UART1, .end = INT_UART1, .flags = IORESOURCE_IRQ, }, { .start = MSM_UART1_PHYS, .end = MSM_UART1_PHYS + MSM_UART1_SIZE - 1, .flags = IORESOURCE_MEM, }, }; static struct resource resources_uart2[] = { { .start = INT_UART2, .end = INT_UART2, .flags = IORESOURCE_IRQ, }, { .start = MSM_UART2_PHYS, .end = MSM_UART2_PHYS + MSM_UART2_SIZE - 1, .flags = IORESOURCE_MEM, }, }; static struct resource resources_uart3[] = { { .start = INT_UART3, .end = INT_UART3, .flags = IORESOURCE_IRQ, }, { .start = MSM_UART3_PHYS, .end = MSM_UART3_PHYS + MSM_UART3_SIZE - 1, .flags = IORESOURCE_MEM, }, }; struct platform_device msm_device_uart1 = { .name = "msm_serial", .id = 0, .num_resources = ARRAY_SIZE(resources_uart1), .resource = resources_uart1, }; struct platform_device msm_device_uart2 = { .name = "msm_serial", .id = 1, .num_resources = ARRAY_SIZE(resources_uart2), .resource = resources_uart2, }; struct platform_device msm_device_uart3 = { .name = "msm_serial", .id = 2, .num_resources = ARRAY_SIZE(resources_uart3), .resource = resources_uart3, }; #define MSM_UART1DM_PHYS 0xA0200000 static struct resource msm_uart1_dm_resources[] = { { .start = MSM_UART1DM_PHYS, .end = MSM_UART1DM_PHYS + PAGE_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = INT_UART1DM_IRQ, .end = INT_UART1DM_IRQ, .flags = IORESOURCE_IRQ, }, { .start = INT_UART1DM_RX, .end = INT_UART1DM_RX, .flags = IORESOURCE_IRQ, }, { .start = DMOV_HSUART1_TX_CHAN, .end = DMOV_HSUART1_RX_CHAN, .name = "uartdm_channels", .flags = IORESOURCE_DMA, }, { .start = DMOV_HSUART1_TX_CRCI, .end = DMOV_HSUART1_RX_CRCI, .name = "uartdm_crci", .flags = IORESOURCE_DMA, }, }; static u64 msm_uart_dm1_dma_mask = DMA_BIT_MASK(32); struct platform_device msm_device_uart_dm1 = { .name = "msm_serial_hs", .id = 0, .num_resources = ARRAY_SIZE(msm_uart1_dm_resources), .resource = msm_uart1_dm_resources, .dev = { .dma_mask = &msm_uart_dm1_dma_mask, .coherent_dma_mask = DMA_BIT_MASK(32), }, }; #define MSM_UART2DM_PHYS 0xA0300000 static struct resource msm_uart2dm_resources[] = { { .start = MSM_UART2DM_PHYS, .end = MSM_UART2DM_PHYS + PAGE_SIZE - 1, .name = "uartdm_resource", .flags = IORESOURCE_MEM, }, { .start = INT_UART2DM_IRQ, .end = INT_UART2DM_IRQ, .flags = IORESOURCE_IRQ, }, }; struct platform_device msm_device_uart_dm2 = { .name = "msm_serial_hsl", .id = 0, .num_resources = ARRAY_SIZE(msm_uart2dm_resources), .resource = msm_uart2dm_resources, }; #define MSM_NAND_PHYS 0xA0A00000 #define MSM_NANDC01_PHYS 0xA0A40000 #define MSM_NANDC10_PHYS 0xA0A80000 #define MSM_NANDC11_PHYS 0xA0AC0000 #define EBI2_REG_BASE 0xA0D00000 static struct resource resources_nand[] = { [0] = { .name = "msm_nand_dmac", .start = DMOV_NAND_CHAN, .end = DMOV_NAND_CHAN, .flags = IORESOURCE_DMA, }, [1] = { .name = "msm_nand_phys", .start = MSM_NAND_PHYS, .end = MSM_NAND_PHYS + 0x7FF, .flags = IORESOURCE_MEM, }, [2] = { .name = "msm_nandc01_phys", .start = MSM_NANDC01_PHYS, .end = MSM_NANDC01_PHYS + 0x7FF, .flags = IORESOURCE_MEM, }, [3] = { .name = "msm_nandc10_phys", .start = MSM_NANDC10_PHYS, .end = MSM_NANDC10_PHYS + 0x7FF, .flags = IORESOURCE_MEM, }, [4] = { .name = "msm_nandc11_phys", .start = MSM_NANDC11_PHYS, .end = MSM_NANDC11_PHYS + 0x7FF, .flags = IORESOURCE_MEM, }, [5] = { .name = "ebi2_reg_base", .start = EBI2_REG_BASE, .end = EBI2_REG_BASE + 0x60, .flags = IORESOURCE_MEM, }, }; struct flash_platform_data msm_nand_data; struct platform_device msm_device_nand = { .name = "msm_nand", .id = -1, .num_resources = ARRAY_SIZE(resources_nand), .resource = resources_nand, .dev = { .platform_data = &msm_nand_data, }, }; #define MSM_SDC1_BASE 0xA0400000 #define MSM_SDC2_BASE 0xA0500000 #define MSM_SDC3_BASE 0xA0600000 #define MSM_SDC4_BASE 0xA0700000 static struct resource resources_sdc1[] = { { .start = MSM_SDC1_BASE, .end = MSM_SDC1_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_SDC1_0, .end = INT_SDC1_1, .flags = IORESOURCE_IRQ, }, { .name = "sdcc_dma_chnl", .start = DMOV_SDC1_CHAN, .end = DMOV_SDC1_CHAN, .flags = IORESOURCE_DMA, }, { .name = "sdcc_dma_crci", .start = DMOV_SDC1_CRCI, .end = DMOV_SDC1_CRCI, .flags = IORESOURCE_DMA, } }; static struct resource resources_sdc2[] = { { .start = MSM_SDC2_BASE, .end = MSM_SDC2_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_SDC2_0, .end = INT_SDC2_1, .flags = IORESOURCE_IRQ, }, { .name = "sdcc_dma_chnl", .start = DMOV_SDC2_CHAN, .end = DMOV_SDC2_CHAN, .flags = IORESOURCE_DMA, }, { .name = "sdcc_dma_crci", .start = DMOV_SDC2_CRCI, .end = DMOV_SDC2_CRCI, .flags = IORESOURCE_DMA, } }; #ifdef CONFIG_ARCH_MSM7X27A static struct resource resources_sdc3[] = { { .start = MSM_SDC3_BASE, .end = MSM_SDC3_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_SDC3_0, .end = INT_SDC3_1, .flags = IORESOURCE_IRQ, }, { .name = "sdcc_dma_chnl", .start = DMOV_SDC3_CHAN, .end = DMOV_SDC3_CHAN, .flags = IORESOURCE_DMA, }, { .name = "sdcc_dma_crci", .start = DMOV_SDC3_CRCI, .end = DMOV_SDC3_CRCI, .flags = IORESOURCE_DMA, }, }; #else static struct resource resources_sdc3[] = { { .start = MSM_SDC3_BASE, .end = MSM_SDC3_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_SDC3_0, .end = INT_SDC3_1, .flags = IORESOURCE_IRQ, }, { .name = "sdcc_dma_chnl", .start = DMOV_SDC4_CHAN, .end = DMOV_SDC4_CHAN, .flags = IORESOURCE_DMA, }, { .name = "sdcc_dma_crci", .start = DMOV_SDC4_CRCI, .end = DMOV_SDC4_CRCI, .flags = IORESOURCE_DMA, }, }; #endif static struct resource resources_sdc4[] = { { .start = MSM_SDC4_BASE, .end = MSM_SDC4_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = INT_SDC4_0, .end = INT_SDC4_1, .flags = IORESOURCE_IRQ, }, { .name = "sdcc_dma_chnl", .start = DMOV_SDC3_CHAN, .end = DMOV_SDC3_CHAN, .flags = IORESOURCE_DMA, }, { .name = "sdcc_dma_crci", .start = DMOV_SDC3_CRCI, .end = DMOV_SDC3_CRCI, .flags = IORESOURCE_DMA, }, }; struct platform_device msm_device_sdc1 = { .name = "msm_sdcc", .id = 1, .num_resources = ARRAY_SIZE(resources_sdc1), .resource = resources_sdc1, .dev = { .coherent_dma_mask = 0xffffffff, }, }; struct platform_device msm_device_sdc2 = { .name = "msm_sdcc", .id = 2, .num_resources = ARRAY_SIZE(resources_sdc2), .resource = resources_sdc2, .dev = { .coherent_dma_mask = 0xffffffff, }, }; struct platform_device msm_device_sdc3 = { .name = "msm_sdcc", .id = 3, .num_resources = ARRAY_SIZE(resources_sdc3), .resource = resources_sdc3, .dev = { .coherent_dma_mask = 0xffffffff, }, }; struct platform_device msm_device_sdc4 = { .name = "msm_sdcc", .id = 4, .num_resources = ARRAY_SIZE(resources_sdc4), .resource = resources_sdc4, .dev = { .coherent_dma_mask = 0xffffffff, }, }; static struct platform_device *msm_sdcc_devices[] __initdata = { &msm_device_sdc1, &msm_device_sdc2, &msm_device_sdc3, &msm_device_sdc4, }; int __init msm_add_sdcc(unsigned int controller, struct mmc_platform_data *plat) { struct platform_device *pdev; if (controller < 1 || controller > 4) return -EINVAL; pdev = msm_sdcc_devices[controller-1]; pdev->dev.platform_data = plat; return platform_device_register(pdev); } #define MDP_BASE 0xAA200000 #define MIPI_DSI_HW_BASE 0xA1100000 static struct resource msm_mipi_dsi_resources[] = { { .name = "mipi_dsi", .start = MIPI_DSI_HW_BASE, .end = MIPI_DSI_HW_BASE + 0x000F0000 - 1, .flags = IORESOURCE_MEM, }, { .start = INT_DSI_IRQ, .end = INT_DSI_IRQ, .flags = IORESOURCE_IRQ, }, }; static struct platform_device msm_mipi_dsi_device = { .name = "mipi_dsi", .id = 1, .num_resources = ARRAY_SIZE(msm_mipi_dsi_resources), .resource = msm_mipi_dsi_resources, }; static struct resource msm_mdp_resources[] = { { .name = "mdp", .start = MDP_BASE, .end = MDP_BASE + 0x000F1008 - 1, .flags = IORESOURCE_MEM, }, { .start = INT_MDP, .end = INT_MDP, .flags = IORESOURCE_IRQ, }, }; static struct platform_device msm_mdp_device = { .name = "mdp", .id = 0, .num_resources = ARRAY_SIZE(msm_mdp_resources), .resource = msm_mdp_resources, }; static struct platform_device msm_lcdc_device = { .name = "lcdc", .id = 0, }; #ifdef CONFIG_MSM_KGSL_ADRENO200 static struct resource kgsl_3d0_resources[] = { { .name = KGSL_3D0_REG_MEMORY, .start = 0xA0000000, .end = 0xA001ffff, .flags = IORESOURCE_MEM, }, { .name = KGSL_3D0_IRQ, .start = INT_GRAPHICS, .end = INT_GRAPHICS, .flags = IORESOURCE_IRQ, }, }; static struct kgsl_device_platform_data kgsl_3d0_pdata = { .pwrlevel = { { .gpu_freq = 245760000, .bus_freq = 200000000, }, { .gpu_freq = 192000000, .bus_freq = 160000000, }, { .gpu_freq = 133330000, .bus_freq = 0, }, }, .init_level = 0, .num_levels = 3, .set_grp_async = set_grp_xbar_async, .idle_timeout = HZ, .strtstp_sleepwake = true, .nap_allowed = false, .clk_map = KGSL_CLK_CORE | KGSL_CLK_IFACE | KGSL_CLK_MEM, }; struct platform_device msm_kgsl_3d0 = { .name = "kgsl-3d0", .id = 0, .num_resources = ARRAY_SIZE(kgsl_3d0_resources), .resource = kgsl_3d0_resources, .dev = { .platform_data = &kgsl_3d0_pdata, }, }; void __init msm7x25a_kgsl_3d0_init(void) { if (cpu_is_msm7x25a() || cpu_is_msm7x25aa()) { kgsl_3d0_pdata.num_levels = 2; kgsl_3d0_pdata.pwrlevel[0].gpu_freq = 133330000; kgsl_3d0_pdata.pwrlevel[0].bus_freq = 160000000; kgsl_3d0_pdata.pwrlevel[1].gpu_freq = 96000000; kgsl_3d0_pdata.pwrlevel[1].bus_freq = 0; } } #endif static void __init msm_register_device(struct platform_device *pdev, void *data) { int ret; pdev->dev.platform_data = data; ret = platform_device_register(pdev); if (ret) dev_err(&pdev->dev, "%s: platform_device_register() failed = %d\n", __func__, ret); } void __init msm_fb_register_device(char *name, void *data) { if (!strncmp(name, "mdp", 3)) msm_register_device(&msm_mdp_device, data); else if (!strncmp(name, "mipi_dsi", 8)) msm_register_device(&msm_mipi_dsi_device, data); else if (!strncmp(name, "lcdc", 4)) msm_register_device(&msm_lcdc_device, data); else printk(KERN_ERR "%s: unknown device! %s\n", __func__, name); } #define PERPH_WEB_BLOCK_ADDR (0xA9D00040) #define PDM0_CTL_OFFSET (0x04) #define SIZE_8B (0x08) static struct resource resources_led[] = { { .start = PERPH_WEB_BLOCK_ADDR, .end = PERPH_WEB_BLOCK_ADDR + (SIZE_8B) - 1, .name = "led-gpio-pdm", .flags = IORESOURCE_MEM, }, }; static struct led_info msm_kpbl_pdm_led_pdata = { .name = "keyboard-backlight", }; struct platform_device led_pdev = { .name = "leds-msm-pdm", /* use pdev id to represent pdm id */ .id = 0, .num_resources = ARRAY_SIZE(resources_led), .resource = resources_led, .dev = { .platform_data = &msm_kpbl_pdm_led_pdata, }, }; struct platform_device asoc_msm_pcm = { .name = "msm-dsp-audio", .id = 0, }; struct platform_device asoc_msm_dai0 = { .name = "msm-codec-dai", .id = 0, }; struct platform_device asoc_msm_dai1 = { .name = "msm-cpu-dai", .id = 0, }; int __init msm7x2x_misc_init(void) { msm_clock_init(&msm7x27a_clock_init_data); if (cpu_is_msm7x27aa()) acpuclk_init(&acpuclk_7x27aa_soc_data); else acpuclk_init(&acpuclk_7x27a_soc_data); return 0; } #ifdef CONFIG_CACHE_L2X0 static int __init msm7x27x_cache_init(void) { int aux_ctrl = 0; /* Way Size 010(0x2) 32KB */ aux_ctrl = (0x1 << L2X0_AUX_CTRL_SHARE_OVERRIDE_SHIFT) | \ (0x2 << L2X0_AUX_CTRL_WAY_SIZE_SHIFT) | \ (0x1 << L2X0_AUX_CTRL_EVNT_MON_BUS_EN_SHIFT); l2x0_init(MSM_L2CC_BASE, aux_ctrl, L2X0_AUX_CTRL_MASK); return 0; } #else static int __init msm7x27x_cache_init(void){ return 0; } #endif void __init msm_common_io_init(void) { msm_map_common_io(); msm7x27x_cache_init(); if (socinfo_init() < 0) pr_err("%s: socinfo_init() failed!\n", __func__); } struct platform_device *msm_footswitch_devices[] = { FS_PCOM(FS_GFX3D, "fs_gfx3d"), }; unsigned msm_num_footswitch_devices = ARRAY_SIZE(msm_footswitch_devices);
cuteprince/ics_kernel_3.0.16_htc_pico
arch/arm/mach-msm/devices-msm7x27a.c
C
gpl-2.0
17,688
/* Copyright (c) 2012-2015, The Linux Foundation. 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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/firmware.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/device.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/debugfs.h> #include <linux/wait.h> #include <linux/bitops.h> #include <linux/mfd/wcd9xxx/core.h> #include <linux/mfd/wcd9xxx/wcd9xxx_registers.h> #include <linux/mfd/wcd9xxx/wcd9306_registers.h> #include <linux/mfd/wcd9xxx/pdata.h> #include <linux/regulator/consumer.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/tlv.h> #include <linux/bitops.h> #include <linux/delay.h> #include <linux/pm_runtime.h> #include <linux/kernel.h> #include <linux/gpio.h> #include "wcd9306.h" #include "wcd9xxx-resmgr.h" #include "wcd9xxx-common.h" #define TAPAN_HPH_PA_SETTLE_COMP_ON 5000 #define TAPAN_HPH_PA_SETTLE_COMP_OFF 13000 #define DAPM_MICBIAS2_EXTERNAL_STANDALONE "MIC BIAS2 External Standalone" #define TAPAN_VALIDATE_RX_SBPORT_RANGE(port) ((port >= 16) && (port <= 20)) #define TAPAN_CONVERT_RX_SBPORT_ID(port) (port - 16) /* RX1 port ID = 0 */ #define TAPAN_VDD_CX_OPTIMAL_UA 10000 #define TAPAN_VDD_CX_SLEEP_UA 2000 /* RX_HPH_CNP_WG_TIME increases by 0.24ms */ #define TAPAN_WG_TIME_FACTOR_US 240 #define TAPAN_SB_PGD_PORT_RX_BASE 0x40 #define TAPAN_SB_PGD_PORT_TX_BASE 0x50 #define TAPAN_REGISTER_START_OFFSET 0x800 #define CODEC_REG_CFG_MINOR_VER 1 static struct regulator *tapan_codec_find_regulator( struct snd_soc_codec *codec, const char *name); static atomic_t kp_tapan_priv; static int spkr_drv_wrnd_param_set(const char *val, const struct kernel_param *kp); static int spkr_drv_wrnd = 1; static struct kernel_param_ops spkr_drv_wrnd_param_ops = { .set = spkr_drv_wrnd_param_set, .get = param_get_int, }; module_param_cb(spkr_drv_wrnd, &spkr_drv_wrnd_param_ops, &spkr_drv_wrnd, 0644); MODULE_PARM_DESC(spkr_drv_wrnd, "Run software workaround to avoid leakage on the speaker drive"); #define WCD9306_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\ SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000 |\ SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000) #define WCD9302_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\ SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000) #define NUM_DECIMATORS 4 #define NUM_INTERPOLATORS 4 #define BITS_PER_REG 8 /* This actual number of TX ports supported in slimbus slave */ #define TAPAN_TX_PORT_NUMBER 16 #define TAPAN_RX_PORT_START_NUMBER 16 /* Nummer of TX ports actually connected from Slimbus slave to codec Digital */ #define TAPAN_SLIM_CODEC_TX_PORTS 5 #define TAPAN_I2S_MASTER_MODE_MASK 0x08 #define TAPAN_MCLK_CLK_12P288MHZ 12288000 #define TAPAN_MCLK_CLK_9P6MHZ 9600000 #define TAPAN_SLIM_CLOSE_TIMEOUT 1000 #define TAPAN_SLIM_IRQ_OVERFLOW (1 << 0) #define TAPAN_SLIM_IRQ_UNDERFLOW (1 << 1) #define TAPAN_SLIM_IRQ_PORT_CLOSED (1 << 2) enum tapan_codec_type { WCD9306, WCD9302, }; static enum tapan_codec_type codec_ver; /* * Multiplication factor to compute impedance on Tapan * This is computed from (Vx / (m*Ical)) = (10mV/(180*30uA)) */ #define TAPAN_ZDET_MUL_FACTOR 1852 static struct afe_param_cdc_reg_cfg audio_reg_cfg[] = { { CODEC_REG_CFG_MINOR_VER, (TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_TX_BASE), SB_PGD_PORT_TX_WATERMARK_N, 0x1E, 8, 0x1 }, { CODEC_REG_CFG_MINOR_VER, (TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_TX_BASE), SB_PGD_PORT_TX_ENABLE_N, 0x1, 8, 0x1 }, { CODEC_REG_CFG_MINOR_VER, (TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_RX_BASE), SB_PGD_PORT_RX_WATERMARK_N, 0x1E, 8, 0x1 }, { CODEC_REG_CFG_MINOR_VER, (TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_RX_BASE), SB_PGD_PORT_RX_ENABLE_N, 0x1, 8, 0x1 }, { CODEC_REG_CFG_MINOR_VER, (TAPAN_REGISTER_START_OFFSET + TAPAN_A_CDC_ANC1_IIR_B1_CTL), AANC_FF_GAIN_ADAPTIVE, 0x4, 8, 0 }, { CODEC_REG_CFG_MINOR_VER, (TAPAN_REGISTER_START_OFFSET + TAPAN_A_CDC_ANC1_IIR_B1_CTL), AANC_FFGAIN_ADAPTIVE_EN, 0x8, 8, 0 }, { CODEC_REG_CFG_MINOR_VER, (TAPAN_REGISTER_START_OFFSET + TAPAN_A_CDC_ANC1_GAIN_CTL), AANC_GAIN_CONTROL, 0xFF, 8, 0 }, }; static struct afe_param_cdc_reg_cfg_data tapan_audio_reg_cfg = { .num_registers = ARRAY_SIZE(audio_reg_cfg), .reg_data = audio_reg_cfg, }; static struct afe_param_id_cdc_aanc_version tapan_cdc_aanc_version = { .cdc_aanc_minor_version = AFE_API_VERSION_CDC_AANC_VERSION, .aanc_hw_version = AANC_HW_BLOCK_VERSION_2, }; enum { AIF1_PB = 0, AIF1_CAP, AIF2_PB, AIF2_CAP, AIF3_PB, AIF3_CAP, NUM_CODEC_DAIS, }; enum { RX_MIX1_INP_SEL_ZERO = 0, RX_MIX1_INP_SEL_SRC1, RX_MIX1_INP_SEL_SRC2, RX_MIX1_INP_SEL_IIR1, RX_MIX1_INP_SEL_IIR2, RX_MIX1_INP_SEL_RX1, RX_MIX1_INP_SEL_RX2, RX_MIX1_INP_SEL_RX3, RX_MIX1_INP_SEL_RX4, RX_MIX1_INP_SEL_RX5, RX_MIX1_INP_SEL_AUXRX, }; #define TAPAN_COMP_DIGITAL_GAIN_OFFSET 3 static const DECLARE_TLV_DB_SCALE(digital_gain, 0, 1, 0); static const DECLARE_TLV_DB_SCALE(line_gain, 0, 7, 1); static const DECLARE_TLV_DB_SCALE(analog_gain, 0, 25, 1); static struct snd_soc_dai_driver tapan_dai[]; static const DECLARE_TLV_DB_SCALE(aux_pga_gain, 0, 2, 0); /* Codec supports 2 IIR filters */ enum { IIR1 = 0, IIR2, IIR_MAX, }; /* Codec supports 5 bands */ enum { BAND1 = 0, BAND2, BAND3, BAND4, BAND5, BAND_MAX, }; enum { COMPANDER_0, COMPANDER_1, COMPANDER_2, COMPANDER_MAX, }; enum { COMPANDER_FS_8KHZ = 0, COMPANDER_FS_16KHZ, COMPANDER_FS_32KHZ, COMPANDER_FS_48KHZ, COMPANDER_FS_96KHZ, COMPANDER_FS_192KHZ, COMPANDER_FS_MAX, }; struct comp_sample_dependent_params { u32 peak_det_timeout; u32 rms_meter_div_fact; u32 rms_meter_resamp_fact; }; struct hpf_work { struct tapan_priv *tapan; u32 decimator; u8 tx_hpf_cut_of_freq; struct delayed_work dwork; }; static struct hpf_work tx_hpf_work[NUM_DECIMATORS]; static const struct wcd9xxx_ch tapan_rx_chs[TAPAN_RX_MAX] = { WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER, 0), WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 1, 1), WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 2, 2), WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 3, 3), WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 4, 4), }; static const struct wcd9xxx_ch tapan_tx_chs[TAPAN_TX_MAX] = { WCD9XXX_CH(0, 0), WCD9XXX_CH(1, 1), WCD9XXX_CH(2, 2), WCD9XXX_CH(3, 3), WCD9XXX_CH(4, 4), }; static const u32 vport_check_table[NUM_CODEC_DAIS] = { 0, /* AIF1_PB */ (1 << AIF2_CAP) | (1 << AIF3_CAP), /* AIF1_CAP */ 0, /* AIF2_PB */ (1 << AIF1_CAP) | (1 << AIF3_CAP), /* AIF2_CAP */ 0, /* AIF2_PB */ (1 << AIF1_CAP) | (1 << AIF2_CAP), /* AIF2_CAP */ }; static const u32 vport_i2s_check_table[NUM_CODEC_DAIS] = { 0, /* AIF1_PB */ 0, /* AIF1_CAP */ }; enum { CP_REG_BUCK = 0, CP_REG_BHELPER, CP_REG_MAX, }; struct tapan_priv { struct snd_soc_codec *codec; u32 adc_count; u32 rx_bias_count; s32 dmic_1_2_clk_cnt; s32 dmic_3_4_clk_cnt; s32 dmic_5_6_clk_cnt; s32 ldo_h_users; s32 micb_2_users; u32 anc_slot; bool anc_func; /*track adie loopback mode*/ bool lb_mode; /*track tapan interface type*/ u8 intf_type; /* num of slim ports required */ struct wcd9xxx_codec_dai_data dai[NUM_CODEC_DAIS]; /*compander*/ int comp_enabled[COMPANDER_MAX]; u32 comp_fs[COMPANDER_MAX]; /* Maintain the status of AUX PGA */ int aux_pga_cnt; u8 aux_l_gain; u8 aux_r_gain; bool dec_active[NUM_DECIMATORS]; bool spkr_pa_widget_on; struct afe_param_cdc_slimbus_slave_cfg slimbus_slave_cfg; /* resmgr module */ struct wcd9xxx_resmgr resmgr; /* mbhc module */ struct wcd9xxx_mbhc mbhc; /* class h specific data */ struct wcd9xxx_clsh_cdc_data clsh_d; /* pointers to regulators required for chargepump */ struct regulator *cp_regulators[CP_REG_MAX]; /* * list used to save/restore registers at start and * end of impedance measurement */ struct list_head reg_save_restore; int (*machine_codec_event_cb)(struct snd_soc_codec *codec, enum wcd9xxx_codec_event); }; static const u32 comp_shift[] = { 0, 1, 2, }; static const int comp_rx_path[] = { COMPANDER_1, COMPANDER_1, COMPANDER_2, COMPANDER_2, COMPANDER_MAX, }; static const struct comp_sample_dependent_params comp_samp_params[] = { { /* 8 Khz */ .peak_det_timeout = 0x06, .rms_meter_div_fact = 0x09, .rms_meter_resamp_fact = 0x06, }, { /* 16 Khz */ .peak_det_timeout = 0x07, .rms_meter_div_fact = 0x0A, .rms_meter_resamp_fact = 0x0C, }, { /* 32 Khz */ .peak_det_timeout = 0x08, .rms_meter_div_fact = 0x0B, .rms_meter_resamp_fact = 0x1E, }, { /* 48 Khz */ .peak_det_timeout = 0x09, .rms_meter_div_fact = 0x0B, .rms_meter_resamp_fact = 0x28, }, { /* 96 Khz */ .peak_det_timeout = 0x0A, .rms_meter_div_fact = 0x0C, .rms_meter_resamp_fact = 0x50, }, { /* 192 Khz */ .peak_det_timeout = 0x0B, .rms_meter_div_fact = 0xC, .rms_meter_resamp_fact = 0xA0, }, }; static unsigned short rx_digital_gain_reg[] = { TAPAN_A_CDC_RX1_VOL_CTL_B2_CTL, TAPAN_A_CDC_RX2_VOL_CTL_B2_CTL, TAPAN_A_CDC_RX3_VOL_CTL_B2_CTL, TAPAN_A_CDC_RX4_VOL_CTL_B2_CTL, }; static unsigned short tx_digital_gain_reg[] = { TAPAN_A_CDC_TX1_VOL_CTL_GAIN, TAPAN_A_CDC_TX2_VOL_CTL_GAIN, TAPAN_A_CDC_TX3_VOL_CTL_GAIN, TAPAN_A_CDC_TX4_VOL_CTL_GAIN, }; static int spkr_drv_wrnd_param_set(const char *val, const struct kernel_param *kp) { struct snd_soc_codec *codec; int ret, old; struct tapan_priv *priv; priv = (struct tapan_priv *)atomic_read(&kp_tapan_priv); if (!priv) { pr_debug("%s: codec isn't yet registered\n", __func__); return 0; } codec = priv->codec; mutex_lock(&codec->mutex); old = spkr_drv_wrnd; ret = param_set_int(val, kp); if (ret) { mutex_unlock(&codec->mutex); return ret; } dev_dbg(codec->dev, "%s: spkr_drv_wrnd %d -> %d\n", __func__, old, spkr_drv_wrnd); if ((old == -1 || old == 0) && spkr_drv_wrnd == 1) { WCD9XXX_BG_CLK_LOCK(&priv->resmgr); wcd9xxx_resmgr_get_bandgap(&priv->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr); snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x80); } else if (old == 1 && spkr_drv_wrnd == 0) { WCD9XXX_BG_CLK_LOCK(&priv->resmgr); wcd9xxx_resmgr_put_bandgap(&priv->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr); if (!priv->spkr_pa_widget_on) snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x00); } mutex_unlock(&codec->mutex); return 0; } static int tapan_get_anc_slot(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = tapan->anc_slot; return 0; } static int tapan_put_anc_slot(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); tapan->anc_slot = ucontrol->value.integer.value[0]; return 0; } static int tapan_get_anc_func(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = (tapan->anc_func == true ? 1 : 0); return 0; } static int tapan_put_anc_func(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); struct snd_soc_dapm_context *dapm = &codec->dapm; mutex_lock(&dapm->codec->mutex); tapan->anc_func = (!ucontrol->value.integer.value[0] ? false : true); dev_err(codec->dev, "%s: anc_func %x", __func__, tapan->anc_func); if (tapan->anc_func == true) { pr_info("enable anc virtual widgets"); snd_soc_dapm_enable_pin(dapm, "ANC HPHR"); snd_soc_dapm_enable_pin(dapm, "ANC HPHL"); snd_soc_dapm_enable_pin(dapm, "ANC HEADPHONE"); snd_soc_dapm_enable_pin(dapm, "ANC EAR PA"); snd_soc_dapm_enable_pin(dapm, "ANC EAR"); snd_soc_dapm_disable_pin(dapm, "HPHR"); snd_soc_dapm_disable_pin(dapm, "HPHL"); snd_soc_dapm_disable_pin(dapm, "HEADPHONE"); snd_soc_dapm_disable_pin(dapm, "EAR PA"); snd_soc_dapm_disable_pin(dapm, "EAR"); } else { pr_info("disable anc virtual widgets"); snd_soc_dapm_disable_pin(dapm, "ANC HPHR"); snd_soc_dapm_disable_pin(dapm, "ANC HPHL"); snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE"); snd_soc_dapm_disable_pin(dapm, "ANC EAR PA"); snd_soc_dapm_disable_pin(dapm, "ANC EAR"); snd_soc_dapm_enable_pin(dapm, "HPHR"); snd_soc_dapm_enable_pin(dapm, "HPHL"); snd_soc_dapm_enable_pin(dapm, "HEADPHONE"); snd_soc_dapm_enable_pin(dapm, "EAR PA"); snd_soc_dapm_enable_pin(dapm, "EAR"); } snd_soc_dapm_sync(dapm); mutex_unlock(&dapm->codec->mutex); return 0; } static int tapan_loopback_mode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = tapan->lb_mode; dev_dbg(codec->dev, "%s: lb_mode = %d\n", __func__, tapan->lb_mode); return 0; } static int tapan_loopback_mode_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: tapan->lb_mode = false; break; case 1: tapan->lb_mode = true; break; default: return -EINVAL; } return 0; } static int tapan_pa_gain_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { u8 ear_pa_gain; int rc = 0; struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); ear_pa_gain = snd_soc_read(codec, TAPAN_A_RX_EAR_GAIN); ear_pa_gain = ear_pa_gain >> 5; switch (ear_pa_gain) { case 0: case 1: case 2: case 3: case 4: case 5: ucontrol->value.integer.value[0] = ear_pa_gain; break; case 7: ucontrol->value.integer.value[0] = (ear_pa_gain - 1); break; default: rc = -EINVAL; pr_err("%s: ERROR: Unsupported Ear Gain = 0x%x\n", __func__, ear_pa_gain); break; } dev_dbg(codec->dev, "%s: ear_pa_gain = 0x%x\n", __func__, ear_pa_gain); return rc; } static int tapan_pa_gain_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { u8 ear_pa_gain; int rc = 0; struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: case 1: case 2: case 3: case 4: case 5: ear_pa_gain = ucontrol->value.integer.value[0]; break; case 6: ear_pa_gain = 0x07; break; default: rc = -EINVAL; break; } if (!rc) snd_soc_update_bits(codec, TAPAN_A_RX_EAR_GAIN, 0xE0, ear_pa_gain << 5); return rc; } static int tapan_get_iir_enable_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; ucontrol->value.integer.value[0] = (snd_soc_read(codec, (TAPAN_A_CDC_IIR1_CTL + 16 * iir_idx)) & (1 << band_idx)) != 0; dev_dbg(codec->dev, "%s: IIR #%d band #%d enable %d\n", __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[0]); return 0; } static int tapan_put_iir_enable_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; int value = ucontrol->value.integer.value[0]; /* Mask first 5 bits, 6-8 are reserved */ snd_soc_update_bits(codec, (TAPAN_A_CDC_IIR1_CTL + 16 * iir_idx), (1 << band_idx), (value << band_idx)); pr_debug("%s: IIR #%d band #%d enable %d\n", __func__, iir_idx, band_idx, ((snd_soc_read(codec, (TAPAN_A_CDC_IIR1_CTL + 16 * iir_idx)) & (1 << band_idx)) != 0)); return 0; } static uint32_t get_iir_band_coeff(struct snd_soc_codec *codec, int iir_idx, int band_idx, int coeff_idx) { uint32_t value = 0; /* Address does not automatically update if reading */ snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t)) & 0x7F); value |= snd_soc_read(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)); snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t) + 1) & 0x7F); value |= (snd_soc_read(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 8); snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t) + 2) & 0x7F); value |= (snd_soc_read(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 16); snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t) + 3) & 0x7F); /* Mask bits top 2 bits since they are reserved */ value |= ((snd_soc_read(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) & 0x3F) << 24); return value; } static int tapan_get_iir_band_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; ucontrol->value.integer.value[0] = get_iir_band_coeff(codec, iir_idx, band_idx, 0); ucontrol->value.integer.value[1] = get_iir_band_coeff(codec, iir_idx, band_idx, 1); ucontrol->value.integer.value[2] = get_iir_band_coeff(codec, iir_idx, band_idx, 2); ucontrol->value.integer.value[3] = get_iir_band_coeff(codec, iir_idx, band_idx, 3); ucontrol->value.integer.value[4] = get_iir_band_coeff(codec, iir_idx, band_idx, 4); dev_dbg(codec->dev, "%s: IIR #%d band #%d b0 = 0x%x\n" "%s: IIR #%d band #%d b1 = 0x%x\n" "%s: IIR #%d band #%d b2 = 0x%x\n" "%s: IIR #%d band #%d a1 = 0x%x\n" "%s: IIR #%d band #%d a2 = 0x%x\n", __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[0], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[1], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[2], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[3], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[4]); return 0; } static void set_iir_band_coeff(struct snd_soc_codec *codec, int iir_idx, int band_idx, uint32_t value) { snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx), (value & 0xFF)); snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx), (value >> 8) & 0xFF); snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx), (value >> 16) & 0xFF); /* Mask top 2 bits, 7-8 are reserved */ snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx), (value >> 24) & 0x3F); } static int tapan_put_iir_band_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; /* Mask top bit it is reserved */ /* Updates addr automatically for each B2 write */ snd_soc_write(codec, (TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx), (band_idx * BAND_MAX * sizeof(uint32_t)) & 0x7F); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[0]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[1]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[2]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[3]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[4]); dev_dbg(codec->dev, "%s: IIR #%d band #%d b0 = 0x%x\n" "%s: IIR #%d band #%d b1 = 0x%x\n" "%s: IIR #%d band #%d b2 = 0x%x\n" "%s: IIR #%d band #%d a1 = 0x%x\n" "%s: IIR #%d band #%d a2 = 0x%x\n", __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 0), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 1), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 2), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 3), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 4)); return 0; } static int tapan_get_compander(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); int comp = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = tapan->comp_enabled[comp]; return 0; } static int tapan_set_compander(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); int comp = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; int value = ucontrol->value.integer.value[0]; dev_dbg(codec->dev, "%s: Compander %d enable current %d, new %d\n", __func__, comp, tapan->comp_enabled[comp], value); tapan->comp_enabled[comp] = value; if (comp == COMPANDER_1 && tapan->comp_enabled[comp] == 1) { /* Wavegen to 5 msec */ snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_CTL, 0xDA); snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_TIME, 0x15); snd_soc_write(codec, TAPAN_A_RX_HPH_BIAS_WG_OCP, 0x2A); /* Enable Chopper */ snd_soc_update_bits(codec, TAPAN_A_RX_HPH_CHOP_CTL, 0x80, 0x80); snd_soc_write(codec, TAPAN_A_NCP_DTEST, 0x20); pr_debug("%s: Enabled Chopper and set wavegen to 5 msec\n", __func__); } else if (comp == COMPANDER_1 && tapan->comp_enabled[comp] == 0) { /* Wavegen to 20 msec */ snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_CTL, 0xDB); snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_TIME, 0x58); snd_soc_write(codec, TAPAN_A_RX_HPH_BIAS_WG_OCP, 0x1A); /* Disable CHOPPER block */ snd_soc_update_bits(codec, TAPAN_A_RX_HPH_CHOP_CTL, 0x80, 0x00); snd_soc_write(codec, TAPAN_A_NCP_DTEST, 0x10); pr_debug("%s: Disabled Chopper and set wavegen to 20 msec\n", __func__); } return 0; } static int tapan_config_gain_compander(struct snd_soc_codec *codec, int comp, bool enable) { int ret = 0; switch (comp) { case COMPANDER_0: snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_GAIN, 1 << 2, !enable << 2); break; case COMPANDER_1: snd_soc_update_bits(codec, TAPAN_A_RX_HPH_L_GAIN, 1 << 5, !enable << 5); snd_soc_update_bits(codec, TAPAN_A_RX_HPH_R_GAIN, 1 << 5, !enable << 5); break; case COMPANDER_2: snd_soc_update_bits(codec, TAPAN_A_RX_LINE_1_GAIN, 1 << 5, !enable << 5); snd_soc_update_bits(codec, TAPAN_A_RX_LINE_2_GAIN, 1 << 5, !enable << 5); break; default: WARN_ON(1); ret = -EINVAL; } return ret; } static void tapan_discharge_comp(struct snd_soc_codec *codec, int comp) { /* Level meter DIV Factor to 5*/ snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B2_CTL + (comp * 8), 0xF0, 0x05 << 4); /* RMS meter Sampling to 0x01 */ snd_soc_write(codec, TAPAN_A_CDC_COMP0_B3_CTL + (comp * 8), 0x01); /* Worst case timeout for compander CnP sleep timeout */ usleep_range(3000, 3000); } static enum wcd9xxx_buck_volt tapan_codec_get_buck_mv( struct snd_soc_codec *codec) { int buck_volt = WCD9XXX_CDC_BUCK_UNSUPPORTED; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); struct wcd9xxx_pdata *pdata = tapan->resmgr.pdata; int i; bool found_regulator = false; for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) { if (pdata->regulator[i].name == NULL) continue; if (!strncmp(pdata->regulator[i].name, WCD9XXX_SUPPLY_BUCK_NAME, sizeof(WCD9XXX_SUPPLY_BUCK_NAME))) { found_regulator = true; if ((pdata->regulator[i].min_uV == WCD9XXX_CDC_BUCK_MV_1P8) || (pdata->regulator[i].min_uV == WCD9XXX_CDC_BUCK_MV_2P15)) buck_volt = pdata->regulator[i].min_uV; break; } } if (!found_regulator) dev_err(codec->dev, "%s: Failed to find regulator for %s\n", __func__, WCD9XXX_SUPPLY_BUCK_NAME); else dev_dbg(codec->dev, "%s: S4 voltage requested is %d\n", __func__, buck_volt); return buck_volt; } static int tapan_config_compander(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { int mask, enable_mask; u8 rdac5_mux; struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); const int comp = w->shift; const u32 rate = tapan->comp_fs[comp]; const struct comp_sample_dependent_params *comp_params = &comp_samp_params[rate]; enum wcd9xxx_buck_volt buck_mv; dev_dbg(codec->dev, "%s: %s event %d compander %d, enabled %d", __func__, w->name, event, comp, tapan->comp_enabled[comp]); if (!tapan->comp_enabled[comp]) return 0; /* Compander 0 has single channel */ mask = (comp == COMPANDER_0 ? 0x01 : 0x03); buck_mv = tapan_codec_get_buck_mv(codec); rdac5_mux = snd_soc_read(codec, TAPAN_A_CDC_CONN_MISC); rdac5_mux = (rdac5_mux & 0x04) >> 2; if (comp == COMPANDER_0) { /* SPK compander */ enable_mask = 0x02; } else if (comp == COMPANDER_1) { /* HPH compander */ enable_mask = 0x03; } else if (comp == COMPANDER_2) { /* LO compander */ if (rdac5_mux == 0) { /* DEM4 */ /* for LO Stereo SE, enable Compander 2 left * channel on RX3 interpolator Path and Compander 2 * rigt channel on RX4 interpolator Path. */ enable_mask = 0x03; } else if (rdac5_mux == 1) { /* DEM3_INV */ /* for LO mono differential only enable Compander 2 * left channel on RX3 interpolator Path. */ enable_mask = 0x02; } else { dev_err(codec->dev, "%s: invalid rdac5_mux val %d", __func__, rdac5_mux); return -EINVAL; } } else { dev_err(codec->dev, "%s: invalid compander %d", __func__, comp); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: /* Set compander Sample rate */ snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_FS_CFG + (comp * 8), 0x07, rate); /* Set the static gain offset for HPH Path */ if (comp == COMPANDER_1) { if (buck_mv == WCD9XXX_CDC_BUCK_MV_2P15) snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B4_CTL + (comp * 8), 0x80, 0x00); else snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B4_CTL + (comp * 8), 0x80, 0x80); } /* Enable RX interpolation path compander clocks */ snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_B2_CTL, 0x01 << comp_shift[comp], 0x01 << comp_shift[comp]); /* Toggle compander reset bits */ snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL, 0x01 << comp_shift[comp], 0x01 << comp_shift[comp]); snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL, 0x01 << comp_shift[comp], 0); /* Set gain source to compander */ tapan_config_gain_compander(codec, comp, true); /* Compander enable */ snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B1_CTL + (comp * 8), enable_mask, enable_mask); tapan_discharge_comp(codec, comp); /* Set sample rate dependent paramater */ snd_soc_write(codec, TAPAN_A_CDC_COMP0_B3_CTL + (comp * 8), comp_params->rms_meter_resamp_fact); snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B2_CTL + (comp * 8), 0xF0, comp_params->rms_meter_div_fact << 4); snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B2_CTL + (comp * 8), 0x0F, comp_params->peak_det_timeout); break; case SND_SOC_DAPM_PRE_PMD: /* Disable compander */ snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B1_CTL + (comp * 8), enable_mask, 0x00); /* Toggle compander reset bits */ snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL, mask << comp_shift[comp], mask << comp_shift[comp]); snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL, mask << comp_shift[comp], 0); /* Turn off the clock for compander in pair */ snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_B2_CTL, mask << comp_shift[comp], 0); /* Set gain source to register */ tapan_config_gain_compander(codec, comp, false); break; } return 0; } static const char * const tapan_loopback_mode_ctrl_text[] = { "DISABLE", "ENABLE"}; static const struct soc_enum tapan_loopback_mode_ctl_enum[] = { SOC_ENUM_SINGLE_EXT(2, tapan_loopback_mode_ctrl_text), }; static const char * const tapan_ear_pa_gain_text[] = {"POS_6_DB", "POS_4P5_DB", "POS_3_DB", "POS_1P5_DB", "POS_0_DB", "NEG_2P5_DB", "NEG_12_DB"}; static const struct soc_enum tapan_ear_pa_gain_enum[] = { SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(tapan_ear_pa_gain_text), tapan_ear_pa_gain_text), }; static const char *const tapan_anc_func_text[] = {"OFF", "ON"}; static const struct soc_enum tapan_anc_func_enum = SOC_ENUM_SINGLE_EXT(2, tapan_anc_func_text); /*cut of frequency for high pass filter*/ static const char * const cf_text[] = { "MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz" }; static const struct soc_enum cf_dec1_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_TX1_MUX_CTL, 4, 3, cf_text); static const struct soc_enum cf_dec2_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_TX2_MUX_CTL, 4, 3, cf_text); static const struct soc_enum cf_dec3_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_TX3_MUX_CTL, 4, 3, cf_text); static const struct soc_enum cf_dec4_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_TX4_MUX_CTL, 4, 3, cf_text); static const struct soc_enum cf_rxmix1_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_RX1_B4_CTL, 0, 3, cf_text); static const struct soc_enum cf_rxmix2_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_RX2_B4_CTL, 0, 3, cf_text); static const struct soc_enum cf_rxmix3_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_RX3_B4_CTL, 0, 3, cf_text); static const struct soc_enum cf_rxmix4_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_RX4_B4_CTL, 0, 3, cf_text); static const char * const class_h_dsm_text[] = { "ZERO", "RX_HPHL", "RX_SPKR" }; static const struct soc_enum class_h_dsm_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_CLSH_CTL, 2, 3, class_h_dsm_text); static const struct snd_kcontrol_new class_h_dsm_mux = SOC_DAPM_ENUM("CLASS_H_DSM MUX Mux", class_h_dsm_enum); static const char * const rx1_interpolator_text[] = { "ZERO", "RX1 MIX2" }; static const struct soc_enum rx1_interpolator_enum = SOC_ENUM_SINGLE(0, 0, 2, rx1_interpolator_text); static const struct snd_kcontrol_new rx1_interpolator = SOC_DAPM_ENUM_VIRT("RX1 INTERPOLATOR Mux", rx1_interpolator_enum); static const char * const rx2_interpolator_text[] = { "ZERO", "RX2 MIX2" }; static const struct soc_enum rx2_interpolator_enum = SOC_ENUM_SINGLE(0, 1, 2, rx2_interpolator_text); static const struct snd_kcontrol_new rx2_interpolator = SOC_DAPM_ENUM_VIRT("RX2 INTERPOLATOR Mux", rx2_interpolator_enum); static int tapan_hph_impedance_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { uint32_t zl, zr; bool hphr; struct soc_multi_mixer_control *mc; struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec); mc = (struct soc_multi_mixer_control *)(kcontrol->private_value); hphr = mc->shift; wcd9xxx_mbhc_get_impedance(&priv->mbhc, &zl, &zr); pr_debug("%s: zl %u, zr %u\n", __func__, zl, zr); ucontrol->value.integer.value[0] = hphr ? zr : zl; return 0; } static const struct snd_kcontrol_new tapan_common_snd_controls[] = { SOC_ENUM_EXT("EAR PA Gain", tapan_ear_pa_gain_enum[0], tapan_pa_gain_get, tapan_pa_gain_put), SOC_ENUM_EXT("LOOPBACK Mode", tapan_loopback_mode_ctl_enum[0], tapan_loopback_mode_get, tapan_loopback_mode_put), SOC_SINGLE_TLV("HPHL Volume", TAPAN_A_RX_HPH_L_GAIN, 0, 20, 1, line_gain), SOC_SINGLE_TLV("HPHR Volume", TAPAN_A_RX_HPH_R_GAIN, 0, 20, 1, line_gain), SOC_SINGLE_TLV("LINEOUT1 Volume", TAPAN_A_RX_LINE_1_GAIN, 0, 20, 1, line_gain), SOC_SINGLE_TLV("LINEOUT2 Volume", TAPAN_A_RX_LINE_2_GAIN, 0, 20, 1, line_gain), SOC_SINGLE_TLV("SPK DRV Volume", TAPAN_A_SPKR_DRV_GAIN, 3, 8, 1, line_gain), SOC_SINGLE_TLV("ADC1 Volume", TAPAN_A_TX_1_EN, 2, 19, 0, analog_gain), SOC_SINGLE_TLV("ADC2 Volume", TAPAN_A_TX_2_EN, 2, 19, 0, analog_gain), SOC_SINGLE_TLV("ADC3 Volume", TAPAN_A_TX_3_EN, 2, 19, 0, analog_gain), SOC_SINGLE_TLV("ADC4 Volume", TAPAN_A_TX_4_EN, 2, 19, 0, analog_gain), SOC_SINGLE_S8_TLV("RX1 Digital Volume", TAPAN_A_CDC_RX1_VOL_CTL_B2_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("RX2 Digital Volume", TAPAN_A_CDC_RX2_VOL_CTL_B2_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("RX3 Digital Volume", TAPAN_A_CDC_RX3_VOL_CTL_B2_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("DEC1 Volume", TAPAN_A_CDC_TX1_VOL_CTL_GAIN, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("DEC2 Volume", TAPAN_A_CDC_TX2_VOL_CTL_GAIN, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR1 INP1 Volume", TAPAN_A_CDC_IIR1_GAIN_B1_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR1 INP2 Volume", TAPAN_A_CDC_IIR1_GAIN_B2_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR1 INP3 Volume", TAPAN_A_CDC_IIR1_GAIN_B3_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR1 INP4 Volume", TAPAN_A_CDC_IIR1_GAIN_B4_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR2 INP1 Volume", TAPAN_A_CDC_IIR2_GAIN_B1_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR2 INP2 Volume", TAPAN_A_CDC_IIR2_GAIN_B2_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR2 INP3 Volume", TAPAN_A_CDC_IIR2_GAIN_B3_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("IIR2 INP4 Volume", TAPAN_A_CDC_IIR2_GAIN_B4_CTL, -84, 40, digital_gain), SOC_ENUM("TX1 HPF cut off", cf_dec1_enum), SOC_ENUM("TX2 HPF cut off", cf_dec2_enum), SOC_ENUM("TX3 HPF cut off", cf_dec3_enum), SOC_ENUM("TX4 HPF cut off", cf_dec4_enum), SOC_SINGLE("TX1 HPF Switch", TAPAN_A_CDC_TX1_MUX_CTL, 3, 1, 0), SOC_SINGLE("TX2 HPF Switch", TAPAN_A_CDC_TX2_MUX_CTL, 3, 1, 0), SOC_SINGLE("TX3 HPF Switch", TAPAN_A_CDC_TX3_MUX_CTL, 3, 1, 0), SOC_SINGLE("TX4 HPF Switch", TAPAN_A_CDC_TX4_MUX_CTL, 3, 1, 0), SOC_SINGLE("RX1 HPF Switch", TAPAN_A_CDC_RX1_B5_CTL, 2, 1, 0), SOC_SINGLE("RX2 HPF Switch", TAPAN_A_CDC_RX2_B5_CTL, 2, 1, 0), SOC_SINGLE("RX3 HPF Switch", TAPAN_A_CDC_RX3_B5_CTL, 2, 1, 0), SOC_ENUM("RX1 HPF cut off", cf_rxmix1_enum), SOC_ENUM("RX2 HPF cut off", cf_rxmix2_enum), SOC_ENUM("RX3 HPF cut off", cf_rxmix3_enum), SOC_SINGLE_EXT("IIR1 Enable Band1", IIR1, BAND1, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band2", IIR1, BAND2, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band3", IIR1, BAND3, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band4", IIR1, BAND4, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band5", IIR1, BAND5, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band1", IIR2, BAND1, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band2", IIR2, BAND2, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band3", IIR2, BAND3, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band4", IIR2, BAND4, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band5", IIR2, BAND5, 1, 0, tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band1", IIR1, BAND1, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band2", IIR1, BAND2, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band3", IIR1, BAND3, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band4", IIR1, BAND4, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band5", IIR1, BAND5, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band1", IIR2, BAND1, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band2", IIR2, BAND2, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band3", IIR2, BAND3, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band4", IIR2, BAND4, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band5", IIR2, BAND5, 255, 0, 5, tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer), SOC_SINGLE_EXT("HPHL Impedance", 0, 0, UINT_MAX, 0, tapan_hph_impedance_get, NULL), SOC_SINGLE_EXT("HPHR Impedance", 0, 1, UINT_MAX, 0, tapan_hph_impedance_get, NULL), }; static const struct snd_kcontrol_new tapan_9306_snd_controls[] = { SOC_SINGLE_TLV("ADC5 Volume", TAPAN_A_TX_5_EN, 2, 19, 0, analog_gain), SOC_SINGLE_S8_TLV("RX4 Digital Volume", TAPAN_A_CDC_RX4_VOL_CTL_B2_CTL, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("DEC3 Volume", TAPAN_A_CDC_TX3_VOL_CTL_GAIN, -84, 40, digital_gain), SOC_SINGLE_S8_TLV("DEC4 Volume", TAPAN_A_CDC_TX4_VOL_CTL_GAIN, -84, 40, digital_gain), SOC_SINGLE_EXT("ANC Slot", SND_SOC_NOPM, 0, 100, 0, tapan_get_anc_slot, tapan_put_anc_slot), SOC_ENUM_EXT("ANC Function", tapan_anc_func_enum, tapan_get_anc_func, tapan_put_anc_func), SOC_SINGLE("RX4 HPF Switch", TAPAN_A_CDC_RX4_B5_CTL, 2, 1, 0), SOC_ENUM("RX4 HPF cut off", cf_rxmix4_enum), SOC_SINGLE_EXT("COMP0 Switch", SND_SOC_NOPM, COMPANDER_0, 1, 0, tapan_get_compander, tapan_set_compander), SOC_SINGLE_EXT("COMP1 Switch", SND_SOC_NOPM, COMPANDER_1, 1, 0, tapan_get_compander, tapan_set_compander), SOC_SINGLE_EXT("COMP2 Switch", SND_SOC_NOPM, COMPANDER_2, 1, 0, tapan_get_compander, tapan_set_compander), }; static const char * const rx_1_2_mix1_text[] = { "ZERO", "SRC1", "SRC2", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4", "RX5", "AUXRX", "AUXTX1" }; static const char * const rx_3_4_mix1_text[] = { "ZERO", "SRC1", "SRC2", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4", "RX5", "AUXRX", "AUXTX1", "AUXTX2" }; static const char * const rx_mix2_text[] = { "ZERO", "SRC1", "SRC2", "IIR1", "IIR2" }; static const char * const rx_rdac3_text[] = { "DEM1", "DEM2" }; static const char * const rx_rdac4_text[] = { "DEM3", "DEM2" }; static const char * const rx_rdac5_text[] = { "DEM4", "DEM3_INV" }; static const char * const sb_tx_1_2_mux_text[] = { "ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RSVD", "RSVD", "RSVD", "DEC1", "DEC2", "DEC3", "DEC4" }; static const char * const sb_tx3_mux_text[] = { "ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RSVD", "RSVD", "RSVD", "RSVD", "RSVD", "DEC3" }; static const char * const sb_tx4_mux_text[] = { "ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RSVD", "RSVD", "RSVD", "RSVD", "RSVD", "RSVD", "DEC4" }; static const char * const sb_tx5_mux_text[] = { "ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RSVD", "RSVD", "RSVD", "DEC1" }; static const char * const dec_1_2_mux_text[] = { "ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADCMB", "DMIC1", "DMIC2", "DMIC3", "DMIC4" }; static const char * const dec3_mux_text[] = { "ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADCMB", "DMIC1", "DMIC2", "DMIC3", "DMIC4", "ANCFBTUNE1" }; static const char * const dec4_mux_text[] = { "ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADCMB", "DMIC1", "DMIC2", "DMIC3", "DMIC4", "ANCFBTUNE2" }; static const char * const anc_mux_text[] = { "ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "RSVD", "RSVD", "RSVD", "DMIC1", "DMIC2", "DMIC3", "DMIC4", "RSVD", "RSVD" }; static const char * const anc1_fb_mux_text[] = { "ZERO", "EAR_HPH_L", "EAR_LINE_1", }; static const char * const iir_inp_text[] = { "ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "RX1", "RX2", "RX3", "RX4", "RX5" }; static const struct soc_enum rx_mix1_inp1_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B1_CTL, 0, 12, rx_1_2_mix1_text); static const struct soc_enum rx_mix1_inp2_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B1_CTL, 4, 12, rx_1_2_mix1_text); static const struct soc_enum rx_mix1_inp3_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B2_CTL, 0, 12, rx_1_2_mix1_text); static const struct soc_enum rx2_mix1_inp1_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B1_CTL, 0, 12, rx_1_2_mix1_text); static const struct soc_enum rx2_mix1_inp2_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B1_CTL, 4, 12, rx_1_2_mix1_text); static const struct soc_enum rx3_mix1_inp1_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX3_B1_CTL, 0, 13, rx_3_4_mix1_text); static const struct soc_enum rx3_mix1_inp2_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX3_B1_CTL, 4, 13, rx_3_4_mix1_text); static const struct soc_enum rx3_mix1_inp3_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX3_B2_CTL, 0, 13, rx_3_4_mix1_text); static const struct soc_enum rx4_mix1_inp1_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B1_CTL, 0, 13, rx_3_4_mix1_text); static const struct soc_enum rx4_mix1_inp2_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B1_CTL, 4, 13, rx_3_4_mix1_text); static const struct soc_enum rx4_mix1_inp3_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B2_CTL, 0, 13, rx_3_4_mix1_text); static const struct soc_enum rx1_mix2_inp1_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B3_CTL, 0, 5, rx_mix2_text); static const struct soc_enum rx1_mix2_inp2_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B3_CTL, 3, 5, rx_mix2_text); static const struct soc_enum rx2_mix2_inp1_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B3_CTL, 0, 5, rx_mix2_text); static const struct soc_enum rx2_mix2_inp2_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B3_CTL, 3, 5, rx_mix2_text); static const struct soc_enum rx4_mix2_inp1_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B3_CTL, 0, 5, rx_mix2_text); static const struct soc_enum rx4_mix2_inp2_chain_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B3_CTL, 3, 5, rx_mix2_text); static const struct soc_enum rx_rdac3_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B2_CTL, 4, 2, rx_rdac3_text); static const struct soc_enum rx_rdac4_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_MISC, 1, 2, rx_rdac4_text); static const struct soc_enum rx_rdac5_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_MISC, 2, 2, rx_rdac5_text); static const struct soc_enum sb_tx1_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B1_CTL, 0, 12, sb_tx_1_2_mux_text); static const struct soc_enum sb_tx2_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B2_CTL, 0, 12, sb_tx_1_2_mux_text); static const struct soc_enum sb_tx3_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B3_CTL, 0, 11, sb_tx3_mux_text); static const struct soc_enum sb_tx4_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B4_CTL, 0, 12, sb_tx4_mux_text); static const struct soc_enum sb_tx5_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B5_CTL, 0, 9, sb_tx5_mux_text); static const struct soc_enum dec1_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B1_CTL, 0, 10, dec_1_2_mux_text); static const struct soc_enum dec2_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B1_CTL, 4, 10, dec_1_2_mux_text); static const struct soc_enum dec3_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B2_CTL, 0, 12, dec3_mux_text); static const struct soc_enum dec4_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B2_CTL, 4, 12, dec4_mux_text); static const struct soc_enum anc1_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_ANC_B1_CTL, 0, 15, anc_mux_text); static const struct soc_enum anc2_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_ANC_B1_CTL, 4, 15, anc_mux_text); static const struct soc_enum anc1_fb_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_ANC_B2_CTL, 0, 3, anc1_fb_mux_text); static const struct soc_enum iir1_inp1_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B1_CTL, 0, 10, iir_inp_text); static const struct soc_enum iir1_inp2_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B2_CTL, 0, 10, iir_inp_text); static const struct soc_enum iir1_inp3_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B3_CTL, 0, 10, iir_inp_text); static const struct soc_enum iir1_inp4_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B4_CTL, 0, 10, iir_inp_text); static const struct soc_enum iir2_inp1_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B1_CTL, 0, 10, iir_inp_text); static const struct soc_enum iir2_inp2_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B2_CTL, 0, 10, iir_inp_text); static const struct soc_enum iir2_inp3_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B3_CTL, 0, 10, iir_inp_text); static const struct soc_enum iir2_inp4_mux_enum = SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B4_CTL, 0, 10, iir_inp_text); static const struct snd_kcontrol_new rx_mix1_inp1_mux = SOC_DAPM_ENUM("RX1 MIX1 INP1 Mux", rx_mix1_inp1_chain_enum); static const struct snd_kcontrol_new rx_mix1_inp2_mux = SOC_DAPM_ENUM("RX1 MIX1 INP2 Mux", rx_mix1_inp2_chain_enum); static const struct snd_kcontrol_new rx_mix1_inp3_mux = SOC_DAPM_ENUM("RX1 MIX1 INP3 Mux", rx_mix1_inp3_chain_enum); static const struct snd_kcontrol_new rx2_mix1_inp1_mux = SOC_DAPM_ENUM("RX2 MIX1 INP1 Mux", rx2_mix1_inp1_chain_enum); static const struct snd_kcontrol_new rx2_mix1_inp2_mux = SOC_DAPM_ENUM("RX2 MIX1 INP2 Mux", rx2_mix1_inp2_chain_enum); static const struct snd_kcontrol_new rx3_mix1_inp1_mux = SOC_DAPM_ENUM("RX3 MIX1 INP1 Mux", rx3_mix1_inp1_chain_enum); static const struct snd_kcontrol_new rx3_mix1_inp2_mux = SOC_DAPM_ENUM("RX3 MIX1 INP2 Mux", rx3_mix1_inp2_chain_enum); static const struct snd_kcontrol_new rx3_mix1_inp3_mux = SOC_DAPM_ENUM("RX3 MIX1 INP3 Mux", rx3_mix1_inp3_chain_enum); static const struct snd_kcontrol_new rx4_mix1_inp1_mux = SOC_DAPM_ENUM("RX4 MIX1 INP1 Mux", rx4_mix1_inp1_chain_enum); static const struct snd_kcontrol_new rx4_mix1_inp2_mux = SOC_DAPM_ENUM("RX4 MIX1 INP2 Mux", rx4_mix1_inp2_chain_enum); static const struct snd_kcontrol_new rx4_mix1_inp3_mux = SOC_DAPM_ENUM("RX4 MIX1 INP3 Mux", rx4_mix1_inp3_chain_enum); static const struct snd_kcontrol_new rx1_mix2_inp1_mux = SOC_DAPM_ENUM("RX1 MIX2 INP1 Mux", rx1_mix2_inp1_chain_enum); static const struct snd_kcontrol_new rx1_mix2_inp2_mux = SOC_DAPM_ENUM("RX1 MIX2 INP2 Mux", rx1_mix2_inp2_chain_enum); static const struct snd_kcontrol_new rx2_mix2_inp1_mux = SOC_DAPM_ENUM("RX2 MIX2 INP1 Mux", rx2_mix2_inp1_chain_enum); static const struct snd_kcontrol_new rx2_mix2_inp2_mux = SOC_DAPM_ENUM("RX2 MIX2 INP2 Mux", rx2_mix2_inp2_chain_enum); static const struct snd_kcontrol_new rx4_mix2_inp1_mux = SOC_DAPM_ENUM("RX4 MIX2 INP1 Mux", rx4_mix2_inp1_chain_enum); static const struct snd_kcontrol_new rx4_mix2_inp2_mux = SOC_DAPM_ENUM("RX4 MIX2 INP2 Mux", rx4_mix2_inp2_chain_enum); static const struct snd_kcontrol_new rx_dac3_mux = SOC_DAPM_ENUM("RDAC3 MUX Mux", rx_rdac3_enum); static const struct snd_kcontrol_new rx_dac4_mux = SOC_DAPM_ENUM("RDAC4 MUX Mux", rx_rdac4_enum); static const struct snd_kcontrol_new rx_dac5_mux = SOC_DAPM_ENUM("RDAC5 MUX Mux", rx_rdac5_enum); static const struct snd_kcontrol_new sb_tx1_mux = SOC_DAPM_ENUM("SLIM TX1 MUX Mux", sb_tx1_mux_enum); static const struct snd_kcontrol_new sb_tx2_mux = SOC_DAPM_ENUM("SLIM TX2 MUX Mux", sb_tx2_mux_enum); static const struct snd_kcontrol_new sb_tx3_mux = SOC_DAPM_ENUM("SLIM TX3 MUX Mux", sb_tx3_mux_enum); static const struct snd_kcontrol_new sb_tx4_mux = SOC_DAPM_ENUM("SLIM TX4 MUX Mux", sb_tx4_mux_enum); static const struct snd_kcontrol_new sb_tx5_mux = SOC_DAPM_ENUM("SLIM TX5 MUX Mux", sb_tx5_mux_enum); static int wcd9306_put_dec_enum(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol); struct snd_soc_dapm_widget *w = wlist->widgets[0]; struct snd_soc_codec *codec = w->codec; struct soc_enum *e = (struct soc_enum *)kcontrol->private_value; unsigned int dec_mux, decimator; char *dec_name = NULL; char *widget_name = NULL; char *temp; u16 tx_mux_ctl_reg; u8 adc_dmic_sel = 0x0; int ret = 0; char *srch = NULL; if (ucontrol->value.enumerated.item[0] > e->max - 1) return -EINVAL; dec_mux = ucontrol->value.enumerated.item[0]; widget_name = kstrndup(w->name, 15, GFP_KERNEL); if (!widget_name) return -ENOMEM; temp = widget_name; dec_name = strsep(&widget_name, " "); widget_name = temp; if (!dec_name) { pr_err("%s: Invalid decimator = %s\n", __func__, w->name); ret = -EINVAL; goto out; } srch = strpbrk(dec_name, "1234"); if (srch == NULL) { pr_err("%s: Invalid decimator name %s\n", __func__, dec_name); return -EINVAL; } ret = kstrtouint(srch, 10, &decimator); if (ret < 0) { pr_err("%s: Invalid decimator = %s\n", __func__, dec_name); ret = -EINVAL; goto out; } dev_dbg(w->dapm->dev, "%s(): widget = %s decimator = %u dec_mux = %u\n" , __func__, w->name, decimator, dec_mux); switch (decimator) { case 1: case 2: if ((dec_mux >= 1) && (dec_mux <= 5)) adc_dmic_sel = 0x0; else if ((dec_mux >= 6) && (dec_mux <= 9)) adc_dmic_sel = 0x1; break; case 3: case 4: if ((dec_mux >= 1) && (dec_mux <= 6)) adc_dmic_sel = 0x0; else if ((dec_mux >= 7) && (dec_mux <= 10)) adc_dmic_sel = 0x1; break; default: pr_err("%s: Invalid Decimator = %u\n", __func__, decimator); ret = -EINVAL; goto out; } tx_mux_ctl_reg = TAPAN_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x1, adc_dmic_sel); ret = snd_soc_dapm_put_enum_double(kcontrol, ucontrol); out: kfree(widget_name); return ret; } #define WCD9306_DEC_ENUM(xname, xenum) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_soc_info_enum_double, \ .get = snd_soc_dapm_get_enum_double, \ .put = wcd9306_put_dec_enum, \ .private_value = (unsigned long)&xenum } static const struct snd_kcontrol_new dec1_mux = WCD9306_DEC_ENUM("DEC1 MUX Mux", dec1_mux_enum); static const struct snd_kcontrol_new dec2_mux = WCD9306_DEC_ENUM("DEC2 MUX Mux", dec2_mux_enum); static const struct snd_kcontrol_new dec3_mux = WCD9306_DEC_ENUM("DEC3 MUX Mux", dec3_mux_enum); static const struct snd_kcontrol_new dec4_mux = WCD9306_DEC_ENUM("DEC4 MUX Mux", dec4_mux_enum); static const struct snd_kcontrol_new iir1_inp1_mux = SOC_DAPM_ENUM("IIR1 INP1 Mux", iir1_inp1_mux_enum); static const struct snd_kcontrol_new iir1_inp2_mux = SOC_DAPM_ENUM("IIR1 INP2 Mux", iir1_inp2_mux_enum); static const struct snd_kcontrol_new iir1_inp3_mux = SOC_DAPM_ENUM("IIR1 INP3 Mux", iir1_inp3_mux_enum); static const struct snd_kcontrol_new iir1_inp4_mux = SOC_DAPM_ENUM("IIR1 INP4 Mux", iir1_inp4_mux_enum); static const struct snd_kcontrol_new iir2_inp1_mux = SOC_DAPM_ENUM("IIR2 INP1 Mux", iir2_inp1_mux_enum); static const struct snd_kcontrol_new iir2_inp2_mux = SOC_DAPM_ENUM("IIR2 INP2 Mux", iir2_inp2_mux_enum); static const struct snd_kcontrol_new iir2_inp3_mux = SOC_DAPM_ENUM("IIR2 INP3 Mux", iir2_inp3_mux_enum); static const struct snd_kcontrol_new iir2_inp4_mux = SOC_DAPM_ENUM("IIR2 INP4 Mux", iir2_inp4_mux_enum); static const struct snd_kcontrol_new anc1_mux = SOC_DAPM_ENUM("ANC1 MUX Mux", anc1_mux_enum); static const struct snd_kcontrol_new anc2_mux = SOC_DAPM_ENUM("ANC2 MUX Mux", anc2_mux_enum); static const struct snd_kcontrol_new anc1_fb_mux = SOC_DAPM_ENUM("ANC1 FB MUX Mux", anc1_fb_mux_enum); static const struct snd_kcontrol_new dac1_switch[] = { SOC_DAPM_SINGLE("Switch", TAPAN_A_RX_EAR_EN, 5, 1, 0) }; static const struct snd_kcontrol_new hphl_switch[] = { SOC_DAPM_SINGLE("Switch", TAPAN_A_RX_HPH_L_DAC_CTL, 6, 1, 0) }; static const struct snd_kcontrol_new spk_dac_switch[] = { SOC_DAPM_SINGLE("Switch", TAPAN_A_SPKR_DRV_DAC_CTL, 2, 1, 0) }; static const struct snd_kcontrol_new hphl_pa_mix[] = { SOC_DAPM_SINGLE("AUX_PGA_L Switch", TAPAN_A_RX_PA_AUX_IN_CONN, 7, 1, 0), }; static const struct snd_kcontrol_new hphr_pa_mix[] = { SOC_DAPM_SINGLE("AUX_PGA_R Switch", TAPAN_A_RX_PA_AUX_IN_CONN, 6, 1, 0), }; static const struct snd_kcontrol_new ear_pa_mix[] = { SOC_DAPM_SINGLE("AUX_PGA_L Switch", TAPAN_A_RX_PA_AUX_IN_CONN, 5, 1, 0), }; static const struct snd_kcontrol_new lineout1_pa_mix[] = { SOC_DAPM_SINGLE("AUX_PGA_L Switch", TAPAN_A_RX_PA_AUX_IN_CONN, 4, 1, 0), }; static const struct snd_kcontrol_new lineout2_pa_mix[] = { SOC_DAPM_SINGLE("AUX_PGA_R Switch", TAPAN_A_RX_PA_AUX_IN_CONN, 3, 1, 0), }; /* virtual port entries */ static int slim_tx_mixer_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol); struct snd_soc_dapm_widget *widget = wlist->widgets[0]; ucontrol->value.integer.value[0] = widget->value; return 0; } static int slim_tx_mixer_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol); struct snd_soc_dapm_widget *widget = wlist->widgets[0]; struct snd_soc_codec *codec = widget->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent); struct soc_multi_mixer_control *mixer = ((struct soc_multi_mixer_control *)kcontrol->private_value); u32 dai_id = widget->shift; u32 port_id = mixer->shift; u32 enable = ucontrol->value.integer.value[0]; u32 vtable = vport_check_table[dai_id]; dev_dbg(codec->dev, "%s: wname %s cname %s\n", __func__, widget->name, ucontrol->id.name); dev_dbg(codec->dev, "%s: value %u shift %d item %ld\n", __func__, widget->value, widget->shift, ucontrol->value.integer.value[0]); mutex_lock(&codec->mutex); if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) { if (dai_id != AIF1_CAP) { dev_err(codec->dev, "%s: invalid AIF for I2C mode\n", __func__); mutex_unlock(&codec->mutex); return -EINVAL; } } switch (dai_id) { case AIF1_CAP: case AIF2_CAP: case AIF3_CAP: /* only add to the list if value not set */ if (enable && !(widget->value & 1 << port_id)) { if (tapan_p->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) vtable = vport_check_table[dai_id]; if (tapan_p->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) vtable = vport_i2s_check_table[dai_id]; if (wcd9xxx_tx_vport_validation( vtable, port_id, tapan_p->dai, NUM_CODEC_DAIS)) { dev_dbg(codec->dev, "%s: TX%u is used by other virtual port\n", __func__, port_id + 1); mutex_unlock(&codec->mutex); return 0; } widget->value |= 1 << port_id; list_add_tail(&core->tx_chs[port_id].list, &tapan_p->dai[dai_id].wcd9xxx_ch_list ); } else if (!enable && (widget->value & 1 << port_id)) { widget->value &= ~(1 << port_id); list_del_init(&core->tx_chs[port_id].list); } else { if (enable) dev_dbg(codec->dev, "%s: TX%u port is used by\n" "this virtual port\n", __func__, port_id + 1); else dev_dbg(codec->dev, "%s: TX%u port is not used by\n" "this virtual port\n", __func__, port_id + 1); /* avoid update power function */ mutex_unlock(&codec->mutex); return 0; } break; default: dev_err(codec->dev, "Unknown AIF %d\n", dai_id); mutex_unlock(&codec->mutex); return -EINVAL; } dev_dbg(codec->dev, "%s: name %s sname %s updated value %u shift %d\n", __func__, widget->name, widget->sname, widget->value, widget->shift); snd_soc_dapm_mixer_update_power(widget, kcontrol, enable); mutex_unlock(&codec->mutex); return 0; } static int slim_rx_mux_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol); struct snd_soc_dapm_widget *widget = wlist->widgets[0]; ucontrol->value.enumerated.item[0] = widget->value; return 0; } static const char *const slim_rx_mux_text[] = { "ZERO", "AIF1_PB", "AIF2_PB", "AIF3_PB" }; static int slim_rx_mux_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol); struct snd_soc_dapm_widget *widget = wlist->widgets[0]; struct snd_soc_codec *codec = widget->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent); struct soc_enum *e = (struct soc_enum *)kcontrol->private_value; u32 port_id = widget->shift; dev_dbg(codec->dev, "%s: wname %s cname %s value %u shift %d item %ld\n", __func__, widget->name, ucontrol->id.name, widget->value, widget->shift, ucontrol->value.integer.value[0]); widget->value = ucontrol->value.enumerated.item[0]; mutex_lock(&codec->mutex); if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) { if (widget->value > 1) { dev_err(codec->dev, "%s: invalid AIF for I2C mode\n", __func__); goto err; } } /* value need to match the Virtual port and AIF number */ switch (widget->value) { case 0: list_del_init(&core->rx_chs[port_id].list); break; case 1: if (wcd9xxx_rx_vport_validation(port_id + TAPAN_RX_PORT_START_NUMBER, &tapan_p->dai[AIF1_PB].wcd9xxx_ch_list)) { dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n", __func__, port_id + 1); goto rtn; } list_add_tail(&core->rx_chs[port_id].list, &tapan_p->dai[AIF1_PB].wcd9xxx_ch_list); break; case 2: if (wcd9xxx_rx_vport_validation(port_id + TAPAN_RX_PORT_START_NUMBER, &tapan_p->dai[AIF2_PB].wcd9xxx_ch_list)) { dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n", __func__, port_id + 1); goto rtn; } list_add_tail(&core->rx_chs[port_id].list, &tapan_p->dai[AIF2_PB].wcd9xxx_ch_list); break; case 3: if (wcd9xxx_rx_vport_validation(port_id + TAPAN_RX_PORT_START_NUMBER, &tapan_p->dai[AIF3_PB].wcd9xxx_ch_list)) { dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n", __func__, port_id + 1); goto rtn; } list_add_tail(&core->rx_chs[port_id].list, &tapan_p->dai[AIF3_PB].wcd9xxx_ch_list); break; default: pr_err("Unknown AIF %d\n", widget->value); goto err; } rtn: snd_soc_dapm_mux_update_power(widget, kcontrol, 1, widget->value, e); mutex_unlock(&codec->mutex); return 0; err: mutex_unlock(&codec->mutex); return -EINVAL; } static const struct soc_enum slim_rx_mux_enum = SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(slim_rx_mux_text), slim_rx_mux_text); static const struct snd_kcontrol_new slim_rx_mux[TAPAN_RX_MAX] = { SOC_DAPM_ENUM_EXT("SLIM RX1 Mux", slim_rx_mux_enum, slim_rx_mux_get, slim_rx_mux_put), SOC_DAPM_ENUM_EXT("SLIM RX2 Mux", slim_rx_mux_enum, slim_rx_mux_get, slim_rx_mux_put), SOC_DAPM_ENUM_EXT("SLIM RX3 Mux", slim_rx_mux_enum, slim_rx_mux_get, slim_rx_mux_put), SOC_DAPM_ENUM_EXT("SLIM RX4 Mux", slim_rx_mux_enum, slim_rx_mux_get, slim_rx_mux_put), SOC_DAPM_ENUM_EXT("SLIM RX5 Mux", slim_rx_mux_enum, slim_rx_mux_get, slim_rx_mux_put), }; static const struct snd_kcontrol_new aif_cap_mixer[] = { SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TAPAN_TX1, 1, 0, slim_tx_mixer_get, slim_tx_mixer_put), SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TAPAN_TX2, 1, 0, slim_tx_mixer_get, slim_tx_mixer_put), SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TAPAN_TX3, 1, 0, slim_tx_mixer_get, slim_tx_mixer_put), SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TAPAN_TX4, 1, 0, slim_tx_mixer_get, slim_tx_mixer_put), SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TAPAN_TX5, 1, 0, slim_tx_mixer_get, slim_tx_mixer_put), }; static int tapan_codec_enable_adc(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); u16 adc_reg; u8 init_bit_shift; dev_dbg(codec->dev, "%s(): %s %d\n", __func__, w->name, event); if (w->reg == TAPAN_A_TX_1_EN) { init_bit_shift = 7; adc_reg = TAPAN_A_TX_1_2_TEST_CTL; } else if (w->reg == TAPAN_A_TX_2_EN) { init_bit_shift = 6; adc_reg = TAPAN_A_TX_1_2_TEST_CTL; } else if (w->reg == TAPAN_A_TX_3_EN) { init_bit_shift = 6; adc_reg = TAPAN_A_TX_1_2_TEST_CTL; } else if (w->reg == TAPAN_A_TX_4_EN) { init_bit_shift = 7; adc_reg = TAPAN_A_TX_4_5_TEST_CTL; } else if (w->reg == TAPAN_A_TX_5_EN) { init_bit_shift = 6; adc_reg = TAPAN_A_TX_4_5_TEST_CTL; } else { pr_err("%s: Error, invalid adc register\n", __func__); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: if (w->reg == TAPAN_A_TX_3_EN || w->reg == TAPAN_A_TX_1_EN) wcd9xxx_resmgr_notifier_call(&tapan->resmgr, WCD9XXX_EVENT_PRE_TX_1_3_ON); snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 1 << init_bit_shift); break; case SND_SOC_DAPM_POST_PMU: usleep_range(2000, 2010); snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 0x00); break; case SND_SOC_DAPM_POST_PMD: if (w->reg == TAPAN_A_TX_3_EN || w->reg == TAPAN_A_TX_1_EN) wcd9xxx_resmgr_notifier_call(&tapan->resmgr, WCD9XXX_EVENT_POST_TX_1_3_OFF); break; } return 0; } static int tapan_codec_enable_aux_pga(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: WCD9XXX_BG_CLK_LOCK(&tapan->resmgr); wcd9xxx_resmgr_get_bandgap(&tapan->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); /* AUX PGA requires RCO or MCLK */ wcd9xxx_resmgr_get_clk_block(&tapan->resmgr, WCD9XXX_CLK_RCO); WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr); wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 1); break; case SND_SOC_DAPM_POST_PMD: wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 0); WCD9XXX_BG_CLK_LOCK(&tapan->resmgr); wcd9xxx_resmgr_put_bandgap(&tapan->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); wcd9xxx_resmgr_put_clk_block(&tapan->resmgr, WCD9XXX_CLK_RCO); WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr); break; } return 0; } static int tapan_codec_enable_lineout(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); u16 lineout_gain_reg; dev_dbg(codec->dev, "%s %d %s\n", __func__, event, w->name); switch (w->shift) { case 0: lineout_gain_reg = TAPAN_A_RX_LINE_1_GAIN; break; case 1: lineout_gain_reg = TAPAN_A_RX_LINE_2_GAIN; break; default: pr_err("%s: Error, incorrect lineout register value\n", __func__); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: break; case SND_SOC_DAPM_POST_PMU: wcd9xxx_clsh_fsm(codec, &tapan->clsh_d, WCD9XXX_CLSH_STATE_LO, WCD9XXX_CLSH_REQ_ENABLE, WCD9XXX_CLSH_EVENT_POST_PA); dev_dbg(codec->dev, "%s: sleeping 5 ms after %s PA turn on\n", __func__, w->name); /* Wait for CnP time after PA enable */ usleep_range(5000, 5100); break; case SND_SOC_DAPM_POST_PMD: wcd9xxx_clsh_fsm(codec, &tapan->clsh_d, WCD9XXX_CLSH_STATE_LO, WCD9XXX_CLSH_REQ_DISABLE, WCD9XXX_CLSH_EVENT_POST_PA); dev_dbg(codec->dev, "%s: sleeping 5 ms after %s PA turn on\n", __func__, w->name); /* Wait for CnP time after PA disable */ usleep_range(5000, 5100); break; } return 0; } static int tapan_codec_enable_spk_pa(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: tapan->spkr_pa_widget_on = true; snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x80); break; case SND_SOC_DAPM_POST_PMD: tapan->spkr_pa_widget_on = false; snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x00); break; } return 0; } static int tapan_codec_enable_dmic(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); u8 dmic_clk_en; u16 dmic_clk_reg; s32 *dmic_clk_cnt; unsigned int dmic; int ret; char *srch = NULL; srch = strpbrk(w->name, "1234"); if (srch == NULL) { pr_err("%s: Invalid widget name %s\n", __func__, w->name); return -EINVAL; } ret = kstrtouint(srch, 10, &dmic); if (ret < 0) { pr_err("%s: Invalid DMIC line on the codec\n", __func__); return -EINVAL; } switch (dmic) { case 1: case 2: dmic_clk_en = 0x01; dmic_clk_cnt = &(tapan->dmic_1_2_clk_cnt); dmic_clk_reg = TAPAN_A_CDC_CLK_DMIC_B1_CTL; dev_dbg(codec->dev, "%s() event %d DMIC%d dmic_1_2_clk_cnt %d\n", __func__, event, dmic, *dmic_clk_cnt); break; case 3: case 4: dmic_clk_en = 0x10; dmic_clk_cnt = &(tapan->dmic_3_4_clk_cnt); dmic_clk_reg = TAPAN_A_CDC_CLK_DMIC_B1_CTL; dev_dbg(codec->dev, "%s() event %d DMIC%d dmic_3_4_clk_cnt %d\n", __func__, event, dmic, *dmic_clk_cnt); break; default: pr_err("%s: Invalid DMIC Selection\n", __func__); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: (*dmic_clk_cnt)++; if (*dmic_clk_cnt == 1) snd_soc_update_bits(codec, dmic_clk_reg, dmic_clk_en, dmic_clk_en); break; case SND_SOC_DAPM_POST_PMD: (*dmic_clk_cnt)--; if (*dmic_clk_cnt == 0) snd_soc_update_bits(codec, dmic_clk_reg, dmic_clk_en, 0); break; } return 0; } static int tapan_codec_enable_anc(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; const char *filename; const struct firmware *fw; int i; int ret; int num_anc_slots; struct wcd9xxx_anc_header *anc_head; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); u32 anc_writes_size = 0; int anc_size_remaining; u32 *anc_ptr; u16 reg; u8 mask, val, old_val; dev_dbg(codec->dev, "%s %d\n", __func__, event); if (tapan->anc_func == 0) return 0; switch (event) { case SND_SOC_DAPM_PRE_PMU: filename = "wcd9306/wcd9306_anc.bin"; ret = request_firmware(&fw, filename, codec->dev); if (ret != 0) { dev_err(codec->dev, "Failed to acquire ANC data: %d\n", ret); return -ENODEV; } if (fw->size < sizeof(struct wcd9xxx_anc_header)) { dev_err(codec->dev, "Not enough data\n"); release_firmware(fw); return -ENOMEM; } /* First number is the number of register writes */ anc_head = (struct wcd9xxx_anc_header *)(fw->data); anc_ptr = (u32 *)((u32)fw->data + sizeof(struct wcd9xxx_anc_header)); anc_size_remaining = fw->size - sizeof(struct wcd9xxx_anc_header); num_anc_slots = anc_head->num_anc_slots; if (tapan->anc_slot >= num_anc_slots) { dev_err(codec->dev, "Invalid ANC slot selected\n"); release_firmware(fw); return -EINVAL; } for (i = 0; i < num_anc_slots; i++) { if (anc_size_remaining < TAPAN_PACKED_REG_SIZE) { dev_err(codec->dev, "Invalid register format\n"); release_firmware(fw); return -EINVAL; } anc_writes_size = (u32)(*anc_ptr); anc_size_remaining -= sizeof(u32); anc_ptr += 1; if (anc_writes_size * TAPAN_PACKED_REG_SIZE > anc_size_remaining) { dev_err(codec->dev, "Invalid register format\n"); release_firmware(fw); return -ENOMEM; } if (tapan->anc_slot == i) break; anc_size_remaining -= (anc_writes_size * TAPAN_PACKED_REG_SIZE); anc_ptr += anc_writes_size; } if (i == num_anc_slots) { dev_err(codec->dev, "Selected ANC slot not present\n"); release_firmware(fw); return -ENOMEM; } for (i = 0; i < anc_writes_size; i++) { TAPAN_CODEC_UNPACK_ENTRY(anc_ptr[i], reg, mask, val); old_val = snd_soc_read(codec, reg); snd_soc_write(codec, reg, (old_val & ~mask) | (val & mask)); } release_firmware(fw); break; case SND_SOC_DAPM_PRE_PMD: msleep(40); snd_soc_update_bits(codec, TAPAN_A_CDC_ANC1_B1_CTL, 0x01, 0x00); snd_soc_update_bits(codec, TAPAN_A_CDC_ANC2_B1_CTL, 0x02, 0x00); msleep(20); snd_soc_write(codec, TAPAN_A_CDC_CLK_ANC_RESET_CTL, 0x0F); snd_soc_write(codec, TAPAN_A_CDC_CLK_ANC_CLK_EN_CTL, 0); snd_soc_write(codec, TAPAN_A_CDC_CLK_ANC_RESET_CTL, 0xFF); break; } return 0; } static int tapan_codec_enable_micbias(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); u16 micb_int_reg = 0, micb_ctl_reg = 0; u8 cfilt_sel_val = 0; char *internal1_text = "Internal1"; char *internal2_text = "Internal2"; char *internal3_text = "Internal3"; enum wcd9xxx_notify_event e_post_off, e_pre_on, e_post_on; pr_debug("%s: w->name %s event %d\n", __func__, w->name, event); if (strnstr(w->name, "MIC BIAS1", sizeof("MIC BIAS1"))) { micb_ctl_reg = TAPAN_A_MICB_1_CTL; micb_int_reg = TAPAN_A_MICB_1_INT_RBIAS; cfilt_sel_val = tapan->resmgr.pdata->micbias.bias1_cfilt_sel; e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_1_ON; e_post_on = WCD9XXX_EVENT_POST_MICBIAS_1_ON; e_post_off = WCD9XXX_EVENT_POST_MICBIAS_1_OFF; } else if (strnstr(w->name, "MIC BIAS2", sizeof("MIC BIAS2"))) { micb_ctl_reg = TAPAN_A_MICB_2_CTL; micb_int_reg = TAPAN_A_MICB_2_INT_RBIAS; cfilt_sel_val = tapan->resmgr.pdata->micbias.bias2_cfilt_sel; e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_2_ON; e_post_on = WCD9XXX_EVENT_POST_MICBIAS_2_ON; e_post_off = WCD9XXX_EVENT_POST_MICBIAS_2_OFF; } else if (strnstr(w->name, "MIC BIAS3", sizeof("MIC BIAS3"))) { micb_ctl_reg = TAPAN_A_MICB_3_CTL; micb_int_reg = TAPAN_A_MICB_3_INT_RBIAS; cfilt_sel_val = tapan->resmgr.pdata->micbias.bias3_cfilt_sel; e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_3_ON; e_post_on = WCD9XXX_EVENT_POST_MICBIAS_3_ON; e_post_off = WCD9XXX_EVENT_POST_MICBIAS_3_OFF; } else { pr_err("%s: Error, invalid micbias %s\n", __func__, w->name); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: /* Let MBHC module know so micbias switch to be off */ wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_pre_on); /* Get cfilt */ wcd9xxx_resmgr_cfilt_get(&tapan->resmgr, cfilt_sel_val); if (strnstr(w->name, internal1_text, 30)) snd_soc_update_bits(codec, micb_int_reg, 0xE0, 0xE0); else if (strnstr(w->name, internal2_text, 30)) snd_soc_update_bits(codec, micb_int_reg, 0x1C, 0x1C); else if (strnstr(w->name, internal3_text, 30)) snd_soc_update_bits(codec, micb_int_reg, 0x3, 0x3); if (micb_ctl_reg == TAPAN_A_MICB_2_CTL) { if (++tapan->micb_2_users == 1) wcd9xxx_resmgr_add_cond_update_bits( &tapan->resmgr, WCD9XXX_COND_HPH_MIC, micb_ctl_reg, w->shift, false); pr_debug("%s: micb_2_users %d\n", __func__, tapan->micb_2_users); } else snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift, 1 << w->shift); break; case SND_SOC_DAPM_POST_PMU: usleep_range(20000, 20000); /* Let MBHC module know so micbias is on */ wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_post_on); break; case SND_SOC_DAPM_POST_PMD: if (micb_ctl_reg == TAPAN_A_MICB_2_CTL) { if (--tapan->micb_2_users == 0) wcd9xxx_resmgr_rm_cond_update_bits( &tapan->resmgr, WCD9XXX_COND_HPH_MIC, micb_ctl_reg, 7, false); pr_debug("%s: micb_2_users %d\n", __func__, tapan->micb_2_users); WARN(tapan->micb_2_users < 0, "Unexpected micbias users %d\n", tapan->micb_2_users); } else snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift, 0); /* Let MBHC module know so micbias switch to be off */ wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_post_off); if (strnstr(w->name, internal1_text, 30)) snd_soc_update_bits(codec, micb_int_reg, 0x80, 0x00); else if (strnstr(w->name, internal2_text, 30)) snd_soc_update_bits(codec, micb_int_reg, 0x10, 0x00); else if (strnstr(w->name, internal3_text, 30)) snd_soc_update_bits(codec, micb_int_reg, 0x2, 0x0); /* Put cfilt */ wcd9xxx_resmgr_cfilt_put(&tapan->resmgr, cfilt_sel_val); break; } return 0; } /* called under codec_resource_lock acquisition */ static int tapan_enable_mbhc_micbias(struct snd_soc_codec *codec, bool enable, enum wcd9xxx_micbias_num micb_num) { int rc; const char *micbias; if (micb_num == MBHC_MICBIAS2) micbias = DAPM_MICBIAS2_EXTERNAL_STANDALONE; else return -EINVAL; if (enable) rc = snd_soc_dapm_force_enable_pin(&codec->dapm, micbias); else rc = snd_soc_dapm_disable_pin(&codec->dapm, micbias); if (!rc) snd_soc_dapm_sync(&codec->dapm); pr_debug("%s: leave ret %d\n", __func__, rc); return rc; } static void tx_hpf_corner_freq_callback(struct work_struct *work) { struct delayed_work *hpf_delayed_work; struct hpf_work *hpf_work; struct tapan_priv *tapan; struct snd_soc_codec *codec; u16 tx_mux_ctl_reg; u8 hpf_cut_of_freq; hpf_delayed_work = to_delayed_work(work); hpf_work = container_of(hpf_delayed_work, struct hpf_work, dwork); tapan = hpf_work->tapan; codec = hpf_work->tapan->codec; hpf_cut_of_freq = hpf_work->tx_hpf_cut_of_freq; tx_mux_ctl_reg = TAPAN_A_CDC_TX1_MUX_CTL + (hpf_work->decimator - 1) * 8; dev_dbg(codec->dev, "%s(): decimator %u hpf_cut_of_freq 0x%x\n", __func__, hpf_work->decimator, (unsigned int)hpf_cut_of_freq); snd_soc_update_bits(codec, TAPAN_A_TX_1_2_TXFE_CLKDIV, 0x55, 0x55); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, hpf_cut_of_freq << 4); } #define TX_MUX_CTL_CUT_OFF_FREQ_MASK 0x30 #define CF_MIN_3DB_4HZ 0x0 #define CF_MIN_3DB_75HZ 0x1 #define CF_MIN_3DB_150HZ 0x2 static int tapan_codec_enable_dec(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; unsigned int decimator; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); char *dec_name = NULL; char *widget_name = NULL; char *temp; int ret = 0, i; u16 dec_reset_reg, tx_vol_ctl_reg, tx_mux_ctl_reg; u8 dec_hpf_cut_of_freq; int offset; char *srch = NULL; dev_dbg(codec->dev, "%s %d\n", __func__, event); widget_name = kstrndup(w->name, 15, GFP_KERNEL); if (!widget_name) return -ENOMEM; temp = widget_name; dec_name = strsep(&widget_name, " "); widget_name = temp; if (!dec_name) { pr_err("%s: Invalid decimator = %s\n", __func__, w->name); ret = -EINVAL; goto out; } srch = strpbrk(dec_name, "123456789"); if (srch == NULL) { pr_err("%s: Invalid decimator name %s\n", __func__, dec_name); return -EINVAL; } ret = kstrtouint(srch, 10, &decimator); if (ret < 0) { pr_err("%s: Invalid decimator = %s\n", __func__, dec_name); ret = -EINVAL; goto out; } dev_dbg(codec->dev, "%s(): widget = %s dec_name = %s decimator = %u\n", __func__, w->name, dec_name, decimator); if (w->reg == TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL) { dec_reset_reg = TAPAN_A_CDC_CLK_TX_RESET_B1_CTL; offset = 0; } else if (w->reg == TAPAN_A_CDC_CLK_TX_CLK_EN_B2_CTL) { dec_reset_reg = TAPAN_A_CDC_CLK_TX_RESET_B2_CTL; offset = 8; } else { pr_err("%s: Error, incorrect dec\n", __func__); ret = -EINVAL; goto out; } tx_vol_ctl_reg = TAPAN_A_CDC_TX1_VOL_CTL_CFG + 8 * (decimator - 1); tx_mux_ctl_reg = TAPAN_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1); switch (event) { case SND_SOC_DAPM_PRE_PMU: for (i = 0; i < NUM_DECIMATORS; i++) { if (decimator == i + 1) tapan_p->dec_active[i] = true; } /* Enableable TX digital mute */ snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01); snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 1 << w->shift); snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 0x0); dec_hpf_cut_of_freq = snd_soc_read(codec, tx_mux_ctl_reg); dec_hpf_cut_of_freq = (dec_hpf_cut_of_freq & 0x30) >> 4; tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq = dec_hpf_cut_of_freq; if ((dec_hpf_cut_of_freq != CF_MIN_3DB_150HZ)) { /* set cut of freq to CF_MIN_3DB_150HZ (0x1); */ snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, CF_MIN_3DB_150HZ << 4); } /* enable HPF */ snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x00); snd_soc_update_bits(codec, TAPAN_A_TX_1_2_TXFE_CLKDIV, 0x55, 0x44); break; case SND_SOC_DAPM_POST_PMU: if (tapan_p->lb_mode) { pr_debug("%s: loopback mode unmute the DEC\n", __func__); snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x00); } if (tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq != CF_MIN_3DB_150HZ) { schedule_delayed_work(&tx_hpf_work[decimator - 1].dwork, msecs_to_jiffies(300)); } /* apply the digital gain after the decimator is enabled*/ if ((w->shift + offset) < ARRAY_SIZE(tx_digital_gain_reg)) snd_soc_write(codec, tx_digital_gain_reg[w->shift + offset], snd_soc_read(codec, tx_digital_gain_reg[w->shift + offset]) ); break; case SND_SOC_DAPM_PRE_PMD: snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01); cancel_delayed_work_sync(&tx_hpf_work[decimator - 1].dwork); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x08, 0x08); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, (tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq) << 4); for (i = 0; i < NUM_DECIMATORS; i++) { if (decimator == i + 1) tapan_p->dec_active[i] = false; } break; } out: kfree(widget_name); return ret; } static int tapan_codec_enable_vdd_spkr(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent); dev_dbg(codec->dev, "%s: %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (spkr_drv_wrnd > 0) { WARN_ON(!(snd_soc_read(codec, TAPAN_A_SPKR_DRV_EN) & 0x80)); snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x00); } if (TAPAN_IS_1_0(core->version)) snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_DBG_PWRSTG, 0x24, 0x00); break; case SND_SOC_DAPM_POST_PMD: if (TAPAN_IS_1_0(core->version)) snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_DBG_PWRSTG, 0x24, 0x24); if (spkr_drv_wrnd > 0) { WARN_ON(!!(snd_soc_read(codec, TAPAN_A_SPKR_DRV_EN) & 0x80)); snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x80); } break; } return 0; } static int tapan_codec_rx_dem_select(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; pr_debug("%s %d %s\n", __func__, event, w->name); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (codec_ver == WCD9306) snd_soc_update_bits(codec, TAPAN_A_CDC_RX2_B6_CTL, 1 << 5, 1 << 5); break; case SND_SOC_DAPM_POST_PMD: if (codec_ver == WCD9306) snd_soc_update_bits(codec, TAPAN_A_CDC_RX2_B6_CTL, 1 << 5, 0); break; } return 0; } static int tapan_codec_enable_interpolator(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; dev_dbg(codec->dev, "%s %d %s\n", __func__, event, w->name); switch (event) { case SND_SOC_DAPM_PRE_PMU: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_RESET_CTL, 1 << w->shift, 1 << w->shift); snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_RESET_CTL, 1 << w->shift, 0x0); break; case SND_SOC_DAPM_POST_PMU: /* apply the digital gain after the interpolator is enabled*/ if ((w->shift) < ARRAY_SIZE(rx_digital_gain_reg)) snd_soc_write(codec, rx_digital_gain_reg[w->shift], snd_soc_read(codec, rx_digital_gain_reg[w->shift]) ); break; } return 0; } /* called under codec_resource_lock acquisition */ static int __tapan_codec_enable_ldo_h(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec); pr_debug("%s: enter\n", __func__); switch (event) { case SND_SOC_DAPM_PRE_PMU: /* * ldo_h_users is protected by codec->mutex, don't need * additional mutex */ if (++priv->ldo_h_users == 1) { WCD9XXX_BG_CLK_LOCK(&priv->resmgr); wcd9xxx_resmgr_get_bandgap(&priv->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); wcd9xxx_resmgr_get_clk_block(&priv->resmgr, WCD9XXX_CLK_RCO); snd_soc_update_bits(codec, TAPAN_A_LDO_H_MODE_1, 1 << 7, 1 << 7); wcd9xxx_resmgr_put_clk_block(&priv->resmgr, WCD9XXX_CLK_RCO); WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr); pr_debug("%s: ldo_h_users %d\n", __func__, priv->ldo_h_users); /* LDO enable requires 1ms to settle down */ usleep_range(1000, 1010); } break; case SND_SOC_DAPM_POST_PMD: if (--priv->ldo_h_users == 0) { WCD9XXX_BG_CLK_LOCK(&priv->resmgr); wcd9xxx_resmgr_get_clk_block(&priv->resmgr, WCD9XXX_CLK_RCO); snd_soc_update_bits(codec, TAPAN_A_LDO_H_MODE_1, 1 << 7, 0); wcd9xxx_resmgr_put_clk_block(&priv->resmgr, WCD9XXX_CLK_RCO); wcd9xxx_resmgr_put_bandgap(&priv->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr); pr_debug("%s: ldo_h_users %d\n", __func__, priv->ldo_h_users); } WARN(priv->ldo_h_users < 0, "Unexpected ldo_h users %d\n", priv->ldo_h_users); break; } pr_debug("%s: leave\n", __func__); return 0; } static int tapan_codec_enable_ldo_h(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { int rc; rc = __tapan_codec_enable_ldo_h(w, kcontrol, event); return rc; } static int tapan_codec_enable_rx_bias(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 1); break; case SND_SOC_DAPM_POST_PMD: wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 0); break; } return 0; } static int tapan_hphl_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0x02, 0x02); wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d, WCD9XXX_CLSH_STATE_HPHL, WCD9XXX_CLSH_REQ_ENABLE, WCD9XXX_CLSH_EVENT_PRE_DAC); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0x02, 0x00); } return 0; } static int tapan_hphr_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0x04, 0x04); snd_soc_update_bits(codec, w->reg, 0x40, 0x40); wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d, WCD9XXX_CLSH_STATE_HPHR, WCD9XXX_CLSH_REQ_ENABLE, WCD9XXX_CLSH_EVENT_PRE_DAC); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0x04, 0x00); snd_soc_update_bits(codec, w->reg, 0x40, 0x00); break; } return 0; } static int tapan_hph_pa_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); enum wcd9xxx_notify_event e_pre_on, e_post_off; u8 req_clsh_state; u32 pa_settle_time = TAPAN_HPH_PA_SETTLE_COMP_OFF; dev_dbg(codec->dev, "%s: %s event = %d\n", __func__, w->name, event); if (w->shift == 5) { e_pre_on = WCD9XXX_EVENT_PRE_HPHL_PA_ON; e_post_off = WCD9XXX_EVENT_POST_HPHL_PA_OFF; req_clsh_state = WCD9XXX_CLSH_STATE_HPHR; } else if (w->shift == 4) { e_pre_on = WCD9XXX_EVENT_PRE_HPHR_PA_ON; e_post_off = WCD9XXX_EVENT_POST_HPHR_PA_OFF; req_clsh_state = WCD9XXX_CLSH_STATE_HPHL; } else { pr_err("%s: Invalid w->shift %d\n", __func__, w->shift); return -EINVAL; } if (tapan->comp_enabled[COMPANDER_1]) pa_settle_time = TAPAN_HPH_PA_SETTLE_COMP_ON; switch (event) { case SND_SOC_DAPM_PRE_PMU: /* Let MBHC module know PA is turning on */ wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_pre_on); break; case SND_SOC_DAPM_POST_PMU: dev_dbg(codec->dev, "%s: sleep %d ms after %s PA enable.\n", __func__, pa_settle_time / 1000, w->name); /* Time needed for PA to settle */ usleep_range(pa_settle_time, pa_settle_time + 1000); wcd9xxx_clsh_fsm(codec, &tapan->clsh_d, req_clsh_state, WCD9XXX_CLSH_REQ_ENABLE, WCD9XXX_CLSH_EVENT_POST_PA); break; case SND_SOC_DAPM_POST_PMD: dev_dbg(codec->dev, "%s: sleep %d ms after %s PA disable.\n", __func__, pa_settle_time / 1000, w->name); /* Time needed for PA to settle */ usleep_range(pa_settle_time, pa_settle_time + 1000); /* Let MBHC module know PA turned off */ wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_post_off); wcd9xxx_clsh_fsm(codec, &tapan->clsh_d, req_clsh_state, WCD9XXX_CLSH_REQ_DISABLE, WCD9XXX_CLSH_EVENT_POST_PA); break; } return 0; } static int tapan_codec_enable_anc_hph(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; int ret = 0; switch (event) { case SND_SOC_DAPM_PRE_PMU: ret = tapan_hph_pa_event(w, kcontrol, event); if (w->shift == 4) { ret |= tapan_codec_enable_anc(w, kcontrol, event); msleep(50); } break; case SND_SOC_DAPM_POST_PMU: if (w->shift == 4) { snd_soc_update_bits(codec, TAPAN_A_RX_HPH_CNP_EN, 0x30, 0x30); msleep(30); } ret = tapan_hph_pa_event(w, kcontrol, event); break; case SND_SOC_DAPM_PRE_PMD: if (w->shift == 5) { snd_soc_update_bits(codec, TAPAN_A_RX_HPH_CNP_EN, 0x30, 0x00); msleep(40); snd_soc_update_bits(codec, TAPAN_A_TX_7_MBHC_EN, 0x80, 00); ret |= tapan_codec_enable_anc(w, kcontrol, event); } break; case SND_SOC_DAPM_POST_PMD: ret = tapan_hph_pa_event(w, kcontrol, event); break; } return ret; } static const struct snd_soc_dapm_widget tapan_dapm_i2s_widgets[] = { SND_SOC_DAPM_SUPPLY("I2S_CLK", TAPAN_A_CDC_CLK_I2S_CTL, 4, 0, NULL, 0), }; static int tapan_lineout_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: wcd9xxx_clsh_fsm(codec, &tapan->clsh_d, WCD9XXX_CLSH_STATE_LO, WCD9XXX_CLSH_REQ_ENABLE, WCD9XXX_CLSH_EVENT_PRE_DAC); snd_soc_update_bits(codec, w->reg, 0x40, 0x40); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, w->reg, 0x40, 0x00); break; } return 0; } static int tapan_spk_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); return 0; } static const struct snd_soc_dapm_route audio_i2s_map[] = { {"I2S_CLK", NULL, "CDC_CONN"}, {"SLIM RX1", NULL, "I2S_CLK"}, {"SLIM RX2", NULL, "I2S_CLK"}, {"SLIM TX1 MUX", NULL, "I2S_CLK"}, {"SLIM TX2 MUX", NULL, "I2S_CLK"}, }; static const struct snd_soc_dapm_route wcd9306_map[] = { {"SLIM TX1 MUX", "RMIX4", "RX4 MIX1"}, {"SLIM TX2 MUX", "RMIX4", "RX4 MIX1"}, {"SLIM TX3 MUX", "RMIX4", "RX4 MIX1"}, {"SLIM TX4 MUX", "RMIX4", "RX4 MIX1"}, {"SLIM TX5 MUX", "RMIX4", "RX4 MIX1"}, {"SLIM TX1 MUX", "DEC3", "DEC3 MUX"}, {"SLIM TX1 MUX", "DEC4", "DEC4 MUX"}, {"SLIM TX2 MUX", "DEC3", "DEC3 MUX"}, {"SLIM TX2 MUX", "DEC4", "DEC4 MUX"}, {"SLIM TX3 MUX", "DEC3", "DEC3 MUX"}, {"SLIM TX4 MUX", "DEC4", "DEC4 MUX"}, {"ANC EAR", NULL, "ANC EAR PA"}, {"ANC EAR PA", NULL, "EAR_PA_MIXER"}, {"ANC1 FB MUX", "EAR_HPH_L", "RX1 MIX2"}, {"ANC1 FB MUX", "EAR_LINE_1", "RX2 MIX2"}, {"ANC HEADPHONE", NULL, "ANC HPHL"}, {"ANC HEADPHONE", NULL, "ANC HPHR"}, {"ANC HPHL", NULL, "HPHL_PA_MIXER"}, {"ANC HPHR", NULL, "HPHR_PA_MIXER"}, {"ANC1 MUX", "ADC1", "ADC1"}, {"ANC1 MUX", "ADC2", "ADC2"}, {"ANC1 MUX", "ADC3", "ADC3"}, {"ANC1 MUX", "ADC4", "ADC4"}, {"ANC1 MUX", "ADC5", "ADC5"}, {"ANC1 MUX", "DMIC1", "DMIC1"}, {"ANC1 MUX", "DMIC2", "DMIC2"}, {"ANC1 MUX", "DMIC3", "DMIC3"}, {"ANC1 MUX", "DMIC4", "DMIC4"}, {"ANC2 MUX", "ADC1", "ADC1"}, {"ANC2 MUX", "ADC2", "ADC2"}, {"ANC2 MUX", "ADC3", "ADC3"}, {"ANC2 MUX", "ADC4", "ADC4"}, {"ANC2 MUX", "ADC5", "ADC5"}, {"ANC2 MUX", "DMIC1", "DMIC1"}, {"ANC2 MUX", "DMIC2", "DMIC2"}, {"ANC2 MUX", "DMIC3", "DMIC3"}, {"ANC2 MUX", "DMIC4", "DMIC4"}, {"ANC HPHR", NULL, "CDC_CONN"}, {"RDAC5 MUX", "DEM4", "RX4 MIX2"}, {"SPK DAC", "Switch", "RX4 MIX2"}, {"RX1 MIX2", NULL, "ANC1 MUX"}, {"RX2 MIX2", NULL, "ANC2 MUX"}, {"RX1 MIX1", NULL, "COMP1_CLK"}, {"RX2 MIX1", NULL, "COMP1_CLK"}, {"RX3 MIX1", NULL, "COMP2_CLK"}, {"RX4 MIX1", NULL, "COMP0_CLK"}, {"RX4 MIX1", NULL, "RX4 MIX1 INP1"}, {"RX4 MIX1", NULL, "RX4 MIX1 INP2"}, {"RX4 MIX2", NULL, "RX4 MIX1"}, {"RX4 MIX2", NULL, "RX4 MIX2 INP1"}, {"RX4 MIX2", NULL, "RX4 MIX2 INP2"}, {"RX4 MIX1 INP1", "RX1", "SLIM RX1"}, {"RX4 MIX1 INP1", "RX2", "SLIM RX2"}, {"RX4 MIX1 INP1", "RX3", "SLIM RX3"}, {"RX4 MIX1 INP1", "RX4", "SLIM RX4"}, {"RX4 MIX1 INP1", "RX5", "SLIM RX5"}, {"RX4 MIX1 INP1", "IIR1", "IIR1"}, {"RX4 MIX1 INP2", "RX1", "SLIM RX1"}, {"RX4 MIX1 INP2", "RX2", "SLIM RX2"}, {"RX4 MIX1 INP2", "RX3", "SLIM RX3"}, {"RX4 MIX1 INP2", "RX5", "SLIM RX5"}, {"RX4 MIX1 INP2", "RX4", "SLIM RX4"}, {"RX4 MIX1 INP2", "IIR1", "IIR1"}, {"RX4 MIX2 INP1", "IIR1", "IIR1"}, {"RX4 MIX2 INP2", "IIR1", "IIR1"}, {"DEC1 MUX", "DMIC3", "DMIC3"}, {"DEC1 MUX", "DMIC4", "DMIC4"}, {"DEC2 MUX", "DMIC3", "DMIC3"}, {"DEC2 MUX", "DMIC4", "DMIC4"}, {"DEC3 MUX", "ADC1", "ADC1"}, {"DEC3 MUX", "ADC2", "ADC2"}, {"DEC3 MUX", "ADC3", "ADC3"}, {"DEC3 MUX", "ADC4", "ADC4"}, {"DEC3 MUX", "ADC5", "ADC5"}, {"DEC3 MUX", "DMIC1", "DMIC1"}, {"DEC3 MUX", "DMIC2", "DMIC2"}, {"DEC3 MUX", "DMIC3", "DMIC3"}, {"DEC3 MUX", "DMIC4", "DMIC4"}, {"DEC3 MUX", NULL, "CDC_CONN"}, {"DEC4 MUX", "ADC1", "ADC1"}, {"DEC4 MUX", "ADC2", "ADC2"}, {"DEC4 MUX", "ADC3", "ADC3"}, {"DEC4 MUX", "ADC4", "ADC4"}, {"DEC4 MUX", "ADC5", "ADC5"}, {"DEC4 MUX", "DMIC1", "DMIC1"}, {"DEC4 MUX", "DMIC2", "DMIC2"}, {"DEC4 MUX", "DMIC3", "DMIC3"}, {"DEC4 MUX", "DMIC4", "DMIC4"}, {"DEC4 MUX", NULL, "CDC_CONN"}, {"ADC5", NULL, "AMIC5"}, {"AUX_PGA_Left", NULL, "AMIC5"}, {"IIR1 INP1 MUX", "DEC3", "DEC3 MUX"}, {"IIR1 INP1 MUX", "DEC4", "DEC4 MUX"}, {"MIC BIAS3 Internal1", NULL, "LDO_H"}, {"MIC BIAS3 Internal2", NULL, "LDO_H"}, {"MIC BIAS3 External", NULL, "LDO_H"}, }; static const struct snd_soc_dapm_route audio_map[] = { /* SLIMBUS Connections */ {"AIF1 CAP", NULL, "AIF1_CAP Mixer"}, {"AIF2 CAP", NULL, "AIF2_CAP Mixer"}, {"AIF3 CAP", NULL, "AIF3_CAP Mixer"}, /* SLIM_MIXER("AIF1_CAP Mixer"),*/ {"AIF1_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"}, {"AIF1_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"}, {"AIF1_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"}, {"AIF1_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"}, {"AIF1_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"}, /* SLIM_MIXER("AIF2_CAP Mixer"),*/ {"AIF2_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"}, {"AIF2_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"}, {"AIF2_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"}, {"AIF2_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"}, {"AIF2_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"}, /* SLIM_MIXER("AIF3_CAP Mixer"),*/ {"AIF3_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"}, {"AIF3_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"}, {"AIF3_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"}, {"AIF3_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"}, {"AIF3_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"}, {"SLIM TX1 MUX", "DEC1", "DEC1 MUX"}, {"SLIM TX1 MUX", "DEC2", "DEC2 MUX"}, {"SLIM TX1 MUX", "RMIX1", "RX1 MIX1"}, {"SLIM TX1 MUX", "RMIX2", "RX2 MIX1"}, {"SLIM TX1 MUX", "RMIX3", "RX3 MIX1"}, {"SLIM TX2 MUX", "DEC1", "DEC1 MUX"}, {"SLIM TX2 MUX", "DEC2", "DEC2 MUX"}, {"SLIM TX2 MUX", "RMIX1", "RX1 MIX1"}, {"SLIM TX2 MUX", "RMIX2", "RX2 MIX1"}, {"SLIM TX2 MUX", "RMIX3", "RX3 MIX1"}, {"SLIM TX3 MUX", "RMIX1", "RX1 MIX1"}, {"SLIM TX3 MUX", "RMIX2", "RX2 MIX1"}, {"SLIM TX3 MUX", "RMIX3", "RX3 MIX1"}, {"SLIM TX4 MUX", "RMIX1", "RX1 MIX1"}, {"SLIM TX4 MUX", "RMIX2", "RX2 MIX1"}, {"SLIM TX4 MUX", "RMIX3", "RX3 MIX1"}, {"SLIM TX5 MUX", "DEC1", "DEC1 MUX"}, {"SLIM TX5 MUX", "RMIX1", "RX1 MIX1"}, {"SLIM TX5 MUX", "RMIX2", "RX2 MIX1"}, {"SLIM TX5 MUX", "RMIX3", "RX3 MIX1"}, /* Earpiece (RX MIX1) */ {"EAR", NULL, "EAR PA"}, {"EAR PA", NULL, "EAR_PA_MIXER"}, {"EAR_PA_MIXER", NULL, "DAC1"}, {"DAC1", NULL, "RX_BIAS"}, {"DAC1", NULL, "CDC_CP_VDD"}, /* Headset (RX MIX1 and RX MIX2) */ {"HEADPHONE", NULL, "HPHL"}, {"HEADPHONE", NULL, "HPHR"}, {"HPHL", NULL, "HPHL_PA_MIXER"}, {"HPHL_PA_MIXER", NULL, "HPHL DAC"}, {"HPHL DAC", NULL, "RX_BIAS"}, {"HPHL DAC", NULL, "CDC_CP_VDD"}, {"HPHR", NULL, "HPHR_PA_MIXER"}, {"HPHR_PA_MIXER", NULL, "HPHR DAC"}, {"HPHR DAC", NULL, "RX_BIAS"}, {"HPHR DAC", NULL, "CDC_CP_VDD"}, {"DAC1", "Switch", "CLASS_H_DSM MUX"}, {"HPHL DAC", "Switch", "CLASS_H_DSM MUX"}, {"HPHR DAC", NULL, "RDAC3 MUX"}, {"LINEOUT1", NULL, "LINEOUT1 PA"}, {"LINEOUT2", NULL, "LINEOUT2 PA"}, {"SPK_OUT", NULL, "SPK PA"}, {"LINEOUT1 PA", NULL, "LINEOUT1_PA_MIXER"}, {"LINEOUT1_PA_MIXER", NULL, "LINEOUT1 DAC"}, {"LINEOUT2 PA", NULL, "LINEOUT2_PA_MIXER"}, {"LINEOUT2_PA_MIXER", NULL, "LINEOUT2 DAC"}, {"RDAC5 MUX", "DEM3_INV", "RX3 MIX1"}, {"LINEOUT2 DAC", NULL, "RDAC5 MUX"}, {"RDAC4 MUX", "DEM3", "RX3 MIX1"}, {"RDAC4 MUX", "DEM2", "RX2 CHAIN"}, {"LINEOUT1 DAC", NULL, "RDAC4 MUX"}, {"SPK PA", NULL, "SPK DAC"}, {"SPK DAC", NULL, "VDD_SPKDRV"}, {"RX1 INTERPOLATOR", NULL, "RX1 MIX2"}, {"RX1 CHAIN", NULL, "RX1 INTERPOLATOR"}, {"RX2 INTERPOLATOR", NULL, "RX2 MIX2"}, {"RX2 CHAIN", NULL, "RX2 INTERPOLATOR"}, {"CLASS_H_DSM MUX", "RX_HPHL", "RX1 CHAIN"}, {"LINEOUT1 DAC", NULL, "RX_BIAS"}, {"LINEOUT2 DAC", NULL, "RX_BIAS"}, {"LINEOUT1 DAC", NULL, "CDC_CP_VDD"}, {"LINEOUT2 DAC", NULL, "CDC_CP_VDD"}, {"RDAC3 MUX", "DEM2", "RX2 CHAIN"}, {"RDAC3 MUX", "DEM1", "RX1 CHAIN"}, {"RX1 MIX1", NULL, "RX1 MIX1 INP1"}, {"RX1 MIX1", NULL, "RX1 MIX1 INP2"}, {"RX1 MIX1", NULL, "RX1 MIX1 INP3"}, {"RX2 MIX1", NULL, "RX2 MIX1 INP1"}, {"RX2 MIX1", NULL, "RX2 MIX1 INP2"}, {"RX3 MIX1", NULL, "RX3 MIX1 INP1"}, {"RX3 MIX1", NULL, "RX3 MIX1 INP2"}, {"RX1 MIX2", NULL, "RX1 MIX1"}, {"RX1 MIX2", NULL, "RX1 MIX2 INP1"}, {"RX1 MIX2", NULL, "RX1 MIX2 INP2"}, {"RX2 MIX2", NULL, "RX2 MIX1"}, {"RX2 MIX2", NULL, "RX2 MIX2 INP1"}, {"RX2 MIX2", NULL, "RX2 MIX2 INP2"}, /* SLIM_MUX("AIF1_PB", "AIF1 PB"),*/ {"SLIM RX1 MUX", "AIF1_PB", "AIF1 PB"}, {"SLIM RX2 MUX", "AIF1_PB", "AIF1 PB"}, {"SLIM RX3 MUX", "AIF1_PB", "AIF1 PB"}, {"SLIM RX4 MUX", "AIF1_PB", "AIF1 PB"}, {"SLIM RX5 MUX", "AIF1_PB", "AIF1 PB"}, /* SLIM_MUX("AIF2_PB", "AIF2 PB"),*/ {"SLIM RX1 MUX", "AIF2_PB", "AIF2 PB"}, {"SLIM RX2 MUX", "AIF2_PB", "AIF2 PB"}, {"SLIM RX3 MUX", "AIF2_PB", "AIF2 PB"}, {"SLIM RX4 MUX", "AIF2_PB", "AIF2 PB"}, {"SLIM RX5 MUX", "AIF2_PB", "AIF2 PB"}, /* SLIM_MUX("AIF3_PB", "AIF3 PB"),*/ {"SLIM RX1 MUX", "AIF3_PB", "AIF3 PB"}, {"SLIM RX2 MUX", "AIF3_PB", "AIF3 PB"}, {"SLIM RX3 MUX", "AIF3_PB", "AIF3 PB"}, {"SLIM RX4 MUX", "AIF3_PB", "AIF3 PB"}, {"SLIM RX5 MUX", "AIF3_PB", "AIF3 PB"}, {"SLIM RX1", NULL, "SLIM RX1 MUX"}, {"SLIM RX2", NULL, "SLIM RX2 MUX"}, {"SLIM RX3", NULL, "SLIM RX3 MUX"}, {"SLIM RX4", NULL, "SLIM RX4 MUX"}, {"SLIM RX5", NULL, "SLIM RX5 MUX"}, {"RX1 MIX1 INP1", "RX1", "SLIM RX1"}, {"RX1 MIX1 INP1", "RX2", "SLIM RX2"}, {"RX1 MIX1 INP1", "RX3", "SLIM RX3"}, {"RX1 MIX1 INP1", "RX4", "SLIM RX4"}, {"RX1 MIX1 INP1", "RX5", "SLIM RX5"}, {"RX1 MIX1 INP1", "IIR1", "IIR1"}, {"RX1 MIX1 INP1", "IIR2", "IIR2"}, {"RX1 MIX1 INP2", "RX1", "SLIM RX1"}, {"RX1 MIX1 INP2", "RX2", "SLIM RX2"}, {"RX1 MIX1 INP2", "RX3", "SLIM RX3"}, {"RX1 MIX1 INP2", "RX4", "SLIM RX4"}, {"RX1 MIX1 INP2", "RX5", "SLIM RX5"}, {"RX1 MIX1 INP2", "IIR1", "IIR1"}, {"RX1 MIX1 INP2", "IIR2", "IIR2"}, {"RX1 MIX1 INP3", "RX1", "SLIM RX1"}, {"RX1 MIX1 INP3", "RX2", "SLIM RX2"}, {"RX1 MIX1 INP3", "RX3", "SLIM RX3"}, {"RX1 MIX1 INP3", "RX4", "SLIM RX4"}, {"RX1 MIX1 INP3", "RX5", "SLIM RX5"}, {"RX2 MIX1 INP1", "RX1", "SLIM RX1"}, {"RX2 MIX1 INP1", "RX2", "SLIM RX2"}, {"RX2 MIX1 INP1", "RX3", "SLIM RX3"}, {"RX2 MIX1 INP1", "RX4", "SLIM RX4"}, {"RX2 MIX1 INP1", "RX5", "SLIM RX5"}, {"RX2 MIX1 INP1", "IIR1", "IIR1"}, {"RX2 MIX1 INP1", "IIR2", "IIR2"}, {"RX2 MIX1 INP2", "RX1", "SLIM RX1"}, {"RX2 MIX1 INP2", "RX2", "SLIM RX2"}, {"RX2 MIX1 INP2", "RX3", "SLIM RX3"}, {"RX2 MIX1 INP2", "RX4", "SLIM RX4"}, {"RX2 MIX1 INP2", "RX5", "SLIM RX5"}, {"RX2 MIX1 INP2", "IIR1", "IIR1"}, {"RX2 MIX1 INP2", "IIR2", "IIR2"}, {"RX3 MIX1 INP1", "RX1", "SLIM RX1"}, {"RX3 MIX1 INP1", "RX2", "SLIM RX2"}, {"RX3 MIX1 INP1", "RX3", "SLIM RX3"}, {"RX3 MIX1 INP1", "RX4", "SLIM RX4"}, {"RX3 MIX1 INP1", "RX5", "SLIM RX5"}, {"RX3 MIX1 INP1", "IIR1", "IIR1"}, {"RX3 MIX1 INP1", "IIR2", "IIR2"}, {"RX3 MIX1 INP2", "RX1", "SLIM RX1"}, {"RX3 MIX1 INP2", "RX2", "SLIM RX2"}, {"RX3 MIX1 INP2", "RX3", "SLIM RX3"}, {"RX3 MIX1 INP2", "RX4", "SLIM RX4"}, {"RX3 MIX1 INP2", "RX5", "SLIM RX5"}, {"RX3 MIX1 INP2", "IIR1", "IIR1"}, {"RX3 MIX1 INP2", "IIR2", "IIR2"}, {"RX1 MIX2 INP1", "IIR1", "IIR1"}, {"RX1 MIX2 INP2", "IIR1", "IIR1"}, {"RX2 MIX2 INP1", "IIR1", "IIR1"}, {"RX2 MIX2 INP2", "IIR1", "IIR1"}, {"RX1 MIX2 INP1", "IIR2", "IIR2"}, {"RX1 MIX2 INP2", "IIR2", "IIR2"}, {"RX2 MIX2 INP1", "IIR2", "IIR2"}, {"RX2 MIX2 INP2", "IIR2", "IIR2"}, /* Decimator Inputs */ {"DEC1 MUX", "ADC1", "ADC1"}, {"DEC1 MUX", "ADC2", "ADC2"}, {"DEC1 MUX", "ADC3", "ADC3"}, {"DEC1 MUX", "ADC4", "ADC4"}, {"DEC1 MUX", "DMIC1", "DMIC1"}, {"DEC1 MUX", "DMIC2", "DMIC2"}, {"DEC1 MUX", NULL, "CDC_CONN"}, {"DEC2 MUX", "ADC1", "ADC1"}, {"DEC2 MUX", "ADC2", "ADC2"}, {"DEC2 MUX", "ADC3", "ADC3"}, {"DEC2 MUX", "ADC4", "ADC4"}, {"DEC2 MUX", "DMIC1", "DMIC1"}, {"DEC2 MUX", "DMIC2", "DMIC2"}, {"DEC2 MUX", NULL, "CDC_CONN"}, /* ADC Connections */ {"ADC1", NULL, "AMIC1"}, {"ADC2", NULL, "AMIC2"}, {"ADC3", NULL, "AMIC3"}, {"ADC4", NULL, "AMIC4"}, /* AUX PGA Connections */ {"EAR_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"}, {"HPHL_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"}, {"HPHR_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"}, {"LINEOUT1_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"}, {"LINEOUT2_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"}, {"MIC BIAS1 Internal1", NULL, "LDO_H"}, {"MIC BIAS1 Internal2", NULL, "LDO_H"}, {"MIC BIAS1 External", NULL, "LDO_H"}, {"MIC BIAS2 Internal1", NULL, "LDO_H"}, {"MIC BIAS2 Internal2", NULL, "LDO_H"}, {"MIC BIAS2 Internal3", NULL, "LDO_H"}, {"MIC BIAS2 External", NULL, "LDO_H"}, {DAPM_MICBIAS2_EXTERNAL_STANDALONE, NULL, "LDO_H Standalone"}, /*sidetone path enable*/ {"IIR1", NULL, "IIR1 INP1 MUX"}, {"IIR1 INP1 MUX", "DEC1", "DEC1 MUX"}, {"IIR1 INP1 MUX", "DEC2", "DEC2 MUX"}, {"IIR1 INP1 MUX", "DEC3", "DEC3 MUX"}, {"IIR1 INP1 MUX", "DEC4", "DEC4 MUX"}, {"IIR1 INP1 MUX", "RX1", "SLIM RX1"}, {"IIR1 INP1 MUX", "RX2", "SLIM RX2"}, {"IIR1 INP1 MUX", "RX3", "SLIM RX3"}, {"IIR1 INP1 MUX", "RX4", "SLIM RX4"}, {"IIR1 INP1 MUX", "RX5", "SLIM RX5"}, {"IIR1", NULL, "IIR1 INP2 MUX"}, {"IIR1 INP2 MUX", "DEC1", "DEC1 MUX"}, {"IIR1 INP2 MUX", "DEC2", "DEC2 MUX"}, {"IIR1 INP2 MUX", "DEC3", "DEC3 MUX"}, {"IIR1 INP2 MUX", "DEC4", "DEC4 MUX"}, {"IIR1 INP2 MUX", "RX1", "SLIM RX1"}, {"IIR1 INP2 MUX", "RX2", "SLIM RX2"}, {"IIR1 INP2 MUX", "RX3", "SLIM RX3"}, {"IIR1 INP2 MUX", "RX4", "SLIM RX4"}, {"IIR1 INP2 MUX", "RX5", "SLIM RX5"}, {"IIR1", NULL, "IIR1 INP3 MUX"}, {"IIR1 INP3 MUX", "DEC1", "DEC1 MUX"}, {"IIR1 INP3 MUX", "DEC2", "DEC2 MUX"}, {"IIR1 INP3 MUX", "DEC3", "DEC3 MUX"}, {"IIR1 INP3 MUX", "DEC4", "DEC4 MUX"}, {"IIR1 INP3 MUX", "RX1", "SLIM RX1"}, {"IIR1 INP3 MUX", "RX2", "SLIM RX2"}, {"IIR1 INP3 MUX", "RX3", "SLIM RX3"}, {"IIR1 INP3 MUX", "RX4", "SLIM RX4"}, {"IIR1 INP3 MUX", "RX5", "SLIM RX5"}, {"IIR1", NULL, "IIR1 INP4 MUX"}, {"IIR1 INP4 MUX", "DEC1", "DEC1 MUX"}, {"IIR1 INP4 MUX", "DEC2", "DEC2 MUX"}, {"IIR1 INP4 MUX", "DEC3", "DEC3 MUX"}, {"IIR1 INP4 MUX", "DEC4", "DEC4 MUX"}, {"IIR1 INP4 MUX", "RX1", "SLIM RX1"}, {"IIR1 INP4 MUX", "RX2", "SLIM RX2"}, {"IIR1 INP4 MUX", "RX3", "SLIM RX3"}, {"IIR1 INP4 MUX", "RX4", "SLIM RX4"}, {"IIR1 INP4 MUX", "RX5", "SLIM RX5"}, {"IIR2", NULL, "IIR2 INP1 MUX"}, {"IIR2 INP1 MUX", "DEC1", "DEC1 MUX"}, {"IIR2 INP1 MUX", "DEC2", "DEC2 MUX"}, {"IIR2 INP1 MUX", "DEC3", "DEC3 MUX"}, {"IIR2 INP1 MUX", "DEC4", "DEC4 MUX"}, {"IIR2 INP1 MUX", "RX1", "SLIM RX1"}, {"IIR2 INP1 MUX", "RX2", "SLIM RX2"}, {"IIR2 INP1 MUX", "RX3", "SLIM RX3"}, {"IIR2 INP1 MUX", "RX4", "SLIM RX4"}, {"IIR2 INP1 MUX", "RX5", "SLIM RX5"}, {"IIR2", NULL, "IIR2 INP2 MUX"}, {"IIR2 INP2 MUX", "DEC1", "DEC1 MUX"}, {"IIR2 INP2 MUX", "DEC2", "DEC2 MUX"}, {"IIR2 INP2 MUX", "DEC3", "DEC3 MUX"}, {"IIR2 INP2 MUX", "DEC4", "DEC4 MUX"}, {"IIR2 INP2 MUX", "RX1", "SLIM RX1"}, {"IIR2 INP2 MUX", "RX2", "SLIM RX2"}, {"IIR2 INP2 MUX", "RX3", "SLIM RX3"}, {"IIR2 INP2 MUX", "RX4", "SLIM RX4"}, {"IIR2 INP2 MUX", "RX5", "SLIM RX5"}, {"IIR2", NULL, "IIR2 INP3 MUX"}, {"IIR2 INP3 MUX", "DEC1", "DEC1 MUX"}, {"IIR2 INP3 MUX", "DEC2", "DEC2 MUX"}, {"IIR2 INP3 MUX", "DEC3", "DEC3 MUX"}, {"IIR2 INP3 MUX", "DEC4", "DEC4 MUX"}, {"IIR2 INP3 MUX", "RX1", "SLIM RX1"}, {"IIR2 INP3 MUX", "RX2", "SLIM RX2"}, {"IIR2 INP3 MUX", "RX3", "SLIM RX3"}, {"IIR2 INP3 MUX", "RX4", "SLIM RX4"}, {"IIR2 INP3 MUX", "RX5", "SLIM RX5"}, {"IIR2", NULL, "IIR2 INP4 MUX"}, {"IIR2 INP4 MUX", "DEC1", "DEC1 MUX"}, {"IIR2 INP4 MUX", "DEC2", "DEC2 MUX"}, {"IIR2 INP4 MUX", "DEC3", "DEC3 MUX"}, {"IIR2 INP4 MUX", "DEC4", "DEC4 MUX"}, {"IIR2 INP4 MUX", "RX1", "SLIM RX1"}, {"IIR2 INP4 MUX", "RX2", "SLIM RX2"}, {"IIR2 INP4 MUX", "RX3", "SLIM RX3"}, {"IIR2 INP4 MUX", "RX4", "SLIM RX4"}, {"IIR2 INP4 MUX", "RX5", "SLIM RX5"}, }; static const struct snd_soc_dapm_route wcd9302_map[] = { {"SPK DAC", "Switch", "RX3 MIX1"}, {"RDAC5 MUX", "DEM4", "RX3 MIX1"}, {"RDAC5 MUX", "DEM3_INV", "RDAC4 MUX"}, }; static int tapan_readable(struct snd_soc_codec *ssc, unsigned int reg) { return tapan_reg_readable[reg]; } static bool tapan_is_digital_gain_register(unsigned int reg) { bool rtn = false; switch (reg) { case TAPAN_A_CDC_RX1_VOL_CTL_B2_CTL: case TAPAN_A_CDC_RX2_VOL_CTL_B2_CTL: case TAPAN_A_CDC_RX3_VOL_CTL_B2_CTL: case TAPAN_A_CDC_RX4_VOL_CTL_B2_CTL: case TAPAN_A_CDC_TX1_VOL_CTL_GAIN: case TAPAN_A_CDC_TX2_VOL_CTL_GAIN: case TAPAN_A_CDC_TX3_VOL_CTL_GAIN: case TAPAN_A_CDC_TX4_VOL_CTL_GAIN: rtn = true; break; default: break; } return rtn; } static int tapan_volatile(struct snd_soc_codec *ssc, unsigned int reg) { int i = 0; /* Registers lower than 0x100 are top level registers which can be * written by the Tapan core driver. */ if ((reg >= TAPAN_A_CDC_MBHC_EN_CTL) || (reg < 0x100)) return 1; /* IIR Coeff registers are not cacheable */ if ((reg >= TAPAN_A_CDC_IIR1_COEF_B1_CTL) && (reg <= TAPAN_A_CDC_IIR2_COEF_B2_CTL)) return 1; /* ANC filter registers are not cacheable */ if ((reg >= TAPAN_A_CDC_ANC1_IIR_B1_CTL) && (reg <= TAPAN_A_CDC_ANC1_LPF_B2_CTL)) return 1; if ((reg >= TAPAN_A_CDC_ANC2_IIR_B1_CTL) && (reg <= TAPAN_A_CDC_ANC2_LPF_B2_CTL)) return 1; /* Digital gain register is not cacheable so we have to write * the setting even it is the same */ if (tapan_is_digital_gain_register(reg)) return 1; /* HPH status registers */ if (reg == TAPAN_A_RX_HPH_L_STATUS || reg == TAPAN_A_RX_HPH_R_STATUS) return 1; if (reg == TAPAN_A_MBHC_INSERT_DET_STATUS) return 1; for (i = 0; i < ARRAY_SIZE(audio_reg_cfg); i++) if (audio_reg_cfg[i].reg_logical_addr - TAPAN_REGISTER_START_OFFSET == reg) return 1; return 0; } #define TAPAN_FORMATS (SNDRV_PCM_FMTBIT_S16_LE) #define TAPAN_FORMATS_S16_S24_LE (SNDRV_PCM_FMTBIT_S16_LE | \ SNDRV_PCM_FORMAT_S24_LE) static int tapan_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { int ret; struct wcd9xxx *wcd9xxx = codec->control_data; if (reg == SND_SOC_NOPM) return 0; BUG_ON(reg > TAPAN_MAX_REGISTER); if (!tapan_volatile(codec, reg)) { ret = snd_soc_cache_write(codec, reg, value); if (ret != 0) dev_err(codec->dev, "Cache write to %x failed: %d\n", reg, ret); } return wcd9xxx_reg_write(&wcd9xxx->core_res, reg, value); } static unsigned int tapan_read(struct snd_soc_codec *codec, unsigned int reg) { unsigned int val; int ret; struct wcd9xxx *wcd9xxx = codec->control_data; if (reg == SND_SOC_NOPM) return 0; BUG_ON(reg > TAPAN_MAX_REGISTER); if (!tapan_volatile(codec, reg) && tapan_readable(codec, reg) && reg < codec->driver->reg_cache_size) { ret = snd_soc_cache_read(codec, reg, &val); if (ret >= 0) { return val; } else dev_err(codec->dev, "Cache read from %x failed: %d\n", reg, ret); } val = wcd9xxx_reg_read(&wcd9xxx->core_res, reg); return val; } static int tapan_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct wcd9xxx *tapan_core = dev_get_drvdata(dai->codec->dev->parent); dev_dbg(dai->codec->dev, "%s(): substream = %s stream = %d\n", __func__, substream->name, substream->stream); if ((tapan_core != NULL) && (tapan_core->dev != NULL) && (tapan_core->dev->parent != NULL)) pm_runtime_get_sync(tapan_core->dev->parent); return 0; } static void tapan_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct wcd9xxx *tapan_core = dev_get_drvdata(dai->codec->dev->parent); struct tapan_priv *tapan = snd_soc_codec_get_drvdata(dai->codec); u32 active = 0; dev_dbg(dai->codec->dev, "%s(): substream = %s stream = %d\n", __func__, substream->name, substream->stream); if (dai->id < NUM_CODEC_DAIS) { if (tapan->dai[dai->id].ch_mask) { active = 1; dev_dbg(dai->codec->dev, "%s(): Codec DAI: chmask[%d] = 0x%lx\n", __func__, dai->id, tapan->dai[dai->id].ch_mask); } } if ((tapan_core != NULL) && (tapan_core->dev != NULL) && (tapan_core->dev->parent != NULL) && (active == 0)) { pm_runtime_mark_last_busy(tapan_core->dev->parent); pm_runtime_put(tapan_core->dev->parent); dev_dbg(dai->codec->dev, "%s: unvote requested", __func__); } } static void tapan_set_vdd_cx_current(struct snd_soc_codec *codec, int current_uA) { struct regulator *cx_regulator; int ret; cx_regulator = tapan_codec_find_regulator(codec, "cdc-vdd-cx"); if (!cx_regulator) { dev_err(codec->dev, "%s: Regulator %s not defined\n", __func__, "cdc-vdd-cx-supply"); return; } ret = regulator_set_optimum_mode(cx_regulator, current_uA); if (ret < 0) dev_err(codec->dev, "%s: Failed to set vdd_cx current to %d\n", __func__, current_uA); } int tapan_mclk_enable(struct snd_soc_codec *codec, int mclk_enable, bool dapm) { struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: mclk_enable = %u, dapm = %d\n", __func__, mclk_enable, dapm); WCD9XXX_BG_CLK_LOCK(&tapan->resmgr); if (mclk_enable) { tapan_set_vdd_cx_current(codec, TAPAN_VDD_CX_OPTIMAL_UA); wcd9xxx_resmgr_get_bandgap(&tapan->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); wcd9xxx_resmgr_get_clk_block(&tapan->resmgr, WCD9XXX_CLK_MCLK); } else { /* Put clock and BG */ wcd9xxx_resmgr_put_clk_block(&tapan->resmgr, WCD9XXX_CLK_MCLK); wcd9xxx_resmgr_put_bandgap(&tapan->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); /* Set the vdd cx power rail sleep mode current */ tapan_set_vdd_cx_current(codec, TAPAN_VDD_CX_SLEEP_UA); } WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr); return 0; } static int tapan_set_dai_sysclk(struct snd_soc_dai *dai, int clk_id, unsigned int freq, int dir) { dev_dbg(dai->codec->dev, "%s\n", __func__); return 0; } static int tapan_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt) { u8 val = 0; struct snd_soc_codec *codec = dai->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s\n", __func__); switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: /* CPU is master */ if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) { if (dai->id == AIF1_CAP) snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, TAPAN_I2S_MASTER_MODE_MASK, 0); else if (dai->id == AIF1_PB) snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, TAPAN_I2S_MASTER_MODE_MASK, 0); } break; case SND_SOC_DAIFMT_CBM_CFM: /* CPU is slave */ if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) { val = TAPAN_I2S_MASTER_MODE_MASK; if (dai->id == AIF1_CAP) snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, val, val); else if (dai->id == AIF1_PB) snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, val, val); } break; default: return -EINVAL; } return 0; } static int tapan_set_channel_map(struct snd_soc_dai *dai, unsigned int tx_num, unsigned int *tx_slot, unsigned int rx_num, unsigned int *rx_slot) { struct tapan_priv *tapan = snd_soc_codec_get_drvdata(dai->codec); struct wcd9xxx *core = dev_get_drvdata(dai->codec->dev->parent); if (!tx_slot || !rx_slot) { pr_err("%s: Invalid\n", __func__); return -EINVAL; } dev_dbg(dai->codec->dev, "%s(): dai_name = %s DAI-ID %x\n", __func__, dai->name, dai->id); dev_dbg(dai->codec->dev, "%s(): tx_ch %d rx_ch %d\n intf_type %d\n", __func__, tx_num, rx_num, tapan->intf_type); if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) wcd9xxx_init_slimslave(core, core->slim->laddr, tx_num, tx_slot, rx_num, rx_slot); return 0; } static int tapan_get_channel_map(struct snd_soc_dai *dai, unsigned int *tx_num, unsigned int *tx_slot, unsigned int *rx_num, unsigned int *rx_slot) { struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(dai->codec); u32 i = 0; struct wcd9xxx_ch *ch; switch (dai->id) { case AIF1_PB: case AIF2_PB: case AIF3_PB: if (!rx_slot || !rx_num) { pr_err("%s: Invalid rx_slot %d or rx_num %d\n", __func__, (u32) rx_slot, (u32) rx_num); return -EINVAL; } list_for_each_entry(ch, &tapan_p->dai[dai->id].wcd9xxx_ch_list, list) { dev_dbg(dai->codec->dev, "%s: rx_slot[%d] %d, ch->ch_num %d\n", __func__, i, rx_slot[i], ch->ch_num); rx_slot[i++] = ch->ch_num; } dev_dbg(dai->codec->dev, "%s: rx_num %d\n", __func__, i); *rx_num = i; break; case AIF1_CAP: case AIF2_CAP: case AIF3_CAP: if (!tx_slot || !tx_num) { pr_err("%s: Invalid tx_slot %d or tx_num %d\n", __func__, (u32) tx_slot, (u32) tx_num); return -EINVAL; } list_for_each_entry(ch, &tapan_p->dai[dai->id].wcd9xxx_ch_list, list) { dev_dbg(dai->codec->dev, "%s: tx_slot[%d] %d, ch->ch_num %d\n", __func__, i, tx_slot[i], ch->ch_num); tx_slot[i++] = ch->ch_num; } dev_dbg(dai->codec->dev, "%s: tx_num %d\n", __func__, i); *tx_num = i; break; default: pr_err("%s: Invalid DAI ID %x\n", __func__, dai->id); break; } return 0; } static int tapan_set_interpolator_rate(struct snd_soc_dai *dai, u8 rx_fs_rate_reg_val, u32 compander_fs, u32 sample_rate) { u32 j; u8 rx_mix1_inp; u16 rx_mix_1_reg_1, rx_mix_1_reg_2; u16 rx_fs_reg; u8 rx_mix_1_reg_1_val, rx_mix_1_reg_2_val; u8 rdac5_mux; struct snd_soc_codec *codec = dai->codec; struct wcd9xxx_ch *ch; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); list_for_each_entry(ch, &tapan->dai[dai->id].wcd9xxx_ch_list, list) { /* for RX port starting from 16 instead of 10 like tabla */ rx_mix1_inp = ch->port + RX_MIX1_INP_SEL_RX1 - TAPAN_TX_PORT_NUMBER; if ((rx_mix1_inp < RX_MIX1_INP_SEL_RX1) || (rx_mix1_inp > RX_MIX1_INP_SEL_RX5)) { pr_err("%s: Invalid TAPAN_RX%u port. Dai ID is %d\n", __func__, rx_mix1_inp - 5 , dai->id); return -EINVAL; } rx_mix_1_reg_1 = TAPAN_A_CDC_CONN_RX1_B1_CTL; rdac5_mux = snd_soc_read(codec, TAPAN_A_CDC_CONN_MISC); rdac5_mux = (rdac5_mux & 0x04) >> 2; for (j = 0; j < NUM_INTERPOLATORS; j++) { rx_mix_1_reg_2 = rx_mix_1_reg_1 + 1; rx_mix_1_reg_1_val = snd_soc_read(codec, rx_mix_1_reg_1); rx_mix_1_reg_2_val = snd_soc_read(codec, rx_mix_1_reg_2); if (((rx_mix_1_reg_1_val & 0x0F) == rx_mix1_inp) || (((rx_mix_1_reg_1_val >> 4) & 0x0F) == rx_mix1_inp) || ((rx_mix_1_reg_2_val & 0x0F) == rx_mix1_inp)) { rx_fs_reg = TAPAN_A_CDC_RX1_B5_CTL + 8 * j; dev_dbg(codec->dev, "%s: AIF_PB DAI(%d) connected to RX%u\n", __func__, dai->id, j + 1); dev_dbg(codec->dev, "%s: set RX%u sample rate to %u\n", __func__, j + 1, sample_rate); snd_soc_update_bits(codec, rx_fs_reg, 0xE0, rx_fs_rate_reg_val); if (comp_rx_path[j] < COMPANDER_MAX) { if ((j == 3) && (rdac5_mux == 1)) tapan->comp_fs[COMPANDER_0] = compander_fs; else tapan->comp_fs[comp_rx_path[j]] = compander_fs; } } if (j <= 1) rx_mix_1_reg_1 += 3; else rx_mix_1_reg_1 += 2; } } return 0; } static int tapan_set_decimator_rate(struct snd_soc_dai *dai, u8 tx_fs_rate_reg_val, u32 sample_rate) { struct snd_soc_codec *codec = dai->codec; struct wcd9xxx_ch *ch; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); u32 tx_port; u16 tx_port_reg, tx_fs_reg; u8 tx_port_reg_val; s8 decimator; list_for_each_entry(ch, &tapan->dai[dai->id].wcd9xxx_ch_list, list) { tx_port = ch->port + 1; dev_dbg(codec->dev, "%s: dai->id = %d, tx_port = %d", __func__, dai->id, tx_port); if ((tx_port < 1) || (tx_port > TAPAN_SLIM_CODEC_TX_PORTS)) { pr_err("%s: Invalid SLIM TX%u port. DAI ID is %d\n", __func__, tx_port, dai->id); return -EINVAL; } tx_port_reg = TAPAN_A_CDC_CONN_TX_SB_B1_CTL + (tx_port - 1); tx_port_reg_val = snd_soc_read(codec, tx_port_reg); decimator = 0; tx_port_reg_val = tx_port_reg_val & 0x0F; if ((tx_port_reg_val >= 0x8) && (tx_port_reg_val <= 0x11)) { decimator = (tx_port_reg_val - 0x8) + 1; } if (decimator) { /* SLIM_TX port has a DEC as input */ tx_fs_reg = TAPAN_A_CDC_TX1_CLK_FS_CTL + 8 * (decimator - 1); dev_dbg(codec->dev, "%s: set DEC%u (-> SLIM_TX%u) rate to %u\n", __func__, decimator, tx_port, sample_rate); snd_soc_update_bits(codec, tx_fs_reg, 0x07, tx_fs_rate_reg_val); } else { if ((tx_port_reg_val >= 0x1) && (tx_port_reg_val <= 0x4)) { dev_dbg(codec->dev, "%s: RMIX%u going to SLIM TX%u\n", __func__, tx_port_reg_val, tx_port); } else if ((tx_port_reg_val >= 0x8) && (tx_port_reg_val <= 0x11)) { pr_err("%s: ERROR: Should not be here\n", __func__); pr_err("%s: ERROR: DEC connected to SLIM TX%u\n", __func__, tx_port); return -EINVAL; } else if (tx_port_reg_val == 0) { dev_dbg(codec->dev, "%s: no signal to SLIM TX%u\n", __func__, tx_port); } else { pr_err("%s: ERROR: wrong signal to SLIM TX%u\n", __func__, tx_port); pr_err("%s: ERROR: wrong signal = %u\n", __func__, tx_port_reg_val); return -EINVAL; } } } return 0; } static void tapan_set_rxsb_port_format(struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); struct wcd9xxx_codec_dai_data *cdc_dai; struct wcd9xxx_ch *ch; int port; u8 bit_sel; u16 sb_ctl_reg, field_shift; switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: bit_sel = 0x2; tapan_p->dai[dai->id].bit_width = 16; break; case SNDRV_PCM_FORMAT_S24_LE: bit_sel = 0x0; tapan_p->dai[dai->id].bit_width = 24; break; default: dev_err(codec->dev, "Invalid format %x\n", params_format(params)); return; } cdc_dai = &tapan_p->dai[dai->id]; list_for_each_entry(ch, &cdc_dai->wcd9xxx_ch_list, list) { port = wcd9xxx_get_slave_port(ch->ch_num); if (IS_ERR_VALUE(port) || !TAPAN_VALIDATE_RX_SBPORT_RANGE(port)) { dev_warn(codec->dev, "%s: invalid port ID %d returned for RX DAI\n", __func__, port); return; } port = TAPAN_CONVERT_RX_SBPORT_ID(port); if (port <= 3) { sb_ctl_reg = TAPAN_A_CDC_CONN_RX_SB_B1_CTL; field_shift = port << 1; } else if (port <= 4) { sb_ctl_reg = TAPAN_A_CDC_CONN_RX_SB_B2_CTL; field_shift = (port - 4) << 1; } else { /* should not happen */ dev_warn(codec->dev, "%s: bad port ID %d\n", __func__, port); return; } dev_dbg(codec->dev, "%s: sb_ctl_reg %x field_shift %x\n" "bit_sel %x\n", __func__, sb_ctl_reg, field_shift, bit_sel); snd_soc_update_bits(codec, sb_ctl_reg, 0x3 << field_shift, bit_sel << field_shift); } } static int tapan_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(dai->codec); u8 tx_fs_rate, rx_fs_rate; u32 compander_fs; int ret; dev_dbg(dai->codec->dev, "%s: dai_name = %s DAI-ID %x rate %d num_ch %d\n", __func__, dai->name, dai->id, params_rate(params), params_channels(params)); switch (params_rate(params)) { case 8000: tx_fs_rate = 0x00; rx_fs_rate = 0x00; compander_fs = COMPANDER_FS_8KHZ; break; case 16000: tx_fs_rate = 0x01; rx_fs_rate = 0x20; compander_fs = COMPANDER_FS_16KHZ; break; case 32000: tx_fs_rate = 0x02; rx_fs_rate = 0x40; compander_fs = COMPANDER_FS_32KHZ; break; case 48000: tx_fs_rate = 0x03; rx_fs_rate = 0x60; compander_fs = COMPANDER_FS_48KHZ; break; case 96000: tx_fs_rate = 0x04; rx_fs_rate = 0x80; compander_fs = COMPANDER_FS_96KHZ; break; case 192000: tx_fs_rate = 0x05; rx_fs_rate = 0xA0; compander_fs = COMPANDER_FS_192KHZ; break; default: pr_err("%s: Invalid sampling rate %d\n", __func__, params_rate(params)); return -EINVAL; } switch (substream->stream) { case SNDRV_PCM_STREAM_CAPTURE: ret = tapan_set_decimator_rate(dai, tx_fs_rate, params_rate(params)); if (ret < 0) { pr_err("%s: set decimator rate failed %d\n", __func__, ret); return ret; } if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) { switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, 0x20, 0x20); break; case SNDRV_PCM_FORMAT_S32_LE: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, 0x20, 0x00); break; default: pr_err("invalid format\n"); break; } snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, 0x07, tx_fs_rate); } else { tapan->dai[dai->id].rate = params_rate(params); } break; case SNDRV_PCM_STREAM_PLAYBACK: ret = tapan_set_interpolator_rate(dai, rx_fs_rate, compander_fs, params_rate(params)); if (ret < 0) { dev_err(codec->dev, "%s: set decimator rate failed %d\n", __func__, ret); return ret; } if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) { switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, 0x20, 0x20); break; case SNDRV_PCM_FORMAT_S32_LE: snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, 0x20, 0x00); break; default: dev_err(codec->dev, "invalid format\n"); break; } snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL, 0x03, (rx_fs_rate >> 0x05)); } else { tapan_set_rxsb_port_format(params, dai); tapan->dai[dai->id].rate = params_rate(params); } break; default: dev_err(codec->dev, "%s: Invalid stream type %d\n", __func__, substream->stream); return -EINVAL; } return 0; } int tapan_digital_mute(struct snd_soc_dai *dai, int mute) { struct snd_soc_codec *codec = NULL; u16 tx_vol_ctl_reg = 0; u8 decimator = 0, i; struct tapan_priv *tapan_p; pr_debug("%s: Digital Mute val = %d\n", __func__, mute); if (!dai || !dai->codec) { pr_err("%s: Invalid params\n", __func__); return -EINVAL; } codec = dai->codec; tapan_p = snd_soc_codec_get_drvdata(codec); if (dai->id != AIF1_CAP) { dev_dbg(codec->dev, "%s: Not capture use case skip\n", __func__); return 0; } mute = (mute) ? 1 : 0; if (!mute) { /* * 5 ms is an emperical value for the mute time * that was arrived by checking the pop level * to be inaudible */ usleep_range(5000, 5010); } for (i = 0; i < NUM_DECIMATORS; i++) { if (tapan_p->dec_active[i]) decimator = i + 1; if (decimator && decimator <= NUM_DECIMATORS) { pr_debug("%s: Mute = %d Decimator = %d", __func__, mute, decimator); tx_vol_ctl_reg = TAPAN_A_CDC_TX1_VOL_CTL_CFG + 8 * (decimator - 1); snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, mute); } decimator = 0; } return 0; } static struct snd_soc_dai_ops tapan_dai_ops = { .startup = tapan_startup, .shutdown = tapan_shutdown, .hw_params = tapan_hw_params, .set_sysclk = tapan_set_dai_sysclk, .set_fmt = tapan_set_dai_fmt, .set_channel_map = tapan_set_channel_map, .get_channel_map = tapan_get_channel_map, .digital_mute = tapan_digital_mute, }; static struct snd_soc_dai_driver tapan9302_dai[] = { { .name = "tapan9302_rx1", .id = AIF1_PB, .playback = { .stream_name = "AIF1 Playback", .rates = WCD9302_RATES, .formats = TAPAN_FORMATS, .rate_max = 48000, .rate_min = 8000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, { .name = "tapan9302_tx1", .id = AIF1_CAP, .capture = { .stream_name = "AIF1 Capture", .rates = WCD9302_RATES, .formats = TAPAN_FORMATS, .rate_max = 48000, .rate_min = 8000, .channels_min = 1, .channels_max = 4, }, .ops = &tapan_dai_ops, }, { .name = "tapan9302_rx2", .id = AIF2_PB, .playback = { .stream_name = "AIF2 Playback", .rates = WCD9302_RATES, .formats = TAPAN_FORMATS, .rate_min = 8000, .rate_max = 48000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, { .name = "tapan9302_tx2", .id = AIF2_CAP, .capture = { .stream_name = "AIF2 Capture", .rates = WCD9302_RATES, .formats = TAPAN_FORMATS, .rate_max = 48000, .rate_min = 8000, .channels_min = 1, .channels_max = 4, }, .ops = &tapan_dai_ops, }, { .name = "tapan9302_tx3", .id = AIF3_CAP, .capture = { .stream_name = "AIF3 Capture", .rates = WCD9302_RATES, .formats = TAPAN_FORMATS, .rate_max = 48000, .rate_min = 8000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, { .name = "tapan9302_rx3", .id = AIF3_PB, .playback = { .stream_name = "AIF3 Playback", .rates = WCD9302_RATES, .formats = TAPAN_FORMATS, .rate_min = 8000, .rate_max = 48000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, }; static struct snd_soc_dai_driver tapan_dai[] = { { .name = "tapan_rx1", .id = AIF1_PB, .playback = { .stream_name = "AIF1 Playback", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS_S16_S24_LE, .rate_max = 192000, .rate_min = 8000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, { .name = "tapan_tx1", .id = AIF1_CAP, .capture = { .stream_name = "AIF1 Capture", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS, .rate_max = 192000, .rate_min = 8000, .channels_min = 1, .channels_max = 4, }, .ops = &tapan_dai_ops, }, { .name = "tapan_rx2", .id = AIF2_PB, .playback = { .stream_name = "AIF2 Playback", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS_S16_S24_LE, .rate_min = 8000, .rate_max = 192000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, { .name = "tapan_tx2", .id = AIF2_CAP, .capture = { .stream_name = "AIF2 Capture", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS, .rate_max = 192000, .rate_min = 8000, .channels_min = 1, .channels_max = 4, }, .ops = &tapan_dai_ops, }, { .name = "tapan_tx3", .id = AIF3_CAP, .capture = { .stream_name = "AIF3 Capture", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS, .rate_max = 48000, .rate_min = 8000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, { .name = "tapan_rx3", .id = AIF3_PB, .playback = { .stream_name = "AIF3 Playback", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS_S16_S24_LE, .rate_min = 8000, .rate_max = 192000, .channels_min = 1, .channels_max = 2, }, .ops = &tapan_dai_ops, }, }; static struct snd_soc_dai_driver tapan_i2s_dai[] = { { .name = "tapan_i2s_rx1", .id = AIF1_PB, .playback = { .stream_name = "AIF1 Playback", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS, .rate_max = 192000, .rate_min = 8000, .channels_min = 1, .channels_max = 4, }, .ops = &tapan_dai_ops, }, { .name = "tapan_i2s_tx1", .id = AIF1_CAP, .capture = { .stream_name = "AIF1 Capture", .rates = WCD9306_RATES, .formats = TAPAN_FORMATS, .rate_max = 192000, .rate_min = 8000, .channels_min = 1, .channels_max = 4, }, .ops = &tapan_dai_ops, }, }; static int tapan_codec_enable_slim_chmask(struct wcd9xxx_codec_dai_data *dai, bool up) { int ret = 0; struct wcd9xxx_ch *ch; if (up) { list_for_each_entry(ch, &dai->wcd9xxx_ch_list, list) { ret = wcd9xxx_get_slave_port(ch->ch_num); if (ret < 0) { pr_debug("%s: Invalid slave port ID: %d\n", __func__, ret); ret = -EINVAL; } else { set_bit(ret, &dai->ch_mask); } } } else { ret = wait_event_timeout(dai->dai_wait, (dai->ch_mask == 0), msecs_to_jiffies( TAPAN_SLIM_CLOSE_TIMEOUT)); if (!ret) { pr_debug("%s: Slim close tx/rx wait timeout\n", __func__); ret = -ETIMEDOUT; } else { ret = 0; } } return ret; } static int tapan_codec_enable_slimrx(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct wcd9xxx *core; struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); int ret = 0; struct wcd9xxx_codec_dai_data *dai; core = dev_get_drvdata(codec->dev->parent); if(core == NULL) { dev_err(codec->dev, "%s: core is null\n", __func__); return -EINVAL; } dev_dbg(codec->dev, "%s: event called! codec name %s\n", __func__, w->codec->name); dev_dbg(codec->dev, "%s: num_dai %d stream name %s event %d\n", __func__, w->codec->num_dai, w->sname, event); /* Execute the callback only if interface type is slimbus */ if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) return 0; dai = &tapan_p->dai[w->shift]; dev_dbg(codec->dev, "%s: w->name %s w->shift %d event %d\n", __func__, w->name, w->shift, event); switch (event) { case SND_SOC_DAPM_POST_PMU: dai->bus_down_in_recovery = false; (void) tapan_codec_enable_slim_chmask(dai, true); ret = wcd9xxx_cfg_slim_sch_rx(core, &dai->wcd9xxx_ch_list, dai->rate, dai->bit_width, &dai->grph); break; case SND_SOC_DAPM_POST_PMD: ret = wcd9xxx_close_slim_sch_rx(core, &dai->wcd9xxx_ch_list, dai->grph); if (!dai->bus_down_in_recovery) ret = tapan_codec_enable_slim_chmask(dai, false); if (ret < 0) { ret = wcd9xxx_disconnect_port(core, &dai->wcd9xxx_ch_list, dai->grph); dev_dbg(codec->dev, "%s: Disconnect RX port, ret = %d\n", __func__, ret); } if ((core != NULL) && (core->dev != NULL) && (core->dev->parent != NULL)) { pm_runtime_mark_last_busy(core->dev->parent); pm_runtime_put(core->dev->parent); dev_dbg(codec->dev, "%s: unvote requested", __func__); } dai->bus_down_in_recovery = false; break; } return ret; } static int tapan_codec_enable_slimtx(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct wcd9xxx *core; struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); u32 ret = 0; struct wcd9xxx_codec_dai_data *dai; core = dev_get_drvdata(codec->dev->parent); dev_dbg(codec->dev, "%s: event called! codec name %s\n", __func__, w->codec->name); dev_dbg(codec->dev, "%s: num_dai %d stream name %s\n", __func__, w->codec->num_dai, w->sname); /* Execute the callback only if interface type is slimbus */ if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) return 0; dev_dbg(codec->dev, "%s(): w->name %s event %d w->shift %d\n", __func__, w->name, event, w->shift); dai = &tapan_p->dai[w->shift]; switch (event) { case SND_SOC_DAPM_POST_PMU: dai->bus_down_in_recovery = false; (void) tapan_codec_enable_slim_chmask(dai, true); ret = wcd9xxx_cfg_slim_sch_tx(core, &dai->wcd9xxx_ch_list, dai->rate, dai->bit_width, &dai->grph); break; case SND_SOC_DAPM_POST_PMD: ret = wcd9xxx_close_slim_sch_tx(core, &dai->wcd9xxx_ch_list, dai->grph); if (!dai->bus_down_in_recovery) ret = tapan_codec_enable_slim_chmask(dai, false); if (ret < 0) { ret = wcd9xxx_disconnect_port(core, &dai->wcd9xxx_ch_list, dai->grph); dev_dbg(codec->dev, "%s: Disconnect RX port, ret = %d\n", __func__, ret); } if ((core != NULL) && (core->dev != NULL) && (core->dev->parent != NULL)) { pm_runtime_mark_last_busy(core->dev->parent); pm_runtime_put(core->dev->parent); dev_dbg(codec->dev, "%s: unvote requested", __func__); } dai->bus_down_in_recovery = false; break; } return ret; } static int tapan_codec_enable_ear_pa(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_POST_PMU: wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d, WCD9XXX_CLSH_STATE_EAR, WCD9XXX_CLSH_REQ_ENABLE, WCD9XXX_CLSH_EVENT_POST_PA); usleep_range(5000, 5010); break; case SND_SOC_DAPM_POST_PMD: usleep_range(5000, 5010); snd_soc_update_bits(codec, TAPAN_A_RX_EAR_EN, 0x40, 0x00); wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d, WCD9XXX_CLSH_STATE_EAR, WCD9XXX_CLSH_REQ_DISABLE, WCD9XXX_CLSH_EVENT_POST_PA); } return 0; } static int tapan_codec_ear_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d, WCD9XXX_CLSH_STATE_EAR, WCD9XXX_CLSH_REQ_ENABLE, WCD9XXX_CLSH_EVENT_PRE_DAC); break; } return 0; } static int tapan_codec_iir_mux_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; pr_debug("%s: event = %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_POST_PMU: snd_soc_write(codec, w->reg, snd_soc_read(codec, w->reg)); break; case SND_SOC_DAPM_POST_PMD: snd_soc_write(codec, w->reg, snd_soc_read(codec, w->reg)); break; } return 0; } static int tapan_codec_dsm_mux_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; u8 reg_val, zoh_mux_val = 0x00; dev_dbg(codec->dev, "%s: event = %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_POST_PMU: reg_val = snd_soc_read(codec, TAPAN_A_CDC_CONN_CLSH_CTL); if ((reg_val & 0x30) == 0x10) zoh_mux_val = 0x04; else if ((reg_val & 0x30) == 0x20) zoh_mux_val = 0x08; if (zoh_mux_val != 0x00) snd_soc_update_bits(codec, TAPAN_A_CDC_CONN_CLSH_CTL, 0x0C, zoh_mux_val); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, TAPAN_A_CDC_CONN_CLSH_CTL, 0x0C, 0x00); break; } return 0; } static int tapan_codec_enable_anc_ear(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; int ret = 0; switch (event) { case SND_SOC_DAPM_PRE_PMU: ret = tapan_codec_enable_anc(w, kcontrol, event); msleep(50); snd_soc_update_bits(codec, TAPAN_A_RX_EAR_EN, 0x10, 0x10); break; case SND_SOC_DAPM_POST_PMU: ret = tapan_codec_enable_ear_pa(w, kcontrol, event); break; case SND_SOC_DAPM_PRE_PMD: snd_soc_update_bits(codec, TAPAN_A_RX_EAR_EN, 0x10, 0x00); msleep(40); ret |= tapan_codec_enable_anc(w, kcontrol, event); break; case SND_SOC_DAPM_POST_PMD: ret = tapan_codec_enable_ear_pa(w, kcontrol, event); break; } return ret; } static int tapan_codec_chargepump_vdd_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec); int ret = 0, i; pr_info("%s: event = %d\n", __func__, event); if (!priv->cp_regulators[CP_REG_BUCK] && !priv->cp_regulators[CP_REG_BHELPER]) { pr_err("%s: No power supply defined for ChargePump\n", __func__); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: for (i = 0; i < CP_REG_MAX ; i++) { if (!priv->cp_regulators[i]) continue; ret = regulator_enable(priv->cp_regulators[i]); if (ret) { pr_err("%s: CP Regulator enable failed, index = %d\n", __func__, i); continue; } else { pr_debug("%s: Enabled CP regulator, index %d\n", __func__, i); } } break; case SND_SOC_DAPM_POST_PMD: for (i = 0; i < CP_REG_MAX; i++) { if (!priv->cp_regulators[i]) continue; ret = regulator_disable(priv->cp_regulators[i]); if (ret) { pr_err("%s: CP Regulator disable failed, index = %d\n", __func__, i); return ret; } else { pr_debug("%s: Disabled CP regulator %d\n", __func__, i); } } break; } return 0; } static int tapan_codec_set_iir_gain(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; int value = 0; switch (event) { case SND_SOC_DAPM_POST_PMU: value = snd_soc_read(codec, TAPAN_A_CDC_IIR1_GAIN_B1_CTL); snd_soc_write(codec, TAPAN_A_CDC_IIR1_GAIN_B1_CTL, value); break; default: pr_err("%s: event = %d not expected\n", __func__, event); } return 0; } static const struct snd_soc_dapm_widget tapan_9306_dapm_widgets[] = { /* RX4 MIX1 mux inputs */ SND_SOC_DAPM_MUX("RX4 MIX1 INP1", SND_SOC_NOPM, 0, 0, &rx4_mix1_inp1_mux), SND_SOC_DAPM_MUX("RX4 MIX1 INP2", SND_SOC_NOPM, 0, 0, &rx4_mix1_inp2_mux), SND_SOC_DAPM_MUX("RX4 MIX1 INP3", SND_SOC_NOPM, 0, 0, &rx4_mix1_inp3_mux), /* RX4 MIX2 mux inputs */ SND_SOC_DAPM_MUX("RX4 MIX2 INP1", SND_SOC_NOPM, 0, 0, &rx4_mix2_inp1_mux), SND_SOC_DAPM_MUX("RX4 MIX2 INP2", SND_SOC_NOPM, 0, 0, &rx4_mix2_inp2_mux), SND_SOC_DAPM_MIXER("RX4 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER_E("RX4 MIX2", TAPAN_A_CDC_CLK_RX_B1_CTL, 3, 0, NULL, 0, tapan_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_MUX_E("DEC3 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 2, 0, &dec3_mux, tapan_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("DEC4 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 3, 0, &dec4_mux, tapan_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY("COMP0_CLK", SND_SOC_NOPM, 0, 0, tapan_config_compander, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD), SND_SOC_DAPM_SUPPLY("COMP1_CLK", SND_SOC_NOPM, 1, 0, tapan_config_compander, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD), SND_SOC_DAPM_SUPPLY("COMP2_CLK", SND_SOC_NOPM, 2, 0, tapan_config_compander, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD), SND_SOC_DAPM_INPUT("AMIC5"), SND_SOC_DAPM_ADC_E("ADC5", NULL, TAPAN_A_TX_5_EN, 7, 0, tapan_codec_enable_adc, SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_MUX("ANC1 MUX", SND_SOC_NOPM, 0, 0, &anc1_mux), SND_SOC_DAPM_MUX("ANC2 MUX", SND_SOC_NOPM, 0, 0, &anc2_mux), SND_SOC_DAPM_OUTPUT("ANC HEADPHONE"), SND_SOC_DAPM_PGA_E("ANC HPHL", SND_SOC_NOPM, 5, 0, NULL, 0, tapan_codec_enable_anc_hph, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_PGA_E("ANC HPHR", SND_SOC_NOPM, 4, 0, NULL, 0, tapan_codec_enable_anc_hph, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_OUTPUT("ANC EAR"), SND_SOC_DAPM_PGA_E("ANC EAR PA", SND_SOC_NOPM, 0, 0, NULL, 0, tapan_codec_enable_anc_ear, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("ANC1 FB MUX", SND_SOC_NOPM, 0, 0, &anc1_fb_mux), SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 External", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal1", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal2", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("DMIC3", NULL, SND_SOC_NOPM, 0, 0, tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("DMIC4", NULL, SND_SOC_NOPM, 0, 0, tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), }; /* Todo: Have seperate dapm widgets for I2S and Slimbus. * Might Need to have callbacks registered only for slimbus */ static const struct snd_soc_dapm_widget tapan_common_dapm_widgets[] = { SND_SOC_DAPM_AIF_IN_E("AIF1 PB", "AIF1 Playback", 0, SND_SOC_NOPM, AIF1_PB, 0, tapan_codec_enable_slimrx, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_AIF_IN_E("AIF2 PB", "AIF2 Playback", 0, SND_SOC_NOPM, AIF2_PB, 0, tapan_codec_enable_slimrx, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_AIF_IN_E("AIF3 PB", "AIF3 Playback", 0, SND_SOC_NOPM, AIF3_PB, 0, tapan_codec_enable_slimrx, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("SLIM RX1 MUX", SND_SOC_NOPM, TAPAN_RX1, 0, &slim_rx_mux[TAPAN_RX1]), SND_SOC_DAPM_MUX("SLIM RX2 MUX", SND_SOC_NOPM, TAPAN_RX2, 0, &slim_rx_mux[TAPAN_RX2]), SND_SOC_DAPM_MUX("SLIM RX3 MUX", SND_SOC_NOPM, TAPAN_RX3, 0, &slim_rx_mux[TAPAN_RX3]), SND_SOC_DAPM_MUX("SLIM RX4 MUX", SND_SOC_NOPM, TAPAN_RX4, 0, &slim_rx_mux[TAPAN_RX4]), SND_SOC_DAPM_MUX("SLIM RX5 MUX", SND_SOC_NOPM, TAPAN_RX5, 0, &slim_rx_mux[TAPAN_RX5]), SND_SOC_DAPM_MIXER("SLIM RX1", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("SLIM RX2", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("SLIM RX3", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("SLIM RX4", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("SLIM RX5", SND_SOC_NOPM, 0, 0, NULL, 0), /* RX1 MIX1 mux inputs */ SND_SOC_DAPM_MUX("RX1 MIX1 INP1", SND_SOC_NOPM, 0, 0, &rx_mix1_inp1_mux), SND_SOC_DAPM_MUX("RX1 MIX1 INP2", SND_SOC_NOPM, 0, 0, &rx_mix1_inp2_mux), SND_SOC_DAPM_MUX("RX1 MIX1 INP3", SND_SOC_NOPM, 0, 0, &rx_mix1_inp3_mux), /* RX2 MIX1 mux inputs */ SND_SOC_DAPM_MUX("RX2 MIX1 INP1", SND_SOC_NOPM, 0, 0, &rx2_mix1_inp1_mux), SND_SOC_DAPM_MUX("RX2 MIX1 INP2", SND_SOC_NOPM, 0, 0, &rx2_mix1_inp2_mux), SND_SOC_DAPM_MUX("RX2 MIX1 INP3", SND_SOC_NOPM, 0, 0, &rx2_mix1_inp2_mux), /* RX3 MIX1 mux inputs */ SND_SOC_DAPM_MUX("RX3 MIX1 INP1", SND_SOC_NOPM, 0, 0, &rx3_mix1_inp1_mux), SND_SOC_DAPM_MUX("RX3 MIX1 INP2", SND_SOC_NOPM, 0, 0, &rx3_mix1_inp2_mux), SND_SOC_DAPM_MUX("RX3 MIX1 INP3", SND_SOC_NOPM, 0, 0, &rx3_mix1_inp3_mux), /* RX1 MIX2 mux inputs */ SND_SOC_DAPM_MUX("RX1 MIX2 INP1", SND_SOC_NOPM, 0, 0, &rx1_mix2_inp1_mux), SND_SOC_DAPM_MUX("RX1 MIX2 INP2", SND_SOC_NOPM, 0, 0, &rx1_mix2_inp2_mux), /* RX2 MIX2 mux inputs */ SND_SOC_DAPM_MUX("RX2 MIX2 INP1", SND_SOC_NOPM, 0, 0, &rx2_mix2_inp1_mux), SND_SOC_DAPM_MUX("RX2 MIX2 INP2", SND_SOC_NOPM, 0, 0, &rx2_mix2_inp2_mux), SND_SOC_DAPM_MIXER("RX1 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("RX2 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("RX1 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("RX2 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER_E("RX3 MIX1", TAPAN_A_CDC_CLK_RX_B1_CTL, 2, 0, NULL, 0, tapan_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_VIRT_MUX_E("RX1 INTERPOLATOR", TAPAN_A_CDC_CLK_RX_B1_CTL, 0, 0, &rx1_interpolator, tapan_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_VIRT_MUX_E("RX2 INTERPOLATOR", TAPAN_A_CDC_CLK_RX_B1_CTL, 1, 0, &rx2_interpolator, tapan_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_MIXER("RX1 CHAIN", TAPAN_A_CDC_RX1_B6_CTL, 5, 0, NULL, 0), SND_SOC_DAPM_MIXER_E("RX2 CHAIN", SND_SOC_NOPM, 0, 0, NULL, 0, tapan_codec_rx_dem_select, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("CLASS_H_DSM MUX", SND_SOC_NOPM, 0, 0, &class_h_dsm_mux, tapan_codec_dsm_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* RX Bias */ SND_SOC_DAPM_SUPPLY("RX_BIAS", SND_SOC_NOPM, 0, 0, tapan_codec_enable_rx_bias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /* CDC_CP_VDD */ SND_SOC_DAPM_SUPPLY("CDC_CP_VDD", SND_SOC_NOPM, 0, 0, tapan_codec_chargepump_vdd_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /*EAR */ SND_SOC_DAPM_PGA_E("EAR PA", TAPAN_A_RX_EAR_EN, 4, 0, NULL, 0, tapan_codec_enable_ear_pa, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER_E("DAC1", TAPAN_A_RX_EAR_EN, 6, 0, dac1_switch, ARRAY_SIZE(dac1_switch), tapan_codec_ear_dac_event, SND_SOC_DAPM_PRE_PMU), /* Headphone Left */ SND_SOC_DAPM_PGA_E("HPHL", TAPAN_A_RX_HPH_CNP_EN, 5, 0, NULL, 0, tapan_hph_pa_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER_E("HPHL DAC", TAPAN_A_RX_HPH_L_DAC_CTL, 7, 0, hphl_switch, ARRAY_SIZE(hphl_switch), tapan_hphl_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /* Headphone Right */ SND_SOC_DAPM_PGA_E("HPHR", TAPAN_A_RX_HPH_CNP_EN, 4, 0, NULL, 0, tapan_hph_pa_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_DAC_E("HPHR DAC", NULL, TAPAN_A_RX_HPH_R_DAC_CTL, 7, 0, tapan_hphr_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /* LINEOUT1*/ SND_SOC_DAPM_DAC_E("LINEOUT1 DAC", NULL, TAPAN_A_RX_LINE_1_DAC_CTL, 7, 0 , tapan_lineout_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("LINEOUT1 PA", TAPAN_A_RX_LINE_CNP_EN, 0, 0, NULL, 0, tapan_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* LINEOUT2*/ SND_SOC_DAPM_MUX("RDAC5 MUX", SND_SOC_NOPM, 0, 0, &rx_dac5_mux), /* LINEOUT1*/ SND_SOC_DAPM_MUX("RDAC4 MUX", SND_SOC_NOPM, 0, 0, &rx_dac4_mux), SND_SOC_DAPM_MUX("RDAC3 MUX", SND_SOC_NOPM, 0, 0, &rx_dac3_mux), SND_SOC_DAPM_DAC_E("LINEOUT2 DAC", NULL, TAPAN_A_RX_LINE_2_DAC_CTL, 7, 0 , tapan_lineout_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("LINEOUT2 PA", TAPAN_A_RX_LINE_CNP_EN, 1, 0, NULL, 0, tapan_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* CLASS-D SPK */ SND_SOC_DAPM_MIXER_E("SPK DAC", SND_SOC_NOPM, 0, 0, spk_dac_switch, ARRAY_SIZE(spk_dac_switch), tapan_spk_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("SPK PA", SND_SOC_NOPM, 0, 0 , NULL, 0, tapan_codec_enable_spk_pa, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY("VDD_SPKDRV", SND_SOC_NOPM, 0, 0, tapan_codec_enable_vdd_spkr, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_OUTPUT("EAR"), SND_SOC_DAPM_OUTPUT("HEADPHONE"), SND_SOC_DAPM_OUTPUT("LINEOUT1"), SND_SOC_DAPM_OUTPUT("LINEOUT2"), SND_SOC_DAPM_OUTPUT("SPK_OUT"), /* TX Path*/ SND_SOC_DAPM_MIXER("AIF1_CAP Mixer", SND_SOC_NOPM, AIF1_CAP, 0, aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)), SND_SOC_DAPM_MIXER("AIF2_CAP Mixer", SND_SOC_NOPM, AIF2_CAP, 0, aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)), SND_SOC_DAPM_MIXER("AIF3_CAP Mixer", SND_SOC_NOPM, AIF3_CAP, 0, aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)), SND_SOC_DAPM_MUX("SLIM TX1 MUX", SND_SOC_NOPM, TAPAN_TX1, 0, &sb_tx1_mux), SND_SOC_DAPM_MUX("SLIM TX2 MUX", SND_SOC_NOPM, TAPAN_TX2, 0, &sb_tx2_mux), SND_SOC_DAPM_MUX("SLIM TX3 MUX", SND_SOC_NOPM, TAPAN_TX3, 0, &sb_tx3_mux), SND_SOC_DAPM_MUX("SLIM TX4 MUX", SND_SOC_NOPM, TAPAN_TX4, 0, &sb_tx4_mux), SND_SOC_DAPM_MUX("SLIM TX5 MUX", SND_SOC_NOPM, TAPAN_TX5, 0, &sb_tx5_mux), SND_SOC_DAPM_SUPPLY("CDC_CONN", WCD9XXX_A_CDC_CLK_OTHR_CTL, 2, 0, NULL, 0), /* Decimator MUX */ SND_SOC_DAPM_MUX_E("DEC1 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 0, 0, &dec1_mux, tapan_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("DEC2 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 1, 0, &dec2_mux, tapan_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY("LDO_H", SND_SOC_NOPM, 7, 0, tapan_codec_enable_ldo_h, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /* * DAPM 'LDO_H Standalone' is to be powered by mbhc driver after * acquring codec_resource lock. * So call __tapan_codec_enable_ldo_h instead and avoid deadlock. */ SND_SOC_DAPM_SUPPLY("LDO_H Standalone", SND_SOC_NOPM, 7, 0, __tapan_codec_enable_ldo_h, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_INPUT("AMIC1"), SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 External", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal1", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal2", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("ADC1", NULL, TAPAN_A_TX_1_EN, 7, 0, tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("ADC2", NULL, TAPAN_A_TX_2_EN, 7, 0, tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_INPUT("AMIC3"), SND_SOC_DAPM_ADC_E("ADC3", NULL, TAPAN_A_TX_3_EN, 7, 0, tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_INPUT("AMIC4"), SND_SOC_DAPM_ADC_E("ADC4", NULL, TAPAN_A_TX_4_EN, 7, 0, tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_INPUT("AMIC2"), SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 External", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal1", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal2", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal3", SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E(DAPM_MICBIAS2_EXTERNAL_STANDALONE, SND_SOC_NOPM, 7, 0, tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_AIF_OUT_E("AIF1 CAP", "AIF1 Capture", 0, SND_SOC_NOPM, AIF1_CAP, 0, tapan_codec_enable_slimtx, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_AIF_OUT_E("AIF2 CAP", "AIF2 Capture", 0, SND_SOC_NOPM, AIF2_CAP, 0, tapan_codec_enable_slimtx, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_AIF_OUT_E("AIF3 CAP", "AIF3 Capture", 0, SND_SOC_NOPM, AIF3_CAP, 0, tapan_codec_enable_slimtx, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* Digital Mic Inputs */ SND_SOC_DAPM_ADC_E("DMIC1", NULL, SND_SOC_NOPM, 0, 0, tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("DMIC2", NULL, SND_SOC_NOPM, 0, 0, tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /* Sidetone */ SND_SOC_DAPM_MUX_E("IIR1 INP1 MUX", TAPAN_A_CDC_IIR1_GAIN_B1_CTL, 0, 0, &iir1_inp1_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("IIR1", TAPAN_A_CDC_CLK_SD_CTL, 0, 0, NULL, 0, tapan_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_MUX_E("IIR1 INP2 MUX", TAPAN_A_CDC_IIR1_GAIN_B2_CTL, 0, 0, &iir1_inp2_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("IIR1 INP3 MUX", TAPAN_A_CDC_IIR1_GAIN_B3_CTL, 0, 0, &iir1_inp3_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("IIR1 INP4 MUX", TAPAN_A_CDC_IIR1_GAIN_B4_CTL, 0, 0, &iir1_inp4_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("IIR2 INP1 MUX", TAPAN_A_CDC_IIR2_GAIN_B1_CTL, 0, 0, &iir2_inp1_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("IIR2 INP2 MUX", TAPAN_A_CDC_IIR2_GAIN_B2_CTL, 0, 0, &iir2_inp2_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("IIR2 INP3 MUX", TAPAN_A_CDC_IIR2_GAIN_B3_CTL, 0, 0, &iir2_inp3_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("IIR2 INP4 MUX", TAPAN_A_CDC_IIR2_GAIN_B4_CTL, 0, 0, &iir2_inp4_mux, tapan_codec_iir_mux_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA("IIR2", TAPAN_A_CDC_CLK_SD_CTL, 1, 0, NULL, 0), /* AUX PGA */ SND_SOC_DAPM_ADC_E("AUX_PGA_Left", NULL, TAPAN_A_RX_AUX_SW_CTL, 7, 0, tapan_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("AUX_PGA_Right", NULL, TAPAN_A_RX_AUX_SW_CTL, 6, 0, tapan_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /* Lineout, ear and HPH PA Mixers */ SND_SOC_DAPM_MIXER("EAR_PA_MIXER", SND_SOC_NOPM, 0, 0, ear_pa_mix, ARRAY_SIZE(ear_pa_mix)), SND_SOC_DAPM_MIXER("HPHL_PA_MIXER", SND_SOC_NOPM, 0, 0, hphl_pa_mix, ARRAY_SIZE(hphl_pa_mix)), SND_SOC_DAPM_MIXER("HPHR_PA_MIXER", SND_SOC_NOPM, 0, 0, hphr_pa_mix, ARRAY_SIZE(hphr_pa_mix)), SND_SOC_DAPM_MIXER("LINEOUT1_PA_MIXER", SND_SOC_NOPM, 0, 0, lineout1_pa_mix, ARRAY_SIZE(lineout1_pa_mix)), SND_SOC_DAPM_MIXER("LINEOUT2_PA_MIXER", SND_SOC_NOPM, 0, 0, lineout2_pa_mix, ARRAY_SIZE(lineout2_pa_mix)), }; static irqreturn_t tapan_slimbus_irq(int irq, void *data) { struct tapan_priv *priv = data; struct snd_soc_codec *codec = priv->codec; unsigned long status = 0; int i, j, port_id, k; u32 bit; u8 val; bool tx, cleared; for (i = TAPAN_SLIM_PGD_PORT_INT_STATUS_RX_0, j = 0; i <= TAPAN_SLIM_PGD_PORT_INT_STATUS_TX_1; i++, j++) { val = wcd9xxx_interface_reg_read(codec->control_data, i); status |= ((u32)val << (8 * j)); } for_each_set_bit(j, &status, 32) { tx = (j >= 16 ? true : false); port_id = (tx ? j - 16 : j); val = wcd9xxx_interface_reg_read(codec->control_data, TAPAN_SLIM_PGD_PORT_INT_RX_SOURCE0 + j); if (val & TAPAN_SLIM_IRQ_OVERFLOW) pr_err_ratelimited( "%s: overflow error on %s port %d, value %x\n", __func__, (tx ? "TX" : "RX"), port_id, val); if (val & TAPAN_SLIM_IRQ_UNDERFLOW) pr_err_ratelimited( "%s: underflow error on %s port %d, value %x\n", __func__, (tx ? "TX" : "RX"), port_id, val); if (val & TAPAN_SLIM_IRQ_PORT_CLOSED) { /* * INT SOURCE register starts from RX to TX * but port number in the ch_mask is in opposite way */ bit = (tx ? j - 16 : j + 16); dev_dbg(codec->dev, "%s: %s port %d closed value %x, bit %u\n", __func__, (tx ? "TX" : "RX"), port_id, val, bit); for (k = 0, cleared = false; k < NUM_CODEC_DAIS; k++) { dev_dbg(codec->dev, "%s: priv->dai[%d].ch_mask = 0x%lx\n", __func__, k, priv->dai[k].ch_mask); if (test_and_clear_bit(bit, &priv->dai[k].ch_mask)) { cleared = true; if (!priv->dai[k].ch_mask) wake_up(&priv->dai[k].dai_wait); /* * There are cases when multiple DAIs * might be using the same slimbus * channel. Hence don't break here. */ } } WARN(!cleared, "Couldn't find slimbus %s port %d for closing\n", (tx ? "TX" : "RX"), port_id); } wcd9xxx_interface_reg_write(codec->control_data, TAPAN_SLIM_PGD_PORT_INT_CLR_RX_0 + (j / 8), 1 << (j % 8)); } return IRQ_HANDLED; } static int tapan_handle_pdata(struct tapan_priv *tapan) { struct snd_soc_codec *codec = tapan->codec; struct wcd9xxx_pdata *pdata = tapan->resmgr.pdata; int k1, k2, k3, rc = 0; u8 txfe_bypass; u8 txfe_buff; u8 flag; u8 i = 0, j = 0; u8 val_txfe = 0, value = 0; u8 dmic_sample_rate_value = 0; u8 dmic_b1_ctl_value = 0; u8 anc_ctl_value = 0; if (!pdata) { dev_err(codec->dev, "%s: NULL pdata\n", __func__); rc = -ENODEV; goto done; } txfe_bypass = pdata->amic_settings.txfe_enable; txfe_buff = pdata->amic_settings.txfe_buff; flag = pdata->amic_settings.use_pdata; /* Make sure settings are correct */ if ((pdata->micbias.ldoh_v > WCD9XXX_LDOH_3P0_V) || (pdata->micbias.bias1_cfilt_sel > WCD9XXX_CFILT3_SEL) || (pdata->micbias.bias2_cfilt_sel > WCD9XXX_CFILT3_SEL) || (pdata->micbias.bias3_cfilt_sel > WCD9XXX_CFILT3_SEL)) { dev_err(codec->dev, "%s: Invalid ldoh voltage or bias cfilt\n", __func__); rc = -EINVAL; goto done; } /* figure out k value */ k1 = wcd9xxx_resmgr_get_k_val(&tapan->resmgr, pdata->micbias.cfilt1_mv); k2 = wcd9xxx_resmgr_get_k_val(&tapan->resmgr, pdata->micbias.cfilt2_mv); k3 = wcd9xxx_resmgr_get_k_val(&tapan->resmgr, pdata->micbias.cfilt3_mv); if (IS_ERR_VALUE(k1) || IS_ERR_VALUE(k2) || IS_ERR_VALUE(k3)) { dev_err(codec->dev, "%s: could not get K value. k1 = %d k2 = %d k3 = %d\n", __func__, k1, k2, k3); rc = -EINVAL; goto done; } /* Set voltage level and always use LDO */ snd_soc_update_bits(codec, TAPAN_A_LDO_H_MODE_1, 0x0C, (pdata->micbias.ldoh_v << 2)); snd_soc_update_bits(codec, TAPAN_A_MICB_CFILT_1_VAL, 0xFC, (k1 << 2)); snd_soc_update_bits(codec, TAPAN_A_MICB_CFILT_2_VAL, 0xFC, (k2 << 2)); snd_soc_update_bits(codec, TAPAN_A_MICB_CFILT_3_VAL, 0xFC, (k3 << 2)); i = 0; while (i < 5) { if (flag & (0x01 << i)) { val_txfe = (txfe_bypass & (0x01 << i)) ? 0x20 : 0x00; val_txfe = val_txfe | ((txfe_buff & (0x01 << i)) ? 0x10 : 0x00); snd_soc_update_bits(codec, TAPAN_A_TX_1_2_TEST_EN + j * 10, 0x30, val_txfe); } if (flag & (0x01 << (i + 1))) { val_txfe = (txfe_bypass & (0x01 << (i + 1))) ? 0x02 : 0x00; val_txfe |= (txfe_buff & (0x01 << (i + 1))) ? 0x01 : 0x00; snd_soc_update_bits(codec, TAPAN_A_TX_1_2_TEST_EN + j * 10, 0x03, val_txfe); } /* Tapan only has TAPAN_A_TX_1_2_TEST_EN and TAPAN_A_TX_4_5_TEST_EN reg */ if (i == 0) { i = 3; continue; } else if (i == 3) { break; } } if (pdata->ocp.use_pdata) { /* not defined in CODEC specification */ if (pdata->ocp.hph_ocp_limit == 1 || pdata->ocp.hph_ocp_limit == 5) { rc = -EINVAL; goto done; } snd_soc_update_bits(codec, TAPAN_A_RX_COM_OCP_CTL, 0x0F, pdata->ocp.num_attempts); snd_soc_write(codec, TAPAN_A_RX_COM_OCP_COUNT, ((pdata->ocp.run_time << 4) | pdata->ocp.wait_time)); snd_soc_update_bits(codec, TAPAN_A_RX_HPH_OCP_CTL, 0xE0, (pdata->ocp.hph_ocp_limit << 5)); } /* Set micbias capless mode with tail current */ value = (pdata->micbias.bias1_cap_mode == MICBIAS_EXT_BYP_CAP ? 0x00 : 0x10); snd_soc_update_bits(codec, TAPAN_A_MICB_1_CTL, 0x10, value); value = (pdata->micbias.bias2_cap_mode == MICBIAS_EXT_BYP_CAP ? 0x00 : 0x10); snd_soc_update_bits(codec, TAPAN_A_MICB_2_CTL, 0x10, value); value = (pdata->micbias.bias3_cap_mode == MICBIAS_EXT_BYP_CAP ? 0x00 : 0x10); snd_soc_update_bits(codec, TAPAN_A_MICB_3_CTL, 0x10, value); /* Set the DMIC sample rate */ if (pdata->mclk_rate == TAPAN_MCLK_CLK_9P6MHZ) { switch (pdata->dmic_sample_rate) { case WCD9XXX_DMIC_SAMPLE_RATE_2P4MHZ: dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_4; dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_4; anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF; break; case WCD9XXX_DMIC_SAMPLE_RATE_4P8MHZ: dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_2; dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_2; anc_ctl_value = WCD9XXX_ANC_DMIC_X2_ON; break; case WCD9XXX_DMIC_SAMPLE_RATE_3P2MHZ: case WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED: dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_3; dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_3; anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF; break; default: dev_err(codec->dev, "%s Invalid sample rate %d for mclk %d\n", __func__, pdata->dmic_sample_rate, pdata->mclk_rate); rc = -EINVAL; goto done; } } else if (pdata->mclk_rate == TAPAN_MCLK_CLK_12P288MHZ) { switch (pdata->dmic_sample_rate) { case WCD9XXX_DMIC_SAMPLE_RATE_3P072MHZ: dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_4; dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_4; anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF; break; case WCD9XXX_DMIC_SAMPLE_RATE_6P144MHZ: dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_2; dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_2; anc_ctl_value = WCD9XXX_ANC_DMIC_X2_ON; break; case WCD9XXX_DMIC_SAMPLE_RATE_4P096MHZ: case WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED: dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_3; dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_3; anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF; break; default: dev_err(codec->dev, "%s Invalid sample rate %d for mclk %d\n", __func__, pdata->dmic_sample_rate, pdata->mclk_rate); rc = -EINVAL; goto done; } } else { dev_err(codec->dev, "%s MCLK is not set!\n", __func__); rc = -EINVAL; goto done; } snd_soc_update_bits(codec, TAPAN_A_CDC_TX1_DMIC_CTL, 0x7, dmic_sample_rate_value); snd_soc_update_bits(codec, TAPAN_A_CDC_TX2_DMIC_CTL, 0x7, dmic_sample_rate_value); snd_soc_update_bits(codec, TAPAN_A_CDC_TX3_DMIC_CTL, 0x7, dmic_sample_rate_value); snd_soc_update_bits(codec, TAPAN_A_CDC_TX4_DMIC_CTL, 0x7, dmic_sample_rate_value); snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_DMIC_B1_CTL, 0xEE, dmic_b1_ctl_value); snd_soc_update_bits(codec, TAPAN_A_CDC_ANC1_B2_CTL, 0x1, anc_ctl_value); done: return rc; } static const struct tapan_reg_mask_val tapan_reg_defaults[] = { /* enable QFUSE for wcd9306 */ TAPAN_REG_VAL(TAPAN_A_QFUSE_CTL, 0x03), /* PROGRAM_THE_0P85V_VBG_REFERENCE = V_0P858V */ TAPAN_REG_VAL(TAPAN_A_BIAS_CURR_CTL_2, 0x04), TAPAN_REG_VAL(TAPAN_A_CDC_CLK_POWER_CTL, 0x03), /* EAR PA deafults */ TAPAN_REG_VAL(TAPAN_A_RX_EAR_CMBUFF, 0x05), /* RX1 and RX2 defaults */ TAPAN_REG_VAL(TAPAN_A_CDC_RX1_B6_CTL, 0xA0), TAPAN_REG_VAL(TAPAN_A_CDC_RX2_B6_CTL, 0x80), /* Heaset set Right from RX2 */ TAPAN_REG_VAL(TAPAN_A_CDC_CONN_RX2_B2_CTL, 0x10), /* * The following only need to be written for Tapan 1.0 parts. * Tapan 2.0 will have appropriate defaults for these registers. */ /* Required defaults for class H operation */ /* borrowed from Taiko class-h */ TAPAN_REG_VAL(TAPAN_A_RX_HPH_CHOP_CTL, 0xF4), TAPAN_REG_VAL(TAPAN_A_BIAS_CURR_CTL_2, 0x08), TAPAN_REG_VAL(WCD9XXX_A_BUCK_CTRL_CCL_1, 0x5B), TAPAN_REG_VAL(WCD9XXX_A_BUCK_CTRL_CCL_3, 0x6F), /* TODO: Check below reg writes conflict with above */ /* PROGRAM_THE_0P85V_VBG_REFERENCE = V_0P858V */ TAPAN_REG_VAL(TAPAN_A_BIAS_CURR_CTL_2, 0x04), TAPAN_REG_VAL(TAPAN_A_RX_HPH_CHOP_CTL, 0x74), TAPAN_REG_VAL(TAPAN_A_RX_BUCK_BIAS1, 0x62), /* Choose max non-overlap time for NCP */ TAPAN_REG_VAL(TAPAN_A_NCP_CLK, 0xFC), /* Use 25mV/50mV for deltap/m to reduce ripple */ TAPAN_REG_VAL(WCD9XXX_A_BUCK_CTRL_VCL_1, 0x08), /* * Set DISABLE_MODE_SEL<1:0> to 0b10 (disable PWM in auto mode). * Note that the other bits of this register will be changed during * Rx PA bring up. */ TAPAN_REG_VAL(WCD9XXX_A_BUCK_MODE_3, 0xCE), /* Reduce HPH DAC bias to 70% */ TAPAN_REG_VAL(TAPAN_A_RX_HPH_BIAS_PA, 0x7A), /*Reduce EAR DAC bias to 70% */ TAPAN_REG_VAL(TAPAN_A_RX_EAR_BIAS_PA, 0x76), /* Reduce LINE DAC bias to 70% */ TAPAN_REG_VAL(TAPAN_A_RX_LINE_BIAS_PA, 0x78), /* * There is a diode to pull down the micbias while doing * insertion detection. This diode can cause leakage. * Set bit 0 to 1 to prevent leakage. * Setting this bit of micbias 2 prevents leakage for all other micbias. */ TAPAN_REG_VAL(TAPAN_A_MICB_2_MBHC, 0x41), /* * Default register settings to support dynamic change of * vdd_buck between 1.8 volts and 2.15 volts. */ TAPAN_REG_VAL(TAPAN_A_BUCK_MODE_2, 0xAA), }; static const struct tapan_reg_mask_val tapan_2_x_reg_reset_values[] = { TAPAN_REG_VAL(TAPAN_A_TX_7_MBHC_EN, 0x6C), TAPAN_REG_VAL(TAPAN_A_BUCK_CTRL_CCL_4, 0x51), TAPAN_REG_VAL(TAPAN_A_RX_HPH_CNP_WG_CTL, 0xDA), TAPAN_REG_VAL(TAPAN_A_RX_EAR_CNP, 0xC0), TAPAN_REG_VAL(TAPAN_A_RX_LINE_1_TEST, 0x02), TAPAN_REG_VAL(TAPAN_A_RX_LINE_2_TEST, 0x02), TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_OCP_CTL, 0x97), TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_CLIP_DET, 0x01), TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_IEC, 0x00), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_B1_CTL, 0xE4), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_B2_CTL, 0x00), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_B3_CTL, 0x00), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_BUCK_NCP_VARS, 0x00), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_HD_EAR, 0x00), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_HD_HPH, 0x00), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_MIN_EAR, 0x00), TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_MIN_HPH, 0x00), }; static const struct tapan_reg_mask_val tapan_1_0_reg_defaults[] = { /* Close leakage on the spkdrv */ TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_DBG_PWRSTG, 0x24), TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_DBG_DAC, 0xE5), }; static void tapan_update_reg_defaults(struct snd_soc_codec *codec) { u32 i; struct wcd9xxx *tapan_core = dev_get_drvdata(codec->dev->parent); if (!TAPAN_IS_1_0(tapan_core->version)) { for (i = 0; i < ARRAY_SIZE(tapan_2_x_reg_reset_values); i++) snd_soc_write(codec, tapan_2_x_reg_reset_values[i].reg, tapan_2_x_reg_reset_values[i].val); } for (i = 0; i < ARRAY_SIZE(tapan_reg_defaults); i++) snd_soc_write(codec, tapan_reg_defaults[i].reg, tapan_reg_defaults[i].val); if (TAPAN_IS_1_0(tapan_core->version)) { for (i = 0; i < ARRAY_SIZE(tapan_1_0_reg_defaults); i++) snd_soc_write(codec, tapan_1_0_reg_defaults[i].reg, tapan_1_0_reg_defaults[i].val); } if (!TAPAN_IS_1_0(tapan_core->version)) spkr_drv_wrnd = -1; else if (spkr_drv_wrnd == 1) snd_soc_write(codec, TAPAN_A_SPKR_DRV_EN, 0xEF); } static void tapan_update_reg_mclk_rate(struct wcd9xxx *wcd9xxx) { struct snd_soc_codec *codec; codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv); dev_dbg(codec->dev, "%s: MCLK Rate = %x\n", __func__, wcd9xxx->mclk_rate); if (wcd9xxx->mclk_rate == TAPAN_MCLK_CLK_12P288MHZ) { snd_soc_update_bits(codec, TAPAN_A_CHIP_CTL, 0x06, 0x0); snd_soc_update_bits(codec, TAPAN_A_RX_COM_TIMER_DIV, 0x01, 0x01); } else if (wcd9xxx->mclk_rate == TAPAN_MCLK_CLK_9P6MHZ) { snd_soc_update_bits(codec, TAPAN_A_CHIP_CTL, 0x06, 0x2); } } static const struct tapan_reg_mask_val tapan_codec_reg_init_val[] = { /* Initialize current threshold to 365MA * number of wait and run cycles to 4096 */ {TAPAN_A_RX_HPH_OCP_CTL, 0xE9, 0x69}, {TAPAN_A_RX_COM_OCP_COUNT, 0xFF, 0xFF}, {TAPAN_A_RX_HPH_L_TEST, 0x01, 0x01}, {TAPAN_A_RX_HPH_R_TEST, 0x01, 0x01}, /* Initialize gain registers to use register gain */ {TAPAN_A_RX_HPH_L_GAIN, 0x20, 0x20}, {TAPAN_A_RX_HPH_R_GAIN, 0x20, 0x20}, {TAPAN_A_RX_LINE_1_GAIN, 0x20, 0x20}, {TAPAN_A_RX_LINE_2_GAIN, 0x20, 0x20}, {TAPAN_A_SPKR_DRV_GAIN, 0x04, 0x04}, /* Set RDAC5 MUX to take input from DEM3_INV. * This sets LO2 DAC to get input from DEM3_INV * for LO1 and LO2 to work as differential outputs. */ {TAPAN_A_CDC_CONN_MISC, 0x04, 0x04}, /* CLASS H config */ {TAPAN_A_CDC_CONN_CLSH_CTL, 0x3C, 0x14}, /* Use 16 bit sample size for TX1 to TX5 */ {TAPAN_A_CDC_CONN_TX_SB_B1_CTL, 0x30, 0x20}, {TAPAN_A_CDC_CONN_TX_SB_B2_CTL, 0x30, 0x20}, {TAPAN_A_CDC_CONN_TX_SB_B3_CTL, 0x30, 0x20}, {TAPAN_A_CDC_CONN_TX_SB_B4_CTL, 0x30, 0x20}, {TAPAN_A_CDC_CONN_TX_SB_B5_CTL, 0x30, 0x20}, /* Disable SPK SWITCH */ {TAPAN_A_SPKR_DRV_DAC_CTL, 0x04, 0x00}, /* Use 16 bit sample size for RX */ {TAPAN_A_CDC_CONN_RX_SB_B1_CTL, 0xFF, 0xAA}, {TAPAN_A_CDC_CONN_RX_SB_B2_CTL, 0xFF, 0x2A}, /*enable HPF filter for TX paths */ {TAPAN_A_CDC_TX1_MUX_CTL, 0x8, 0x0}, {TAPAN_A_CDC_TX2_MUX_CTL, 0x8, 0x0}, {TAPAN_A_CDC_TX3_MUX_CTL, 0x8, 0x0}, {TAPAN_A_CDC_TX4_MUX_CTL, 0x8, 0x0}, /* Compander zone selection */ {TAPAN_A_CDC_COMP0_B4_CTL, 0x3F, 0x37}, {TAPAN_A_CDC_COMP1_B4_CTL, 0x3F, 0x37}, {TAPAN_A_CDC_COMP2_B4_CTL, 0x3F, 0x37}, {TAPAN_A_CDC_COMP0_B5_CTL, 0x7F, 0x7F}, {TAPAN_A_CDC_COMP1_B5_CTL, 0x7F, 0x7F}, {TAPAN_A_CDC_COMP2_B5_CTL, 0x7F, 0x7F}, /* * Setup wavegen timer to 20msec and disable chopper * as default. This corresponds to Compander OFF */ {TAPAN_A_RX_HPH_CNP_WG_CTL, 0xFF, 0xDB}, {TAPAN_A_RX_HPH_CNP_WG_TIME, 0xFF, 0x58}, {TAPAN_A_RX_HPH_BIAS_WG_OCP, 0xFF, 0x1A}, {TAPAN_A_RX_HPH_CHOP_CTL, 0xFF, 0x24}, }; void *tapan_get_afe_config(struct snd_soc_codec *codec, enum afe_config_type config_type) { struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec); switch (config_type) { case AFE_SLIMBUS_SLAVE_CONFIG: return &priv->slimbus_slave_cfg; case AFE_CDC_REGISTERS_CONFIG: return &tapan_audio_reg_cfg; case AFE_AANC_VERSION: return &tapan_cdc_aanc_version; default: pr_err("%s: Unknown config_type 0x%x\n", __func__, config_type); return NULL; } } static void tapan_init_slim_slave_cfg(struct snd_soc_codec *codec) { struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec); struct afe_param_cdc_slimbus_slave_cfg *cfg; struct wcd9xxx *wcd9xxx = codec->control_data; uint64_t eaddr = 0; pr_debug("%s\n", __func__); cfg = &priv->slimbus_slave_cfg; cfg->minor_version = 1; cfg->tx_slave_port_offset = 0; cfg->rx_slave_port_offset = 16; memcpy(&eaddr, &wcd9xxx->slim->e_addr, sizeof(wcd9xxx->slim->e_addr)); /* e-addr is 6-byte elemental address of the device */ WARN_ON(sizeof(wcd9xxx->slim->e_addr) != 6); cfg->device_enum_addr_lsw = eaddr & 0xFFFFFFFF; cfg->device_enum_addr_msw = eaddr >> 32; pr_debug("%s: slimbus logical address 0x%llx\n", __func__, eaddr); } static void tapan_codec_init_reg(struct snd_soc_codec *codec) { u32 i; for (i = 0; i < ARRAY_SIZE(tapan_codec_reg_init_val); i++) snd_soc_update_bits(codec, tapan_codec_reg_init_val[i].reg, tapan_codec_reg_init_val[i].mask, tapan_codec_reg_init_val[i].val); } static void tapan_slim_interface_init_reg(struct snd_soc_codec *codec) { int i; for (i = 0; i < WCD9XXX_SLIM_NUM_PORT_REG; i++) wcd9xxx_interface_reg_write(codec->control_data, TAPAN_SLIM_PGD_PORT_INT_EN0 + i, 0xFF); } static int tapan_setup_irqs(struct tapan_priv *tapan) { int ret = 0; struct snd_soc_codec *codec = tapan->codec; struct wcd9xxx *wcd9xxx = codec->control_data; struct wcd9xxx_core_resource *core_res = &wcd9xxx->core_res; ret = wcd9xxx_request_irq(core_res, WCD9XXX_IRQ_SLIMBUS, tapan_slimbus_irq, "SLIMBUS Slave", tapan); if (ret) pr_err("%s: Failed to request irq %d\n", __func__, WCD9XXX_IRQ_SLIMBUS); else tapan_slim_interface_init_reg(codec); return ret; } static void tapan_cleanup_irqs(struct tapan_priv *tapan) { struct snd_soc_codec *codec = tapan->codec; struct wcd9xxx *wcd9xxx = codec->control_data; struct wcd9xxx_core_resource *core_res = &wcd9xxx->core_res; wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_SLIMBUS, tapan); } static void tapan_enable_mux_bias_block(struct snd_soc_codec *codec) { snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x80, 0x00); } static void tapan_put_cfilt_fast_mode(struct snd_soc_codec *codec, struct wcd9xxx_mbhc *mbhc) { snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl, 0x30, 0x30); } static void tapan_codec_specific_cal_setup(struct snd_soc_codec *codec, struct wcd9xxx_mbhc *mbhc) { snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x04, 0x04); snd_soc_update_bits(codec, WCD9XXX_A_TX_7_MBHC_EN, 0xE0, 0xE0); } static struct wcd9xxx_cfilt_mode tapan_codec_switch_cfilt_mode( struct wcd9xxx_mbhc *mbhc, bool fast) { struct snd_soc_codec *codec = mbhc->codec; struct wcd9xxx_cfilt_mode cfilt_mode; if (fast) cfilt_mode.reg_mode_val = WCD9XXX_CFILT_EXT_PRCHG_EN; else cfilt_mode.reg_mode_val = WCD9XXX_CFILT_EXT_PRCHG_DSBL; cfilt_mode.cur_mode_val = snd_soc_read(codec, mbhc->mbhc_bias_regs.cfilt_ctl) & 0x30; cfilt_mode.reg_mask = 0x30; return cfilt_mode; } static void tapan_select_cfilt(struct snd_soc_codec *codec, struct wcd9xxx_mbhc *mbhc) { snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x60, 0x00); } enum wcd9xxx_cdc_type tapan_get_cdc_type(void) { return WCD9XXX_CDC_TYPE_TAPAN; } static void wcd9xxx_prepare_hph_pa(struct wcd9xxx_mbhc *mbhc, struct list_head *lh) { int i; struct snd_soc_codec *codec = mbhc->codec; u32 delay; const struct wcd9xxx_reg_mask_val reg_set_paon[] = { {WCD9XXX_A_CDC_CLSH_B1_CTL, 0x0F, 0x00}, {WCD9XXX_A_RX_HPH_CHOP_CTL, 0xFF, 0xA4}, {WCD9XXX_A_RX_HPH_OCP_CTL, 0xFF, 0x67}, {WCD9XXX_A_RX_HPH_L_TEST, 0x1, 0x0}, {WCD9XXX_A_RX_HPH_R_TEST, 0x1, 0x0}, {WCD9XXX_A_RX_HPH_BIAS_WG_OCP, 0xFF, 0x1A}, {WCD9XXX_A_RX_HPH_CNP_WG_CTL, 0xFF, 0xDB}, {WCD9XXX_A_RX_HPH_CNP_WG_TIME, 0xFF, 0x2A}, {TAPAN_A_CDC_CONN_RX2_B2_CTL, 0xFF, 0x10}, {WCD9XXX_A_CDC_CLK_OTHR_CTL, 0xFF, 0x05}, {WCD9XXX_A_CDC_RX1_B6_CTL, 0xFF, 0x81}, {WCD9XXX_A_CDC_CLK_RX_B1_CTL, 0x03, 0x03}, {WCD9XXX_A_RX_HPH_L_GAIN, 0xFF, 0x2C}, {WCD9XXX_A_CDC_RX2_B6_CTL, 0xFF, 0x81}, {WCD9XXX_A_RX_HPH_R_GAIN, 0xFF, 0x2C}, {WCD9XXX_A_BUCK_CTRL_CCL_4, 0xFF, 0x50}, {WCD9XXX_A_BUCK_CTRL_VCL_1, 0xFF, 0x08}, {WCD9XXX_A_BUCK_CTRL_CCL_1, 0xFF, 0x5B}, {WCD9XXX_A_NCP_CLK, 0xFF, 0x9C}, {WCD9XXX_A_NCP_CLK, 0xFF, 0xFC}, {WCD9XXX_A_BUCK_MODE_3, 0xFF, 0xCE}, {WCD9XXX_A_BUCK_CTRL_CCL_3, 0xFF, 0x6B}, {WCD9XXX_A_BUCK_CTRL_CCL_3, 0xFF, 0x6F}, {TAPAN_A_RX_BUCK_BIAS1, 0xFF, 0x62}, {TAPAN_A_RX_HPH_BIAS_PA, 0xFF, 0x7A}, {TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0xFF, 0x02}, {TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0xFF, 0x06}, {WCD9XXX_A_RX_COM_BIAS, 0xFF, 0x80}, {WCD9XXX_A_BUCK_MODE_3, 0xFF, 0xC6}, {WCD9XXX_A_BUCK_MODE_4, 0xFF, 0xE6}, {WCD9XXX_A_BUCK_MODE_5, 0xFF, 0x02}, {WCD9XXX_A_BUCK_MODE_1, 0xFF, 0xA1}, /* Delay 1ms */ {WCD9XXX_A_NCP_EN, 0xFF, 0xFF}, /* Delay 1ms */ {WCD9XXX_A_BUCK_MODE_5, 0xFF, 0x03}, {WCD9XXX_A_BUCK_MODE_5, 0xFF, 0x7B}, {WCD9XXX_A_CDC_CLSH_B1_CTL, 0xFF, 0xE6}, {WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xFF, 0x40}, {WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xFF, 0xC0}, {WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xFF, 0x40}, {WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xFF, 0xC0}, {WCD9XXX_A_NCP_STATIC, 0xFF, 0x08}, {WCD9XXX_A_RX_HPH_L_DAC_CTL, 0x03, 0x01}, {WCD9XXX_A_RX_HPH_R_DAC_CTL, 0x03, 0x01}, }; /* * Configure PA in class-AB, -18dB gain, * companding off, OCP off, Chopping ON */ for (i = 0; i < ARRAY_SIZE(reg_set_paon); i++) { /* * Some of the codec registers like BUCK_MODE_1 * and NCP_EN requires 1ms wait time for them * to take effect. Other register writes for * PA configuration do not require any wait time. */ if (reg_set_paon[i].reg == WCD9XXX_A_BUCK_MODE_1 || reg_set_paon[i].reg == WCD9XXX_A_NCP_EN) delay = 1000; else delay = 0; wcd9xxx_soc_update_bits_push(codec, lh, reg_set_paon[i].reg, reg_set_paon[i].mask, reg_set_paon[i].val, delay); } pr_debug("%s: PAs are prepared\n", __func__); return; } static int wcd9xxx_enable_static_pa(struct wcd9xxx_mbhc *mbhc, bool enable) { struct snd_soc_codec *codec = mbhc->codec; int wg_time = snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME) * TAPAN_WG_TIME_FACTOR_US; /* * Tapan requires additional time to enable PA. * It is observed during experiments that we need * an additional wait time about 0.35 times of * the WG_TIME */ wg_time += (int) (wg_time * 35) / 100; snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_CNP_EN, 0x30, enable ? 0x30 : 0x0); /* Wait for wave gen time to avoid pop noise */ usleep_range(wg_time, wg_time + WCD9XXX_USLEEP_RANGE_MARGIN_US); pr_debug("%s: PAs are %s as static mode (wg_time %d)\n", __func__, enable ? "enabled" : "disabled", wg_time); return 0; } static int tapan_setup_zdet(struct wcd9xxx_mbhc *mbhc, enum mbhc_impedance_detect_stages stage) { int ret = 0; struct snd_soc_codec *codec = mbhc->codec; struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); const int mux_wait_us = 25; switch (stage) { case MBHC_ZDET_PRE_MEASURE: INIT_LIST_HEAD(&tapan->reg_save_restore); /* Configure PA */ wcd9xxx_prepare_hph_pa(mbhc, &tapan->reg_save_restore); #define __wr(reg, mask, value) \ do { \ ret = wcd9xxx_soc_update_bits_push(codec, \ &tapan->reg_save_restore, \ reg, mask, value, 0); \ if (ret < 0) \ return ret; \ } while (0) /* Setup MBHC */ __wr(WCD9XXX_A_MBHC_SCALING_MUX_1, 0x7F, 0x40); __wr(WCD9XXX_A_MBHC_SCALING_MUX_2, 0xFF, 0xF0); __wr(WCD9XXX_A_TX_7_MBHC_TEST_CTL, 0xFF, 0x78); __wr(WCD9XXX_A_TX_7_MBHC_EN, 0xFF, 0xEC); __wr(WCD9XXX_A_CDC_MBHC_TIMER_B4_CTL, 0xFF, 0x45); __wr(WCD9XXX_A_CDC_MBHC_TIMER_B5_CTL, 0xFF, 0x80); __wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xFF, 0x0A); snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x2); __wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xFF, 0x02); /* Enable Impedance Detection */ __wr(WCD9XXX_A_MBHC_HPH, 0xFF, 0xC8); /* * CnP setup for 0mV * Route static data as input to noise shaper */ __wr(TAPAN_A_CDC_RX1_B3_CTL, 0xFF, 0x02); __wr(TAPAN_A_CDC_RX2_B3_CTL, 0xFF, 0x02); snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_L_TEST, 0x02, 0x00); snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_R_TEST, 0x02, 0x00); /* Reset the HPHL static data pointer */ __wr(TAPAN_A_CDC_RX1_B2_CTL, 0xFF, 0x00); /* Four consecutive writes to set 0V as static data input */ snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00); /* Reset the HPHR static data pointer */ __wr(TAPAN_A_CDC_RX2_B2_CTL, 0xFF, 0x00); /* Four consecutive writes to set 0V as static data input */ snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00); /* Enable the HPHL and HPHR PA */ wcd9xxx_enable_static_pa(mbhc, true); break; case MBHC_ZDET_POST_MEASURE: /* Turn off ICAL */ snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_2, 0xF0); wcd9xxx_enable_static_pa(mbhc, false); /* * Setup CnP wavegen to ramp to the desired * output using a 40ms ramp */ /* CnP wavegen current to 0.5uA */ snd_soc_write(codec, WCD9XXX_A_RX_HPH_BIAS_WG_OCP, 0x1A); /* Set the current division ratio to 2000 */ snd_soc_write(codec, WCD9XXX_A_RX_HPH_CNP_WG_CTL, 0xDF); /* Set the wavegen timer to max (60msec) */ snd_soc_write(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME, 0xA0); /* Set the CnP reference current to sc_bias */ snd_soc_write(codec, WCD9XXX_A_RX_HPH_OCP_CTL, 0x6D); snd_soc_write(codec, TAPAN_A_CDC_RX1_B2_CTL, 0x00); /* Four consecutive writes to set -10mV as static data input */ snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x1F); snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x19); snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0xAA); snd_soc_write(codec, TAPAN_A_CDC_RX2_B2_CTL, 0x00); /* Four consecutive writes to set -10mV as static data input */ snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00); snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x1F); snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x19); snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0xAA); snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_L_TEST, 0x02, 0x02); snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_R_TEST, 0x02, 0x02); /* Enable the HPHL and HPHR PA and wait for 60mS */ wcd9xxx_enable_static_pa(mbhc, true); snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x7F, 0x40); usleep_range(mux_wait_us, mux_wait_us + WCD9XXX_USLEEP_RANGE_MARGIN_US); break; case MBHC_ZDET_PA_DISABLE: if (!mbhc->hph_pa_dac_state) wcd9xxx_enable_static_pa(mbhc, false); wcd9xxx_restore_registers(codec, &tapan->reg_save_restore); break; default: dev_dbg(codec->dev, "%s: Case %d not supported\n", __func__, stage); break; } #undef __wr return ret; } static void tapan_compute_impedance(struct wcd9xxx_mbhc *mbhc, s16 *l, s16 *r, uint32_t *zl, uint32_t *zr) { int zln, zld; int zrn, zrd; int rl = 0, rr = 0; if (!mbhc) { pr_err("%s: NULL pointer for MBHC", __func__); return; } zln = (l[1] - l[0]) * TAPAN_ZDET_MUL_FACTOR; zld = (l[2] - l[0]); if (zld) rl = zln / zld; zrn = (r[1] - r[0]) * TAPAN_ZDET_MUL_FACTOR; zrd = (r[2] - r[0]); if (zrd) rr = zrn / zrd; *zl = rl; *zr = rr; } static const struct wcd9xxx_mbhc_cb mbhc_cb = { .enable_mux_bias_block = tapan_enable_mux_bias_block, .cfilt_fast_mode = tapan_put_cfilt_fast_mode, .codec_specific_cal = tapan_codec_specific_cal_setup, .switch_cfilt_mode = tapan_codec_switch_cfilt_mode, .select_cfilt = tapan_select_cfilt, .get_cdc_type = tapan_get_cdc_type, .setup_zdet = tapan_setup_zdet, .compute_impedance = tapan_compute_impedance, }; int tapan_hs_detect(struct snd_soc_codec *codec, struct wcd9xxx_mbhc_config *mbhc_cfg) { struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); return wcd9xxx_mbhc_start(&tapan->mbhc, mbhc_cfg); } EXPORT_SYMBOL(tapan_hs_detect); void tapan_hs_detect_exit(struct snd_soc_codec *codec) { struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); wcd9xxx_mbhc_stop(&tapan->mbhc); } EXPORT_SYMBOL(tapan_hs_detect_exit); void tapan_event_register( int (*machine_event_cb)(struct snd_soc_codec *codec, enum wcd9xxx_codec_event), struct snd_soc_codec *codec) { struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); tapan->machine_codec_event_cb = machine_event_cb; } EXPORT_SYMBOL(tapan_event_register); static int tapan_device_down(struct wcd9xxx *wcd9xxx) { struct snd_soc_codec *codec; codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv); snd_soc_card_change_online_state(codec->card, 0); return 0; } static const struct wcd9xxx_mbhc_intr cdc_intr_ids = { .poll_plug_rem = WCD9XXX_IRQ_MBHC_REMOVAL, .shortavg_complete = WCD9XXX_IRQ_MBHC_SHORT_TERM, .potential_button_press = WCD9XXX_IRQ_MBHC_PRESS, .button_release = WCD9XXX_IRQ_MBHC_RELEASE, .dce_est_complete = WCD9XXX_IRQ_MBHC_POTENTIAL, .insertion = WCD9XXX_IRQ_MBHC_INSERTION, .hph_left_ocp = WCD9306_IRQ_HPH_PA_OCPL_FAULT, .hph_right_ocp = WCD9306_IRQ_HPH_PA_OCPR_FAULT, .hs_jack_switch = WCD9306_IRQ_MBHC_JACK_SWITCH, }; static int tapan_post_reset_cb(struct wcd9xxx *wcd9xxx) { int ret = 0; int rco_clk_rate; struct snd_soc_codec *codec; struct tapan_priv *tapan; int count; codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv); tapan = snd_soc_codec_get_drvdata(codec); snd_soc_card_change_online_state(codec->card, 1); mutex_lock(&codec->mutex); if (codec->reg_def_copy) { pr_debug("%s: Update ASOC cache", __func__); kfree(codec->reg_cache); codec->reg_cache = kmemdup(codec->reg_def_copy, codec->reg_size, GFP_KERNEL); if (!codec->reg_cache) { pr_err("%s: Cache update failed!\n", __func__); mutex_unlock(&codec->mutex); return -ENOMEM; } } if (spkr_drv_wrnd == 1) snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x80); tapan_update_reg_defaults(codec); tapan_update_reg_mclk_rate(wcd9xxx); tapan_codec_init_reg(codec); ret = tapan_handle_pdata(tapan); if (IS_ERR_VALUE(ret)) pr_err("%s: bad pdata\n", __func__); tapan_slim_interface_init_reg(codec); wcd9xxx_resmgr_post_ssr(&tapan->resmgr); wcd9xxx_mbhc_deinit(&tapan->mbhc); if (TAPAN_IS_1_0(wcd9xxx->version)) rco_clk_rate = TAPAN_MCLK_CLK_12P288MHZ; else rco_clk_rate = TAPAN_MCLK_CLK_9P6MHZ; ret = wcd9xxx_mbhc_init(&tapan->mbhc, &tapan->resmgr, codec, tapan_enable_mbhc_micbias, &mbhc_cb, &cdc_intr_ids, rco_clk_rate, TAPAN_CDC_ZDET_SUPPORTED); if (ret) pr_err("%s: mbhc init failed %d\n", __func__, ret); else wcd9xxx_mbhc_start(&tapan->mbhc, tapan->mbhc.mbhc_cfg); tapan_cleanup_irqs(tapan); ret = tapan_setup_irqs(tapan); if (ret) pr_err("%s: Failed to setup irq: %d\n", __func__, ret); tapan->machine_codec_event_cb(codec, WCD9XXX_CODEC_EVENT_CODEC_UP); for (count = 0; count < NUM_CODEC_DAIS; count++) tapan->dai[count].bus_down_in_recovery = true; mutex_unlock(&codec->mutex); return ret; } static struct wcd9xxx_reg_address tapan_reg_address = { }; static int wcd9xxx_ssr_register(struct wcd9xxx *control, int (*device_down_cb)(struct wcd9xxx *wcd9xxx), int (*device_up_cb)(struct wcd9xxx *wcd9xxx), void *priv) { control->dev_down = device_down_cb; control->post_reset = device_up_cb; control->ssr_priv = priv; return 0; } static struct regulator *tapan_codec_find_regulator( struct snd_soc_codec *codec, const char *name) { int i; struct wcd9xxx *core = NULL; if (codec == NULL) { dev_err(codec->dev, "%s: codec not initialized\n", __func__); return NULL; } core = dev_get_drvdata(codec->dev->parent); if (core == NULL) { dev_err(codec->dev, "%s: core not initialized\n", __func__); return NULL; } for (i = 0; i < core->num_of_supplies; i++) { if (core->supplies[i].supply && !strcmp(core->supplies[i].supply, name)) return core->supplies[i].consumer; } return NULL; } static void tapan_enable_config_rco(struct wcd9xxx *core, bool enable) { struct wcd9xxx_core_resource *core_res = &core->core_res; if (enable) { wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL, 0x80, 0x80); wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL, 0x04, 0x04); wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL, 0x01, 0x01); usleep_range(1000, 1000); wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL, 0x80, 0x00); /* Enable RC Oscillator */ wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_FREQ, 0x10, 0x00); wcd9xxx_reg_write(core_res, WCD9XXX_A_BIAS_OSC_BG_CTL, 0x17); usleep_range(5, 5); wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_FREQ, 0x80, 0x80); wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_TEST, 0x80, 0x80); usleep_range(10, 10); wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_TEST, 0x80, 0x00); usleep_range(20, 20); wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN1, 0x08, 0x08); /* Enable MCLK and wait 1ms till it gets enabled */ wcd9xxx_reg_write(core_res, WCD9XXX_A_CLK_BUFF_EN2, 0x02); usleep_range(1000, 1000); /* Enable CLK BUFF and wait for 1.2ms */ wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN1, 0x01, 0x01); usleep_range(1000, 1200); wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x02, 0x00); wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x04, 0x04); wcd9xxx_reg_update(core, WCD9XXX_A_CDC_CLK_MCLK_CTL, 0x01, 0x01); usleep_range(50, 50); } else { wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x04, 0x00); usleep_range(50, 50); wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x02, 0x02); wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN1, 0x05, 0x00); usleep_range(50, 50); wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_FREQ, 0x80, 0x00); usleep_range(10, 10); wcd9xxx_reg_write(core_res, WCD9XXX_A_BIAS_OSC_BG_CTL, 0x16); wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL, 0x03, 0x00); usleep_range(100, 100); } } static bool tapan_check_wcd9306(struct device *cdc_dev, bool sensed) { struct wcd9xxx *core = dev_get_drvdata(cdc_dev->parent); u8 reg_val; bool ret = true; unsigned long timeout; bool timedout; struct wcd9xxx_core_resource *core_res = &core->core_res; if (!core) { dev_err(cdc_dev, "%s: core not initialized\n", __func__); return -EINVAL; } tapan_enable_config_rco(core, 1); if (sensed == false) { reg_val = wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_CTL); wcd9xxx_reg_write(core_res, TAPAN_A_QFUSE_CTL, (reg_val | 0x03)); } timeout = jiffies + HZ; do { if ((wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_STATUS))) break; } while (!(timedout = time_after(jiffies, timeout))); if (wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_DATA_OUT1) || wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_DATA_OUT2)) { dev_info(cdc_dev, "%s: wcd9302 detected\n", __func__); ret = false; } else dev_info(cdc_dev, "%s: wcd9306 detected\n", __func__); tapan_enable_config_rco(core, 0); return ret; }; static int tapan_codec_probe(struct snd_soc_codec *codec) { struct wcd9xxx *control; struct tapan_priv *tapan; struct wcd9xxx_pdata *pdata; struct wcd9xxx *wcd9xxx; struct snd_soc_dapm_context *dapm = &codec->dapm; int ret = 0; int i, rco_clk_rate; void *ptr = NULL; struct wcd9xxx_core_resource *core_res; codec->control_data = dev_get_drvdata(codec->dev->parent); control = codec->control_data; wcd9xxx_ssr_register(control, tapan_device_down, tapan_post_reset_cb, (void *)codec); dev_info(codec->dev, "%s()\n", __func__); tapan = kzalloc(sizeof(struct tapan_priv), GFP_KERNEL); if (!tapan) { dev_err(codec->dev, "Failed to allocate private data\n"); return -ENOMEM; } for (i = 0 ; i < NUM_DECIMATORS; i++) { tx_hpf_work[i].tapan = tapan; tx_hpf_work[i].decimator = i + 1; INIT_DELAYED_WORK(&tx_hpf_work[i].dwork, tx_hpf_corner_freq_callback); } snd_soc_codec_set_drvdata(codec, tapan); /* codec resmgr module init */ wcd9xxx = codec->control_data; core_res = &wcd9xxx->core_res; pdata = dev_get_platdata(codec->dev->parent); ret = wcd9xxx_resmgr_init(&tapan->resmgr, codec, core_res, pdata, &pdata->micbias, &tapan_reg_address, WCD9XXX_CDC_TYPE_TAPAN); if (ret) { pr_err("%s: wcd9xxx init failed %d\n", __func__, ret); return ret; } tapan->cp_regulators[CP_REG_BUCK] = tapan_codec_find_regulator(codec, WCD9XXX_SUPPLY_BUCK_NAME); tapan->cp_regulators[CP_REG_BHELPER] = tapan_codec_find_regulator(codec, "cdc-vdd-buckhelper"); tapan->clsh_d.buck_mv = tapan_codec_get_buck_mv(codec); /* * If 1.8 volts is requested on the vdd_cp line, then * assume that S4 is in a dynamically switchable state * and can switch between 1.8 volts and 2.15 volts */ if (tapan->clsh_d.buck_mv == WCD9XXX_CDC_BUCK_MV_1P8) tapan->clsh_d.is_dynamic_vdd_cp = true; wcd9xxx_clsh_init(&tapan->clsh_d, &tapan->resmgr); if (TAPAN_IS_1_0(control->version)) rco_clk_rate = TAPAN_MCLK_CLK_12P288MHZ; else rco_clk_rate = TAPAN_MCLK_CLK_9P6MHZ; ret = wcd9xxx_mbhc_init(&tapan->mbhc, &tapan->resmgr, codec, tapan_enable_mbhc_micbias, &mbhc_cb, &cdc_intr_ids, rco_clk_rate, TAPAN_CDC_ZDET_SUPPORTED); if (ret) { pr_err("%s: mbhc init failed %d\n", __func__, ret); return ret; } tapan->codec = codec; for (i = 0; i < COMPANDER_MAX; i++) { tapan->comp_enabled[i] = 0; tapan->comp_fs[i] = COMPANDER_FS_48KHZ; } tapan->intf_type = wcd9xxx_get_intf_type(); tapan->aux_pga_cnt = 0; tapan->aux_l_gain = 0x1F; tapan->aux_r_gain = 0x1F; tapan->ldo_h_users = 0; tapan->micb_2_users = 0; tapan->lb_mode = false; tapan_update_reg_defaults(codec); tapan_update_reg_mclk_rate(wcd9xxx); tapan_codec_init_reg(codec); ret = tapan_handle_pdata(tapan); if (IS_ERR_VALUE(ret)) { dev_err(codec->dev, "%s: bad pdata\n", __func__); goto err_pdata; } if (spkr_drv_wrnd > 0) { WCD9XXX_BG_CLK_LOCK(&tapan->resmgr); wcd9xxx_resmgr_get_bandgap(&tapan->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr); } ptr = kmalloc((sizeof(tapan_rx_chs) + sizeof(tapan_tx_chs)), GFP_KERNEL); if (!ptr) { pr_err("%s: no mem for slim chan ctl data\n", __func__); ret = -ENOMEM; goto err_nomem_slimch; } if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) { snd_soc_dapm_new_controls(dapm, tapan_dapm_i2s_widgets, ARRAY_SIZE(tapan_dapm_i2s_widgets)); snd_soc_dapm_add_routes(dapm, audio_i2s_map, ARRAY_SIZE(audio_i2s_map)); for (i = 0; i < ARRAY_SIZE(tapan_i2s_dai); i++) INIT_LIST_HEAD(&tapan->dai[i].wcd9xxx_ch_list); } else if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) { for (i = 0; i < NUM_CODEC_DAIS; i++) { INIT_LIST_HEAD(&tapan->dai[i].wcd9xxx_ch_list); init_waitqueue_head(&tapan->dai[i].dai_wait); } tapan_init_slim_slave_cfg(codec); } if (codec_ver == WCD9306) { snd_soc_add_codec_controls(codec, tapan_9306_snd_controls, ARRAY_SIZE(tapan_9306_snd_controls)); snd_soc_dapm_new_controls(dapm, tapan_9306_dapm_widgets, ARRAY_SIZE(tapan_9306_dapm_widgets)); snd_soc_dapm_add_routes(dapm, wcd9306_map, ARRAY_SIZE(wcd9306_map)); } else { snd_soc_dapm_add_routes(dapm, wcd9302_map, ARRAY_SIZE(wcd9302_map)); } control->num_rx_port = TAPAN_RX_MAX; control->rx_chs = ptr; memcpy(control->rx_chs, tapan_rx_chs, sizeof(tapan_rx_chs)); control->num_tx_port = TAPAN_TX_MAX; control->tx_chs = ptr + sizeof(tapan_rx_chs); memcpy(control->tx_chs, tapan_tx_chs, sizeof(tapan_tx_chs)); snd_soc_dapm_sync(dapm); (void) tapan_setup_irqs(tapan); atomic_set(&kp_tapan_priv, (unsigned long)tapan); mutex_lock(&dapm->codec->mutex); if (codec_ver == WCD9306) { snd_soc_dapm_disable_pin(dapm, "ANC HPHL"); snd_soc_dapm_disable_pin(dapm, "ANC HPHR"); snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE"); snd_soc_dapm_disable_pin(dapm, "ANC EAR PA"); snd_soc_dapm_disable_pin(dapm, "ANC EAR"); } snd_soc_dapm_sync(dapm); mutex_unlock(&dapm->codec->mutex); codec->ignore_pmdown_time = 1; if (ret) tapan_cleanup_irqs(tapan); return ret; err_pdata: kfree(ptr); err_nomem_slimch: kfree(tapan); return ret; } static int tapan_codec_remove(struct snd_soc_codec *codec) { struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec); int index = 0; WCD9XXX_BG_CLK_LOCK(&tapan->resmgr); atomic_set(&kp_tapan_priv, 0); if (spkr_drv_wrnd > 0) wcd9xxx_resmgr_put_bandgap(&tapan->resmgr, WCD9XXX_BANDGAP_AUDIO_MODE); WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr); tapan_cleanup_irqs(tapan); /* cleanup MBHC */ wcd9xxx_mbhc_deinit(&tapan->mbhc); /* cleanup resmgr */ wcd9xxx_resmgr_deinit(&tapan->resmgr); for (index = 0; index < CP_REG_MAX; index++) tapan->cp_regulators[index] = NULL; kfree(tapan); return 0; } static struct snd_soc_codec_driver soc_codec_dev_tapan = { .probe = tapan_codec_probe, .remove = tapan_codec_remove, .read = tapan_read, .write = tapan_write, .readable_register = tapan_readable, .volatile_register = tapan_volatile, .reg_cache_size = TAPAN_CACHE_SIZE, .reg_cache_default = tapan_reset_reg_defaults, .reg_word_size = 1, .controls = tapan_common_snd_controls, .num_controls = ARRAY_SIZE(tapan_common_snd_controls), .dapm_widgets = tapan_common_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(tapan_common_dapm_widgets), .dapm_routes = audio_map, .num_dapm_routes = ARRAY_SIZE(audio_map), }; #ifdef CONFIG_PM static int tapan_suspend(struct device *dev) { dev_dbg(dev, "%s: system suspend\n", __func__); return 0; } static int tapan_resume(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct tapan_priv *tapan = platform_get_drvdata(pdev); dev_dbg(dev, "%s: system resume\n", __func__); /* Notify */ wcd9xxx_resmgr_notifier_call(&tapan->resmgr, WCD9XXX_EVENT_POST_RESUME); return 0; } static const struct dev_pm_ops tapan_pm_ops = { .suspend = tapan_suspend, .resume = tapan_resume, }; #endif static int __devinit tapan_probe(struct platform_device *pdev) { int ret = 0; bool is_wcd9306; is_wcd9306 = tapan_check_wcd9306(&pdev->dev, false); if (is_wcd9306 < 0) { dev_info(&pdev->dev, "%s: cannot find codec type, default to 9306\n", __func__); is_wcd9306 = true; } codec_ver = is_wcd9306 ? WCD9306 : WCD9302; if (!is_wcd9306) { if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS) ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tapan, tapan9302_dai, ARRAY_SIZE(tapan9302_dai)); else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C) ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tapan, tapan_i2s_dai, ARRAY_SIZE(tapan_i2s_dai)); } else { if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS) ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tapan, tapan_dai, ARRAY_SIZE(tapan_dai)); else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C) ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tapan, tapan_i2s_dai, ARRAY_SIZE(tapan_i2s_dai)); } return ret; } static int __devexit tapan_remove(struct platform_device *pdev) { snd_soc_unregister_codec(&pdev->dev); return 0; } static struct platform_driver tapan_codec_driver = { .probe = tapan_probe, .remove = tapan_remove, .driver = { .name = "tapan_codec", .owner = THIS_MODULE, #ifdef CONFIG_PM .pm = &tapan_pm_ops, #endif }, }; static int __init tapan_codec_init(void) { return platform_driver_register(&tapan_codec_driver); } static void __exit tapan_codec_exit(void) { platform_driver_unregister(&tapan_codec_driver); } module_init(tapan_codec_init); module_exit(tapan_codec_exit); MODULE_DESCRIPTION("Tapan codec driver"); MODULE_LICENSE("GPL v2");
smac0628/caf-LA.BF.1.1.2.1
sound/soc/codecs/wcd9306.c
C
gpl-2.0
197,279
/* linux/drivers/media/video/samsung/tv20/s5pv210/hdcp_s5pv210.c * * hdcp raw ftn file for Samsung TVOut driver * * Copyright (c) 2010 Samsung Electronics * http://www.samsungsemi.com/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/wait.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/irq.h> #include <linux/io.h> #include <plat/gpio-cfg.h> #include <mach/regs-gpio.h> #include <mach/gpio.h> #include <plat/regs-hdmi.h> #include "../ddc.h" #include "tv_out_s5pv210.h" /* for Operation check */ #ifdef CONFIG_TVOUT_RAW_DBG #define S5P_HDCP_DEBUG 1 #define S5P_HDCP_AUTH_DEBUG 1 #endif #ifdef S5P_HDCP_DEBUG #define HDCPPRINTK(fmt, args...) \ printk(KERN_INFO "\t\t[HDCP] %s: " fmt, __func__ , ## args) #else #define HDCPPRINTK(fmt, args...) #endif /* for authentication key check */ #ifdef S5P_HDCP_AUTH_DEBUG #define AUTHPRINTK(fmt, args...) \ printk("\t\t\t[AUTHKEY] %s: " fmt, __func__ , ## args) #else #define AUTHPRINTK(fmt, args...) #endif enum hdmi_run_mode { DVI_MODE = 0, HDMI_MODE }; enum hdmi_resolution { SD480P = 0, SD480I, WWSD480P, HD720P, SD576P, WWSD576P, HD1080I }; enum hdmi_color_bar_type { HORIZONTAL = 0, VERTICAL }; enum hdcp_event { /* Stop HDCP */ HDCP_EVENT_STOP = 0, /* Start HDCP*/ HDCP_EVENT_START, /* Start to read Bksv, Bcaps */ HDCP_EVENT_READ_BKSV_START, /* Start to write Aksv, An */ HDCP_EVENT_WRITE_AKSV_START, /* Start to check if Ri is equal to Rj */ HDCP_EVENT_CHECK_RI_START, /* Start 2nd authentication process */ HDCP_EVENT_SECOND_AUTH_START }; enum hdcp_state { NOT_AUTHENTICATED = 0, RECEIVER_READ_READY, BCAPS_READ_DONE, BKSV_READ_DONE, AN_WRITE_DONE, AKSV_WRITE_DONE, FIRST_AUTHENTICATION_DONE, SECOND_AUTHENTICATION_RDY, RECEIVER_FIFOLSIT_READY, SECOND_AUTHENTICATION_DONE, }; /* * Below CSC_TYPE is temporary. CSC_TYPE enum. * may be included in SetSD480pVars_60Hz etc. * * LR : Limited Range (16~235) * FR : Full Range (0~255) */ enum hdmi_intr_src { WAIT_FOR_ACTIVE_RX = 0, WDT_FOR_REPEATER, EXCHANGE_KSV, UPDATE_P_VAL, UPDATE_R_VAL, AUDIO_OVERFLOW, AUTHEN_ACK, UNKNOWN_INT }; struct s5p_hdcp_info { bool is_repeater; bool hpd_status; u32 time_out; u32 hdcp_enable; spinlock_t lock; spinlock_t reset_lock; struct i2c_client *client; wait_queue_head_t waitq; enum hdcp_event event; enum hdcp_state auth_status; struct work_struct work; }; static struct s5p_hdcp_info hdcp_info = { .is_repeater = false, .time_out = 0, .hdcp_enable = false, .client = NULL, .event = HDCP_EVENT_STOP, .auth_status = NOT_AUTHENTICATED, }; #define HDCP_RI_OFFSET 0x08 #define INFINITE 0xffffffff #define HDMI_SYS_ENABLE (1 << 0) #define HDMI_ASP_ENABLE (1 << 2) #define HDMI_ASP_DISABLE (~HDMI_ASP_ENABLE) #define MAX_DEVS_EXCEEDED (0x1 << 7) #define MAX_CASCADE_EXCEEDED (0x1 << 3) #define MAX_CASCADE_EXCEEDED_ERROR (-1) #define MAX_DEVS_EXCEEDED_ERROR (-2) #define REPEATER_ILLEGAL_DEVICE_ERROR (-3) #define REPEATER_TIMEOUT_ERROR (-4) #define AINFO_SIZE 1 #define BCAPS_SIZE 1 #define BSTATUS_SIZE 2 #define SHA_1_HASH_SIZE 20 #define KSV_FIFO_READY (0x1 << 5) /* spmoon for test : it's not in manual */ #define SET_HDCP_KSV_WRITE_DONE (0x1 << 3) #define CLEAR_HDCP_KSV_WRITE_DONE (~SET_HDCP_KSV_WRITE_DONE) #define SET_HDCP_KSV_LIST_EMPTY (0x1 << 2) #define CLEAR_HDCP_KSV_LIST_EMPTY (~SET_HDCP_KSV_LIST_EMPTY) #define SET_HDCP_KSV_END (0x1 << 1) #define CLEAR_HDCP_KSV_END (~SET_HDCP_KSV_END) #define SET_HDCP_KSV_READ (0x1 << 0) #define CLEAR_HDCP_KSV_READ (~SET_HDCP_KSV_READ) #define SET_HDCP_SHA_VALID_READY (0x1 << 1) #define CLEAR_HDCP_SHA_VALID_READY (~SET_HDCP_SHA_VALID_READY) #define SET_HDCP_SHA_VALID (0x1 << 0) #define CLEAR_HDCP_SHA_VALID (~SET_HDCP_SHA_VALID) #define TRANSMIT_EVERY_VSYNC (0x1 << 1) /* must be checked */ static bool g_sw_reset; static bool g_is_dvi; static bool g_av_mute; static bool g_audio_en; /* * 1st Authentication step func. * Write the Ainfo data to Rx */ static bool write_ainfo(void) { int ret = 0; u8 ainfo[2]; ainfo[0] = HDCP_Ainfo; ainfo[1] = 0; ret = ddc_write(ainfo, 2); if (ret < 0) { pr_err("%s::Can't write ainfo data through i2c bus\n", __func__); } return (ret < 0) ? false : true; } /* * Write the An data to Rx */ static bool write_an(void) { int ret = 0; u8 an[AN_SIZE+1]; an[0] = HDCP_An; an[1] = readb(g_hdmi_base + S5P_HDCP_An_0_0); an[2] = readb(g_hdmi_base + S5P_HDCP_An_0_1); an[3] = readb(g_hdmi_base + S5P_HDCP_An_0_2); an[4] = readb(g_hdmi_base + S5P_HDCP_An_0_3); an[5] = readb(g_hdmi_base + S5P_HDCP_An_1_0); an[6] = readb(g_hdmi_base + S5P_HDCP_An_1_1); an[7] = readb(g_hdmi_base + S5P_HDCP_An_1_2); an[8] = readb(g_hdmi_base + S5P_HDCP_An_1_3); ret = ddc_write(an, AN_SIZE + 1); if (ret < 0) { pr_err("%s::Can't write an data through i2c bus\n", __func__); } #ifdef S5P_HDCP_AUTH_DEBUG { u16 i = 0; for (i = 1; i < AN_SIZE + 1; i++) AUTHPRINTK("HDCPAn[%d]: 0x%x\n", i, an[i]); } #endif return (ret < 0) ? false : true; } /* * Write the Aksv data to Rx */ static bool write_aksv(void) { int ret = 0; u8 aksv[AKSV_SIZE+1]; aksv[0] = HDCP_Aksv; aksv[1] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_0); aksv[2] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_1); aksv[3] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_2); aksv[4] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_3); aksv[5] = readb(g_hdmi_base + S5P_HDCP_AKSV_1); if (aksv[1] == 0 && aksv[2] == 0 && aksv[3] == 0 && aksv[4] == 0 && aksv[5] == 0) return false; ret = ddc_write(aksv, AKSV_SIZE + 1); if (ret < 0) { pr_err("%s::Can't write aksv data through i2c bus\n", __func__); } #ifdef S5P_HDCP_AUTH_DEBUG { u16 i = 0; for (i = 1; i < AKSV_SIZE + 1; i++) AUTHPRINTK("HDCPAksv[%d]: 0x%x\n", i, aksv[i]); } #endif return (ret < 0) ? false : true; } static bool read_bcaps(void) { int ret = 0; u8 bcaps[BCAPS_SIZE] = {0}; ret = ddc_read(HDCP_Bcaps, bcaps, BCAPS_SIZE); if (ret < 0) { pr_err("%s::Can't read bcaps data from i2c bus\n", __func__); return false; } writel(bcaps[0], g_hdmi_base + S5P_HDCP_BCAPS); HDCPPRINTK("BCAPS(from i2c) : 0x%08x\n", bcaps[0]); if (bcaps[0] & REPEATER_SET) hdcp_info.is_repeater = true; else hdcp_info.is_repeater = false; HDCPPRINTK("attached device type : %s !!\n", hdcp_info.is_repeater ? "REPEATER" : "SINK"); HDCPPRINTK("BCAPS(from sfr) = 0x%08x\n", readl(g_hdmi_base + S5P_HDCP_BCAPS)); return true; } static bool read_again_bksv(void) { u8 bk_sv[BKSV_SIZE] = {0, 0, 0, 0, 0}; u8 i = 0; u8 j = 0; u32 no_one = 0; u32 no_zero = 0; u32 result = 0; int ret = 0; ret = ddc_read(HDCP_Bksv, bk_sv, BKSV_SIZE); if (ret < 0) { pr_err("%s::Can't read bk_sv data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("i2c read : Bksv[%d]: 0x%x\n", i, bk_sv[i]); #endif for (i = 0; i < BKSV_SIZE; i++) { for (j = 0; j < 8; j++) { result = bk_sv[i] & (0x1 << j); if (result == 0) no_zero += 1; else no_one += 1; } } if ((no_zero == 20) && (no_one == 20)) { HDCPPRINTK("Suucess: no_zero, and no_one is 20\n"); writel(bk_sv[0], g_hdmi_base + S5P_HDCP_BKSV_0_0); writel(bk_sv[1], g_hdmi_base + S5P_HDCP_BKSV_0_1); writel(bk_sv[2], g_hdmi_base + S5P_HDCP_BKSV_0_2); writel(bk_sv[3], g_hdmi_base + S5P_HDCP_BKSV_0_3); writel(bk_sv[4], g_hdmi_base + S5P_HDCP_BKSV_1); #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("set reg : Bksv[%d]: 0x%x\n", i, bk_sv[i]); /* writel(HDCP_ENC_ENABLE, g_hdmi_base + S5P_ENC_EN); */ #endif return true; } else { pr_err("%s::no_zero or no_one is NOT 20\n", __func__); return false; } } static bool read_bksv(void) { u8 bk_sv[BKSV_SIZE] = {0, 0, 0, 0, 0}; int i = 0; int j = 0; u32 no_one = 0; u32 no_zero = 0; u32 result = 0; u32 count = 0; int ret = 0; ret = ddc_read(HDCP_Bksv, bk_sv, BKSV_SIZE); if (ret < 0) { pr_err("%s::Can't read bk_sv data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("i2c read : Bksv[%d]: 0x%x\n", i, bk_sv[i]); #endif for (i = 0; i < BKSV_SIZE; i++) { for (j = 0; j < 8; j++) { result = bk_sv[i] & (0x1 << j); if (result == 0) no_zero++; else no_one++; } } if ((no_zero == 20) && (no_one == 20)) { writel(bk_sv[0], g_hdmi_base + S5P_HDCP_BKSV_0_0); writel(bk_sv[1], g_hdmi_base + S5P_HDCP_BKSV_0_1); writel(bk_sv[2], g_hdmi_base + S5P_HDCP_BKSV_0_2); writel(bk_sv[3], g_hdmi_base + S5P_HDCP_BKSV_0_3); writel(bk_sv[4], g_hdmi_base + S5P_HDCP_BKSV_1); #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("set reg : Bksv[%d]: 0x%x\n", i, bk_sv[i]); #endif HDCPPRINTK("Success: no_zero, and no_one is 20\n"); } else { HDCPPRINTK("Failed: no_zero or no_one is NOT 20\n"); while (!read_again_bksv()) { count++; mdelay(200); if (count == 14) return false; } } return true; } /* * Compare the R value of Tx with that of Rx */ static bool compare_r_val(void) { int ret = 0; u8 ri[2] = {0, 0}; u8 rj[2] = {0, 0}; u16 i; for (i = 0; i < R_VAL_RETRY_CNT; i++) { if (hdcp_info.auth_status < AKSV_WRITE_DONE) { ret = false; break; } /* Read R value from Tx */ ri[0] = readl(g_hdmi_base + S5P_HDCP_Ri_0); ri[1] = readl(g_hdmi_base + S5P_HDCP_Ri_1); /* Read R value from Rx */ ret = ddc_read(HDCP_Ri, rj, 2); if (ret < 0) { pr_err("%s::Can't read r data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_AUTH_DEBUG AUTHPRINTK("retries :: %d\n", i); printk("\t\t\t Rx(ddc)\t ->"); printk("rj[0]: 0x%02x, rj[1]: 0x%02x\n", rj[0], rj[1]); printk("\t\t\t Tx(register)\t ->"); printk("ri[0]: 0x%02x, ri[1]: 0x%02x\n", ri[0], ri[1]); #endif /* Compare R value */ if ((ri[0] == rj[0]) && (ri[1] == rj[1]) && (ri[0] | ri[1])) { writel(Ri_MATCH_RESULT__YES, g_hdmi_base + S5P_HDCP_CHECK_RESULT); HDCPPRINTK("R0, R0' is matched!!\n"); /* for simplay test */ mdelay(1); ret = true; break; } else { writel(Ri_MATCH_RESULT__NO, g_hdmi_base + S5P_HDCP_CHECK_RESULT); HDCPPRINTK("R0, R0' is not matched!!\n"); ret = false; } ri[0] = 0; ri[1] = 0; rj[0] = 0; rj[1] = 0; } if (!ret) { hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; } return ret ? true : false; } /* * Enable/Disable Software HPD control */ static void sw_hpd_enable(bool enable) { u8 reg; reg = readb(g_hdmi_base + S5P_HPD); reg &= ~HPD_SW_ENABLE; if (enable) writeb(reg | HPD_SW_ENABLE, g_hdmi_base + S5P_HPD); else writeb(reg, g_hdmi_base + S5P_HPD); } /* * Set Software HPD level * * @param level [in] if 0 - low;othewise, high */ static void set_sw_hpd(bool level) { u8 reg; reg = readb(g_hdmi_base + S5P_HPD); reg &= ~HPD_ON; if (level) writeb(reg | HPD_ON, g_hdmi_base + S5P_HPD); else writeb(reg, g_hdmi_base + S5P_HPD); } /* * Reset Authentication */ static void reset_authentication(void) { u8 reg; spin_lock_irq(&hdcp_info.reset_lock); hdcp_info.time_out = INFINITE; hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; /* Disable hdcp */ writeb(0x0, g_hdmi_base + S5P_HDCP_CTRL1); writeb(0x0, g_hdmi_base + S5P_HDCP_CTRL2); s5p_hdmi_mute_en(true); /* Disable encryption */ HDCPPRINTK("Stop Encryption by reset!!\n"); writeb(HDCP_ENC_DIS, g_hdmi_base + S5P_ENC_EN); HDCPPRINTK("Now reset authentication\n"); /* disable hdmi status enable reg. */ reg = readb(g_hdmi_base + S5P_STATUS_EN); reg &= HDCP_STATUS_DIS_ALL; writeb(reg, g_hdmi_base + S5P_STATUS_EN); /* clear all result */ writeb(CLEAR_ALL_RESULTS, g_hdmi_base + S5P_HDCP_CHECK_RESULT); /* * 1. Mask HPD plug and unplug interrupt * disable HPD INT */ g_sw_reset = true; reg = s5p_hdmi_get_enabled_interrupt(); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_PLUG); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_UNPLUG); /* for simplay test */ mdelay(50); /* 2. Enable software HPD */ sw_hpd_enable(true); /* 3. Make software HPD logical 0 */ set_sw_hpd(false); /* 4. Make software HPD logical 1 */ set_sw_hpd(true); /* 5. Disable software HPD */ sw_hpd_enable(false); /* 6. Unmask HPD plug and unplug interrupt */ if (reg & 1<<HDMI_IRQ_HPD_PLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_PLUG); if (reg & 1<<HDMI_IRQ_HPD_UNPLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_UNPLUG); g_sw_reset = false; /* clear result */ #if 0 writel(Ri_MATCH_RESULT__NO, g_hdmi_base + S5P_HDCP_CHECK_RESULT); writel(readl(g_hdmi_base + S5P_HDMI_CON_0) & HDMI_DIS, g_hdmi_base + S5P_HDMI_CON_0); writel(readl(g_hdmi_base + S5P_HDMI_CON_0) | HDMI_EN, g_hdmi_base + S5P_HDMI_CON_0); #endif writel(CLEAR_ALL_RESULTS, g_hdmi_base + S5P_HDCP_CHECK_RESULT); /* set hdcp_int enable */ reg = readb(g_hdmi_base + S5P_STATUS_EN); reg |= WTFORACTIVERX_INT_OCCURRED | WATCHDOG_INT_OCCURRED | EXCHANGEKSV_INT_OCCURRED | UPDATE_RI_INT_OCCURRED; writeb(reg, g_hdmi_base + S5P_STATUS_EN); /* HDCP Enable */ writeb(CP_DESIRED_EN, g_hdmi_base + S5P_HDCP_CTRL1); spin_unlock_irq(&hdcp_info.reset_lock); } /* * Set the timing parameter for load e-fuse key. */ /* TODO: must use clk_get for pclk rate */ #define PCLK_D_RATE_FOR_HDCP 166000000 static u32 efuse_ceil(u32 val, u32 time) { u32 res; res = val / time; if (val % time) res += 1; return res; } #if 0 static void hdcp_efuse_timing(void) { u32 time, val; /* TODO: must use clk_get for pclk rate */ time = 1000000000/PCLK_D_RATE_FOR_HDCP; val = efuse_ceil(EFUSE_ADDR_WIDTH, time); writeb(val, g_hdmi_base + S5P_EFUSE_ADDR_WIDTH); val = efuse_ceil(EFUSE_SIGDEV_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SIGDEV_ASSERT); val = efuse_ceil(EFUSE_SIGDEV_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SIGDEV_DEASSERT); val = efuse_ceil(EFUSE_PRCHG_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_PRCHG_ASSERT); val = efuse_ceil(EFUSE_PRCHG_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_PRCHG_DEASSERT); val = efuse_ceil(EFUSE_FSET_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_FSET_ASSERT); val = efuse_ceil(EFUSE_FSET_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_FSET_DEASSERT); val = efuse_ceil(EFUSE_SENSING, time); writeb(val, g_hdmi_base + S5P_EFUSE_SENSING); val = efuse_ceil(EFUSE_SCK_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SCK_ASSERT); val = efuse_ceil(EFUSE_SCK_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SCK_DEASSERT); val = efuse_ceil(EFUSE_SDOUT_OFFSET, time); writeb(val, g_hdmi_base + S5P_EFUSE_SDOUT_OFFSET); val = efuse_ceil(EFUSE_READ_OFFSET, time); writeb(val, g_hdmi_base + S5P_EFUSE_READ_OFFSET); } #endif /* * load hdcp key from e-fuse mem. */ static int hdcp_loadkey(void) { u8 status; int time_out = HDMI_TIME_OUT; #if 0 hdcp_efuse_timing(); #endif /* read HDCP key from E-Fuse */ writeb(EFUSE_CTRL_ACTIVATE, g_hdmi_base + S5P_EFUSE_CTRL); do { status = readb(g_hdmi_base + S5P_EFUSE_STATUS); time_out--; } while (!(status & EFUSE_ECC_DONE) && time_out); if (readb(g_hdmi_base + S5P_EFUSE_STATUS) & EFUSE_ECC_FAIL) { pr_err("%s::Can't load key from fuse ctrl.\n", __func__); return -EINVAL; } else { HDCPPRINTK("%s::readb S5P_EFUSE_STATUS for EFUSE_ECC_FAIL: 0\n", __func__); } return 0; } /* * Start encryption */ static void start_encryption(void) { int time_out = HDMI_TIME_OUT; if (readl(g_hdmi_base + S5P_HDCP_CHECK_RESULT) == Ri_MATCH_RESULT__YES) { do { if (readl(g_hdmi_base + S5P_STATUS) & AUTHENTICATED) { writel(HDCP_ENC_ENABLE, g_hdmi_base + S5P_ENC_EN); HDCPPRINTK("Encryption start!!\n"); s5p_hdmi_mute_en(false); break; } else { time_out--; mdelay(1); } } while (time_out); if (time_out <= 0) pr_err("%s::readl S5P_STATUS for AUTHENTICATED fail!!\n", __func__); } else { writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); HDCPPRINTK("Encryption stop!!\n"); } } /* * Check whether Rx is repeater or not */ static int check_repeater(void) { int ret = 0; u8 i = 0; u16 j = 0; u8 bcaps[BCAPS_SIZE] = {0}; u8 status[BSTATUS_SIZE] = {0, 0}; u8 rx_v[SHA_1_HASH_SIZE] = {0}; u8 ksv_list[HDCP_MAX_DEVS*HDCP_KSV_SIZE] = {0}; u32 dev_cnt; u32 stat; bool ksv_fifo_ready = false; memset(rx_v, 0x0, SHA_1_HASH_SIZE); memset(ksv_list, 0x0, HDCP_MAX_DEVS * HDCP_KSV_SIZE); while (j <= 50) { ret = ddc_read(HDCP_Bcaps, bcaps, BCAPS_SIZE); if (ret < 0) { pr_err("%s::Can't read bcaps data from i2c bus\n", __func__); return false; } if (bcaps[0] & KSV_FIFO_READY) { HDCPPRINTK("ksv fifo is ready\n"); ksv_fifo_ready = true; writel(bcaps[0], g_hdmi_base + S5P_HDCP_BCAPS); break; } else { HDCPPRINTK("ksv fifo is not ready\n"); ksv_fifo_ready = false; mdelay(100); j++; } bcaps[0] = 0; } if (!ksv_fifo_ready) return REPEATER_TIMEOUT_ERROR; /* * Check MAX_CASCADE_EXCEEDED * or MAX_DEVS_EXCEEDED indicator */ ret = ddc_read(HDCP_BStatus, status, BSTATUS_SIZE); if (ret < 0) { pr_err("%s::Can't read status data from i2c bus\n", __func__); return false; } /* MAX_CASCADE_EXCEEDED || MAX_DEVS_EXCEEDED */ if (status[1] & MAX_CASCADE_EXCEEDED) { HDCPPRINTK("MAX_CASCADE_EXCEEDED\n"); return MAX_CASCADE_EXCEEDED_ERROR; } else if (status[0] & MAX_DEVS_EXCEEDED) { HDCPPRINTK("MAX_CASCADE_EXCEEDED\n"); return MAX_DEVS_EXCEEDED_ERROR; } writel(status[0], g_hdmi_base + S5P_HDCP_BSTATUS_0); writel(status[1], g_hdmi_base + S5P_HDCP_BSTATUS_1); /* Read KSV list */ dev_cnt = status[0] & 0x7f; HDCPPRINTK("status[0] :0x%08x, status[1] :0x%08x!!\n", status[0], status[1]); if (dev_cnt) { u32 val = 0; /* read ksv */ ret = ddc_read(HDCP_KSVFIFO, ksv_list, dev_cnt * HDCP_KSV_SIZE); if (ret < 0) { pr_err("%s::Can't read ksv fifo!!\n", __func__); return false; } /* write ksv */ for (i = 0; i < dev_cnt - 1; i++) { writel(ksv_list[(i*5) + 0], g_hdmi_base + S5P_HDCP_RX_KSV_0_0); writel(ksv_list[(i*5) + 1], g_hdmi_base + S5P_HDCP_RX_KSV_0_1); writel(ksv_list[(i*5) + 2], g_hdmi_base + S5P_HDCP_RX_KSV_0_2); writel(ksv_list[(i*5) + 3], g_hdmi_base + S5P_HDCP_RX_KSV_0_3); writel(ksv_list[(i*5) + 4], g_hdmi_base + S5P_HDCP_RX_KSV_0_4); mdelay(1); writel(SET_HDCP_KSV_WRITE_DONE, g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); mdelay(1); stat = readl(g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); if (!(stat & SET_HDCP_KSV_READ)) return false; HDCPPRINTK("HDCP_RX_KSV_1 = 0x%x\n", readl(g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL)); HDCPPRINTK("i : %d, dev_cnt : %d, val = 0x%08x\n", i, dev_cnt, val); } writel(ksv_list[(i*5) + 0], g_hdmi_base + S5P_HDCP_RX_KSV_0_0); writel(ksv_list[(i*5) + 1], g_hdmi_base + S5P_HDCP_RX_KSV_0_1); writel(ksv_list[(i*5) + 2], g_hdmi_base + S5P_HDCP_RX_KSV_0_2); writel(ksv_list[(i*5) + 3], g_hdmi_base + S5P_HDCP_RX_KSV_0_3); writel(ksv_list[(i*5) + 4], g_hdmi_base + S5P_HDCP_RX_KSV_0_4); mdelay(1); /* end of ksv */ val = SET_HDCP_KSV_END|SET_HDCP_KSV_WRITE_DONE; writel(val, g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); HDCPPRINTK("HDCP_RX_KSV_1 = 0x%x\n", readl(g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL)); HDCPPRINTK("i : %d, dev_cnt : %d, val = 0x%08x\n", i, dev_cnt, val); } else { /* mdelay(200); */ writel(SET_HDCP_KSV_LIST_EMPTY, g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); } /* Read SHA-1 from receiver */ ret = ddc_read(HDCP_SHA1, rx_v, SHA_1_HASH_SIZE); if (ret < 0) { pr_err("%s::Can't read sha_1_hash data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_DEBUG for (i = 0; i < SHA_1_HASH_SIZE; i++) HDCPPRINTK("SHA_1 rx :: %x\n", rx_v[i]); #endif /* write SHA-1 to register */ writeb(rx_v[0], g_hdmi_base + S5P_HDCP_RX_SHA1_0_0); writeb(rx_v[1], g_hdmi_base + S5P_HDCP_RX_SHA1_0_1); writeb(rx_v[2], g_hdmi_base + S5P_HDCP_RX_SHA1_0_2); writeb(rx_v[3], g_hdmi_base + S5P_HDCP_RX_SHA1_0_3); writeb(rx_v[4], g_hdmi_base + S5P_HDCP_RX_SHA1_1_0); writeb(rx_v[5], g_hdmi_base + S5P_HDCP_RX_SHA1_1_1); writeb(rx_v[6], g_hdmi_base + S5P_HDCP_RX_SHA1_1_2); writeb(rx_v[7], g_hdmi_base + S5P_HDCP_RX_SHA1_1_3); writeb(rx_v[8], g_hdmi_base + S5P_HDCP_RX_SHA1_2_0); writeb(rx_v[9], g_hdmi_base + S5P_HDCP_RX_SHA1_2_1); writeb(rx_v[10], g_hdmi_base + S5P_HDCP_RX_SHA1_2_2); writeb(rx_v[11], g_hdmi_base + S5P_HDCP_RX_SHA1_2_3); writeb(rx_v[12], g_hdmi_base + S5P_HDCP_RX_SHA1_3_0); writeb(rx_v[13], g_hdmi_base + S5P_HDCP_RX_SHA1_3_1); writeb(rx_v[14], g_hdmi_base + S5P_HDCP_RX_SHA1_3_2); writeb(rx_v[15], g_hdmi_base + S5P_HDCP_RX_SHA1_3_3); writeb(rx_v[16], g_hdmi_base + S5P_HDCP_RX_SHA1_4_0); writeb(rx_v[17], g_hdmi_base + S5P_HDCP_RX_SHA1_4_1); writeb(rx_v[18], g_hdmi_base + S5P_HDCP_RX_SHA1_4_2); writeb(rx_v[19], g_hdmi_base + S5P_HDCP_RX_SHA1_4_3); /* SHA write done, and wait for SHA computation being done */ mdelay(1); /* check authentication success or not */ stat = readb(g_hdmi_base + S5P_HDCP_AUTH_STATUS); HDCPPRINTK("auth status %d\n", stat); if (stat & SET_HDCP_SHA_VALID_READY) { stat = readb(g_hdmi_base + S5P_HDCP_AUTH_STATUS); if (stat & SET_HDCP_SHA_VALID) ret = true; else ret = false; } else { pr_err("%s::SHA not ready 0x%x\n", __func__, stat); ret = false; } /* clear all validate bit */ writeb(0x0, g_hdmi_base + S5P_HDCP_AUTH_STATUS); return ret; } static bool try_read_receiver(void) { u16 i = 0; bool ret = false; s5p_hdmi_mute_en(true); for (i = 0; i < 400; i++) { msleep(250); if (hdcp_info.auth_status != RECEIVER_READ_READY) { pr_err("%s::hdcp stat. changed!!\ failed attempt no = %d\n", __func__, i); return false; } ret = read_bcaps(); if (ret) { HDCPPRINTK("succeeded at attempt no= %d\n", i); return true; } else pr_err("%s::can't read bcaps!! \ failed attempt no=%d\n", __func__, i); } return false; } static void s5p_hdcp_reset(void) { s5p_stop_hdcp(); g_hdcp_protocol_status = 2; HDCPPRINTK("HDCP ftn. reset!!\n"); } static void bksv_start_bh(void) { bool ret = false; HDCPPRINTK("HDCP_EVENT_READ_BKSV_START bh\n"); hdcp_info.auth_status = RECEIVER_READ_READY; ret = read_bcaps(); if (!ret) { ret = try_read_receiver(); if (!ret) { pr_err("%s::Can't read bcaps!! retry failed!!\ hdcp ftn. will be stopped\n", __func__); reset_authentication(); return; } } hdcp_info.auth_status = BCAPS_READ_DONE; ret = read_bksv(); if (!ret) { pr_err("%s::Can't read bksv!!\ hdcp ftn. will be reset\n", __func__); reset_authentication(); return; } hdcp_info.auth_status = BKSV_READ_DONE; HDCPPRINTK("authentication status : bksv is done (0x%08x)\n", hdcp_info.auth_status); } static void second_auth_start_bh(void) { u8 count = 0; int reg; bool ret = false; int ret_err; u32 bcaps; HDCPPRINTK("HDCP_EVENT_SECOND_AUTH_START bh\n"); ret = read_bcaps(); if (!ret) { ret = try_read_receiver(); if (!ret) { pr_err("%s::Can't read bcaps!! retry failed!!\ hdcp ftn. will be stopped\n", __func__); reset_authentication(); return; } } bcaps = readl(g_hdmi_base + S5P_HDCP_BCAPS); bcaps &= (KSV_FIFO_READY); if (!bcaps) { HDCPPRINTK("ksv fifo is not ready\n"); do { count++; ret = read_bcaps(); if (!ret) { ret = try_read_receiver(); if (!ret) reset_authentication(); return; } bcaps = readl(g_hdmi_base + S5P_HDCP_BCAPS); bcaps &= (KSV_FIFO_READY); if (bcaps) { HDCPPRINTK("bcaps retries : %d\n", count); break; } mdelay(100); if (!hdcp_info.hdcp_enable) { reset_authentication(); return; } } while (count <= 50); /* wait times exceeded 5 seconds */ if (count > 50) { hdcp_info.time_out = INFINITE; /* * time-out (This bit is only available in a REPEATER) */ writel(readl(g_hdmi_base + S5P_HDCP_CTRL1) | 0x1 << 2, g_hdmi_base + S5P_HDCP_CTRL1); reset_authentication(); return; } } HDCPPRINTK("ksv fifo ready\n"); ret_err = check_repeater(); if (ret_err == true) { u32 flag; hdcp_info.auth_status = SECOND_AUTHENTICATION_DONE; HDCPPRINTK("second authentication done!!\n"); flag = readb(g_hdmi_base + S5P_STATUS); HDCPPRINTK("hdcp state : %s authenticated!!\n", flag & AUTHENTICATED ? "" : "not not"); start_encryption(); } else if (ret_err == false) { /* i2c error */ pr_err("%s::repeater check error!!\n", __func__); reset_authentication(); } else { if (ret_err == REPEATER_ILLEGAL_DEVICE_ERROR) { /* * No need to start the HDCP * in case of invalid KSV (revocation case) */ pr_err("%s::illegal dev. error!!\n", __func__); reg = readl(g_hdmi_base + S5P_HDCP_CTRL2); reg = 0x1; writel(reg, g_hdmi_base + S5P_HDCP_CTRL2); reg = 0x0; writel(reg, g_hdmi_base + S5P_HDCP_CTRL2); hdcp_info.auth_status = NOT_AUTHENTICATED; } else if (ret_err == REPEATER_TIMEOUT_ERROR) { reg = readl(g_hdmi_base + S5P_HDCP_CTRL1); reg |= SET_REPEATER_TIMEOUT; writel(reg, g_hdmi_base + S5P_HDCP_CTRL1); reg &= ~SET_REPEATER_TIMEOUT; writel(reg, g_hdmi_base + S5P_HDCP_CTRL1); hdcp_info.auth_status = NOT_AUTHENTICATED; } else { /* * MAX_CASCADE_EXCEEDED_ERROR * MAX_DEVS_EXCEEDED_ERROR */ pr_err("%s::repeater check error(MAX_EXCEEDED)!!\n", __func__); reset_authentication(); } } } static bool write_aksv_start_bh(void) { bool ret = false; HDCPPRINTK("HDCP_EVENT_WRITE_AKSV_START bh\n"); if (hdcp_info.auth_status != BKSV_READ_DONE) { pr_err("%s::bksv is not ready!!\n", __func__); return false; } ret = write_an(); if (!ret) return false; hdcp_info.auth_status = AN_WRITE_DONE; HDCPPRINTK("an write done!!\n"); ret = write_aksv(); if (!ret) return false; /* * Wait for 100ms. Transmitter must not read * Ro' value sooner than 100ms after writing * Aksv */ mdelay(100); hdcp_info.auth_status = AKSV_WRITE_DONE; HDCPPRINTK("aksv write done!!\n"); return ret; } static bool check_ri_start_bh(void) { bool ret = false; HDCPPRINTK("HDCP_EVENT_CHECK_RI_START bh\n"); if (hdcp_info.auth_status == AKSV_WRITE_DONE || hdcp_info.auth_status == FIRST_AUTHENTICATION_DONE || hdcp_info.auth_status == SECOND_AUTHENTICATION_DONE) { ret = compare_r_val(); if (ret) { if (hdcp_info.auth_status == AKSV_WRITE_DONE) { /* * Check whether HDMI receiver is * repeater or not */ if (hdcp_info.is_repeater) hdcp_info.auth_status = SECOND_AUTHENTICATION_RDY; else { hdcp_info.auth_status = FIRST_AUTHENTICATION_DONE; start_encryption(); } } } else { HDCPPRINTK("authentication reset\n"); reset_authentication(); } HDCPPRINTK("auth_status = 0x%08x\n", hdcp_info.auth_status); return true; } else reset_authentication(); HDCPPRINTK("aksv_write or first/second" " authentication is not done\n"); return false; } /* * bottom half for hdmi interrupt * */ static void hdcp_work(void *arg) { /* HDCPPRINTK("event : 0x%08x\n", hdcp_info.event); */ /* * I2C int. was occurred * for reading Bksv and Bcaps */ if (hdcp_info.event & (1 << HDCP_EVENT_READ_BKSV_START)) { bksv_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_READ_BKSV_START); /* spin_unlock_bh(&hdcp_info.lock); */ } /* * Watchdog timer int. was occurred * for checking repeater */ if (hdcp_info.event & (1 << HDCP_EVENT_SECOND_AUTH_START)) { second_auth_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_SECOND_AUTH_START); /* spin_unlock_bh(&hdcp_info.lock); */ } /* * An_Write int. was occurred * for writing Ainfo, An and Aksv */ if (hdcp_info.event & (1 << HDCP_EVENT_WRITE_AKSV_START)) { write_aksv_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_WRITE_AKSV_START); /* spin_unlock_bh(&hdcp_info.lock); */ } /* * Ri int. was occurred * for comparing Ri and Ri'(from HDMI sink) */ if (hdcp_info.event & (1 << HDCP_EVENT_CHECK_RI_START)) { check_ri_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_CHECK_RI_START); /* spin_unlock_bh(&hdcp_info.lock); */ } } irqreturn_t s5p_hdcp_irq_handler(int irq, void *dev_id) { u32 event = 0; u8 flag; unsigned long spin_flags; event = 0; /* check HDCP Status */ flag = readb(g_hdmi_base + S5P_STATUS); HDCPPRINTK("irq_status : 0x%08x\n", readb(g_hdmi_base + S5P_STATUS)); HDCPPRINTK("hdcp state : %s authenticated!!\n", flag & AUTHENTICATED ? "" : "not"); spin_lock_irqsave(&hdcp_info.lock, spin_flags); /* * processing interrupt * interrupt processing seq. is firstly set event for workqueue, * and interrupt pending clear. 'flag|' was used for preventing * to clear AUTHEN_ACK.- it caused many problem. be careful. */ /* I2C INT */ if (flag & WTFORACTIVERX_INT_OCCURRED) { event |= (1 << HDCP_EVENT_READ_BKSV_START); writeb(flag | WTFORACTIVERX_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_I2C_INT); } /* AN INT */ if (flag & EXCHANGEKSV_INT_OCCURRED) { event |= (1 << HDCP_EVENT_WRITE_AKSV_START); writeb(flag | EXCHANGEKSV_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_AN_INT); } /* RI INT */ if (flag & UPDATE_RI_INT_OCCURRED) { event |= (1 << HDCP_EVENT_CHECK_RI_START); writeb(flag | UPDATE_RI_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_RI_INT); } /* WATCHDOG INT */ if (flag & WATCHDOG_INT_OCCURRED) { event |= (1 << HDCP_EVENT_SECOND_AUTH_START); writeb(flag | WATCHDOG_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_WDT_INT); } if (!event) { pr_err("%s::unknown irq.\n", __func__); spin_unlock_irqrestore(&hdcp_info.lock, spin_flags); return IRQ_HANDLED; } hdcp_info.event |= event; schedule_work(&hdcp_info.work); spin_unlock_irqrestore(&hdcp_info.lock, spin_flags); return IRQ_HANDLED; } static int s5p_hdcp_is_reset(void) { int ret = 0; if (spin_is_locked(&hdcp_info.reset_lock)) return 1; return ret; } static bool s5p_set_hpd_detection(bool detection, bool hdcp_enabled, struct i2c_client *client) { u32 hpd_reg_val = 0; if (detection) hpd_reg_val = CABLE_PLUGGED; else hpd_reg_val = CABLE_UNPLUGGED; writel(hpd_reg_val, g_hdmi_base + S5P_HPD); HDCPPRINTK("HPD status :: 0x%08x\n", readl(g_hdmi_base + S5P_HPD)); return true; } int s5p_hdcp_init(void) { HDCPPRINTK("HDCP ftn. Init!!\n"); g_is_dvi = false; g_av_mute = false; g_audio_en = true; /* for bh */ INIT_WORK(&hdcp_info.work, (work_func_t)hdcp_work); init_waitqueue_head(&hdcp_info.waitq); /* for dev_dbg err. */ spin_lock_init(&hdcp_info.lock); spin_lock_init(&hdcp_info.reset_lock); s5p_hdmi_register_isr((hdmi_isr)s5p_hdcp_irq_handler, (u8)HDMI_IRQ_HDCP); return 0; } /* * start - start functions are only called under stopping HDCP */ bool s5p_start_hdcp(void) { u8 reg; u32 sfr_val; hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.time_out = INFINITE; hdcp_info.auth_status = NOT_AUTHENTICATED; HDCPPRINTK("HDCP ftn. Start!!\n"); g_sw_reset = true; reg = s5p_hdmi_get_enabled_interrupt(); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_PLUG); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_UNPLUG); /* 2. Enable software HPD */ sw_hpd_enable(true); /* 3. Make software HPD logical */ set_sw_hpd(false); /* 4. Make software HPD logical */ set_sw_hpd(true); /* 5. Disable software HPD */ sw_hpd_enable(false); set_sw_hpd(false); /* 6. Unmask HPD plug and unplug interrupt */ if (reg & 1<<HDMI_IRQ_HPD_PLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_PLUG); if (reg & 1<<HDMI_IRQ_HPD_UNPLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_UNPLUG); g_sw_reset = false; HDCPPRINTK("Stop Encryption by Start!!\n"); writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); g_hdcp_protocol_status = 1; if (hdcp_loadkey() < 0) return false; /* for av mute */ writel(DO_NOT_TRANSMIT, g_hdmi_base + S5P_GCP_CON); /* * 1-1. set hdmi status enable reg. * Update_Ri_int_en should be enabled after * s/w gets ExchangeKSV_int. */ writel(HDCP_STATUS_EN_ALL, g_hdmi_base + S5P_STATUS_EN); /* * 3. set hdcp control reg. * Disable advance cipher option, Enable CP(Content Protection), * Disable time-out (This bit is only available in a REPEATER) * Disable XOR shift, Disable Pj port update, Use external key */ sfr_val = 0; sfr_val |= CP_DESIRED_EN; writel(sfr_val, g_hdmi_base + S5P_HDCP_CTRL1); s5p_hdmi_enable_interrupts(HDMI_IRQ_HDCP); if (!read_bcaps()) { pr_err("%s::can't read ddc port!\n", __func__); reset_authentication(); } hdcp_info.hdcp_enable = true; HDCPPRINTK("\tSTATUS \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS)); HDCPPRINTK("\tSTATUS_EN \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS_EN)); HDCPPRINTK("\tHPD \t0x%08x\n", readl(g_hdmi_base + S5P_HPD)); HDCPPRINTK("\tHDCP_CTRL \t0x%08x\n", readl(g_hdmi_base + S5P_HDCP_CTRL1)); HDCPPRINTK("\tMODE_SEL \t0x%08x\n", readl(g_hdmi_base + S5P_MODE_SEL)); HDCPPRINTK("\tENC_EN \t0x%08x\n", readl(g_hdmi_base + S5P_ENC_EN)); HDCPPRINTK("\tHDMI_CON_0 \t0x%08x\n", readl(g_hdmi_base + S5P_HDMI_CON_0)); return true; } /* * stop - stop functions are only called under running HDCP */ bool s5p_stop_hdcp(void) { u32 sfr_val = 0; HDCPPRINTK("HDCP ftn. Stop!!\n"); /* s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_PLUG); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_UNPLUG); */ s5p_hdmi_disable_interrupts(HDMI_IRQ_HDCP); g_hdcp_protocol_status = 0; hdcp_info.time_out = INFINITE; hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; hdcp_info.hdcp_enable = false; /* hdcp_info.client = NULL; */ /* 3. disable hdcp control reg. */ sfr_val = readl(g_hdmi_base + S5P_HDCP_CTRL1); sfr_val &= (ENABLE_1_DOT_1_FEATURE_DIS & CLEAR_REPEATER_TIMEOUT & EN_PJ_DIS & CP_DESIRED_DIS); writel(sfr_val, g_hdmi_base + S5P_HDCP_CTRL1); /* 1-3. disable hdmi hpd reg. */ sw_hpd_enable(false); /* 1-2. disable hdmi status enable reg. */ sfr_val = readl(g_hdmi_base + S5P_STATUS_EN); sfr_val &= HDCP_STATUS_DIS_ALL; writel(sfr_val, g_hdmi_base + S5P_STATUS_EN); /* 1-1. clear all status pending */ sfr_val = readl(g_hdmi_base + S5P_STATUS); sfr_val |= HDCP_STATUS_EN_ALL; writel(sfr_val, g_hdmi_base + S5P_STATUS); /* disable encryption */ HDCPPRINTK("Stop Encryption by Stop!!\n"); writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); /* clear result */ writel(Ri_MATCH_RESULT__NO, g_hdmi_base + S5P_HDCP_CHECK_RESULT); writel(CLEAR_ALL_RESULTS, g_hdmi_base + S5P_HDCP_CHECK_RESULT); #if 0 /* hdmi disable */ sfr_val = readl(g_hdmi_base + S5P_HDMI_CON_0); sfr_val &= ~(PWDN_ENB_NORMAL | HDMI_EN | ASP_EN); writel(sfr_val, g_hdmi_base + S5P_HDMI_CON_0); */ HDCPPRINTK("\tSTATUS \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS)); HDCPPRINTK("\tSTATUS_EN \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS_EN)); HDCPPRINTK("\tHPD \t0x%08x\n", readl(g_hdmi_base + S5P_HPD)); HDCPPRINTK("\tHDCP_CTRL \t0x%08x\n", readl(g_hdmi_base + S5P_HDCP_CTRL1)); HDCPPRINTK("\tMODE_SEL \t0x%08x\n", readl(g_hdmi_base + S5P_MODE_SEL)); HDCPPRINTK("\tENC_EN \t0x%08x\n", readl(g_hdmi_base + S5P_ENC_EN)); HDCPPRINTK("\tHDMI_CON_0 \t0x%08x\n", readl(g_hdmi_base + S5P_HDMI_CON_0)); writel(sfr_val, g_hdmi_base + S5P_HDMI_CON_0); #endif return true; } /* called by hpd */ int s5p_hdcp_encrypt_stop(bool on) { u32 reg; if (hdcp_info.hdcp_enable) { /* clear interrupt pending all */ writeb(0x0, g_hdmi_base + S5P_HDCP_I2C_INT); writeb(0x0, g_hdmi_base + S5P_HDCP_AN_INT); writeb(0x0, g_hdmi_base + S5P_HDCP_RI_INT); writeb(0x0, g_hdmi_base + S5P_HDCP_WDT_INT); writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); if (!g_sw_reset) { reg = readl(g_hdmi_base + S5P_HDCP_CTRL1); if (on) { writel(reg | CP_DESIRED_EN, g_hdmi_base + S5P_HDCP_CTRL1); s5p_hdmi_enable_interrupts(HDMI_IRQ_HDCP); } else { hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; writel(reg & ~CP_DESIRED_EN, g_hdmi_base + S5P_HDCP_CTRL1); s5p_hdmi_disable_interrupts(HDMI_IRQ_HDCP); } } HDCPPRINTK("Stop Encryption by HPD Event!!\n"); } return 0; } int s5p_hdmi_set_dvi(bool en) { if (en) g_is_dvi = true; else g_is_dvi = false; return 0; } void s5p_hdmi_set_audio(bool en) { if (en) g_audio_en = true; else g_audio_en = false; } int s5p_hdmi_audio_enable(bool en) { u8 reg; if (!g_is_dvi) { reg = readl(g_hdmi_base + S5P_HDMI_CON_0); if (en) { reg |= ASP_EN; writel(HDMI_TRANS_EVERY_SYNC , g_hdmi_base + S5P_AUI_CON); } else { reg &= ~ASP_EN; writel(HDMI_DO_NOT_TANS , g_hdmi_base + S5P_AUI_CON); } writel(reg, g_hdmi_base + S5P_HDMI_CON_0); } return 0; } int s5p_hdmi_set_mute(bool en) { if (en) g_av_mute = true; else g_av_mute = false; return 0; } int s5p_hdmi_get_mute(void) { return g_av_mute ? true : false; } void s5p_hdmi_mute_en(bool en) { if (!g_av_mute) { if (en) { s5p_hdmi_video_set_bluescreen(true, 128, 0, 128); s5p_hdmi_audio_enable(false); } else { s5p_hdmi_video_set_bluescreen(false, 128, 0, 128); if (g_audio_en) s5p_hdmi_audio_enable(true); } } }
Jolocotroco/android_kernel_samsung_smdkv210
drivers/media/video/samsung/tv20/s5pv210/hdcp_s5pv210.c
C
gpl-2.0
38,054
/****************************************************************************** * File : velocity_tria3.c * * Author : Carlos Rosales Fernandez (carlos@ihpc.a-star.edu.sg) * * Date : 01-09-2006 * * Revision : 1.0 * ******************************************************************************* * DESCRIPTION * * Calculates the three components of the flow speed at a given point Xin[] * * and returns the values in array U[]. * * Works for linear interpolation in triangular elements (3-noded triangles). * ******************************************************************************/ /****************************************************************************** * COPYRIGHT & LICENSE INFORMATION * * * * Copyright 2006 Carlos Rosales Fernandez and The Institute of High * * Performance Computing (A*STAR) * * * * This file is part of stkSolver. * * * * stkSolver 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. * * * * stkSolver 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 stkSolver; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ******************************************************************************/ #include "constants.h" #include "velocity_tria3.h" int velocity_tria3(double *Xin, double **mNodes, unsigned int **mElems, double *vProbParam, double *vB, double *U) { const unsigned int ELEMS = nElems, NODES_IN_ELEM = 3; unsigned int currentNode, i, j, SinNode, test, xNode, yNode, zNode; double dx, dy, dz, factor; double X[3][3]; double Int[3][3][3]; /* Initialize */ U[0] = U[1] = U[2] = 0.0; factor = 1.0/(8.0*pi*vProbParam[0]); for(i = 0; i < ELEMS; i++){ for(j = 0; j < NODES_IN_ELEM; j++){ currentNode = mElems[i][j] - 1; X[j][0] = mNodes[currentNode][0]; X[j][1] = mNodes[currentNode][1]; X[j][2] = mNodes[currentNode][2]; } /* Check for singular case */ test = 0; for(j = 0; j < NODES_IN_ELEM; j++){ dx = X[j][0] - Xin[0]; dy = X[j][1] - Xin[1]; dz = X[j][2] - Xin[2]; if(dx == 0.0 && dy == 0.0 && dz == 0.0){ test = 1; SinNode = j+1; break; } } if(test == 0) intGStk_tria3(X,Xin,Int); else intSingularGStk_tria3(SinNode,X,Xin,Int); /* Add cotribution from each node j in element i */ for(j = 0; j < NODES_IN_ELEM; j++){ xNode = mElems[i][j] - 1; yNode = xNode + nNodes; zNode = yNode + nNodes; U[0] -= Int[0][0][j]*vB[xNode] + Int[0][1][j]*vB[yNode] + /* Ux */ Int[0][2][j]*vB[zNode]; U[1] -= Int[1][0][j]*vB[xNode] + Int[1][1][j]*vB[yNode] + /* Uy */ Int[1][2][j]*vB[zNode]; U[2] -= Int[2][0][j]*vB[xNode] + Int[2][1][j]*vB[yNode] + /* Uz */ Int[2][2][j]*vB[zNode]; } } U[0] = U[0]*factor; U[1] = U[1]*factor; U[2] = U[2]*factor; return 0; }
carlosrosales/stksolver
src/velocity_tria3.c
C
gpl-2.0
4,564
/*********************************************************************** * * avra - Assembler for the Atmel AVR microcontroller series * * Copyright (C) 1998-2004 Jon Anders Haugum, TObias Weber * * 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; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * Authors of avra can be reached at: * email: jonah@omegav.ntnu.no, tobiw@suprafluid.com * www: http://sourceforge.net/projects/avra */ /* * In append_type: added generic register names support * Alexey Pavluchenko, 16.Nov.2005 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "misc.h" #include "args.h" #include "avra.h" #include "device.h" /* Only Windows LIBC does support itoa, so we add this function for other systems here manually. Thank you Peter Hettkamp for your work. */ #ifndef WIN32 char * itoa(int num, char *str, const int number_format) { int num1 = num; int num_chars = 0; int pos; while (num1>0) { num_chars++; num1 /= number_format; } if (num_chars == 0) num_chars = 1; str[num_chars] = 0; for (pos = num_chars-1; pos>=0; pos--) { int cur_char = num % number_format; if (cur_char < 10) /* Insert number */ { str[pos] = cur_char + '0'; } else { str[pos] = cur_char-10 + 'A'; } num /= number_format; } return(str); } #endif int read_macro(struct prog_info *pi, char *name) { int loopok; int i; int start; struct macro *macro; struct macro_line *macro_line; struct macro_line **last_macro_line = NULL; struct macro_label *macro_label; if (pi->pass == PASS_1) { if (!name) { print_msg(pi, MSGTYPE_ERROR, "missing macro name"); return(True); } get_next_token(name, TERM_END); for (i = 0; !IS_END_OR_COMMENT(name[i]); i++) { if (!IS_LABEL(name[i])) { print_msg(pi, MSGTYPE_ERROR, "illegal characters used in macro name '%s'",name); return(False); } } macro = calloc(1, sizeof(struct macro)); if (!macro) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } if (pi->last_macro) pi->last_macro->next = macro; else pi->first_macro = macro; pi->last_macro = macro; macro->name = malloc(strlen(name) + 1); if (!macro->name) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(macro->name, name); macro->include_file = pi->fi->include_file; macro->first_line_number = pi->fi->line_number; last_macro_line = &macro->first_macro_line; } else /* pi->pass == PASS_2 */ { if (pi->list_line && pi->list_on) { fprintf(pi->list_file, " %s\n", pi->list_line); pi->list_line = NULL; } // reset macro label running numbers get_next_token(name, TERM_END); macro = get_macro(pi, name); if (!macro) { print_msg(pi, MSGTYPE_ERROR, "macro inconsistency in '%s'", name); return(True); } for (macro_label = macro->first_label; macro_label; macro_label = macro_label->next) { macro_label->running_number = 0; } } loopok = True; while (loopok) { if (fgets_new(pi,pi->fi->buff, LINEBUFFER_LENGTH, pi->fi->fp)) { pi->fi->line_number++; i = 0; while (IS_HOR_SPACE(pi->fi->buff[i]) && !IS_END_OR_COMMENT(pi->fi->buff[i])) i++; if (pi->fi->buff[i] == '.') { i++; if (!nocase_strncmp(&pi->fi->buff[i], "endm", 4)) loopok = False; if (!nocase_strncmp(&pi->fi->buff[i], "endmacro", 8)) loopok = False; } if (pi->pass == PASS_1) { if (loopok) { i = 0; /* find start of line */ while (IS_HOR_SPACE(pi->fi->buff[i]) && !IS_END_OR_COMMENT(pi->fi->buff[i])) { i++; } start = i; /* find end of line */ while (!IS_END_OR_COMMENT(pi->fi->buff[i]) && (IS_LABEL(pi->fi->buff[i]) || pi->fi->buff[i] == ':')) { i++; } if (pi->fi->buff[i-1] == ':' && (pi->fi->buff[i-2] == '%' && (IS_HOR_SPACE(pi->fi->buff[i]) || IS_END_OR_COMMENT(pi->fi->buff[i])))) { if (macro->first_label) { for (macro_label = macro->first_label; macro_label->next; macro_label=macro_label->next) { } macro_label->next = calloc(1,sizeof(struct macro_label)); macro_label = macro_label->next; } else { macro_label = calloc(1,sizeof(struct macro_label)); macro->first_label = macro_label; } macro_label->label = malloc(strlen(&pi->fi->buff[start])+1); pi->fi->buff[i-1] = '\0'; strcpy(macro_label->label, &pi->fi->buff[start]); pi->fi->buff[i-1] = ':'; macro_label->running_number = 0; } macro_line = calloc(1, sizeof(struct macro_line)); if (!macro_line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } *last_macro_line = macro_line; last_macro_line = &macro_line->next; macro_line->line = malloc(strlen(pi->fi->buff) + 1); if (!macro_line->line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(macro_line->line, &pi->fi->buff[start]); } } else if (pi->fi->buff && pi->list_file && pi->list_on) { if (pi->fi->buff[i] == ';') fprintf(pi->list_file, " %s\n", pi->fi->buff); else fprintf(pi->list_file, " %s\n", pi->fi->buff); } } else { if (feof(pi->fi->fp)) { print_msg(pi, MSGTYPE_ERROR, "Found no closing .ENDMACRO"); return(True); } else { perror(pi->fi->include_file->name); return(False); } } } return(True); } struct macro *get_macro(struct prog_info *pi, char *name) { struct macro *macro; for (macro = pi->first_macro; macro; macro = macro->next) if (!nocase_strcmp(macro->name, name)) return(macro); return(NULL); } void append_type(struct prog_info *pi, char *name, int c, char *value) { int p, l; struct def *def; p = strlen(name); name[p++] = '_'; if (c == 0) { name[p++] = 'v'; name[p] = '\0'; return; } l = strlen(value); if ((l==2 || l==3) && (tolower(value[0])=='r') && isdigit(value[1]) && (l==3 ? isdigit(value[2]) : 1) && (atoi(&value[1])<32)) { itoa((c*8),&name[p],10); return; } for (def = pi->first_def; def; def = def->next) if (!nocase_strcmp(def->name, value)) { itoa((c*8),&name[p],10); return; } name[p++] = 'i'; name[p] = '\0'; } /********************************************************* * This routine replaces the macro call with mnemonics. * *********************************************************/ int expand_macro(struct prog_info *pi, struct macro *macro, char *rest_line) { int ok = True, macro_arg_count = 0, off, a, b = 0, c, i = 0, j = 0; char *line = NULL; char *temp; char *macro_args[MAX_MACRO_ARGS]; char tmp[7]; char buff[LINEBUFFER_LENGTH]; char arg = False; char *nmn; //string buffer for 'n'ew 'm'acro 'n'ame struct macro_line *old_macro_line; struct macro_call *macro_call; struct macro_label *macro_label; if (rest_line) { //we reserve some extra space for extended macro parameters line = malloc(strlen(rest_line) + 20); if (!line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } /* exchange amca word 'src' with YH:YL and 'dst' with ZH:ZL */ for (c = 0, a = strlen(rest_line); c < a; c++) { switch (tolower(rest_line[c])) { case 's': if (IS_SEPARATOR(rest_line[c-1]) && (rest_line[c+1] == 'r') && (rest_line[c+2] == 'c') && IS_SEPARATOR(rest_line[c+3])) { strcpy(&line[b],"YH:YL"); b += 5; c += 2; } else { line[b++] = rest_line[c]; } break; case 'd': if (IS_SEPARATOR(rest_line[c-1]) && (rest_line[c+1] == 's') && (rest_line[c+2] == 't') && IS_SEPARATOR(rest_line[c+3])) { strcpy(&line[b],"ZH:ZL"); b += 5; c += 2; } else { line[b++] = rest_line[c]; } break; // case ';': // break; default: line[b++] = rest_line[c]; } } strcpy(&line[b],"\n"); /* set CR/LF at the end of the line */ /* here we split up the macro arguments into "macro_args" * Extended macro code interpreter added by TW 2002 */ temp = line; /* test for advanced parameters */ if ( temp[0] == '[' ) // there must be "[" " then "]", else it is garbage { if (!strchr(temp, ']')) { print_msg(pi, MSGTYPE_ERROR, "found no closing ']'"); return(False); } // Okay now we are within the advanced code interpreter temp++; // = &temp[1]; // skip the first bracket nmn = malloc(LINEBUFFER_LENGTH); if (!nmn) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(nmn,macro->name); // create a new macro name buffer c = 1; // byte counter arg = True; // loop flag while (arg) { while (IS_HOR_SPACE(temp[0])) //skip leading spaces { temp++; // = &temp[1]; } off = 0; // pointer offset do { switch (temp[off]) //test current character code { case ':': temp[off] = '\0'; if (off > 0) { c++; macro_args[macro_arg_count++] = temp; } else { print_msg(pi, MSGTYPE_ERROR, "missing register before ':'",nmn); return(False); } break; case ']': arg = False; case ',': a = off; do temp[a--] = '\0'; while ( IS_HOR_SPACE(temp[a]) ); if (off > 0) { macro_args[macro_arg_count++] = temp; append_type(pi, nmn, c, temp); c = 1; } else { append_type(pi, nmn, 0, temp); c = 1; } break; default: off++; } } while (temp[off] != '\0'); if (arg) temp = &temp[off+1]; else break; } macro = get_macro(pi,nmn); if (macro == NULL) { print_msg(pi, MSGTYPE_ERROR, "Macro %s is not defined !",nmn); return(False); } free(nmn); } /* or else, we handle the macro as normal macro */ else { line = malloc(strlen(rest_line) + 1); if (!line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(line, rest_line); temp = line; while (temp) { macro_args[macro_arg_count++] = temp; temp = get_next_token(temp, TERM_COMMA); } } } if (pi->pass == PASS_1) { macro_call = calloc(1, sizeof(struct macro_call)); if (!macro_call) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } if (pi->last_macro_call) pi->last_macro_call->next = macro_call; else pi->first_macro_call = macro_call; pi->last_macro_call = macro_call; macro_call->line_number = pi->fi->line_number; macro_call->include_file = pi->fi->include_file; macro_call->macro = macro; macro_call->prev_on_stack = pi->macro_call; if (macro_call->prev_on_stack) { macro_call->nest_level = macro_call->prev_on_stack->nest_level + 1; macro_call->prev_line_index = macro_call->prev_on_stack->line_index; } } else { for (macro_call = pi->first_macro_call; macro_call; macro_call = macro_call->next) { if ((macro_call->include_file->num == pi->fi->include_file->num) && (macro_call->line_number == pi->fi->line_number)) { if (pi->macro_call) { /* Find correct macro_call when using recursion and nesting */ if (macro_call->prev_on_stack == pi->macro_call) if ((macro_call->nest_level == (pi->macro_call->nest_level + 1)) && (macro_call->prev_line_index == pi->macro_call->line_index)) break; } else break; } } if (pi->list_line && pi->list_on) { fprintf(pi->list_file, "C:%06x + %s\n", pi->cseg_addr, pi->list_line); pi->list_line = NULL; } } macro_call->line_index = 0; pi->macro_call = macro_call; old_macro_line = pi->macro_line; //printf("\nconvert macro: '%s'\n",macro->name); for (pi->macro_line = macro->first_macro_line; pi->macro_line && ok; pi->macro_line = pi->macro_line->next) { macro_call->line_index++; if (GET_ARG(pi->args, ARG_LISTMAC)) pi->list_line = buff; else pi->list_line = NULL; /* here we change jumps/calls within macro that corresponds to macro labels. Only in case there is an entry in macro_label list */ strcpy(buff,"\0"); macro_label = get_macro_label(pi->macro_line->line,macro); if (macro_label) { /* test if the right macro label has been found */ temp = strstr(pi->macro_line->line,macro_label->label); c = strlen(macro_label->label); if (temp[c] == ':') /* it is a label definition */ { macro_label->running_number++; strncpy(buff, macro_label->label, c - 1); buff[c - 1] = 0; i = strlen(buff) + 2; /* we set the process indeafter label */ /* add running number to it */ strcpy(&buff[c-1],itoa(macro_label->running_number, tmp, 10)); strcat(buff, ":\0"); } else if (IS_HOR_SPACE(temp[c]) || IS_END_OR_COMMENT(temp[c])) /* it is a jump to a macro defined label */ { strcpy(buff,pi->macro_line->line); temp = strstr(buff, macro_label->label); i = temp - buff + strlen(macro_label->label); strncpy(temp, macro_label->label, c - 1); strcpy(&temp[c-1], itoa(macro_label->running_number, tmp, 10)); } } else { i = 0; } /* here we check every character of current line */ for (j = i; pi->macro_line->line[i] != '\0'; i++) { /* check for register place holders */ if (pi->macro_line->line[i] == '@') { i++; if (!isdigit(pi->macro_line->line[i])) print_msg(pi, MSGTYPE_ERROR, "@ must be followed by a number"); else if ((pi->macro_line->line[i] - '0') >= macro_arg_count) print_msg(pi, MSGTYPE_ERROR, "Missing macro argument (for @%c)", pi->macro_line->line[i]); else { /* and replace them with given registers */ strcat(&buff[j], macro_args[pi->macro_line->line[i] - '0']); j += strlen(macro_args[pi->macro_line->line[i] - '0']); } } else if (pi->macro_line->line[i] == ';') { strncat(buff, "\n", 1); break; } else { strncat(buff, &pi->macro_line->line[i], 1); } } ok = parse_line(pi, buff); if (ok) { if ((pi->pass == PASS_2) && pi->list_line && pi->list_on) fprintf(pi->list_file, " %s\n", pi->list_line); if (pi->error_count >= pi->max_errors) { print_msg(pi, MSGTYPE_MESSAGE, "Maximum error count reached. Exiting..."); ok = False; break; } } } pi->macro_line = old_macro_line; pi->macro_call = macro_call->prev_on_stack; if (rest_line) free(line); return(ok); } struct macro_label *get_macro_label(char *line, struct macro *macro) { char *temp; struct macro_label *macro_label; for (macro_label = macro->first_label; macro_label; macro_label = macro_label->next) { temp = strstr(line,macro_label->label); if (temp) { return macro_label; } } return NULL; } /* end of macro.c */
pearsonalan/avra
src/macro.c
C
gpl-2.0
15,499
/* * linux/init/main.c * * Copyright (C) 1991, 1992 Linus Torvalds * * GK 2/5/95 - Changed to support mounting root fs via NFS * Added initrd & change_root: Werner Almesberger & Hans Lermen, Feb '96 * Moan early if gcc is old, avoiding bogus kernels - Paul Gortmaker, May '96 * Simplified starting of init: Michael A. Griffith <grif@acm.org> */ #define DEBUG #include <linux/types.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/kernel.h> #include <linux/syscalls.h> #include <linux/stackprotector.h> #include <linux/string.h> #include <linux/ctype.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/initrd.h> #include <linux/bootmem.h> #include <linux/acpi.h> #include <linux/tty.h> #include <linux/percpu.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/kernel_stat.h> #include <linux/start_kernel.h> #include <linux/security.h> #include <linux/smp.h> #include <linux/profile.h> #include <linux/rcupdate.h> #include <linux/moduleparam.h> #include <linux/kallsyms.h> #include <linux/writeback.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/cgroup.h> #include <linux/efi.h> #include <linux/tick.h> #include <linux/interrupt.h> #include <linux/taskstats_kern.h> #include <linux/delayacct.h> #include <linux/unistd.h> #include <linux/rmap.h> #include <linux/mempolicy.h> #include <linux/key.h> #include <linux/buffer_head.h> #include <linux/page_cgroup.h> #include <linux/debug_locks.h> #include <linux/debugobjects.h> #include <linux/lockdep.h> #include <linux/kmemleak.h> #include <linux/pid_namespace.h> #include <linux/device.h> #include <linux/kthread.h> #include <linux/sched.h> #include <linux/signal.h> #include <linux/idr.h> #include <linux/kgdb.h> #include <linux/ftrace.h> #include <linux/async.h> #include <linux/kmemcheck.h> #include <linux/sfi.h> #include <linux/shmem_fs.h> #include <linux/slab.h> #include <linux/perf_event.h> #include <linux/file.h> #include <linux/ptrace.h> #include <linux/blkdev.h> #include <linux/elevator.h> #include <linux/sched_clock.h> #include <linux/random.h> #include <asm/io.h> #include <asm/bugs.h> #include <asm/setup.h> #include <asm/sections.h> #include <asm/cacheflush.h> #ifdef CONFIG_X86_LOCAL_APIC #include <asm/smp.h> #endif #ifdef CONFIG_HTC_EARLY_RTB #include <linux/msm_rtb.h> #endif static int kernel_init(void *); extern void init_IRQ(void); extern void fork_init(unsigned long); extern void mca_init(void); extern void sbus_init(void); extern void radix_tree_init(void); #ifndef CONFIG_DEBUG_RODATA static inline void mark_rodata_ro(void) { } #endif #ifdef CONFIG_TC extern void tc_init(void); #endif bool early_boot_irqs_disabled __read_mostly; enum system_states system_state __read_mostly; EXPORT_SYMBOL(system_state); #define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT #define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT extern void time_init(void); void (*__initdata late_time_init)(void); extern void softirq_init(void); char __initdata boot_command_line[COMMAND_LINE_SIZE]; char *saved_command_line; char *hashed_command_line; static char *static_command_line; static char *execute_command; static char *ramdisk_execute_command; unsigned int reset_devices; EXPORT_SYMBOL(reset_devices); static int __init set_reset_devices(char *str) { reset_devices = 1; return 1; } __setup("reset_devices", set_reset_devices); static const char * argv_init[MAX_INIT_ARGS+2] = { "init", NULL, }; const char * envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, }; static const char *panic_later, *panic_param; extern const struct obs_kernel_param __setup_start[], __setup_end[]; static int __init obsolete_checksetup(char *line) { const struct obs_kernel_param *p; int had_early_param = 0; p = __setup_start; do { int n = strlen(p->str); if (parameqn(line, p->str, n)) { if (p->early) { if (line[n] == '\0' || line[n] == '=') had_early_param = 1; } else if (!p->setup_func) { pr_warn("Parameter %s is obsolete, ignored\n", p->str); return 1; } else if (p->setup_func(line + n)) return 1; } p++; } while (p < __setup_end); return had_early_param; } unsigned long loops_per_jiffy = (1<<12); EXPORT_SYMBOL(loops_per_jiffy); static int __init debug_kernel(char *str) { console_loglevel = 10; return 0; } static int __init quiet_kernel(char *str) { console_loglevel = 4; return 0; } early_param("debug", debug_kernel); early_param("quiet", quiet_kernel); static int __init loglevel(char *str) { int newlevel; if (get_option(&str, &newlevel)) { console_loglevel = newlevel; return 0; } return -EINVAL; } early_param("loglevel", loglevel); static int __init repair_env_string(char *param, char *val, const char *unused) { if (val) { if (val == param+strlen(param)+1) val[-1] = '='; else if (val == param+strlen(param)+2) { val[-2] = '='; memmove(val-1, val, strlen(val)+1); val--; } else BUG(); } return 0; } static int __init unknown_bootoption(char *param, char *val, const char *unused) { repair_env_string(param, val, unused); if (obsolete_checksetup(param)) return 0; if (strchr(param, '.') && (!val || strchr(param, '.') < val)) return 0; if (panic_later) return 0; if (val) { unsigned int i; for (i = 0; envp_init[i]; i++) { if (i == MAX_INIT_ENVS) { panic_later = "Too many boot env vars at `%s'"; panic_param = param; } if (!strncmp(param, envp_init[i], val - param)) break; } envp_init[i] = param; } else { unsigned int i; for (i = 0; argv_init[i]; i++) { if (i == MAX_INIT_ARGS) { panic_later = "Too many boot init vars at `%s'"; panic_param = param; } } argv_init[i] = param; } return 0; } static int __init init_setup(char *str) { unsigned int i; execute_command = str; for (i = 1; i < MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } __setup("init=", init_setup); static int __init rdinit_setup(char *str) { unsigned int i; ramdisk_execute_command = str; for (i = 1; i < MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } __setup("rdinit=", rdinit_setup); #ifndef CONFIG_SMP static const unsigned int setup_max_cpus = NR_CPUS; #ifdef CONFIG_X86_LOCAL_APIC static void __init smp_init(void) { APIC_init_uniprocessor(); } #else #define smp_init() do { } while (0) #endif static inline void setup_nr_cpu_ids(void) { } static inline void smp_prepare_cpus(unsigned int maxcpus) { } #endif static void __init setup_command_line(char *command_line) { saved_command_line = alloc_bootmem(strlen (boot_command_line)+1); static_command_line = alloc_bootmem(strlen (command_line)+1); strcpy (saved_command_line, boot_command_line); strcpy (static_command_line, command_line); } #define RAW_SN_LEN 4 static void __init hash_sn(void) { char *p; unsigned int td_sf = 0; size_t cmdline_len, sf_len; cmdline_len = strlen(saved_command_line); sf_len = strlen("td.sf="); hashed_command_line = alloc_bootmem(cmdline_len + 1); strncpy(hashed_command_line, saved_command_line, cmdline_len); hashed_command_line[cmdline_len] = '\0'; p = saved_command_line; for (p = saved_command_line; p < saved_command_line + cmdline_len - sf_len; p++) { if (!strncmp(p, "td.sf=", sf_len)) { p += sf_len; if (*p != '0') td_sf = 1; break; } } if (td_sf) { unsigned int i; size_t sn_len = 0; for (p = hashed_command_line; p < hashed_command_line + cmdline_len - strlen("androidboot.serialno="); p++) { if (!strncmp(p, "androidboot.serialno=", strlen("androidboot.serialno="))) { p += strlen("androidboot.serialno="); while (*p != ' ' && *p != '\0') { sn_len++; p++; } p -= sn_len; for (i = sn_len - 1; i >= RAW_SN_LEN; i--) *p++ = '*'; break; } } } } static __initdata DECLARE_COMPLETION(kthreadd_done); static noinline void __init_refok rest_init(void) { int pid; const struct sched_param param = { .sched_priority = 1 }; rcu_scheduler_starting(); kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND); numa_default_policy(); pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES); rcu_read_lock(); kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns); rcu_read_unlock(); sched_setscheduler_nocheck(kthreadd_task, SCHED_FIFO, &param); complete(&kthreadd_done); init_idle_bootup_task(current); schedule_preempt_disabled(); cpu_startup_entry(CPUHP_ONLINE); } static int __init do_early_param(char *param, char *val, const char *unused) { const struct obs_kernel_param *p; for (p = __setup_start; p < __setup_end; p++) { if ((p->early && parameq(param, p->str)) || (strcmp(param, "console") == 0 && strcmp(p->str, "earlycon") == 0) ) { if (p->setup_func(val) != 0) pr_warn("Malformed early option '%s'\n", param); } } return 0; } void __init parse_early_options(char *cmdline) { parse_args("early options", cmdline, NULL, 0, 0, 0, do_early_param); } void __init parse_early_param(void) { #if defined(CONFIG_EARLY_PRINTK) void deferred_early_console_init(void); #endif static __initdata int done = 0; static __initdata char tmp_cmdline[COMMAND_LINE_SIZE]; if (done) return; strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE); parse_early_options(tmp_cmdline); done = 1; #if defined(CONFIG_EARLY_PRINTK) deferred_early_console_init(); #endif } static void __init boot_cpu_init(void) { int cpu = smp_processor_id(); set_cpu_online(cpu, true); set_cpu_active(cpu, true); set_cpu_present(cpu, true); set_cpu_possible(cpu, true); } void __init __weak smp_setup_processor_id(void) { } # if THREAD_SIZE >= PAGE_SIZE void __init __weak thread_info_cache_init(void) { } #endif static void __init mm_init(void) { page_cgroup_init_flatmem(); mem_init(); kmem_cache_init(); percpu_init_late(); pgtable_cache_init(); vmalloc_init(); } asmlinkage void __init start_kernel(void) { char * command_line; extern const struct kernel_param __start___param[], __stop___param[]; lockdep_init(); smp_setup_processor_id(); debug_objects_early_init(); cgroup_init_early(); local_irq_disable(); early_boot_irqs_disabled = true; boot_cpu_init(); page_address_init(); pr_notice("%s", linux_banner); setup_arch(&command_line); boot_init_stack_canary(); mm_init_owner(&init_mm, &init_task); mm_init_cpumask(&init_mm); setup_command_line(command_line); hash_sn(); setup_nr_cpu_ids(); setup_per_cpu_areas(); smp_prepare_boot_cpu(); build_all_zonelists(NULL, NULL); page_alloc_init(); pr_notice("Kernel command line: %s\n", hashed_command_line); parse_early_param(); parse_args("Booting kernel", static_command_line, __start___param, __stop___param - __start___param, -1, -1, &unknown_bootoption); jump_label_init(); setup_log_buf(0); pidhash_init(); vfs_caches_init_early(); sort_main_extable(); trap_init(); mm_init(); sched_init(); preempt_disable(); if (WARN(!irqs_disabled(), "Interrupts were enabled *very* early, fixing it\n")) local_irq_disable(); idr_init_cache(); perf_event_init(); rcu_init(); tick_nohz_init(); radix_tree_init(); early_irq_init(); init_IRQ(); tick_init(); init_timers(); hrtimers_init(); softirq_init(); timekeeping_init(); time_init(); sched_clock_postinit(); profile_init(); call_function_init(); WARN(!irqs_disabled(), "Interrupts were enabled early\n"); early_boot_irqs_disabled = false; local_irq_enable(); kmem_cache_init_late(); console_init(); if (panic_later) panic(panic_later, panic_param); lockdep_info(); locking_selftest(); #ifdef CONFIG_BLK_DEV_INITRD if (initrd_start && !initrd_below_start_ok && page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) { pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\n", page_to_pfn(virt_to_page((void *)initrd_start)), min_low_pfn); initrd_start = 0; } #endif page_cgroup_init(); debug_objects_mem_init(); kmemleak_init(); setup_per_cpu_pageset(); numa_policy_init(); if (late_time_init) late_time_init(); sched_clock_init(); calibrate_delay(); pidmap_init(); anon_vma_init(); #ifdef CONFIG_X86 if (efi_enabled(EFI_RUNTIME_SERVICES)) efi_enter_virtual_mode(); #endif #ifdef CONFIG_X86_ESPFIX64 init_espfix_bsp(); #endif thread_info_cache_init(); cred_init(); fork_init(totalram_pages); proc_caches_init(); buffer_init(); key_init(); security_init(); dbg_late_init(); vfs_caches_init(totalram_pages); signals_init(); page_writeback_init(); #ifdef CONFIG_PROC_FS proc_root_init(); #endif cgroup_init(); cpuset_init(); taskstats_init_early(); delayacct_init(); check_bugs(); acpi_early_init(); sfi_init_late(); if (efi_enabled(EFI_RUNTIME_SERVICES)) { efi_late_init(); efi_free_boot_services(); } ftrace_init(); rest_init(); } static void __init do_ctors(void) { #ifdef CONFIG_CONSTRUCTORS ctor_fn_t *fn = (ctor_fn_t *) __ctors_start; for (; fn < (ctor_fn_t *) __ctors_end; fn++) (*fn)(); #endif } bool initcall_debug; core_param(initcall_debug, initcall_debug, bool, 0644); static char msgbuf[64]; static int __init_or_module do_one_initcall_debug(initcall_t fn) { ktime_t calltime, delta, rettime; unsigned long long duration; int ret; pr_debug("calling %pF @ %i\n", fn, task_pid_nr(current)); calltime = ktime_get(); ret = fn(); rettime = ktime_get(); delta = ktime_sub(rettime, calltime); duration = (unsigned long long) ktime_to_ns(delta) >> 10; pr_debug("initcall %pF returned %d after %lld usecs\n", fn, ret, duration); return ret; } int __init_or_module do_one_initcall(initcall_t fn) { int count = preempt_count(); int ret; #ifdef CONFIG_HTC_EARLY_RTB uncached_logk_pc(LOGK_INITCALL, (void *)fn, (void *)(0x00000000)); #endif if (initcall_debug) ret = do_one_initcall_debug(fn); else ret = fn(); #ifdef CONFIG_HTC_EARLY_RTB uncached_logk_pc(LOGK_INITCALL, (void *)fn, (void *)(0xffffffff)); #endif msgbuf[0] = 0; if (preempt_count() != count) { sprintf(msgbuf, "preemption imbalance "); preempt_count() = count; } if (irqs_disabled()) { strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf)); local_irq_enable(); } WARN(msgbuf[0], "initcall %pF returned with %s\n", fn, msgbuf); return ret; } extern initcall_t __initcall_start[]; extern initcall_t __initcall0_start[]; extern initcall_t __initcall1_start[]; extern initcall_t __initcall2_start[]; extern initcall_t __initcall3_start[]; extern initcall_t __initcall4_start[]; extern initcall_t __initcall5_start[]; extern initcall_t __initcall6_start[]; extern initcall_t __initcall7_start[]; extern initcall_t __initcall_end[]; static initcall_t *initcall_levels[] __initdata = { __initcall0_start, __initcall1_start, __initcall2_start, __initcall3_start, __initcall4_start, __initcall5_start, __initcall6_start, __initcall7_start, __initcall_end, }; static char *initcall_level_names[] __initdata = { "early", "core", "postcore", "arch", "subsys", "fs", "device", "late", }; static void __init do_initcall_level(int level) { extern const struct kernel_param __start___param[], __stop___param[]; initcall_t *fn; strcpy(static_command_line, saved_command_line); parse_args(initcall_level_names[level], static_command_line, __start___param, __stop___param - __start___param, level, level, &repair_env_string); for (fn = initcall_levels[level]; fn < initcall_levels[level+1]; fn++) do_one_initcall(*fn); } static void __init do_initcalls(void) { int level; for (level = 0; level < ARRAY_SIZE(initcall_levels) - 1; level++) do_initcall_level(level); } static void __init do_basic_setup(void) { cpuset_init_smp(); usermodehelper_init(); shmem_init(); driver_init(); init_irq_proc(); do_ctors(); usermodehelper_enable(); do_initcalls(); random_int_secret_init(); } static void __init do_pre_smp_initcalls(void) { initcall_t *fn; for (fn = __initcall_start; fn < __initcall0_start; fn++) do_one_initcall(*fn); } void __init load_default_modules(void) { load_default_elevator_module(); } static int run_init_process(const char *init_filename) { argv_init[0] = init_filename; return do_execve(init_filename, (const char __user *const __user *)argv_init, (const char __user *const __user *)envp_init); } static noinline void __init kernel_init_freeable(void); static int __ref kernel_init(void *unused) { kernel_init_freeable(); async_synchronize_full(); free_initmem(); mark_rodata_ro(); system_state = SYSTEM_RUNNING; numa_default_policy(); flush_delayed_fput(); if (ramdisk_execute_command) { if (!run_init_process(ramdisk_execute_command)) return 0; pr_err("Failed to execute %s\n", ramdisk_execute_command); } if (execute_command) { if (!run_init_process(execute_command)) return 0; pr_err("Failed to execute %s. Attempting defaults...\n", execute_command); } if (!run_init_process("/sbin/init") || !run_init_process("/etc/init") || !run_init_process("/bin/init") || !run_init_process("/bin/sh")) return 0; panic("No init found. Try passing init= option to kernel. " "See Linux Documentation/init.txt for guidance."); } static noinline void __init kernel_init_freeable(void) { wait_for_completion(&kthreadd_done); gfp_allowed_mask = __GFP_BITS_MASK; set_mems_allowed(node_states[N_MEMORY]); set_cpus_allowed_ptr(current, cpu_all_mask); cad_pid = task_pid(current); smp_prepare_cpus(setup_max_cpus); do_pre_smp_initcalls(); lockup_detector_init(); smp_init(); #ifdef CONFIG_HTC_EARLY_RTB htc_early_rtb_init(); #endif sched_init_smp(); do_basic_setup(); if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0) pr_err("Warning: unable to open an initial console.\n"); (void) sys_dup(0); (void) sys_dup(0); if (!ramdisk_execute_command) ramdisk_execute_command = "/init"; if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) { ramdisk_execute_command = NULL; prepare_namespace(); } load_default_modules(); }
flar2/ElementalX-m9
init/main.c
C
gpl-2.0
18,082
/* Festalon - NSF Player * Copyright (C) 2004 Xodnizel * * 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 <string.h> #include <stdlib.h> #include "../types.h" #include "x6502.h" #include "cart.h" #include "memory.h" /* 16 are (sort of) reserved for UNIF/iNES and 16 to map other stuff. */ static INLINE void setpageptr(NESCART *ca, int s, uint32 A, uint8 *p, int ram) { uint32 AB=A>>11; int x; if(p) for(x=(s>>1)-1;x>=0;x--) { ca->PRGIsRAM[AB+x]=ram; ca->Page[AB+x]=p-A; } else for(x=(s>>1)-1;x>=0;x--) { ca->PRGIsRAM[AB+x]=0; ca->Page[AB+x]=0; } } static uint8 nothing[8192]; void FESTAC_Kill(NESCART *ca) { free(ca); } NESCART *FESTAC_Init(void) { int x; NESCART *ca; if(!(ca=malloc(sizeof(NESCART)))) return(0); memset(ca,0,sizeof(NESCART)); for(x=0;x<32;x++) { ca->Page[x]=nothing-x*2048; ca->PRGptr[x]=0; ca->PRGsize[x]=0; } return(ca); } void FESTAC_SetupPRG(NESCART *ca, int chip, uint8 *p, uint32 size, int ram) { ca->PRGptr[chip]=p; ca->PRGsize[chip]=size; ca->PRGmask2[chip]=(size>>11)-1; ca->PRGmask4[chip]=(size>>12)-1; ca->PRGmask8[chip]=(size>>13)-1; ca->PRGmask16[chip]=(size>>14)-1; ca->PRGmask32[chip]=(size>>15)-1; ca->PRGram[chip]=ram?1:0; } DECLFR(CartBR) { NESCART *ca=private; return ca->Page[A>>11][A]; } DECLFW(CartBW) { NESCART *ca=private; if(ca->PRGIsRAM[A>>11] && ca->Page[A>>11]) ca->Page[A>>11][A]=V; } DECLFR(CartBROB) { NESCART *ca=private; if(!ca->Page[A>>11]) return(DB); return ca->Page[A>>11][A]; } void FASTAPASS(3) setprg2r(NESCART *ca, int r, unsigned int A, unsigned int V) { V&=ca->PRGmask2[r]; setpageptr(ca,2,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<11]):0,ca->PRGram[r]); } void FASTAPASS(2) setprg2(NESCART *ca, uint32 A, uint32 V) { setprg2r(ca,0,A,V); } void FASTAPASS(3) setprg4r(NESCART *ca, int r, unsigned int A, unsigned int V) { V&=ca->PRGmask4[r]; setpageptr(ca,4,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<12]):0,ca->PRGram[r]); } void FASTAPASS(2) setprg4(NESCART *ca, uint32 A, uint32 V) { setprg4r(ca,0,A,V); } void FASTAPASS(3) setprg8r(NESCART *ca, int r, unsigned int A, unsigned int V) { if(ca->PRGsize[r]>=8192) { V&=ca->PRGmask8[r]; setpageptr(ca,8,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<13]):0,ca->PRGram[r]); } else { uint32 VA=V<<2; int x; for(x=0;x<4;x++) setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]); } } void FASTAPASS(2) setprg8(NESCART *ca, uint32 A, uint32 V) { setprg8r(ca,0,A,V); } void FASTAPASS(3) setprg16r(NESCART *ca, int r, unsigned int A, unsigned int V) { if(ca->PRGsize[r]>=16384) { V&=ca->PRGmask16[r]; setpageptr(ca,16,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<14]):0,ca->PRGram[r]); } else { uint32 VA=V<<3; int x; for(x=0;x<8;x++) setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]); } } void FASTAPASS(2) setprg16(NESCART *ca, uint32 A, uint32 V) { setprg16r(ca,0,A,V); } void FASTAPASS(3) setprg32r(NESCART *ca, int r,unsigned int A, unsigned int V) { if(ca->PRGsize[r]>=32768) { V&=ca->PRGmask32[r]; setpageptr(ca,32,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<15]):0,ca->PRGram[r]); } else { uint32 VA=V<<4; int x; for(x=0;x<16;x++) setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]); } } void FASTAPASS(2) setprg32(NESCART *ca, uint32 A, uint32 V) { setprg32r(ca,0,A,V); }
ahefner/festalon
src/nes/cart.c
C
gpl-2.0
4,179
/****************************************************************************** * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110, * USA * * The full GNU General Public License is included in this distribution * in the file called COPYING. * * Contact Information: * Intel Linux Wireless <ilw@linux.intel.com> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * * BSD LICENSE * * Copyright(c) 2012 - 2014 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 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 <linux/etherdevice.h> #include <linux/ip.h> #include <linux/fs.h> #include <net/cfg80211.h> #include <net/ipv6.h> #include <net/tcp.h> #include <net/addrconf.h> #include "iwl-modparams.h" #include "fw-api.h" #include "mvm.h" void iwl_mvm_set_rekey_data(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_gtk_rekey_data *data) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); if (iwlwifi_mod_params.sw_crypto) return; mutex_lock(&mvm->mutex); memcpy(mvmvif->rekey_data.kek, data->kek, NL80211_KEK_LEN); memcpy(mvmvif->rekey_data.kck, data->kck, NL80211_KCK_LEN); mvmvif->rekey_data.replay_ctr = cpu_to_le64(be64_to_cpup((__be64 *)&data->replay_ctr)); mvmvif->rekey_data.valid = true; mutex_unlock(&mvm->mutex); } #if IS_ENABLED(CONFIG_IPV6) void iwl_mvm_ipv6_addr_change(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct inet6_dev *idev) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct inet6_ifaddr *ifa; int idx = 0; read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { mvmvif->target_ipv6_addrs[idx] = ifa->addr; idx++; if (idx >= IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_MAX) break; } read_unlock_bh(&idev->lock); mvmvif->num_target_ipv6_addrs = idx; } #endif void iwl_mvm_set_default_unicast_key(struct ieee80211_hw *hw, struct ieee80211_vif *vif, int idx) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); mvmvif->tx_key_idx = idx; } static void iwl_mvm_convert_p1k(u16 *p1k, __le16 *out) { int i; for (i = 0; i < IWL_P1K_SIZE; i++) out[i] = cpu_to_le16(p1k[i]); } struct wowlan_key_data { struct iwl_wowlan_rsc_tsc_params_cmd *rsc_tsc; struct iwl_wowlan_tkip_params_cmd *tkip; bool error, use_rsc_tsc, use_tkip; int wep_key_idx; }; static void iwl_mvm_wowlan_program_keys(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key, void *_data) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct wowlan_key_data *data = _data; struct aes_sc *aes_sc, *aes_tx_sc = NULL; struct tkip_sc *tkip_sc, *tkip_tx_sc = NULL; struct iwl_p1k_cache *rx_p1ks; u8 *rx_mic_key; struct ieee80211_key_seq seq; u32 cur_rx_iv32 = 0; u16 p1k[IWL_P1K_SIZE]; int ret, i; mutex_lock(&mvm->mutex); switch (key->cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: { /* hack it for now */ struct { struct iwl_mvm_wep_key_cmd wep_key_cmd; struct iwl_mvm_wep_key wep_key; } __packed wkc = { .wep_key_cmd.mac_id_n_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)), .wep_key_cmd.num_keys = 1, /* firmware sets STA_KEY_FLG_WEP_13BYTES */ .wep_key_cmd.decryption_type = STA_KEY_FLG_WEP, .wep_key.key_index = key->keyidx, .wep_key.key_size = key->keylen, }; /* * This will fail -- the key functions don't set support * pairwise WEP keys. However, that's better than silently * failing WoWLAN. Or maybe not? */ if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) break; memcpy(&wkc.wep_key.key[3], key->key, key->keylen); if (key->keyidx == mvmvif->tx_key_idx) { /* TX key must be at offset 0 */ wkc.wep_key.key_offset = 0; } else { /* others start at 1 */ data->wep_key_idx++; wkc.wep_key.key_offset = data->wep_key_idx; } ret = iwl_mvm_send_cmd_pdu(mvm, WEP_KEY, CMD_SYNC, sizeof(wkc), &wkc); data->error = ret != 0; mvm->ptk_ivlen = key->iv_len; mvm->ptk_icvlen = key->icv_len; mvm->gtk_ivlen = key->iv_len; mvm->gtk_icvlen = key->icv_len; /* don't upload key again */ goto out_unlock; } default: data->error = true; goto out_unlock; case WLAN_CIPHER_SUITE_AES_CMAC: /* * Ignore CMAC keys -- the WoWLAN firmware doesn't support them * but we also shouldn't abort suspend due to that. It does have * support for the IGTK key renewal, but doesn't really use the * IGTK for anything. This means we could spuriously wake up or * be deauthenticated, but that was considered acceptable. */ goto out_unlock; case WLAN_CIPHER_SUITE_TKIP: if (sta) { tkip_sc = data->rsc_tsc->all_tsc_rsc.tkip.unicast_rsc; tkip_tx_sc = &data->rsc_tsc->all_tsc_rsc.tkip.tsc; rx_p1ks = data->tkip->rx_uni; ieee80211_get_key_tx_seq(key, &seq); tkip_tx_sc->iv16 = cpu_to_le16(seq.tkip.iv16); tkip_tx_sc->iv32 = cpu_to_le32(seq.tkip.iv32); ieee80211_get_tkip_p1k_iv(key, seq.tkip.iv32, p1k); iwl_mvm_convert_p1k(p1k, data->tkip->tx.p1k); memcpy(data->tkip->mic_keys.tx, &key->key[NL80211_TKIP_DATA_OFFSET_TX_MIC_KEY], IWL_MIC_KEY_SIZE); rx_mic_key = data->tkip->mic_keys.rx_unicast; } else { tkip_sc = data->rsc_tsc->all_tsc_rsc.tkip.multicast_rsc; rx_p1ks = data->tkip->rx_multi; rx_mic_key = data->tkip->mic_keys.rx_mcast; } /* * For non-QoS this relies on the fact that both the uCode and * mac80211 use TID 0 (as they need to to avoid replay attacks) * for checking the IV in the frames. */ for (i = 0; i < IWL_NUM_RSC; i++) { ieee80211_get_key_rx_seq(key, i, &seq); tkip_sc[i].iv16 = cpu_to_le16(seq.tkip.iv16); tkip_sc[i].iv32 = cpu_to_le32(seq.tkip.iv32); /* wrapping isn't allowed, AP must rekey */ if (seq.tkip.iv32 > cur_rx_iv32) cur_rx_iv32 = seq.tkip.iv32; } ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid, cur_rx_iv32, p1k); iwl_mvm_convert_p1k(p1k, rx_p1ks[0].p1k); ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid, cur_rx_iv32 + 1, p1k); iwl_mvm_convert_p1k(p1k, rx_p1ks[1].p1k); memcpy(rx_mic_key, &key->key[NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY], IWL_MIC_KEY_SIZE); data->use_tkip = true; data->use_rsc_tsc = true; break; case WLAN_CIPHER_SUITE_CCMP: if (sta) { u8 *pn = seq.ccmp.pn; aes_sc = data->rsc_tsc->all_tsc_rsc.aes.unicast_rsc; aes_tx_sc = &data->rsc_tsc->all_tsc_rsc.aes.tsc; ieee80211_get_key_tx_seq(key, &seq); aes_tx_sc->pn = cpu_to_le64((u64)pn[5] | ((u64)pn[4] << 8) | ((u64)pn[3] << 16) | ((u64)pn[2] << 24) | ((u64)pn[1] << 32) | ((u64)pn[0] << 40)); } else { aes_sc = data->rsc_tsc->all_tsc_rsc.aes.multicast_rsc; } /* * For non-QoS this relies on the fact that both the uCode and * mac80211 use TID 0 for checking the IV in the frames. */ for (i = 0; i < IWL_NUM_RSC; i++) { u8 *pn = seq.ccmp.pn; ieee80211_get_key_rx_seq(key, i, &seq); aes_sc->pn = cpu_to_le64((u64)pn[5] | ((u64)pn[4] << 8) | ((u64)pn[3] << 16) | ((u64)pn[2] << 24) | ((u64)pn[1] << 32) | ((u64)pn[0] << 40)); } data->use_rsc_tsc = true; break; } /* * The D3 firmware hardcodes the key offset 0 as the key it uses * to transmit packets to the AP, i.e. the PTK. */ if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) { key->hw_key_idx = 0; mvm->ptk_ivlen = key->iv_len; mvm->ptk_icvlen = key->icv_len; } else { /* * firmware only supports TSC/RSC for a single key, * so if there are multiple keep overwriting them * with new ones -- this relies on mac80211 doing * list_add_tail(). */ key->hw_key_idx = 1; mvm->gtk_ivlen = key->iv_len; mvm->gtk_icvlen = key->icv_len; } ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, true); data->error = ret != 0; out_unlock: mutex_unlock(&mvm->mutex); } static int iwl_mvm_send_patterns(struct iwl_mvm *mvm, struct cfg80211_wowlan *wowlan) { struct iwl_wowlan_patterns_cmd *pattern_cmd; struct iwl_host_cmd cmd = { .id = WOWLAN_PATTERNS, .dataflags[0] = IWL_HCMD_DFL_NOCOPY, .flags = CMD_SYNC, }; int i, err; if (!wowlan->n_patterns) return 0; cmd.len[0] = sizeof(*pattern_cmd) + wowlan->n_patterns * sizeof(struct iwl_wowlan_pattern); pattern_cmd = kmalloc(cmd.len[0], GFP_KERNEL); if (!pattern_cmd) return -ENOMEM; pattern_cmd->n_patterns = cpu_to_le32(wowlan->n_patterns); for (i = 0; i < wowlan->n_patterns; i++) { int mask_len = DIV_ROUND_UP(wowlan->patterns[i].pattern_len, 8); memcpy(&pattern_cmd->patterns[i].mask, wowlan->patterns[i].mask, mask_len); memcpy(&pattern_cmd->patterns[i].pattern, wowlan->patterns[i].pattern, wowlan->patterns[i].pattern_len); pattern_cmd->patterns[i].mask_size = mask_len; pattern_cmd->patterns[i].pattern_size = wowlan->patterns[i].pattern_len; } cmd.data[0] = pattern_cmd; err = iwl_mvm_send_cmd(mvm, &cmd); kfree(pattern_cmd); return err; } static int iwl_mvm_send_proto_offload(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { union { struct iwl_proto_offload_cmd_v1 v1; struct iwl_proto_offload_cmd_v2 v2; struct iwl_proto_offload_cmd_v3_small v3s; struct iwl_proto_offload_cmd_v3_large v3l; } cmd = {}; struct iwl_host_cmd hcmd = { .id = PROT_OFFLOAD_CONFIG_CMD, .flags = CMD_SYNC, .data[0] = &cmd, .dataflags[0] = IWL_HCMD_DFL_DUP, }; struct iwl_proto_offload_cmd_common *common; u32 enabled = 0, size; u32 capa_flags = mvm->fw->ucode_capa.flags; #if IS_ENABLED(CONFIG_IPV6) struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); int i; if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL || capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_LARGE) { struct iwl_ns_config *nsc; struct iwl_targ_addr *addrs; int n_nsc, n_addrs; int c; if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL) { nsc = cmd.v3s.ns_config; n_nsc = IWL_PROTO_OFFLOAD_NUM_NS_CONFIG_V3S; addrs = cmd.v3s.targ_addrs; n_addrs = IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V3S; } else { nsc = cmd.v3l.ns_config; n_nsc = IWL_PROTO_OFFLOAD_NUM_NS_CONFIG_V3L; addrs = cmd.v3l.targ_addrs; n_addrs = IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V3L; } if (mvmvif->num_target_ipv6_addrs) enabled |= IWL_D3_PROTO_OFFLOAD_NS; /* * For each address we have (and that will fit) fill a target * address struct and combine for NS offload structs with the * solicited node addresses. */ for (i = 0, c = 0; i < mvmvif->num_target_ipv6_addrs && i < n_addrs && c < n_nsc; i++) { struct in6_addr solicited_addr; int j; addrconf_addr_solict_mult(&mvmvif->target_ipv6_addrs[i], &solicited_addr); for (j = 0; j < c; j++) if (ipv6_addr_cmp(&nsc[j].dest_ipv6_addr, &solicited_addr) == 0) break; if (j == c) c++; addrs[i].addr = mvmvif->target_ipv6_addrs[i]; addrs[i].config_num = cpu_to_le32(j); nsc[j].dest_ipv6_addr = solicited_addr; memcpy(nsc[j].target_mac_addr, vif->addr, ETH_ALEN); } if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL) cmd.v3s.num_valid_ipv6_addrs = cpu_to_le32(i); else cmd.v3l.num_valid_ipv6_addrs = cpu_to_le32(i); } else if (capa_flags & IWL_UCODE_TLV_FLAGS_D3_6_IPV6_ADDRS) { if (mvmvif->num_target_ipv6_addrs) { enabled |= IWL_D3_PROTO_OFFLOAD_NS; memcpy(cmd.v2.ndp_mac_addr, vif->addr, ETH_ALEN); } BUILD_BUG_ON(sizeof(cmd.v2.target_ipv6_addr[0]) != sizeof(mvmvif->target_ipv6_addrs[0])); for (i = 0; i < min(mvmvif->num_target_ipv6_addrs, IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V2); i++) memcpy(cmd.v2.target_ipv6_addr[i], &mvmvif->target_ipv6_addrs[i], sizeof(cmd.v2.target_ipv6_addr[i])); } else { if (mvmvif->num_target_ipv6_addrs) { enabled |= IWL_D3_PROTO_OFFLOAD_NS; memcpy(cmd.v1.ndp_mac_addr, vif->addr, ETH_ALEN); } BUILD_BUG_ON(sizeof(cmd.v1.target_ipv6_addr[0]) != sizeof(mvmvif->target_ipv6_addrs[0])); for (i = 0; i < min(mvmvif->num_target_ipv6_addrs, IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V1); i++) memcpy(cmd.v1.target_ipv6_addr[i], &mvmvif->target_ipv6_addrs[i], sizeof(cmd.v1.target_ipv6_addr[i])); } #endif if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL) { common = &cmd.v3s.common; size = sizeof(cmd.v3s); } else if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_LARGE) { common = &cmd.v3l.common; size = sizeof(cmd.v3l); } else if (capa_flags & IWL_UCODE_TLV_FLAGS_D3_6_IPV6_ADDRS) { common = &cmd.v2.common; size = sizeof(cmd.v2); } else { common = &cmd.v1.common; size = sizeof(cmd.v1); } if (vif->bss_conf.arp_addr_cnt) { enabled |= IWL_D3_PROTO_OFFLOAD_ARP; common->host_ipv4_addr = vif->bss_conf.arp_addr_list[0]; memcpy(common->arp_mac_addr, vif->addr, ETH_ALEN); } if (!enabled) return 0; common->enabled = cpu_to_le32(enabled); hcmd.len[0] = size; return iwl_mvm_send_cmd(mvm, &hcmd); } enum iwl_mvm_tcp_packet_type { MVM_TCP_TX_SYN, MVM_TCP_RX_SYNACK, MVM_TCP_TX_DATA, MVM_TCP_RX_ACK, MVM_TCP_RX_WAKE, MVM_TCP_TX_FIN, }; static __le16 pseudo_hdr_check(int len, __be32 saddr, __be32 daddr) { __sum16 check = tcp_v4_check(len, saddr, daddr, 0); return cpu_to_le16(be16_to_cpu((__force __be16)check)); } static void iwl_mvm_build_tcp_packet(struct ieee80211_vif *vif, struct cfg80211_wowlan_tcp *tcp, void *_pkt, u8 *mask, __le16 *pseudo_hdr_csum, enum iwl_mvm_tcp_packet_type ptype) { struct { struct ethhdr eth; struct iphdr ip; struct tcphdr tcp; u8 data[]; } __packed *pkt = _pkt; u16 ip_tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr); int i; pkt->eth.h_proto = cpu_to_be16(ETH_P_IP), pkt->ip.version = 4; pkt->ip.ihl = 5; pkt->ip.protocol = IPPROTO_TCP; switch (ptype) { case MVM_TCP_TX_SYN: case MVM_TCP_TX_DATA: case MVM_TCP_TX_FIN: memcpy(pkt->eth.h_dest, tcp->dst_mac, ETH_ALEN); memcpy(pkt->eth.h_source, vif->addr, ETH_ALEN); pkt->ip.ttl = 128; pkt->ip.saddr = tcp->src; pkt->ip.daddr = tcp->dst; pkt->tcp.source = cpu_to_be16(tcp->src_port); pkt->tcp.dest = cpu_to_be16(tcp->dst_port); /* overwritten for TX SYN later */ pkt->tcp.doff = sizeof(struct tcphdr) / 4; pkt->tcp.window = cpu_to_be16(65000); break; case MVM_TCP_RX_SYNACK: case MVM_TCP_RX_ACK: case MVM_TCP_RX_WAKE: memcpy(pkt->eth.h_dest, vif->addr, ETH_ALEN); memcpy(pkt->eth.h_source, tcp->dst_mac, ETH_ALEN); pkt->ip.saddr = tcp->dst; pkt->ip.daddr = tcp->src; pkt->tcp.source = cpu_to_be16(tcp->dst_port); pkt->tcp.dest = cpu_to_be16(tcp->src_port); break; default: WARN_ON(1); return; } switch (ptype) { case MVM_TCP_TX_SYN: /* firmware assumes 8 option bytes - 8 NOPs for now */ memset(pkt->data, 0x01, 8); ip_tot_len += 8; pkt->tcp.doff = (sizeof(struct tcphdr) + 8) / 4; pkt->tcp.syn = 1; break; case MVM_TCP_TX_DATA: ip_tot_len += tcp->payload_len; memcpy(pkt->data, tcp->payload, tcp->payload_len); pkt->tcp.psh = 1; pkt->tcp.ack = 1; break; case MVM_TCP_TX_FIN: pkt->tcp.fin = 1; pkt->tcp.ack = 1; break; case MVM_TCP_RX_SYNACK: pkt->tcp.syn = 1; pkt->tcp.ack = 1; break; case MVM_TCP_RX_ACK: pkt->tcp.ack = 1; break; case MVM_TCP_RX_WAKE: ip_tot_len += tcp->wake_len; pkt->tcp.psh = 1; pkt->tcp.ack = 1; memcpy(pkt->data, tcp->wake_data, tcp->wake_len); break; } switch (ptype) { case MVM_TCP_TX_SYN: case MVM_TCP_TX_DATA: case MVM_TCP_TX_FIN: pkt->ip.tot_len = cpu_to_be16(ip_tot_len); pkt->ip.check = ip_fast_csum(&pkt->ip, pkt->ip.ihl); break; case MVM_TCP_RX_WAKE: for (i = 0; i < DIV_ROUND_UP(tcp->wake_len, 8); i++) { u8 tmp = tcp->wake_mask[i]; mask[i + 6] |= tmp << 6; if (i + 1 < DIV_ROUND_UP(tcp->wake_len, 8)) mask[i + 7] = tmp >> 2; } /* fall through for ethernet/IP/TCP headers mask */ case MVM_TCP_RX_SYNACK: case MVM_TCP_RX_ACK: mask[0] = 0xff; /* match ethernet */ /* * match ethernet, ip.version, ip.ihl * the ip.ihl half byte is really masked out by firmware */ mask[1] = 0x7f; mask[2] = 0x80; /* match ip.protocol */ mask[3] = 0xfc; /* match ip.saddr, ip.daddr */ mask[4] = 0x3f; /* match ip.daddr, tcp.source, tcp.dest */ mask[5] = 0x80; /* match tcp flags */ /* leave rest (0 or set for MVM_TCP_RX_WAKE) */ break; }; *pseudo_hdr_csum = pseudo_hdr_check(ip_tot_len - sizeof(struct iphdr), pkt->ip.saddr, pkt->ip.daddr); } static int iwl_mvm_send_remote_wake_cfg(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct cfg80211_wowlan_tcp *tcp) { struct iwl_wowlan_remote_wake_config *cfg; struct iwl_host_cmd cmd = { .id = REMOTE_WAKE_CONFIG_CMD, .len = { sizeof(*cfg), }, .dataflags = { IWL_HCMD_DFL_NOCOPY, }, .flags = CMD_SYNC, }; int ret; if (!tcp) return 0; cfg = kzalloc(sizeof(*cfg), GFP_KERNEL); if (!cfg) return -ENOMEM; cmd.data[0] = cfg; cfg->max_syn_retries = 10; cfg->max_data_retries = 10; cfg->tcp_syn_ack_timeout = 1; /* seconds */ cfg->tcp_ack_timeout = 1; /* seconds */ /* SYN (TX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->syn_tx.data, NULL, &cfg->syn_tx.info.tcp_pseudo_header_checksum, MVM_TCP_TX_SYN); cfg->syn_tx.info.tcp_payload_length = 0; /* SYN/ACK (RX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->synack_rx.data, cfg->synack_rx.rx_mask, &cfg->synack_rx.info.tcp_pseudo_header_checksum, MVM_TCP_RX_SYNACK); cfg->synack_rx.info.tcp_payload_length = 0; /* KEEPALIVE/ACK (TX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->keepalive_tx.data, NULL, &cfg->keepalive_tx.info.tcp_pseudo_header_checksum, MVM_TCP_TX_DATA); cfg->keepalive_tx.info.tcp_payload_length = cpu_to_le16(tcp->payload_len); cfg->sequence_number_offset = tcp->payload_seq.offset; /* length must be 0..4, the field is little endian */ cfg->sequence_number_length = tcp->payload_seq.len; cfg->initial_sequence_number = cpu_to_le32(tcp->payload_seq.start); cfg->keepalive_interval = cpu_to_le16(tcp->data_interval); if (tcp->payload_tok.len) { cfg->token_offset = tcp->payload_tok.offset; cfg->token_length = tcp->payload_tok.len; cfg->num_tokens = cpu_to_le16(tcp->tokens_size % tcp->payload_tok.len); memcpy(cfg->tokens, tcp->payload_tok.token_stream, tcp->tokens_size); } else { /* set tokens to max value to almost never run out */ cfg->num_tokens = cpu_to_le16(65535); } /* ACK (RX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->keepalive_ack_rx.data, cfg->keepalive_ack_rx.rx_mask, &cfg->keepalive_ack_rx.info.tcp_pseudo_header_checksum, MVM_TCP_RX_ACK); cfg->keepalive_ack_rx.info.tcp_payload_length = 0; /* WAKEUP (RX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->wake_rx.data, cfg->wake_rx.rx_mask, &cfg->wake_rx.info.tcp_pseudo_header_checksum, MVM_TCP_RX_WAKE); cfg->wake_rx.info.tcp_payload_length = cpu_to_le16(tcp->wake_len); /* FIN */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->fin_tx.data, NULL, &cfg->fin_tx.info.tcp_pseudo_header_checksum, MVM_TCP_TX_FIN); cfg->fin_tx.info.tcp_payload_length = 0; ret = iwl_mvm_send_cmd(mvm, &cmd); kfree(cfg); return ret; } struct iwl_d3_iter_data { struct iwl_mvm *mvm; struct ieee80211_vif *vif; bool error; }; static void iwl_mvm_d3_iface_iterator(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_d3_iter_data *data = _data; struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); if (vif->type != NL80211_IFTYPE_STATION || vif->p2p) return; if (mvmvif->ap_sta_id == IWL_MVM_STATION_COUNT) return; if (data->vif) { IWL_ERR(data->mvm, "More than one managed interface active!\n"); data->error = true; return; } data->vif = vif; } static int iwl_mvm_d3_reprogram(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct ieee80211_sta *ap_sta) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct ieee80211_chanctx_conf *ctx; u8 chains_static, chains_dynamic; struct cfg80211_chan_def chandef; int ret, i; struct iwl_binding_cmd binding_cmd = {}; struct iwl_time_quota_cmd quota_cmd = {}; u32 status; /* add back the PHY */ if (WARN_ON(!mvmvif->phy_ctxt)) return -EINVAL; rcu_read_lock(); ctx = rcu_dereference(vif->chanctx_conf); if (WARN_ON(!ctx)) { rcu_read_unlock(); return -EINVAL; } chandef = ctx->def; chains_static = ctx->rx_chains_static; chains_dynamic = ctx->rx_chains_dynamic; rcu_read_unlock(); ret = iwl_mvm_phy_ctxt_add(mvm, mvmvif->phy_ctxt, &chandef, chains_static, chains_dynamic); if (ret) return ret; /* add back the MAC */ mvmvif->uploaded = false; if (WARN_ON(!vif->bss_conf.assoc)) return -EINVAL; /* hack */ vif->bss_conf.assoc = false; ret = iwl_mvm_mac_ctxt_add(mvm, vif); vif->bss_conf.assoc = true; if (ret) return ret; /* add back binding - XXX refactor? */ binding_cmd.id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id, mvmvif->phy_ctxt->color)); binding_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD); binding_cmd.phy = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id, mvmvif->phy_ctxt->color)); binding_cmd.macs[0] = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)); for (i = 1; i < MAX_MACS_IN_BINDING; i++) binding_cmd.macs[i] = cpu_to_le32(FW_CTXT_INVALID); status = 0; ret = iwl_mvm_send_cmd_pdu_status(mvm, BINDING_CONTEXT_CMD, sizeof(binding_cmd), &binding_cmd, &status); if (ret) { IWL_ERR(mvm, "Failed to add binding: %d\n", ret); return ret; } if (status) { IWL_ERR(mvm, "Binding command failed: %u\n", status); return -EIO; } ret = iwl_mvm_sta_send_to_fw(mvm, ap_sta, false); if (ret) return ret; rcu_assign_pointer(mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], ap_sta); ret = iwl_mvm_mac_ctxt_changed(mvm, vif); if (ret) return ret; /* and some quota */ quota_cmd.quotas[0].id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id, mvmvif->phy_ctxt->color)); quota_cmd.quotas[0].quota = cpu_to_le32(100); quota_cmd.quotas[0].max_duration = cpu_to_le32(1000); for (i = 1; i < MAX_BINDINGS; i++) quota_cmd.quotas[i].id_and_color = cpu_to_le32(FW_CTXT_INVALID); ret = iwl_mvm_send_cmd_pdu(mvm, TIME_QUOTA_CMD, CMD_SYNC, sizeof(quota_cmd), &quota_cmd); if (ret) IWL_ERR(mvm, "Failed to send quota: %d\n", ret); return 0; } static int iwl_mvm_get_last_nonqos_seq(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_nonqos_seq_query_cmd query_cmd = { .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_GET), .mac_id_n_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)), }; struct iwl_host_cmd cmd = { .id = NON_QOS_TX_COUNTER_CMD, .flags = CMD_SYNC | CMD_WANT_SKB, }; int err; u32 size; if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) { cmd.data[0] = &query_cmd; cmd.len[0] = sizeof(query_cmd); } err = iwl_mvm_send_cmd(mvm, &cmd); if (err) return err; size = le32_to_cpu(cmd.resp_pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK; size -= sizeof(cmd.resp_pkt->hdr); if (size < sizeof(__le16)) { err = -EINVAL; } else { err = le16_to_cpup((__le16 *)cmd.resp_pkt->data); /* new API returns next, not last-used seqno */ if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) err = (u16) (err - 0x10); } iwl_free_resp(&cmd); return err; } void iwl_mvm_set_last_nonqos_seq(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_nonqos_seq_query_cmd query_cmd = { .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_SET), .mac_id_n_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)), .value = cpu_to_le16(mvmvif->seqno), }; /* return if called during restart, not resume from D3 */ if (!mvmvif->seqno_valid) return; mvmvif->seqno_valid = false; if (!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API)) return; if (iwl_mvm_send_cmd_pdu(mvm, NON_QOS_TX_COUNTER_CMD, CMD_SYNC, sizeof(query_cmd), &query_cmd)) IWL_ERR(mvm, "failed to set non-QoS seqno\n"); } static int __iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan, bool test) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); struct iwl_d3_iter_data suspend_iter_data = { .mvm = mvm, }; struct ieee80211_vif *vif; struct iwl_mvm_vif *mvmvif; struct ieee80211_sta *ap_sta; struct iwl_mvm_sta *mvm_ap_sta; struct iwl_wowlan_config_cmd wowlan_config_cmd = {}; struct iwl_wowlan_kek_kck_material_cmd kek_kck_cmd = {}; struct iwl_wowlan_tkip_params_cmd tkip_cmd = {}; struct iwl_d3_manager_config d3_cfg_cmd_data = { /* * Program the minimum sleep time to 10 seconds, as many * platforms have issues processing a wakeup signal while * still being in the process of suspending. */ .min_sleep_time = cpu_to_le32(10 * 1000 * 1000), }; struct iwl_host_cmd d3_cfg_cmd = { .id = D3_CONFIG_CMD, .flags = CMD_SYNC | CMD_WANT_SKB, .data[0] = &d3_cfg_cmd_data, .len[0] = sizeof(d3_cfg_cmd_data), }; struct wowlan_key_data key_data = { .use_rsc_tsc = false, .tkip = &tkip_cmd, .use_tkip = false, }; int ret, i; int len __maybe_unused; u8 old_aux_sta_id, old_ap_sta_id = IWL_MVM_STATION_COUNT; if (!wowlan) { /* * mac80211 shouldn't get here, but for D3 test * it doesn't warrant a warning */ WARN_ON(!test); return -EINVAL; } key_data.rsc_tsc = kzalloc(sizeof(*key_data.rsc_tsc), GFP_KERNEL); if (!key_data.rsc_tsc) return -ENOMEM; mutex_lock(&mvm->mutex); old_aux_sta_id = mvm->aux_sta.sta_id; /* see if there's only a single BSS vif and it's associated */ ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_iface_iterator, &suspend_iter_data); if (suspend_iter_data.error || !suspend_iter_data.vif) { ret = 1; goto out_noreset; } vif = suspend_iter_data.vif; mvmvif = iwl_mvm_vif_from_mac80211(vif); ap_sta = rcu_dereference_protected( mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], lockdep_is_held(&mvm->mutex)); if (IS_ERR_OR_NULL(ap_sta)) { ret = -EINVAL; goto out_noreset; } mvm_ap_sta = (struct iwl_mvm_sta *)ap_sta->drv_priv; /* TODO: wowlan_config_cmd.wowlan_ba_teardown_tids */ wowlan_config_cmd.is_11n_connection = ap_sta->ht_cap.ht_supported; /* Query the last used seqno and set it */ ret = iwl_mvm_get_last_nonqos_seq(mvm, vif); if (ret < 0) goto out_noreset; wowlan_config_cmd.non_qos_seq = cpu_to_le16(ret); /* * For QoS counters, we store the one to use next, so subtract 0x10 * since the uCode will add 0x10 *before* using the value while we * increment after using the value (i.e. store the next value to use). */ for (i = 0; i < IWL_MAX_TID_COUNT; i++) { u16 seq = mvm_ap_sta->tid_data[i].seq_number; seq -= 0x10; wowlan_config_cmd.qos_seq[i] = cpu_to_le16(seq); } if (wowlan->disconnect) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS | IWL_WOWLAN_WAKEUP_LINK_CHANGE); if (wowlan->magic_pkt) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_MAGIC_PACKET); if (wowlan->gtk_rekey_failure) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_GTK_REKEY_FAIL); if (wowlan->eap_identity_req) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_EAP_IDENT_REQ); if (wowlan->four_way_handshake) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_4WAY_HANDSHAKE); if (wowlan->n_patterns) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_PATTERN_MATCH); if (wowlan->rfkill_release) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT); if (wowlan->tcp) { /* * Set the "link change" (really "link lost") flag as well * since that implies losing the TCP connection. */ wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_REMOTE_LINK_LOSS | IWL_WOWLAN_WAKEUP_REMOTE_SIGNATURE_TABLE | IWL_WOWLAN_WAKEUP_REMOTE_WAKEUP_PACKET | IWL_WOWLAN_WAKEUP_LINK_CHANGE); } iwl_mvm_cancel_scan(mvm); iwl_trans_stop_device(mvm->trans); /* * The D3 firmware still hardcodes the AP station ID for the * BSS we're associated with as 0. Store the real STA ID here * and assign 0. When we leave this function, we'll restore * the original value for the resume code. */ old_ap_sta_id = mvm_ap_sta->sta_id; mvm_ap_sta->sta_id = 0; mvmvif->ap_sta_id = 0; /* * Set the HW restart bit -- this is mostly true as we're * going to load new firmware and reprogram that, though * the reprogramming is going to be manual to avoid adding * all the MACs that aren't support. * We don't have to clear up everything though because the * reprogramming is manual. When we resume, we'll actually * go through a proper restart sequence again to switch * back to the runtime firmware image. */ set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status); /* We reprogram keys and shouldn't allocate new key indices */ memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table)); mvm->ptk_ivlen = 0; mvm->ptk_icvlen = 0; mvm->ptk_ivlen = 0; mvm->ptk_icvlen = 0; /* * The D3 firmware still hardcodes the AP station ID for the * BSS we're associated with as 0. As a result, we have to move * the auxiliary station to ID 1 so the ID 0 remains free for * the AP station for later. * We set the sta_id to 1 here, and reset it to its previous * value (that we stored above) later. */ mvm->aux_sta.sta_id = 1; ret = iwl_mvm_load_d3_fw(mvm); if (ret) goto out; ret = iwl_mvm_d3_reprogram(mvm, vif, ap_sta); if (ret) goto out; if (!iwlwifi_mod_params.sw_crypto) { /* * This needs to be unlocked due to lock ordering * constraints. Since we're in the suspend path * that isn't really a problem though. */ mutex_unlock(&mvm->mutex); ieee80211_iter_keys(mvm->hw, vif, iwl_mvm_wowlan_program_keys, &key_data); mutex_lock(&mvm->mutex); if (key_data.error) { ret = -EIO; goto out; } if (key_data.use_rsc_tsc) { struct iwl_host_cmd rsc_tsc_cmd = { .id = WOWLAN_TSC_RSC_PARAM, .flags = CMD_SYNC, .data[0] = key_data.rsc_tsc, .dataflags[0] = IWL_HCMD_DFL_NOCOPY, .len[0] = sizeof(*key_data.rsc_tsc), }; ret = iwl_mvm_send_cmd(mvm, &rsc_tsc_cmd); if (ret) goto out; } if (key_data.use_tkip) { ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_TKIP_PARAM, CMD_SYNC, sizeof(tkip_cmd), &tkip_cmd); if (ret) goto out; } if (mvmvif->rekey_data.valid) { memset(&kek_kck_cmd, 0, sizeof(kek_kck_cmd)); memcpy(kek_kck_cmd.kck, mvmvif->rekey_data.kck, NL80211_KCK_LEN); kek_kck_cmd.kck_len = cpu_to_le16(NL80211_KCK_LEN); memcpy(kek_kck_cmd.kek, mvmvif->rekey_data.kek, NL80211_KEK_LEN); kek_kck_cmd.kek_len = cpu_to_le16(NL80211_KEK_LEN); kek_kck_cmd.replay_ctr = mvmvif->rekey_data.replay_ctr; ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_KEK_KCK_MATERIAL, CMD_SYNC, sizeof(kek_kck_cmd), &kek_kck_cmd); if (ret) goto out; } } ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, CMD_SYNC, sizeof(wowlan_config_cmd), &wowlan_config_cmd); if (ret) goto out; ret = iwl_mvm_send_patterns(mvm, wowlan); if (ret) goto out; ret = iwl_mvm_send_proto_offload(mvm, vif); if (ret) goto out; ret = iwl_mvm_send_remote_wake_cfg(mvm, vif, wowlan->tcp); if (ret) goto out; ret = iwl_mvm_power_update_device_mode(mvm); if (ret) goto out; ret = iwl_mvm_power_update_mode(mvm, vif); if (ret) goto out; #ifdef CONFIG_IWLWIFI_DEBUGFS if (mvm->d3_wake_sysassert) d3_cfg_cmd_data.wakeup_flags |= cpu_to_le32(IWL_WAKEUP_D3_CONFIG_FW_ERROR); #endif /* must be last -- this switches firmware state */ ret = iwl_mvm_send_cmd(mvm, &d3_cfg_cmd); if (ret) goto out; #ifdef CONFIG_IWLWIFI_DEBUGFS len = le32_to_cpu(d3_cfg_cmd.resp_pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK; if (len >= sizeof(u32) * 2) { mvm->d3_test_pme_ptr = le32_to_cpup((__le32 *)d3_cfg_cmd.resp_pkt->data); } #endif iwl_free_resp(&d3_cfg_cmd); clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status); iwl_trans_d3_suspend(mvm->trans, test); out: mvm->aux_sta.sta_id = old_aux_sta_id; mvm_ap_sta->sta_id = old_ap_sta_id; mvmvif->ap_sta_id = old_ap_sta_id; if (ret < 0) ieee80211_restart_hw(mvm->hw); out_noreset: kfree(key_data.rsc_tsc); mutex_unlock(&mvm->mutex); return ret; } int iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan) { return __iwl_mvm_suspend(hw, wowlan, false); } /* converted data from the different status responses */ struct iwl_wowlan_status_data { u16 pattern_number; u16 qos_seq_ctr[8]; u32 wakeup_reasons; u32 wake_packet_length; u32 wake_packet_bufsize; const u8 *wake_packet; }; static void iwl_mvm_report_wakeup_reasons(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct iwl_wowlan_status_data *status) { struct sk_buff *pkt = NULL; struct cfg80211_wowlan_wakeup wakeup = { .pattern_idx = -1, }; struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup; u32 reasons = status->wakeup_reasons; if (reasons == IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS) { wakeup_report = NULL; goto report; } if (reasons & IWL_WOWLAN_WAKEUP_BY_MAGIC_PACKET) wakeup.magic_pkt = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_PATTERN) wakeup.pattern_idx = status->pattern_number; if (reasons & (IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON | IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH)) wakeup.disconnect = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_GTK_REKEY_FAILURE) wakeup.gtk_rekey_failure = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED) wakeup.rfkill_release = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_EAPOL_REQUEST) wakeup.eap_identity_req = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_FOUR_WAY_HANDSHAKE) wakeup.four_way_handshake = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_LINK_LOSS) wakeup.tcp_connlost = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_SIGNATURE_TABLE) wakeup.tcp_nomoretokens = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_WAKEUP_PACKET) wakeup.tcp_match = true; if (status->wake_packet_bufsize) { int pktsize = status->wake_packet_bufsize; int pktlen = status->wake_packet_length; const u8 *pktdata = status->wake_packet; struct ieee80211_hdr *hdr = (void *)pktdata; int truncated = pktlen - pktsize; /* this would be a firmware bug */ if (WARN_ON_ONCE(truncated < 0)) truncated = 0; if (ieee80211_is_data(hdr->frame_control)) { int hdrlen = ieee80211_hdrlen(hdr->frame_control); int ivlen = 0, icvlen = 4; /* also FCS */ pkt = alloc_skb(pktsize, GFP_KERNEL); if (!pkt) goto report; memcpy(skb_put(pkt, hdrlen), pktdata, hdrlen); pktdata += hdrlen; pktsize -= hdrlen; if (ieee80211_has_protected(hdr->frame_control)) { /* * This is unlocked and using gtk_i(c)vlen, * but since everything is under RTNL still * that's not really a problem - changing * it would be difficult. */ if (is_multicast_ether_addr(hdr->addr1)) { ivlen = mvm->gtk_ivlen; icvlen += mvm->gtk_icvlen; } else { ivlen = mvm->ptk_ivlen; icvlen += mvm->ptk_icvlen; } } /* if truncated, FCS/ICV is (partially) gone */ if (truncated >= icvlen) { icvlen = 0; truncated -= icvlen; } else { icvlen -= truncated; truncated = 0; } pktsize -= ivlen + icvlen; pktdata += ivlen; memcpy(skb_put(pkt, pktsize), pktdata, pktsize); if (ieee80211_data_to_8023(pkt, vif->addr, vif->type)) goto report; wakeup.packet = pkt->data; wakeup.packet_present_len = pkt->len; wakeup.packet_len = pkt->len - truncated; wakeup.packet_80211 = false; } else { int fcslen = 4; if (truncated >= 4) { truncated -= 4; fcslen = 0; } else { fcslen -= truncated; truncated = 0; } pktsize -= fcslen; wakeup.packet = status->wake_packet; wakeup.packet_present_len = pktsize; wakeup.packet_len = pktlen - truncated; wakeup.packet_80211 = true; } } report: ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL); kfree_skb(pkt); } static void iwl_mvm_aes_sc_to_seq(struct aes_sc *sc, struct ieee80211_key_seq *seq) { u64 pn; pn = le64_to_cpu(sc->pn); seq->ccmp.pn[0] = pn >> 40; seq->ccmp.pn[1] = pn >> 32; seq->ccmp.pn[2] = pn >> 24; seq->ccmp.pn[3] = pn >> 16; seq->ccmp.pn[4] = pn >> 8; seq->ccmp.pn[5] = pn; } static void iwl_mvm_tkip_sc_to_seq(struct tkip_sc *sc, struct ieee80211_key_seq *seq) { seq->tkip.iv32 = le32_to_cpu(sc->iv32); seq->tkip.iv16 = le16_to_cpu(sc->iv16); } static void iwl_mvm_set_aes_rx_seq(struct aes_sc *scs, struct ieee80211_key_conf *key) { int tid; BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS); for (tid = 0; tid < IWL_NUM_RSC; tid++) { struct ieee80211_key_seq seq = {}; iwl_mvm_aes_sc_to_seq(&scs[tid], &seq); ieee80211_set_key_rx_seq(key, tid, &seq); } } static void iwl_mvm_set_tkip_rx_seq(struct tkip_sc *scs, struct ieee80211_key_conf *key) { int tid; BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS); for (tid = 0; tid < IWL_NUM_RSC; tid++) { struct ieee80211_key_seq seq = {}; iwl_mvm_tkip_sc_to_seq(&scs[tid], &seq); ieee80211_set_key_rx_seq(key, tid, &seq); } } static void iwl_mvm_set_key_rx_seq(struct ieee80211_key_conf *key, struct iwl_wowlan_status_v6 *status) { union iwl_all_tsc_rsc *rsc = &status->gtk.rsc.all_tsc_rsc; switch (key->cipher) { case WLAN_CIPHER_SUITE_CCMP: iwl_mvm_set_aes_rx_seq(rsc->aes.multicast_rsc, key); break; case WLAN_CIPHER_SUITE_TKIP: iwl_mvm_set_tkip_rx_seq(rsc->tkip.multicast_rsc, key); break; default: WARN_ON(1); } } struct iwl_mvm_d3_gtk_iter_data { struct iwl_wowlan_status_v6 *status; void *last_gtk; u32 cipher; bool find_phase, unhandled_cipher; int num_keys; }; static void iwl_mvm_d3_update_gtks(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key, void *_data) { struct iwl_mvm_d3_gtk_iter_data *data = _data; if (data->unhandled_cipher) return; switch (key->cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: /* ignore WEP completely, nothing to do */ return; case WLAN_CIPHER_SUITE_CCMP: case WLAN_CIPHER_SUITE_TKIP: /* we support these */ break; default: /* everything else (even CMAC for MFP) - disconnect from AP */ data->unhandled_cipher = true; return; } data->num_keys++; /* * pairwise key - update sequence counters only; * note that this assumes no TDLS sessions are active */ if (sta) { struct ieee80211_key_seq seq = {}; union iwl_all_tsc_rsc *sc = &data->status->gtk.rsc.all_tsc_rsc; if (data->find_phase) return; switch (key->cipher) { case WLAN_CIPHER_SUITE_CCMP: iwl_mvm_aes_sc_to_seq(&sc->aes.tsc, &seq); iwl_mvm_set_aes_rx_seq(sc->aes.unicast_rsc, key); break; case WLAN_CIPHER_SUITE_TKIP: iwl_mvm_tkip_sc_to_seq(&sc->tkip.tsc, &seq); iwl_mvm_set_tkip_rx_seq(sc->tkip.unicast_rsc, key); break; } ieee80211_set_key_tx_seq(key, &seq); /* that's it for this key */ return; } if (data->find_phase) { data->last_gtk = key; data->cipher = key->cipher; return; } if (data->status->num_of_gtk_rekeys) ieee80211_remove_key(key); else if (data->last_gtk == key) iwl_mvm_set_key_rx_seq(key, data->status); } static bool iwl_mvm_setup_connection_keep(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct iwl_wowlan_status_v6 *status) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mvm_d3_gtk_iter_data gtkdata = { .status = status, }; u32 disconnection_reasons = IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON | IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH; if (!status || !vif->bss_conf.bssid) return false; if (le32_to_cpu(status->wakeup_reasons) & disconnection_reasons) return false; /* find last GTK that we used initially, if any */ gtkdata.find_phase = true; ieee80211_iter_keys(mvm->hw, vif, iwl_mvm_d3_update_gtks, &gtkdata); /* not trying to keep connections with MFP/unhandled ciphers */ if (gtkdata.unhandled_cipher) return false; if (!gtkdata.num_keys) goto out; if (!gtkdata.last_gtk) return false; /* * invalidate all other GTKs that might still exist and update * the one that we used */ gtkdata.find_phase = false; ieee80211_iter_keys(mvm->hw, vif, iwl_mvm_d3_update_gtks, &gtkdata); if (status->num_of_gtk_rekeys) { struct ieee80211_key_conf *key; struct { struct ieee80211_key_conf conf; u8 key[32]; } conf = { .conf.cipher = gtkdata.cipher, .conf.keyidx = status->gtk.key_index, }; switch (gtkdata.cipher) { case WLAN_CIPHER_SUITE_CCMP: conf.conf.keylen = WLAN_KEY_LEN_CCMP; memcpy(conf.conf.key, status->gtk.decrypt_key, WLAN_KEY_LEN_CCMP); break; case WLAN_CIPHER_SUITE_TKIP: conf.conf.keylen = WLAN_KEY_LEN_TKIP; memcpy(conf.conf.key, status->gtk.decrypt_key, 16); /* leave TX MIC key zeroed, we don't use it anyway */ memcpy(conf.conf.key + NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY, status->gtk.tkip_mic_key, 8); break; } key = ieee80211_gtk_rekey_add(vif, &conf.conf); if (IS_ERR(key)) return false; iwl_mvm_set_key_rx_seq(key, status); } if (status->num_of_gtk_rekeys) { __be64 replay_ctr = cpu_to_be64(le64_to_cpu(status->replay_ctr)); ieee80211_gtk_rekey_notify(vif, vif->bss_conf.bssid, (void *)&replay_ctr, GFP_KERNEL); } out: mvmvif->seqno_valid = true; /* +0x10 because the set API expects next-to-use, not last-used */ mvmvif->seqno = le16_to_cpu(status->non_qos_seq_ctr) + 0x10; return true; } /* releases the MVM mutex */ static bool iwl_mvm_query_wakeup_reasons(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { u32 base = mvm->error_event_table; struct error_table_start { /* cf. struct iwl_error_event_table */ u32 valid; u32 error_id; } err_info; struct iwl_host_cmd cmd = { .id = WOWLAN_GET_STATUSES, .flags = CMD_SYNC | CMD_WANT_SKB, }; struct iwl_wowlan_status_data status; struct iwl_wowlan_status_v6 *status_v6; int ret, len, status_size, i; bool keep; struct ieee80211_sta *ap_sta; struct iwl_mvm_sta *mvm_ap_sta; iwl_trans_read_mem_bytes(mvm->trans, base, &err_info, sizeof(err_info)); if (err_info.valid) { IWL_INFO(mvm, "error table is valid (%d)\n", err_info.valid); if (err_info.error_id == RF_KILL_INDICATOR_FOR_WOWLAN) { struct cfg80211_wowlan_wakeup wakeup = { .rfkill_release = true, }; ieee80211_report_wowlan_wakeup(vif, &wakeup, GFP_KERNEL); } goto out_unlock; } /* only for tracing for now */ ret = iwl_mvm_send_cmd_pdu(mvm, OFFLOADS_QUERY_CMD, CMD_SYNC, 0, NULL); if (ret) IWL_ERR(mvm, "failed to query offload statistics (%d)\n", ret); ret = iwl_mvm_send_cmd(mvm, &cmd); if (ret) { IWL_ERR(mvm, "failed to query status (%d)\n", ret); goto out_unlock; } /* RF-kill already asserted again... */ if (!cmd.resp_pkt) goto out_unlock; if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) status_size = sizeof(struct iwl_wowlan_status_v6); else status_size = sizeof(struct iwl_wowlan_status_v4); len = le32_to_cpu(cmd.resp_pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK; if (len - sizeof(struct iwl_cmd_header) < status_size) { IWL_ERR(mvm, "Invalid WoWLAN status response!\n"); goto out_free_resp; } if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) { status_v6 = (void *)cmd.resp_pkt->data; status.pattern_number = le16_to_cpu(status_v6->pattern_number); for (i = 0; i < 8; i++) status.qos_seq_ctr[i] = le16_to_cpu(status_v6->qos_seq_ctr[i]); status.wakeup_reasons = le32_to_cpu(status_v6->wakeup_reasons); status.wake_packet_length = le32_to_cpu(status_v6->wake_packet_length); status.wake_packet_bufsize = le32_to_cpu(status_v6->wake_packet_bufsize); status.wake_packet = status_v6->wake_packet; } else { struct iwl_wowlan_status_v4 *status_v4; status_v6 = NULL; status_v4 = (void *)cmd.resp_pkt->data; status.pattern_number = le16_to_cpu(status_v4->pattern_number); for (i = 0; i < 8; i++) status.qos_seq_ctr[i] = le16_to_cpu(status_v4->qos_seq_ctr[i]); status.wakeup_reasons = le32_to_cpu(status_v4->wakeup_reasons); status.wake_packet_length = le32_to_cpu(status_v4->wake_packet_length); status.wake_packet_bufsize = le32_to_cpu(status_v4->wake_packet_bufsize); status.wake_packet = status_v4->wake_packet; } if (len - sizeof(struct iwl_cmd_header) != status_size + ALIGN(status.wake_packet_bufsize, 4)) { IWL_ERR(mvm, "Invalid WoWLAN status response!\n"); goto out_free_resp; } /* still at hard-coded place 0 for D3 image */ ap_sta = rcu_dereference_protected( mvm->fw_id_to_mac_id[0], lockdep_is_held(&mvm->mutex)); if (IS_ERR_OR_NULL(ap_sta)) goto out_free_resp; mvm_ap_sta = (struct iwl_mvm_sta *)ap_sta->drv_priv; for (i = 0; i < IWL_MAX_TID_COUNT; i++) { u16 seq = status.qos_seq_ctr[i]; /* firmware stores last-used value, we store next value */ seq += 0x10; mvm_ap_sta->tid_data[i].seq_number = seq; } /* now we have all the data we need, unlock to avoid mac80211 issues */ mutex_unlock(&mvm->mutex); iwl_mvm_report_wakeup_reasons(mvm, vif, &status); keep = iwl_mvm_setup_connection_keep(mvm, vif, status_v6); iwl_free_resp(&cmd); return keep; out_free_resp: iwl_free_resp(&cmd); out_unlock: mutex_unlock(&mvm->mutex); return false; } static void iwl_mvm_read_d3_sram(struct iwl_mvm *mvm) { #ifdef CONFIG_IWLWIFI_DEBUGFS const struct fw_img *img = &mvm->fw->img[IWL_UCODE_WOWLAN]; u32 len = img->sec[IWL_UCODE_SECTION_DATA].len; u32 offs = img->sec[IWL_UCODE_SECTION_DATA].offset; if (!mvm->store_d3_resume_sram) return; if (!mvm->d3_resume_sram) { mvm->d3_resume_sram = kzalloc(len, GFP_KERNEL); if (!mvm->d3_resume_sram) return; } iwl_trans_read_mem_bytes(mvm->trans, offs, mvm->d3_resume_sram, len); #endif } static void iwl_mvm_d3_disconnect_iter(void *data, u8 *mac, struct ieee80211_vif *vif) { /* skip the one we keep connection on */ if (data == vif) return; if (vif->type == NL80211_IFTYPE_STATION) ieee80211_resume_disconnect(vif); } static int __iwl_mvm_resume(struct iwl_mvm *mvm, bool test) { struct iwl_d3_iter_data resume_iter_data = { .mvm = mvm, }; struct ieee80211_vif *vif = NULL; int ret; enum iwl_d3_status d3_status; bool keep = false; mutex_lock(&mvm->mutex); /* get the BSS vif pointer again */ ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_iface_iterator, &resume_iter_data); if (WARN_ON(resume_iter_data.error || !resume_iter_data.vif)) goto out_unlock; vif = resume_iter_data.vif; ret = iwl_trans_d3_resume(mvm->trans, &d3_status, test); if (ret) goto out_unlock; if (d3_status != IWL_D3_STATUS_ALIVE) { IWL_INFO(mvm, "Device was reset during suspend\n"); goto out_unlock; } /* query SRAM first in case we want event logging */ iwl_mvm_read_d3_sram(mvm); keep = iwl_mvm_query_wakeup_reasons(mvm, vif); #ifdef CONFIG_IWLWIFI_DEBUGFS if (keep) mvm->keep_vif = vif; #endif /* has unlocked the mutex, so skip that */ goto out; out_unlock: mutex_unlock(&mvm->mutex); out: if (!test) ieee80211_iterate_active_interfaces_rtnl(mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_disconnect_iter, keep ? vif : NULL); /* return 1 to reconfigure the device */ set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status); return 1; } int iwl_mvm_resume(struct ieee80211_hw *hw) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); return __iwl_mvm_resume(mvm, false); } void iwl_mvm_set_wakeup(struct ieee80211_hw *hw, bool enabled) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); device_set_wakeup_enable(mvm->trans->dev, enabled); } #ifdef CONFIG_IWLWIFI_DEBUGFS static int iwl_mvm_d3_test_open(struct inode *inode, struct file *file) { struct iwl_mvm *mvm = inode->i_private; int err; if (mvm->d3_test_active) return -EBUSY; file->private_data = inode->i_private; ieee80211_stop_queues(mvm->hw); synchronize_net(); /* start pseudo D3 */ rtnl_lock(); err = __iwl_mvm_suspend(mvm->hw, mvm->hw->wiphy->wowlan_config, true); rtnl_unlock(); if (err > 0) err = -EINVAL; if (err) { ieee80211_wake_queues(mvm->hw); return err; } mvm->d3_test_active = true; mvm->keep_vif = NULL; return 0; } static ssize_t iwl_mvm_d3_test_read(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_mvm *mvm = file->private_data; u32 pme_asserted; while (true) { /* read pme_ptr if available */ if (mvm->d3_test_pme_ptr) { pme_asserted = iwl_trans_read_mem32(mvm->trans, mvm->d3_test_pme_ptr); if (pme_asserted) break; } if (msleep_interruptible(100)) break; } return 0; } static void iwl_mvm_d3_test_disconn_work_iter(void *_data, u8 *mac, struct ieee80211_vif *vif) { /* skip the one we keep connection on */ if (_data == vif) return; if (vif->type == NL80211_IFTYPE_STATION) ieee80211_connection_loss(vif); } static int iwl_mvm_d3_test_release(struct inode *inode, struct file *file) { struct iwl_mvm *mvm = inode->i_private; int remaining_time = 10; mvm->d3_test_active = false; __iwl_mvm_resume(mvm, true); iwl_abort_notification_waits(&mvm->notif_wait); ieee80211_restart_hw(mvm->hw); /* wait for restart and disconnect all interfaces */ while (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) && remaining_time > 0) { remaining_time--; msleep(1000); } if (remaining_time == 0) IWL_ERR(mvm, "Timed out waiting for HW restart to finish!\n"); ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_test_disconn_work_iter, mvm->keep_vif); ieee80211_wake_queues(mvm->hw); return 0; } const struct file_operations iwl_dbgfs_d3_test_ops = { .llseek = no_llseek, .open = iwl_mvm_d3_test_open, .read = iwl_mvm_d3_test_read, .release = iwl_mvm_d3_test_release, }; #endif
freedesktop-unofficial-mirror/tegra__linux
drivers/net/wireless/iwlwifi/mvm/d3.c
C
gpl-2.0
53,080
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * Copyright © 2000-2004 Marco Pesenti Gritti * Copyright © 2009 Collabora Ltd. * Copyright © 2011 Igalia S.L. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "config.h" #include "window-commands.h" #include "ephy-bookmarks-editor.h" #include "ephy-bookmarks-ui.h" #include "ephy-debug.h" #include "ephy-dialog.h" #include "ephy-embed-container.h" #include "ephy-embed-prefs.h" #include "ephy-embed-shell.h" #include "ephy-embed-single.h" #include "ephy-embed-utils.h" #include "ephy-embed.h" #include "ephy-file-chooser.h" #include "ephy-file-helpers.h" #include "ephy-find-toolbar.h" #include "ephy-gui.h" #include "ephy-history-window.h" #include "ephy-link.h" #include "ephy-location-entry.h" #include "ephy-notebook.h" #include "ephy-prefs.h" #include "ephy-private.h" #include "ephy-settings.h" #include "ephy-shell.h" #include "ephy-state.h" #include "ephy-string.h" #include "ephy-web-app-utils.h" #include "ephy-zoom.h" #include "pdm-dialog.h" #include <gio/gio.h> #include <glib.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #include <libnotify/notify.h> #include <libsoup/soup.h> #include <string.h> #ifdef HAVE_WEBKIT2 #include <webkit2/webkit2.h> #else #include <webkit/webkit.h> #endif void window_cmd_file_print (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; EphyWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (EPHY_IS_EMBED (embed)); view = ephy_embed_get_web_view (embed); ephy_web_view_print (view); } void window_cmd_file_send_to (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; char *command, *subject, *body; const char *location, *title; GdkScreen *screen; GError *error = NULL; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); location = ephy_web_view_get_address (ephy_embed_get_web_view (embed)); title = ephy_web_view_get_title (ephy_embed_get_web_view (embed)); subject = g_uri_escape_string (title, NULL, TRUE); body = g_uri_escape_string (location, NULL, TRUE); command = g_strconcat ("mailto:", "?Subject=", subject, "&Body=", body, NULL); g_free (subject); g_free (body); if (window) { screen = gtk_widget_get_screen (GTK_WIDGET (window)); } else { screen = gdk_screen_get_default (); } if (!gtk_show_uri (screen, command, gtk_get_current_event_time(), &error)) { g_warning ("Unable to send link by email: %s\n", error->message); g_error_free (error); } g_free (command); } static gboolean event_with_shift (void) { GdkEvent *event; GdkEventType type = 0; guint state = 0; event = gtk_get_current_event (); if (event) { type = event->type; if (type == GDK_BUTTON_RELEASE) { state = event->button.state; } else if (type == GDK_KEY_PRESS || type == GDK_KEY_RELEASE) { state = event->key.state; } gdk_event_free (event); } return (state & GDK_SHIFT_MASK) != 0; } void window_cmd_go_location (GtkAction *action, EphyWindow *window) { ephy_window_activate_location (window); } void window_cmd_view_stop (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); gtk_widget_grab_focus (GTK_WIDGET (embed)); webkit_web_view_stop_loading (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); } void window_cmd_view_reload (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; WebKitWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); gtk_widget_grab_focus (GTK_WIDGET (embed)); view = EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed); if (event_with_shift ()) webkit_web_view_reload_bypass_cache (view); else webkit_web_view_reload (view); } void window_cmd_file_bookmark_page (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); ephy_bookmarks_ui_add_bookmark (GTK_WINDOW (window), ephy_web_view_get_address (ephy_embed_get_web_view (embed)), ephy_web_view_get_title (ephy_embed_get_web_view (embed))); } static void open_response_cb (GtkDialog *dialog, int response, EphyWindow *window) { if (response == GTK_RESPONSE_ACCEPT) { char *uri, *converted; uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog)); if (uri != NULL) { converted = g_filename_to_utf8 (uri, -1, NULL, NULL, NULL); if (converted != NULL) { ephy_window_load_url (window, converted); } g_free (converted); g_free (uri); } } gtk_widget_destroy (GTK_WIDGET (dialog)); } static void save_response_cb (GtkDialog *dialog, int response, EphyEmbed *embed) { if (response == GTK_RESPONSE_ACCEPT) { char *uri, *converted; uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog)); if (uri != NULL) { converted = g_filename_to_utf8 (uri, -1, NULL, NULL, NULL); if (converted != NULL) { EphyWebView *web_view = ephy_embed_get_web_view (embed); ephy_web_view_save (web_view, converted); } g_free (converted); g_free (uri); } } gtk_widget_destroy (GTK_WIDGET (dialog)); } void window_cmd_file_open (GtkAction *action, EphyWindow *window) { EphyFileChooser *dialog; dialog = ephy_file_chooser_new (_("Open"), GTK_WIDGET (window), GTK_FILE_CHOOSER_ACTION_OPEN, EPHY_PREFS_STATE_OPEN_DIR, EPHY_FILE_FILTER_ALL_SUPPORTED); g_signal_connect (dialog, "response", G_CALLBACK (open_response_cb), window); gtk_widget_show (GTK_WIDGET (dialog)); } static char * get_suggested_filename (EphyWebView *view) { char *suggested_filename; const char *mimetype; #ifdef HAVE_WEBKIT2 WebKitURIResponse *response; #else WebKitWebFrame *frame; WebKitWebDataSource *data_source; #endif WebKitWebResource *web_resource; #ifdef HAVE_WEBKIT2 web_resource = webkit_web_view_get_main_resource (WEBKIT_WEB_VIEW (view)); response = webkit_web_resource_get_response (web_resource); mimetype = webkit_uri_response_get_mime_type (response); #else frame = webkit_web_view_get_main_frame (WEBKIT_WEB_VIEW (view)); data_source = webkit_web_frame_get_data_source (frame); web_resource = webkit_web_data_source_get_main_resource (data_source); mimetype = webkit_web_resource_get_mime_type (web_resource); #endif if ((g_ascii_strncasecmp (mimetype, "text/html", 9)) == 0) { /* Web Title will be used as suggested filename*/ suggested_filename = g_strconcat (ephy_web_view_get_title (view), ".html", NULL); } else { SoupURI *soup_uri = soup_uri_new (webkit_web_resource_get_uri (web_resource)); suggested_filename = g_path_get_basename (soup_uri->path); soup_uri_free (soup_uri); } return suggested_filename; } void window_cmd_file_save_as (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; EphyFileChooser *dialog; char *suggested_filename; EphyWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); dialog = ephy_file_chooser_new (_("Save"), GTK_WIDGET (window), GTK_FILE_CHOOSER_ACTION_SAVE, EPHY_PREFS_STATE_SAVE_DIR, EPHY_FILE_FILTER_NONE); gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE); view = ephy_embed_get_web_view (embed); suggested_filename = get_suggested_filename (view); gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), suggested_filename); g_free (suggested_filename); g_signal_connect (dialog, "response", G_CALLBACK (save_response_cb), embed); gtk_widget_show (GTK_WIDGET (dialog)); } typedef struct { EphyWebView *view; GtkWidget *image; GtkWidget *entry; GtkWidget *spinner; GtkWidget *box; char *icon_href; } EphyApplicationDialogData; static void ephy_application_dialog_data_free (EphyApplicationDialogData *data) { g_free (data->icon_href); g_slice_free (EphyApplicationDialogData, data); } static void take_page_snapshot_and_set_image (EphyApplicationDialogData *data) { GdkPixbuf *snapshot; int x, y, w, h; x = y = 0; w = h = 128; /* GNOME hi-res icon size. */ snapshot = ephy_web_view_get_snapshot (data->view, x, y, w, h); gtk_image_set_from_pixbuf (GTK_IMAGE (data->image), snapshot); g_object_unref (snapshot); } #ifdef HAVE_WEBKIT2 static void download_finished_cb (WebKitDownload *download, EphyApplicationDialogData *data) { char *filename; filename = g_filename_from_uri (webkit_download_get_destination (download), NULL, NULL); gtk_image_set_from_file (GTK_IMAGE (data->image), filename); g_free (filename); } static void download_failed_cb (WebKitDownload *download, GError *error, EphyApplicationDialogData *data) { g_signal_handlers_disconnect_by_func (download, download_finished_cb, data); /* Something happened, default to a page snapshot. */ take_page_snapshot_and_set_image (data); } #else static void download_status_changed_cb (WebKitDownload *download, GParamSpec *spec, EphyApplicationDialogData *data) { WebKitDownloadStatus status = webkit_download_get_status (download); char *filename; switch (status) { case WEBKIT_DOWNLOAD_STATUS_FINISHED: filename = g_filename_from_uri (webkit_download_get_destination_uri (download), NULL, NULL); gtk_image_set_from_file (GTK_IMAGE (data->image), filename); g_free (filename); break; case WEBKIT_DOWNLOAD_STATUS_ERROR: case WEBKIT_DOWNLOAD_STATUS_CANCELLED: /* Something happened, default to a page snapshot. */ take_page_snapshot_and_set_image (data); break; default: break; } } #endif static void download_icon_and_set_image (EphyApplicationDialogData *data) { #ifndef HAVE_WEBKIT2 WebKitNetworkRequest *request; #endif WebKitDownload *download; char *destination, *destination_uri, *tmp_filename; #ifdef HAVE_WEBKIT2 download = webkit_web_context_download_uri (webkit_web_context_get_default (), data->icon_href); #else request = webkit_network_request_new (data->icon_href); download = webkit_download_new (request); g_object_unref (request); #endif tmp_filename = ephy_file_tmp_filename ("ephy-download-XXXXXX", NULL); destination = g_build_filename (ephy_file_tmp_dir (), tmp_filename, NULL); destination_uri = g_filename_to_uri (destination, NULL, NULL); #ifdef HAVE_WEBKIT2 webkit_download_set_destination (download, destination_uri); #else webkit_download_set_destination_uri (download, destination_uri); #endif g_free (destination); g_free (destination_uri); g_free (tmp_filename); #ifdef HAVE_WEBKIT2 g_signal_connect (download, "finished", G_CALLBACK (download_finished_cb), data); g_signal_connect (download, "failed", G_CALLBACK (download_failed_cb), data); #else g_signal_connect (download, "notify::status", G_CALLBACK (download_status_changed_cb), data); webkit_download_start (download); #endif } static void fill_default_application_image (EphyApplicationDialogData *data) { #ifdef HAVE_WEBKIT2 /* TODO: DOM Bindindgs */ #else WebKitDOMDocument *document; WebKitDOMNodeList *links; gulong length, i; document = webkit_web_view_get_dom_document (WEBKIT_WEB_VIEW (data->view)); links = webkit_dom_document_get_elements_by_tag_name (document, "link"); length = webkit_dom_node_list_get_length (links); for (i = 0; i < length; i++) { char *rel; WebKitDOMNode *node = webkit_dom_node_list_item (links, i); rel = webkit_dom_html_link_element_get_rel (WEBKIT_DOM_HTML_LINK_ELEMENT (node)); /* TODO: support more than one possible icon. */ if (g_strcmp0 (rel, "apple-touch-icon") == 0 || g_strcmp0 (rel, "apple-touch-icon-precomposed") == 0) { data->icon_href = webkit_dom_html_link_element_get_href (WEBKIT_DOM_HTML_LINK_ELEMENT (node)); download_icon_and_set_image (data); g_free (rel); return; } } #endif /* If we make it here, no "apple-touch-icon" link was * found. Take a snapshot of the page. */ take_page_snapshot_and_set_image (data); } static void fill_default_application_title (EphyApplicationDialogData *data) { const char *title = ephy_web_view_get_title (data->view); gtk_entry_set_text (GTK_ENTRY (data->entry), title); } static void notify_launch_cb (NotifyNotification *notification, char *action, gpointer user_data) { char * desktop_file = user_data; /* A gross hack to be able to launch epiphany from within * Epiphany. Might be a good idea to figure out a better * solution... */ g_unsetenv (EPHY_UUID_ENVVAR); ephy_file_launch_desktop_file (desktop_file, NULL, 0, NULL); g_free (desktop_file); } static gboolean confirm_web_application_overwrite (GtkWindow *parent, const char *title) { GtkResponseType response; GtkWidget *dialog; dialog = gtk_message_dialog_new (parent, 0, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("A web application named '%s' already exists. Do you want to replace it?"), title); gtk_dialog_add_buttons (GTK_DIALOG (dialog), _("Cancel"), GTK_RESPONSE_CANCEL, _("Replace"), GTK_RESPONSE_OK, NULL); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), _("An application with the same name already exists. Replacing it will " "overwrite it.")); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); return response == GTK_RESPONSE_OK; } static void dialog_save_as_application_response_cb (GtkDialog *dialog, gint response, EphyApplicationDialogData *data) { const char *app_name; char *desktop_file; char *message; NotifyNotification *notification; if (response == GTK_RESPONSE_OK) { app_name = gtk_entry_get_text (GTK_ENTRY (data->entry)); if (ephy_web_application_exists (app_name)) { if (confirm_web_application_overwrite (GTK_WINDOW (dialog), app_name)) ephy_web_application_delete (app_name); else return; } /* Create Web Application, including a new profile and .desktop file. */ desktop_file = ephy_web_application_create (webkit_web_view_get_uri (WEBKIT_WEB_VIEW (data->view)), app_name, gtk_image_get_pixbuf (GTK_IMAGE (data->image))); if (desktop_file) message = g_strdup_printf (_("The application '%s' is ready to be used"), app_name); else message = g_strdup_printf (_("The application '%s' could not be created"), app_name); notification = notify_notification_new (message, NULL, NULL); g_free (message); if (desktop_file) { notify_notification_add_action (notification, "launch", _("Launch"), (NotifyActionCallback)notify_launch_cb, g_path_get_basename (desktop_file), NULL); notify_notification_set_icon_from_pixbuf (notification, gtk_image_get_pixbuf (GTK_IMAGE (data->image))); g_free (desktop_file); } notify_notification_set_timeout (notification, NOTIFY_EXPIRES_DEFAULT); notify_notification_set_urgency (notification, NOTIFY_URGENCY_LOW); notify_notification_set_hint (notification, "transient", g_variant_new_boolean (TRUE)); notify_notification_show (notification, NULL); } ephy_application_dialog_data_free (data); gtk_widget_destroy (GTK_WIDGET (dialog)); } void window_cmd_file_save_as_application (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; GtkWidget *dialog, *box, *image, *entry, *content_area; EphyWebView *view; EphyApplicationDialogData *data; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); view = EPHY_WEB_VIEW (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); /* Show dialog with icon, title. */ dialog = gtk_dialog_new_with_buttons (_("Create Web Application"), GTK_WINDOW (window), 0, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, _("C_reate"), GTK_RESPONSE_OK, NULL); content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog)); gtk_container_set_border_width (GTK_CONTAINER (dialog), 5); gtk_box_set_spacing (GTK_BOX (content_area), 14); /* 14 + 2 * 5 = 24 */ box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5); gtk_container_add (GTK_CONTAINER (content_area), box); image = gtk_image_new (); gtk_widget_set_size_request (image, 128, 128); gtk_container_add (GTK_CONTAINER (box), image); entry = gtk_entry_new (); gtk_entry_set_activates_default (GTK_ENTRY (entry), TRUE); gtk_box_pack_end (GTK_BOX (box), entry, FALSE, FALSE, 0); data = g_slice_new0 (EphyApplicationDialogData); data->view = view; data->image = image; data->entry = entry; fill_default_application_image (data); fill_default_application_title (data); gtk_widget_show_all (dialog); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK); g_signal_connect (dialog, "response", G_CALLBACK (dialog_save_as_application_response_cb), data); gtk_widget_show_all (dialog); } void window_cmd_file_work_offline (GtkAction *action, EphyWindow *window) { /* TODO: WebKitGTK+ does not currently support offline status. */ #if 0 EphyEmbedSingle *single; gboolean offline; single = EPHY_EMBED_SINGLE (ephy_embed_shell_get_embed_single (embed_shell)); offline = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); ephy_embed_single_set_network_status (single, !offline); #endif } void window_cmd_file_close_window (GtkAction *action, EphyWindow *window) { GtkWidget *notebook; EphyEmbed *embed; notebook = ephy_window_get_notebook (window); if (g_settings_get_boolean (EPHY_SETTINGS_LOCKDOWN, EPHY_PREFS_LOCKDOWN_QUIT) && gtk_notebook_get_n_pages (GTK_NOTEBOOK (notebook)) == 1) { return; } embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); g_signal_emit_by_name (notebook, "tab-close-request", embed); } void window_cmd_edit_undo (GtkAction *action, EphyWindow *window) { GtkWidget *widget; GtkWidget *embed; GtkWidget *location_entry; widget = gtk_window_get_focus (GTK_WINDOW (window)); location_entry = gtk_widget_get_ancestor (widget, EPHY_TYPE_LOCATION_ENTRY); if (location_entry) { ephy_location_entry_reset (EPHY_LOCATION_ENTRY (location_entry)); } else { embed = gtk_widget_get_ancestor (widget, EPHY_TYPE_EMBED); if (embed) { #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed)), "Undo"); #else webkit_web_view_undo (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed))); #endif } } } void window_cmd_edit_redo (GtkAction *action, EphyWindow *window) { GtkWidget *widget; GtkWidget *embed; GtkWidget *location_entry; widget = gtk_window_get_focus (GTK_WINDOW (window)); location_entry = gtk_widget_get_ancestor (widget, EPHY_TYPE_LOCATION_ENTRY); if (location_entry) { ephy_location_entry_undo_reset (EPHY_LOCATION_ENTRY (location_entry)); } else { embed = gtk_widget_get_ancestor (widget, EPHY_TYPE_EMBED); if (embed) { #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed)), "Redo"); #else webkit_web_view_redo (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed))); #endif } } } void window_cmd_edit_cut (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_cut_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_CUT); #else webkit_web_view_cut_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_copy (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_copy_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_COPY); #else webkit_web_view_copy_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_paste (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_paste_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_PASTE); #else webkit_web_view_paste_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_delete (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_delete_text (GTK_EDITABLE (widget), 0, -1); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); /* FIXME: TODO */ #if 0 ephy_command_manager_do_command (EPHY_COMMAND_MANAGER (embed), "cmd_delete"); #endif } } void window_cmd_edit_select_all (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_select_region (GTK_EDITABLE (widget), 0, -1); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), "SelectAll"); #else webkit_web_view_select_all (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_find (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_open (toolbar, FALSE, FALSE); } void window_cmd_edit_find_next (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_find_next (toolbar); } void window_cmd_edit_find_prev (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_find_previous (toolbar); } void window_cmd_view_fullscreen (GtkAction *action, EphyWindow *window) { if (gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action))) gtk_window_fullscreen (GTK_WINDOW (window)); else gtk_window_unfullscreen (GTK_WINDOW (window)); } void window_cmd_view_zoom_in (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, ZOOM_IN); } void window_cmd_view_zoom_out (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, ZOOM_OUT); } void window_cmd_view_zoom_normal (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, 1.0); } static void view_source_embedded (const char *uri, EphyEmbed *embed) { EphyEmbed *new_embed; new_embed = ephy_shell_new_tab (ephy_shell_get_default (), EPHY_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (embed))), embed, NULL, EPHY_NEW_TAB_JUMP | EPHY_NEW_TAB_IN_EXISTING_WINDOW | EPHY_NEW_TAB_APPEND_AFTER); #ifdef HAVE_WEBKIT2 /* TODO: View Source */ #else webkit_web_view_set_view_source_mode (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (new_embed), TRUE); webkit_web_view_load_uri (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (new_embed), uri); #endif } static void save_temp_source_close_cb (GOutputStream *ostream, GAsyncResult *result, gpointer data) { char *uri; GFile *file; GError *error = NULL; g_output_stream_close_finish (ostream, result, &error); if (error) { g_warning ("Unable to close file: %s", error->message); g_error_free (error); return; } uri = (char*)g_object_get_data (G_OBJECT (ostream), "ephy-save-temp-source-uri"); file = g_file_new_for_uri (uri); if (!ephy_file_launch_handler ("text/plain", file, gtk_get_current_event_time ())) { /* Fallback to view the source inside the browser */ const char *uri; EphyEmbed *embed; uri = (const char*) g_object_get_data (G_OBJECT (ostream), "ephy-original-source-uri"); embed = (EphyEmbed*)g_object_get_data (G_OBJECT (ostream), "ephy-save-temp-source-embed"); view_source_embedded (uri, embed); } g_object_unref (ostream); g_object_unref (file); } static void save_temp_source_write_cb (GOutputStream *ostream, GAsyncResult *result, GString *data) { GError *error = NULL; gssize written; written = g_output_stream_write_finish (ostream, result, &error); if (error) { g_string_free (data, TRUE); g_warning ("Unable to write to file: %s", error->message); g_error_free (error); g_output_stream_close_async (ostream, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_close_cb, NULL); return; } if (written == data->len) { g_string_free (data, TRUE); g_output_stream_close_async (ostream, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_close_cb, NULL); return; } data->len -= written; data->str += written; g_output_stream_write_async (ostream, data->str, data->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data); } #ifdef HAVE_WEBKIT2 static void get_main_resource_data_cb (WebKitWebResource *resource, GAsyncResult *result, GOutputStream *ostream) { guchar *data; gsize data_length; GString *data_str; GError *error = NULL; data = webkit_web_resource_get_data_finish (resource, result, &data_length, &error); if (error) { g_warning ("Unable to get main resource data: %s", error->message); g_error_free (error); return; } /* We create a new GString here because we need to make sure * we keep writing in case of partial writes */ data_str = g_string_new_len ((gchar *)data, data_length); g_free (data); g_output_stream_write_async (ostream, data_str->str, data_str->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data_str); } #endif static void save_temp_source_replace_cb (GFile *file, GAsyncResult *result, EphyEmbed *embed) { EphyWebView *view; #ifdef HAVE_WEBKIT2 WebKitWebResource *resource; #else WebKitWebFrame *frame; WebKitWebDataSource *data_source; GString *const_data; GString *data; #endif GFileOutputStream *ostream; GError *error = NULL; ostream = g_file_replace_finish (file, result, &error); if (error) { g_warning ("Unable to replace file: %s", error->message); g_error_free (error); return; } g_object_set_data_full (G_OBJECT (ostream), "ephy-save-temp-source-uri", g_file_get_uri (file), g_free); view = ephy_embed_get_web_view (embed); g_object_set_data_full (G_OBJECT (ostream), "ephy-original-source-uri", g_strdup (webkit_web_view_get_uri (WEBKIT_WEB_VIEW (view))), g_free), g_object_set_data_full (G_OBJECT (ostream), "ephy-save-temp-source-embed", g_object_ref (embed), g_object_unref); #ifdef HAVE_WEBKIT2 resource = webkit_web_view_get_main_resource (WEBKIT_WEB_VIEW (view)); webkit_web_resource_get_data (resource, NULL, (GAsyncReadyCallback)get_main_resource_data_cb, ostream); #else frame = webkit_web_view_get_main_frame (WEBKIT_WEB_VIEW (view)); data_source = webkit_web_frame_get_data_source (frame); const_data = webkit_web_data_source_get_data (data_source); /* We create a new GString here because we need to make sure * we keep writing in case of partial writes */ if (const_data) data = g_string_new_len (const_data->str, const_data->len); else data = g_string_new_len ("", 0); g_output_stream_write_async (G_OUTPUT_STREAM (ostream), data->str, data->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data); #endif } static void save_temp_source (EphyEmbed *embed, guint32 user_time) { GFile *file; char *tmp, *base; const char *static_temp_dir; static_temp_dir = ephy_file_tmp_dir (); if (static_temp_dir == NULL) { return; } base = g_build_filename (static_temp_dir, "viewsourceXXXXXX", NULL); tmp = ephy_file_tmp_filename (base, "html"); g_free (base); if (tmp == NULL) { return; } file = g_file_new_for_path (tmp); g_file_replace_async (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION|G_FILE_CREATE_PRIVATE, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_replace_cb, embed); g_object_unref (file); g_free (tmp); } void window_cmd_view_page_source (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; const char *address; guint32 user_time; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); address = ephy_web_view_get_address (ephy_embed_get_web_view (embed)); #ifdef HAVE_WEBKIT2 /* TODO: View Source */ #else if (g_settings_get_boolean (EPHY_SETTINGS_MAIN, EPHY_PREFS_INTERNAL_VIEW_SOURCE)) { view_source_embedded (address, embed); return; } #endif user_time = gtk_get_current_event_time (); if (g_str_has_prefix (address, "file://")) { GFile *file; file = g_file_new_for_uri (address); ephy_file_launch_handler ("text/plain", file, user_time); g_object_unref (file); } else { save_temp_source (embed, user_time); } } #define ABOUT_GROUP "About" void window_cmd_help_about (GtkAction *action, GtkWidget *window) { const char *licence_part[] = { N_("Web 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."), N_("The GNOME Web Browser 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."), N_("You should have received a copy of the GNU General Public License " "along with the GNOME Web Browser; if not, write to the Free Software Foundation, Inc., " "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA") }; char *licence = NULL, *comments = NULL; GKeyFile *key_file; GError *error = NULL; char **list, **authors, **contributors, **past_authors, **artists, **documenters; gsize n_authors, n_contributors, n_past_authors, n_artists, n_documenters, i, j; key_file = g_key_file_new (); if (!g_key_file_load_from_file (key_file, DATADIR G_DIR_SEPARATOR_S "about.ini", 0, &error)) { g_warning ("Couldn't load about data: %s\n", error->message); g_error_free (error); return; } list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Authors", &n_authors, NULL); contributors = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Contributors", &n_contributors, NULL); past_authors = g_key_file_get_string_list (key_file, ABOUT_GROUP, "PastAuthors", &n_past_authors, NULL); #define APPEND(_to,_from) \ _to[i++] = g_strdup (_from); #define APPEND_STRV_AND_FREE(_to,_from) \ if (_from)\ {\ for (j = 0; _from[j] != NULL; ++j)\ {\ _to[i++] = _from[j];\ }\ g_free (_from);\ } authors = g_new (char *, (list ? n_authors : 0) + (contributors ? n_contributors : 0) + (past_authors ? n_past_authors : 0) + 7 + 1); i = 0; APPEND_STRV_AND_FREE (authors, list); APPEND (authors, ""); APPEND (authors, _("Contact us at:")); APPEND (authors, "<epiphany-list@gnome.org>"); APPEND (authors, ""); APPEND (authors, _("Contributors:")); APPEND_STRV_AND_FREE (authors, contributors); APPEND (authors, ""); APPEND (authors, _("Past developers:")); APPEND_STRV_AND_FREE (authors, past_authors); authors[i++] = NULL; list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Artists", &n_artists, NULL); artists = g_new (char *, (list ? n_artists : 0) + 4 + 1); i = 0; APPEND_STRV_AND_FREE (artists, list); APPEND (artists, ""); APPEND (artists, _("Contact us at:")); APPEND (artists, "<gnome-art-list@gnome.org>"); APPEND (artists, "<gnome-themes-list@gnome.org>"); artists[i++] = NULL; list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Documenters", &n_documenters, NULL); documenters = g_new (char *, (list ? n_documenters : 0) + 3 + 1); i = 0; APPEND_STRV_AND_FREE (documenters, list); APPEND (documenters, ""); APPEND (documenters, _("Contact us at:")); APPEND (documenters, "<gnome-doc-list@gnome.org>"); documenters[i++] = NULL; #undef APPEND #undef APPEND_STRV_AND_FREE g_key_file_free (key_file); #ifdef HAVE_WEBKIT2 comments = g_strdup_printf (_("Lets you view web pages and find information on the internet.\n" "Powered by WebKit %d.%d.%d"), webkit_get_major_version (), webkit_get_minor_version (), webkit_get_micro_version ()); #else comments = g_strdup_printf (_("Lets you view web pages and find information on the internet.\n" "Powered by WebKit %d.%d.%d"), webkit_major_version (), webkit_minor_version (), webkit_micro_version ()); #endif licence = g_strjoin ("\n\n", _(licence_part[0]), _(licence_part[1]), _(licence_part[2]), NULL); gtk_show_about_dialog (window ? GTK_WINDOW (window) : NULL, "program-name", _("Web"), "version", VERSION, "copyright", "Copyright © 2002–2004 Marco Pesenti Gritti\n" "Copyright © 2003–2012 The Web Developers", "artists", artists, "authors", authors, "comments", comments, "documenters", documenters, /* Translators: This is a special message that shouldn't be translated * literally. It is used in the about box to give credits to * the translators. * Thus, you should translate it to your name and email address. * You should also include other translators who have contributed to * this translation; in that case, please write each of them on a separate * line seperated by newlines (\n). */ "translator-credits", _("translator-credits"), "logo-icon-name", "web-browser", "website", "http://www.gnome.org/projects/epiphany", "website-label", _("Web Website"), "license", licence, "wrap-license", TRUE, NULL); g_free (comments); g_free (licence); g_strfreev (artists); g_strfreev (authors); g_strfreev (documenters); } void window_cmd_tabs_next (GtkAction *action, EphyWindow *window) { GtkWidget *nb; nb = ephy_window_get_notebook (window); g_return_if_fail (nb != NULL); ephy_notebook_next_page (EPHY_NOTEBOOK (nb)); } void window_cmd_tabs_previous (GtkAction *action, EphyWindow *window) { GtkWidget *nb; nb = ephy_window_get_notebook (window); g_return_if_fail (nb != NULL); ephy_notebook_prev_page (EPHY_NOTEBOOK (nb)); } void window_cmd_tabs_move_left (GtkAction *action, EphyWindow *window) { GtkWidget *child; GtkNotebook *notebook; int page; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); page = gtk_notebook_get_current_page (notebook); if (page < 1) return; child = gtk_notebook_get_nth_page (notebook, page); gtk_notebook_reorder_child (notebook, child, page - 1); } void window_cmd_tabs_move_right (GtkAction *action, EphyWindow *window) { GtkWidget *child; GtkNotebook *notebook; int page, n_pages; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); page = gtk_notebook_get_current_page (notebook); n_pages = gtk_notebook_get_n_pages (notebook) - 1; if (page > n_pages - 1) return; child = gtk_notebook_get_nth_page (notebook, page); gtk_notebook_reorder_child (notebook, child, page + 1); } void window_cmd_tabs_detach (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; GtkNotebook *notebook; EphyWindow *new_window; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); if (gtk_notebook_get_n_pages (notebook) <= 1) return; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_object_ref_sink (embed); gtk_notebook_remove_page (notebook, gtk_notebook_page_num (notebook, GTK_WIDGET (embed))); new_window = ephy_window_new (); ephy_embed_container_add_child (EPHY_EMBED_CONTAINER (new_window), embed, 0, FALSE); g_object_unref (embed); gtk_window_present (GTK_WINDOW (new_window)); } void window_cmd_load_location (GtkAction *action, EphyWindow *window) { const char *location; location = ephy_window_get_location (window); if (location) { EphyBookmarks *bookmarks; char *address; bookmarks = ephy_shell_get_bookmarks (ephy_shell_get_default ()); address = ephy_bookmarks_resolve_address (bookmarks, location, NULL); g_return_if_fail (address != NULL); ephy_link_open (EPHY_LINK (window), address, ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)), ephy_link_flags_from_current_event ()); } } void window_cmd_browse_with_caret (GtkAction *action, EphyWindow *window) { gboolean active; EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); active = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); /* FIXME: perhaps a bit of a kludge; we check if there's an * active embed because we don't want to show the dialog on * startup when we sync the GtkAction with our GConf * preference */ if (active && embed) { GtkWidget *dialog; int response; dialog = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_CANCEL, _("Enable caret browsing mode?")); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), _("Pressing F7 turns caret browsing on or off. This feature " "places a moveable cursor in web pages, allowing you to move " "around with your keyboard. Do you want to enable caret browsing on?")); gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Enable"), GTK_RESPONSE_ACCEPT); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); if (response == GTK_RESPONSE_CANCEL) { gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), FALSE); return; } } g_settings_set_boolean (EPHY_SETTINGS_MAIN, EPHY_PREFS_ENABLE_CARET_BROWSING, active); }
jdapena/epiphany
src/window-commands.c
C
gpl-2.0
40,646
/* * Copyright (C) 2013 Andreas Steffen * HSR Hochschule fuer Technik Rapperswil * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ #include "tcg_swid_attr_tag_inv.h" #include <pa_tnc/pa_tnc_msg.h> #include <bio/bio_writer.h> #include <bio/bio_reader.h> #include <utils/debug.h> typedef struct private_tcg_swid_attr_tag_inv_t private_tcg_swid_attr_tag_inv_t; /** * SWID Tag Inventory * see section 4.10 of TCG TNC SWID Message and Attributes for IF-M * * 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved | Tag ID Count | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Request ID Copy | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | EID Epoch | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Last EID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Unique Sequence ID Length |Unique Sequence ID (var length)| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Tag Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Tag (Variable) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ #define SWID_TAG_INV_SIZE 16 #define SWID_TAG_INV_RESERVED 0x00 /** * Private data of an tcg_swid_attr_tag_inv_t object. */ struct private_tcg_swid_attr_tag_inv_t { /** * Public members of tcg_swid_attr_tag_inv_t */ tcg_swid_attr_tag_inv_t public; /** * Vendor-specific attribute type */ pen_type_t type; /** * Attribute value */ chunk_t value; /** * Noskip flag */ bool noskip_flag; /** * Request ID */ u_int32_t request_id; /** * Event ID Epoch */ u_int32_t eid_epoch; /** * Last Event ID */ u_int32_t last_eid; /** * SWID Tag Inventory */ swid_inventory_t *inventory; /** * Reference count */ refcount_t ref; }; METHOD(pa_tnc_attr_t, get_type, pen_type_t, private_tcg_swid_attr_tag_inv_t *this) { return this->type; } METHOD(pa_tnc_attr_t, get_value, chunk_t, private_tcg_swid_attr_tag_inv_t *this) { return this->value; } METHOD(pa_tnc_attr_t, get_noskip_flag, bool, private_tcg_swid_attr_tag_inv_t *this) { return this->noskip_flag; } METHOD(pa_tnc_attr_t, set_noskip_flag,void, private_tcg_swid_attr_tag_inv_t *this, bool noskip) { this->noskip_flag = noskip; } METHOD(pa_tnc_attr_t, build, void, private_tcg_swid_attr_tag_inv_t *this) { bio_writer_t *writer; swid_tag_t *tag; enumerator_t *enumerator; if (this->value.ptr) { return; } writer = bio_writer_create(SWID_TAG_INV_SIZE); writer->write_uint8 (writer, SWID_TAG_INV_RESERVED); writer->write_uint24(writer, this->inventory->get_count(this->inventory)); writer->write_uint32(writer, this->request_id); writer->write_uint32(writer, this->eid_epoch); writer->write_uint32(writer, this->last_eid); enumerator = this->inventory->create_enumerator(this->inventory); while (enumerator->enumerate(enumerator, &tag)) { writer->write_data16(writer, tag->get_unique_seq_id(tag)); writer->write_data32(writer, tag->get_encoding(tag)); } enumerator->destroy(enumerator); this->value = writer->extract_buf(writer); writer->destroy(writer); } METHOD(pa_tnc_attr_t, process, status_t, private_tcg_swid_attr_tag_inv_t *this, u_int32_t *offset) { bio_reader_t *reader; u_int32_t tag_count; u_int8_t reserved; chunk_t tag_encoding, unique_seq_id; swid_tag_t *tag; if (this->value.len < SWID_TAG_INV_SIZE) { DBG1(DBG_TNC, "insufficient data for SWID Tag Inventory"); *offset = 0; return FAILED; } reader = bio_reader_create(this->value); reader->read_uint8 (reader, &reserved); reader->read_uint24(reader, &tag_count); reader->read_uint32(reader, &this->request_id); reader->read_uint32(reader, &this->eid_epoch); reader->read_uint32(reader, &this->last_eid); *offset = SWID_TAG_INV_SIZE; while (tag_count--) { if (!reader->read_data16(reader, &unique_seq_id)) { DBG1(DBG_TNC, "insufficient data for Unique Sequence ID"); return FAILED; } *offset += 2 + unique_seq_id.len; if (!reader->read_data32(reader, &tag_encoding)) { DBG1(DBG_TNC, "insufficient data for Tag"); return FAILED; } *offset += 4 + tag_encoding.len; tag = swid_tag_create(tag_encoding, unique_seq_id); this->inventory->add(this->inventory, tag); } reader->destroy(reader); return SUCCESS; } METHOD(pa_tnc_attr_t, get_ref, pa_tnc_attr_t*, private_tcg_swid_attr_tag_inv_t *this) { ref_get(&this->ref); return &this->public.pa_tnc_attribute; } METHOD(pa_tnc_attr_t, destroy, void, private_tcg_swid_attr_tag_inv_t *this) { if (ref_put(&this->ref)) { this->inventory->destroy(this->inventory); free(this->value.ptr); free(this); } } METHOD(tcg_swid_attr_tag_inv_t, get_request_id, u_int32_t, private_tcg_swid_attr_tag_inv_t *this) { return this->request_id; } METHOD(tcg_swid_attr_tag_inv_t, get_last_eid, u_int32_t, private_tcg_swid_attr_tag_inv_t *this, u_int32_t *eid_epoch) { if (eid_epoch) { *eid_epoch = this->eid_epoch; } return this->last_eid; } METHOD(tcg_swid_attr_tag_inv_t, get_inventory, swid_inventory_t*, private_tcg_swid_attr_tag_inv_t *this) { return this->inventory; } /** * Described in header. */ pa_tnc_attr_t *tcg_swid_attr_tag_inv_create(u_int32_t request_id, u_int32_t eid_epoch, u_int32_t eid, swid_inventory_t *inventory) { private_tcg_swid_attr_tag_inv_t *this; INIT(this, .public = { .pa_tnc_attribute = { .get_type = _get_type, .get_value = _get_value, .get_noskip_flag = _get_noskip_flag, .set_noskip_flag = _set_noskip_flag, .build = _build, .process = _process, .get_ref = _get_ref, .destroy = _destroy, }, .get_request_id = _get_request_id, .get_last_eid = _get_last_eid, .get_inventory = _get_inventory, }, .type = { PEN_TCG, TCG_SWID_TAG_INVENTORY }, .request_id = request_id, .eid_epoch = eid_epoch, .last_eid = eid, .inventory = inventory, .ref = 1, ); return &this->public.pa_tnc_attribute; } /** * Described in header. */ pa_tnc_attr_t *tcg_swid_attr_tag_inv_create_from_data(chunk_t data) { private_tcg_swid_attr_tag_inv_t *this; INIT(this, .public = { .pa_tnc_attribute = { .get_type = _get_type, .get_value = _get_value, .get_noskip_flag = _get_noskip_flag, .set_noskip_flag = _set_noskip_flag, .build = _build, .process = _process, .get_ref = _get_ref, .destroy = _destroy, }, .get_request_id = _get_request_id, .get_last_eid = _get_last_eid, .get_inventory = _get_inventory, }, .type = { PEN_TCG, TCG_SWID_TAG_INVENTORY }, .value = chunk_clone(data), .inventory = swid_inventory_create(TRUE), .ref = 1, ); return &this->public.pa_tnc_attribute; }
maire/strongswan
src/libpts/tcg/swid/tcg_swid_attr_tag_inv.c
C
gpl-2.0
7,725
/* HTVMS_WAISProt.c ** ** Adaptation for Lynx by F.Macrides (macrides@sci.wfeb.edu) ** ** 31-May-1994 FM Initial version. ** **----------------------------------------------------------------------*/ /* ** Routines originally from WProt.c -- FM ** **----------------------------------------------------------------------*/ /* WIDE AREA INFORMATION SERVER SOFTWARE: No guarantees or restrictions. See the readme file for the full standard disclaimer. 3.26.90 Harry Morris, morris@think.com 3.30.90 Harry Morris - removed chunk code from WAISSearchAPDU, - added makeWAISQueryType1Query() and readWAISType1Query() which replace makeWAISQueryTerms() and makeWAISQueryDocs(). 4.11.90 HWM - generalized conditional includes (see c-dialect.h) - renamed makeWAISType1Query() to makeWAISTextQuery() renamed readWAISType1Query() to readWAISTextQuery() 5.29.90 TS - fixed bug in makeWAISQueryDocs added CSTFreeWAISFoo functions */ #define _C_WAIS_protocol_ /* This file implements the Z39.50 extensions required for WAIS */ #include <HTUtils.h> #include <HTVMS_WaisUI.h> #include <HTVMS_WaisProt.h> #include <LYLeaks.h> /* very rough estimates of the size of an object */ #define DefWAISInitResponseSize (size_t)200 #define DefWAISSearchSize (size_t)3000 #define DefWAISSearchResponseSize (size_t)6000 #define DefWAISPresentSize (size_t)1000 #define DefWAISPresentResponseSize (size_t)6000 #define DefWAISDocHeaderSize (size_t)500 #define DefWAISShortHeaderSize (size_t)200 #define DefWAISLongHeaderSize (size_t)800 #define DefWAISDocTextSize (size_t)6000 #define DefWAISDocHeadlineSize (size_t)500 #define DefWAISDocCodeSize (size_t)500 #define RESERVE_SPACE_FOR_WAIS_HEADER(len) \ if (*len > 0) \ *len -= header_len; /*----------------------------------------------------------------------*/ static unsigned long userInfoTagSize PARAMS((data_tag tag, unsigned long length)); static unsigned long userInfoTagSize(tag,length) data_tag tag; unsigned long length; /* return the number of bytes required to write the user info tag and length */ { unsigned long size; /* calculate bytes required to represent tag. max tag is 16K */ size = writtenCompressedIntSize(tag); size += writtenCompressedIntSize(length); return(size); } /*----------------------------------------------------------------------*/ static char* writeUserInfoHeader PARAMS((data_tag tag,long infoSize, long estHeaderSize,char* buffer, long* len)); static char* writeUserInfoHeader(tag,infoSize,estHeaderSize,buffer,len) data_tag tag; long infoSize; long estHeaderSize; char* buffer; long* len; /* write the tag and size, making sure the info fits. return the true end of the info (after adjustment) note that the argument infoSize includes estHeaderSize. Note that the argument len is the number of bytes remaining in the buffer. Since we write the tag and size at the begining of the buffer (in space that we reserved) we don't want to pass len the calls which do that writing. */ { long dummyLen = 100; /* plenty of space for a tag and size */ char* buf = buffer; long realSize = infoSize - estHeaderSize; long realHeaderSize = userInfoTagSize(tag,realSize); if (buffer == NULL || *len == 0) return(NULL); /* write the tag */ buf = writeTag(tag,buf,&dummyLen); /* see if the if the header size was correct. if not, we have to shift the info to fit the real header size */ if (estHeaderSize != realHeaderSize) { /* make sure there is enough space */ CHECK_FOR_SPACE_LEFT(realHeaderSize - estHeaderSize,len); memmove(buffer + realHeaderSize,buffer + estHeaderSize,(size_t)(realSize)); } /* write the size */ writeCompressedInteger(realSize,buf,&dummyLen); /* return the true end of buffer */ return(buffer + realHeaderSize + realSize); } /*----------------------------------------------------------------------*/ static char* readUserInfoHeader PARAMS((data_tag* tag,unsigned long* num, char* buffer)); static char* readUserInfoHeader(tag,num,buffer) data_tag* tag; unsigned long* num; char* buffer; /* read the tag and size */ { char* buf = buffer; buf = readTag(tag,buf); buf = readCompressedInteger(num,buf); return(buf); } /*----------------------------------------------------------------------*/ WAISInitResponse* makeWAISInitResponse(chunkCode, chunkIDLen, chunkMarker, highlightMarker, deHighlightMarker, newLineChars) long chunkCode; long chunkIDLen; char* chunkMarker; char* highlightMarker; char* deHighlightMarker; char* newLineChars; /* create a WAIS init response object */ { WAISInitResponse* init = (WAISInitResponse*)s_malloc((size_t)sizeof(WAISInitResponse)); init->ChunkCode = chunkCode; /* note: none are copied! */ init->ChunkIDLength = chunkIDLen; init->ChunkMarker = chunkMarker; init->HighlightMarker = highlightMarker; init->DeHighlightMarker = deHighlightMarker; init->NewlineCharacters = newLineChars; return(init); } /*----------------------------------------------------------------------*/ void freeWAISInitResponse(init) WAISInitResponse* init; /* free an object made with makeWAISInitResponse */ { s_free(init->ChunkMarker); s_free(init->HighlightMarker); s_free(init->DeHighlightMarker); s_free(init->NewlineCharacters); s_free(init); } /*----------------------------------------------------------------------*/ char* writeInitResponseInfo(init,buffer,len) InitResponseAPDU* init; char* buffer; long* len; /* write an init response object */ { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISInitResponseSize); char* buf = buffer + header_len; WAISInitResponse* info = (WAISInitResponse*)init->UserInformationField; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeNum(info->ChunkCode,DT_ChunkCode,buf,len); buf = writeNum(info->ChunkIDLength,DT_ChunkIDLength,buf,len); buf = writeString(info->ChunkMarker,DT_ChunkMarker,buf,len); buf = writeString(info->HighlightMarker,DT_HighlightMarker,buf,len); buf = writeString(info->DeHighlightMarker,DT_DeHighlightMarker,buf,len); buf = writeString(info->NewlineCharacters,DT_NewlineCharacters,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readInitResponseInfo(info,buffer) void** info; char* buffer; /* read an init response object */ { char* buf = buffer; unsigned long size; unsigned long headerSize; long chunkCode,chunkIDLen; data_tag tag1; char* chunkMarker = NULL; char* highlightMarker = NULL; char* deHighlightMarker = NULL; char* newLineChars = NULL; chunkCode = chunkIDLen = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_ChunkCode: buf = readNum(&chunkCode,buf); break; case DT_ChunkIDLength: buf = readNum(&chunkIDLen,buf); break; case DT_ChunkMarker: buf = readString(&chunkMarker,buf); break; case DT_HighlightMarker: buf = readString(&highlightMarker,buf); break; case DT_DeHighlightMarker: buf = readString(&deHighlightMarker,buf); break; case DT_NewlineCharacters: buf = readString(&newLineChars,buf); break; default: s_free(highlightMarker); s_free(deHighlightMarker); s_free(newLineChars); REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISInitResponse(chunkCode,chunkIDLen,chunkMarker, highlightMarker,deHighlightMarker, newLineChars); return(buf); } /*----------------------------------------------------------------------*/ WAISSearch* makeWAISSearch(seedWords, docs, textList, dateFactor, beginDateRange, endDateRange, maxDocsRetrieved) char* seedWords; DocObj** docs; char** textList; long dateFactor; char* beginDateRange; char* endDateRange; long maxDocsRetrieved; /* create a type 3 query object */ { WAISSearch* query = (WAISSearch*)s_malloc((size_t)sizeof(WAISSearch)); query->SeedWords = seedWords; /* not copied! */ query->Docs = docs; /* not copied! */ query->TextList = textList; /* not copied! */ query->DateFactor = dateFactor; query->BeginDateRange = beginDateRange; query->EndDateRange = endDateRange; query->MaxDocumentsRetrieved = maxDocsRetrieved; return(query); } /*----------------------------------------------------------------------*/ void freeWAISSearch(query) WAISSearch* query; /* destroy an object made with makeWAISSearch() */ { void* ptr = NULL; long i; s_free(query->SeedWords); if (query->Docs != NULL) for (i = 0,ptr = (void *)query->Docs[i]; ptr != NULL; ptr = (void *)query->Docs[++i]) freeDocObj((DocObj*)ptr); s_free(query->Docs); if (query->TextList != NULL) /* XXX revisit when textlist is fully defined */ for (i = 0,ptr = (void *)query->TextList[i]; ptr != NULL; ptr = (void *)query->TextList[++i]) s_free(ptr); s_free(query->TextList); s_free(query->BeginDateRange); s_free(query->EndDateRange); s_free(query); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingWholeDocument(docID,type) any* docID; char* type; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->DocumentID = docID; /* not copied! */ doc->Type = type; /* not copied! */ doc->ChunkCode = CT_document; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingLines(docID,type,start,end) any* docID; char* type; long start; long end; /* construct a document object using line chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_line; doc->DocumentID = docID; /* not copied */ doc->Type = type; /* not copied! */ doc->ChunkStart.Pos = start; doc->ChunkEnd.Pos = end; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingBytes(docID,type,start,end) any* docID; char* type; long start; long end; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_byte; doc->DocumentID = docID; /* not copied */ doc->Type = type; /* not copied! */ doc->ChunkStart.Pos = start; doc->ChunkEnd.Pos = end; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingParagraphs(docID,type,start,end) any* docID; char* type; any* start; any* end; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_paragraph; doc->DocumentID = docID; /* not copied */ doc->Type = type; doc->ChunkStart.ID = start; doc->ChunkEnd.ID = end; return(doc); } /*----------------------------------------------------------------------*/ void freeDocObj(doc) DocObj* doc; /* free a docObj */ { freeAny(doc->DocumentID); s_free(doc->Type); if (doc->ChunkCode == CT_paragraph) { freeAny(doc->ChunkStart.ID); freeAny(doc->ChunkEnd.ID); } s_free(doc); } /*----------------------------------------------------------------------*/ static char* writeDocObj PARAMS((DocObj* doc,char* buffer,long* len)); static char* writeDocObj(doc,buffer,len) DocObj* doc; char* buffer; long* len; /* write as little as we can about the doc obj */ { char* buf = buffer; /* we alwasy have to write the id, but its tag depends on if its a chunk */ if (doc->ChunkCode == CT_document) buf = writeAny(doc->DocumentID,DT_DocumentID,buf,len); else buf = writeAny(doc->DocumentID,DT_DocumentIDChunk,buf,len); if (doc->Type != NULL) buf = writeString(doc->Type,DT_TYPE,buf,len); switch (doc->ChunkCode) { case CT_document: /* do nothing - there is no chunk data */ break; case CT_byte: case CT_line: buf = writeNum(doc->ChunkCode,DT_ChunkCode,buf,len); buf = writeNum(doc->ChunkStart.Pos,DT_ChunkStartID,buf,len); buf = writeNum(doc->ChunkEnd.Pos,DT_ChunkEndID,buf,len); break; case CT_paragraph: buf = writeNum(doc->ChunkCode,DT_ChunkCode,buf,len); buf = writeAny(doc->ChunkStart.ID,DT_ChunkStartID,buf,len); buf = writeAny(doc->ChunkEnd.ID,DT_ChunkEndID,buf,len); break; default: panic("Implementation error: unknown chuck type %ld", doc->ChunkCode); break; } return(buf); } /*----------------------------------------------------------------------*/ static char* readDocObj PARAMS((DocObj** doc,char* buffer)); static char* readDocObj(doc,buffer) DocObj** doc; char* buffer; /* read whatever we have about the new document */ { char* buf = buffer; data_tag tag; *doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); tag = peekTag(buf); buf = readAny(&((*doc)->DocumentID),buf); if (tag == DT_DocumentID) { (*doc)->ChunkCode = CT_document; tag = peekTag(buf); if (tag == DT_TYPE) /* XXX depends on DT_TYPE != what comes next */ buf = readString(&((*doc)->Type),buf); /* ChunkStart and ChunkEnd are undefined */ } else if (tag == DT_DocumentIDChunk) { boolean readParagraphs = false; /* for cleanup */ tag = peekTag(buf); if (tag == DT_TYPE) /* XXX depends on DT_TYPE != CT_FOO */ buf = readString(&((*doc)->Type),buf); buf = readNum(&((*doc)->ChunkCode),buf); switch ((*doc)->ChunkCode) { case CT_byte: case CT_line: buf = readNum(&((*doc)->ChunkStart.Pos),buf); buf = readNum(&((*doc)->ChunkEnd.Pos),buf); break; case CT_paragraph: readParagraphs = true; buf = readAny(&((*doc)->ChunkStart.ID),buf); buf = readAny(&((*doc)->ChunkEnd.ID),buf); break; default: freeAny((*doc)->DocumentID); if (readParagraphs) { freeAny((*doc)->ChunkStart.ID); freeAny((*doc)->ChunkEnd.ID); } s_free(doc); REPORT_READ_ERROR(buf); break; } } else { freeAny((*doc)->DocumentID); s_free(*doc); REPORT_READ_ERROR(buf); } return(buf); } /*----------------------------------------------------------------------*/ char* writeSearchInfo(query,buffer,len) SearchAPDU* query; char* buffer; long* len; /* write out a WAIS query (type 1 or 3) */ { if (strcmp(query->QueryType,QT_TextRetrievalQuery) == 0) { return(writeAny((any*)query->Query,DT_Query,buffer,len)); } else { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISSearchSize); char* buf = buffer + header_len; WAISSearch* info = (WAISSearch*)query->Query; unsigned long size; long i; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeString(info->SeedWords,DT_SeedWords,buf,len); if (info->Docs != NULL) { for (i = 0; info->Docs[i] != NULL; i++) { buf = writeDocObj(info->Docs[i],buf,len); } } /* XXX text list */ buf = writeNum(info->DateFactor,DT_DateFactor,buf,len); buf = writeString(info->BeginDateRange,DT_BeginDateRange,buf,len); buf = writeString(info->EndDateRange,DT_EndDateRange,buf,len); buf = writeNum(info->MaxDocumentsRetrieved,DT_MaxDocumentsRetrieved,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } } /*----------------------------------------------------------------------*/ char* readSearchInfo(info,buffer) void** info; char* buffer; /* read a WAIS query (type 1 or 3) */ { data_tag type = peekTag(buffer); if (type == DT_Query) /* this is a type 1 query */ { char* buf = buffer; any* query = NULL; buf = readAny(&query,buf); *info = (void *)query; return(buf); } else /* a type 3 query */ { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; char* seedWords = NULL; char* beginDateRange = NULL; char* endDateRange = NULL; long dateFactor,maxDocsRetrieved; char** textList = NULL; DocObj** docIDs = NULL; DocObj* doc = NULL; long docs = 0; long i; void* ptr = NULL; dateFactor = maxDocsRetrieved = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_SeedWords: buf = readString(&seedWords,buf); break; case DT_DocumentID: case DT_DocumentIDChunk: if (docIDs == NULL) /* create a new doc list */ { docIDs = (DocObj**)s_malloc((size_t)sizeof(DocObj*) * 2); } else /* grow the doc list */ { docIDs = (DocObj**)s_realloc((char*)docIDs,(size_t)(sizeof(DocObj*) * (docs + 2))); } buf = readDocObj(&doc,buf); if (buf == NULL) { s_free(seedWords); s_free(beginDateRange); s_free(endDateRange); if (docIDs != NULL) for (i = 0,ptr = (void *)docIDs[i]; ptr != NULL; ptr = (void *)docIDs[++i]) freeDocObj((DocObj*)ptr); s_free(docIDs); /* XXX should also free textlist when it is fully defined */ } RETURN_ON_NULL(buf); docIDs[docs++] = doc; /* put it in the list */ docIDs[docs] = NULL; break; case DT_TextList: /* XXX */ break; case DT_DateFactor: buf = readNum(&dateFactor,buf); break; case DT_BeginDateRange: buf = readString(&beginDateRange,buf); break; case DT_EndDateRange: buf = readString(&endDateRange,buf); break; case DT_MaxDocumentsRetrieved: buf = readNum(&maxDocsRetrieved,buf); break; default: s_free(seedWords); s_free(beginDateRange); s_free(endDateRange); if (docIDs != NULL) for (i = 0,ptr = (void *)docIDs[i]; ptr != NULL; ptr = (void *)docIDs[++i]) freeDocObj((DocObj*)ptr); s_free(docIDs); /* XXX should also free textlist when it is fully defined */ REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISSearch(seedWords,docIDs,textList, dateFactor,beginDateRange,endDateRange, maxDocsRetrieved); return(buf); } } /*----------------------------------------------------------------------*/ WAISDocumentHeader* makeWAISDocumentHeader(docID, versionNumber, score, bestMatch, docLen, lines, types, source, date, headline, originCity) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; char** types; char* source; char* date; char* headline; char* originCity; /* construct a standard document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentHeader* header = (WAISDocumentHeader*)s_malloc((size_t)sizeof(WAISDocumentHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; header->Types = types; header->Source = source; header->Date = date; header->Headline = headline; header->OriginCity = originCity; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentHeader(header) WAISDocumentHeader* header; { freeAny(header->DocumentID); doList((void**)header->Types,fs_free); /* can't use the macro here ! */ s_free(header->Types); s_free(header->Source); s_free(header->Date); s_free(header->Headline); s_free(header->OriginCity); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentHeader(header,buffer,len) WAISDocumentHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentHeaderGroup , DefWAISDocHeaderSize); char* buf = buffer + header_len; unsigned long size1; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); if (header->Types != NULL) { long size; char* ptr = NULL; long i; buf = writeTag(DT_TYPE_BLOCK,buf,len); for (i = 0,size = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) { long typeSize = strlen(ptr); size += writtenTagSize(DT_TYPE); size += writtenCompressedIntSize(typeSize); size += typeSize; } buf = writeCompressedInteger((unsigned long)size,buf,len); for (i = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) buf = writeString(ptr,DT_TYPE,buf,len); } buf = writeString(header->Source,DT_Source,buf,len); buf = writeString(header->Date,DT_Date,buf,len); buf = writeString(header->Headline,DT_Headline,buf,len); buf = writeString(header->OriginCity,DT_OriginCity,buf,len); /* now write the header and size */ size1 = buf - buffer; buf = writeUserInfoHeader(DT_DocumentHeaderGroup,size1,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentHeader(header,buffer) WAISDocumentHeader** header; char* buffer; { char* buf = buffer; unsigned long size1; unsigned long headerSize; data_tag tag1; any* docID = NULL; long versionNumber,score,bestMatch,docLength,lines; char** types = NULL; char *source = NULL; char *date = NULL; char *headline = NULL; char *originCity = NULL; versionNumber = score = bestMatch = docLength = lines = UNUSED; buf = readUserInfoHeader(&tag1,&size1,buf); headerSize = buf - buffer; while (buf < (buffer + size1 + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; case DT_TYPE_BLOCK: { unsigned long size = -1; long numTypes = 0; buf = readTag(&tag,buf); buf = readCompressedInteger(&size,buf); while (size > 0) { char* type = NULL; char* originalBuf = buf; buf = readString(&type,buf); types = (char**)s_realloc(types,(size_t)(sizeof(char*) * (numTypes + 2))); types[numTypes++] = type; types[numTypes] = NULL; size -= (buf - originalBuf); } } /* FALLTHRU */ case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentHeader(docID,versionNumber,score,bestMatch, docLength,lines,types,source,date,headline, originCity); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentShortHeader* makeWAISDocumentShortHeader(docID, versionNumber, score, bestMatch, docLen, lines) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; /* construct a short document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentShortHeader* header = (WAISDocumentShortHeader*)s_malloc((size_t)sizeof(WAISDocumentShortHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentShortHeader(header) WAISDocumentShortHeader* header; { freeAny(header->DocumentID); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentShortHeader(header,buffer,len) WAISDocumentShortHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentShortHeaderGroup , DefWAISShortHeaderSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentShortHeaderGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentShortHeader(header,buffer) WAISDocumentShortHeader** header; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID = NULL; long versionNumber,score,bestMatch,docLength,lines; versionNumber = score = bestMatch = docLength = lines = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; default: freeAny(docID); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentShortHeader(docID,versionNumber,score,bestMatch, docLength,lines); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentLongHeader* makeWAISDocumentLongHeader(docID, versionNumber, score, bestMatch, docLen, lines, types, source, date, headline, originCity, stockCodes, companyCodes, industryCodes) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; char** types; char* source; char* date; char* headline; char* originCity; char* stockCodes; char* companyCodes; char* industryCodes; /* construct a long document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentLongHeader* header = (WAISDocumentLongHeader*)s_malloc((size_t)sizeof(WAISDocumentLongHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; header->Types = types; header->Source = source; header->Date = date; header->Headline = headline; header->OriginCity = originCity; header->StockCodes = stockCodes; header->CompanyCodes = companyCodes; header->IndustryCodes = industryCodes; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentLongHeader(header) WAISDocumentLongHeader* header; { freeAny(header->DocumentID); doList((void**)header->Types,fs_free); /* can't use the macro here! */ s_free(header->Source); s_free(header->Date); s_free(header->Headline); s_free(header->OriginCity); s_free(header->StockCodes); s_free(header->CompanyCodes); s_free(header->IndustryCodes); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentLongHeader(header,buffer,len) WAISDocumentLongHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentLongHeaderGroup , DefWAISLongHeaderSize); char* buf = buffer + header_len; unsigned long size1; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); if (header->Types != NULL) { long size; char* ptr = NULL; long i; buf = writeTag(DT_TYPE_BLOCK,buf,len); for (i = 0,size = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) { long typeSize = strlen(ptr); size += writtenTagSize(DT_TYPE); size += writtenCompressedIntSize(typeSize); size += typeSize; } buf = writeCompressedInteger((unsigned long)size,buf,len); for (i = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) buf = writeString(ptr,DT_TYPE,buf,len); } buf = writeString(header->Source,DT_Source,buf,len); buf = writeString(header->Date,DT_Date,buf,len); buf = writeString(header->Headline,DT_Headline,buf,len); buf = writeString(header->OriginCity,DT_OriginCity,buf,len); buf = writeString(header->StockCodes,DT_StockCodes,buf,len); buf = writeString(header->CompanyCodes,DT_CompanyCodes,buf,len); buf = writeString(header->IndustryCodes,DT_IndustryCodes,buf,len); /* now write the header and size */ size1 = buf - buffer; buf = writeUserInfoHeader(DT_DocumentLongHeaderGroup,size1,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentLongHeader(header,buffer) WAISDocumentLongHeader** header; char* buffer; { char* buf = buffer; unsigned long size1; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber,score,bestMatch,docLength,lines; char **types; char *source,*date,*headline,*originCity,*stockCodes,*companyCodes,*industryCodes; docID = NULL; versionNumber = score = bestMatch = docLength = lines = UNUSED; types = NULL; source = date = headline = originCity = stockCodes = companyCodes = industryCodes = NULL; buf = readUserInfoHeader(&tag1,&size1,buf); headerSize = buf - buffer; while (buf < (buffer + size1 + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; case DT_TYPE_BLOCK: { unsigned long size = -1; long numTypes = 0; buf = readTag(&tag,buf); readCompressedInteger(&size,buf); while (size > 0) { char* type = NULL; char* originalBuf = buf; buf = readString(&type,buf); types = (char**)s_realloc(types,(size_t)(sizeof(char*) * (numTypes + 2))); types[numTypes++] = type; types[numTypes] = NULL; size -= (buf - originalBuf); } } /* FALLTHRU */ case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; case DT_StockCodes: buf = readString(&stockCodes,buf); break; case DT_CompanyCodes: buf = readString(&companyCodes,buf); break; case DT_IndustryCodes: buf = readString(&industryCodes,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); s_free(stockCodes); s_free(companyCodes); s_free(industryCodes); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentLongHeader(docID,versionNumber,score,bestMatch, docLength,lines,types,source,date,headline, originCity,stockCodes,companyCodes, industryCodes); return(buf); } /*----------------------------------------------------------------------*/ WAISSearchResponse* makeWAISSearchResponse(seedWordsUsed, docHeaders, shortHeaders, longHeaders, text, headlines, codes, diagnostics) char* seedWordsUsed; WAISDocumentHeader** docHeaders; WAISDocumentShortHeader** shortHeaders; WAISDocumentLongHeader** longHeaders; WAISDocumentText** text; WAISDocumentHeadlines** headlines; WAISDocumentCodes** codes; diagnosticRecord** diagnostics; { WAISSearchResponse* response = (WAISSearchResponse*)s_malloc((size_t)sizeof(WAISSearchResponse)); response->SeedWordsUsed = seedWordsUsed; response->DocHeaders = docHeaders; response->ShortHeaders = shortHeaders; response->LongHeaders = longHeaders; response->Text = text; response->Headlines = headlines; response->Codes = codes; response->Diagnostics = diagnostics; return(response); } /*----------------------------------------------------------------------*/ void freeWAISSearchResponse(response) WAISSearchResponse* response; { void* ptr = NULL; long i; s_free(response->SeedWordsUsed); if (response->DocHeaders != NULL) for (i = 0,ptr = (void *)response->DocHeaders[i]; ptr != NULL; ptr = (void *)response->DocHeaders[++i]) freeWAISDocumentHeader((WAISDocumentHeader*)ptr); s_free(response->DocHeaders); if (response->ShortHeaders != NULL) for (i = 0,ptr = (void *)response->ShortHeaders[i]; ptr != NULL; ptr = (void *)response->ShortHeaders[++i]) freeWAISDocumentShortHeader((WAISDocumentShortHeader*)ptr); s_free(response->ShortHeaders); if (response->LongHeaders != NULL) for (i = 0,ptr = (void *)response->LongHeaders[i]; ptr != NULL; ptr = (void *)response->LongHeaders[++i]) freeWAISDocumentLongHeader((WAISDocumentLongHeader*)ptr); s_free(response->LongHeaders); if (response->Text != NULL) for (i = 0,ptr = (void *)response->Text[i]; ptr != NULL; ptr = (void *)response->Text[++i]) freeWAISDocumentText((WAISDocumentText*)ptr); s_free(response->Text); if (response->Headlines != NULL) for (i = 0,ptr = (void *)response->Headlines[i]; ptr != NULL; ptr = (void *)response->Headlines[++i]) freeWAISDocumentHeadlines((WAISDocumentHeadlines*)ptr); s_free(response->Headlines); if (response->Codes != NULL) for (i = 0,ptr = (void *)response->Codes[i]; ptr != NULL; ptr = (void *)response->Codes[++i]) freeWAISDocumentCodes((WAISDocumentCodes*)ptr); s_free(response->Codes); if (response->Diagnostics != NULL) for (i = 0,ptr = (void *)response->Diagnostics[i]; ptr != NULL; ptr = (void *)response->Diagnostics[++i]) freeDiag((diagnosticRecord*)ptr); s_free(response->Diagnostics); s_free(response); } /*----------------------------------------------------------------------*/ char* writeSearchResponseInfo(query,buffer,len) SearchResponseAPDU* query; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISSearchResponseSize); char* buf = buffer + header_len; WAISSearchResponse* info = (WAISSearchResponse*)query->DatabaseDiagnosticRecords; unsigned long size; void* header = NULL; long i; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeString(info->SeedWordsUsed,DT_SeedWordsUsed,buf,len); /* write out all the headers */ if (info->DocHeaders != NULL) { for (i = 0,header = (void *)info->DocHeaders[i]; header != NULL; header = (void *)info->DocHeaders[++i]) buf = writeWAISDocumentHeader((WAISDocumentHeader*)header,buf,len); } if (info->ShortHeaders != NULL) { for (i = 0,header = (void *)info->ShortHeaders[i]; header != NULL; header = (void *)info->ShortHeaders[++i]) buf = writeWAISDocumentShortHeader((WAISDocumentShortHeader*)header,buf,len); } if (info->LongHeaders != NULL) { for (i = 0,header = (void *)info->LongHeaders[i]; header != NULL; header = (void *)info->LongHeaders[++i]) buf = writeWAISDocumentLongHeader((WAISDocumentLongHeader*)header,buf,len); } if (info->Text != NULL) { for (i = 0,header = (void *)info->Text[i]; header != NULL; header = (void *)info->Text[++i]) buf = writeWAISDocumentText((WAISDocumentText*)header,buf,len); } if (info->Headlines != NULL) { for (i = 0,header = (void *)info->Headlines[i]; header != NULL; header = (void *)info->Headlines[++i]) buf = writeWAISDocumentHeadlines((WAISDocumentHeadlines*)header,buf,len); } if (info->Codes != NULL) { for (i = 0,header = (void *)info->Codes[i]; header != NULL;header = (void *)info->Codes[++i]) buf = writeWAISDocumentCodes((WAISDocumentCodes*)header,buf,len); } if (info->Diagnostics != NULL) { for (i = 0, header = (void *)info->Diagnostics[i]; header != NULL; header = (void *)info->Diagnostics[++i]) buf = writeDiag((diagnosticRecord*)header,buf,len); } /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ static void cleanUpWaisSearchResponse PARAMS((char* buf,char* seedWordsUsed, WAISDocumentHeader** docHeaders, WAISDocumentShortHeader** shortHeaders, WAISDocumentLongHeader** longHeaders, WAISDocumentText** text, WAISDocumentHeadlines** headlines, WAISDocumentCodes** codes, diagnosticRecord**diags)); static void cleanUpWaisSearchResponse (buf,seedWordsUsed,docHeaders,shortHeaders, longHeaders,text,headlines,codes,diags) char* buf; char* seedWordsUsed; WAISDocumentHeader** docHeaders; WAISDocumentShortHeader** shortHeaders; WAISDocumentLongHeader** longHeaders; WAISDocumentText** text; WAISDocumentHeadlines** headlines; WAISDocumentCodes** codes; diagnosticRecord** diags; /* if buf is NULL, we have just gotten a read error, and need to clean up any state we have built. If not, then everything is going fine, and we should just hang loose */ { void* ptr = NULL; long i; if (buf == NULL) { s_free(seedWordsUsed); if (docHeaders != NULL) for (i = 0,ptr = (void *)docHeaders[i]; ptr != NULL; ptr = (void *)docHeaders[++i]) freeWAISDocumentHeader((WAISDocumentHeader*)ptr); s_free(docHeaders); if (shortHeaders != NULL) for (i = 0,ptr = (void *)shortHeaders[i]; ptr != NULL; ptr = (void *)shortHeaders[++i]) freeWAISDocumentShortHeader((WAISDocumentShortHeader*)ptr); s_free(shortHeaders); if (longHeaders != NULL) for (i = 0,ptr = (void *)longHeaders[i]; ptr != NULL; ptr = (void *)longHeaders[++i]) freeWAISDocumentLongHeader((WAISDocumentLongHeader*)ptr); s_free(longHeaders); if (text != NULL) for (i = 0,ptr = (void *)text[i]; ptr != NULL; ptr = (void *)text[++i]) freeWAISDocumentText((WAISDocumentText*)ptr); s_free(text); if (headlines != NULL) for (i = 0,ptr = (void *)headlines[i]; ptr != NULL; ptr = (void *)headlines[++i]) freeWAISDocumentHeadlines((WAISDocumentHeadlines*)ptr); s_free(headlines); if (codes != NULL) for (i = 0,ptr = (void *)codes[i]; ptr != NULL; ptr = (void *)codes[++i]) freeWAISDocumentCodes((WAISDocumentCodes*)ptr); s_free(codes); if (diags != NULL) for (i = 0,ptr = (void *)diags[i]; ptr != NULL; ptr = (void *)diags[++i]) freeDiag((diagnosticRecord*)ptr); s_free(diags); } } /*----------------------------------------------------------------------*/ char* readSearchResponseInfo(info,buffer) void** info; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; void* header = NULL; WAISDocumentHeader** docHeaders = NULL; WAISDocumentShortHeader** shortHeaders = NULL; WAISDocumentLongHeader** longHeaders = NULL; WAISDocumentText** text = NULL; WAISDocumentHeadlines** headlines = NULL; WAISDocumentCodes** codes = NULL; long numDocHeaders,numLongHeaders,numShortHeaders,numText,numHeadlines; long numCodes; char* seedWordsUsed = NULL; diagnosticRecord** diags = NULL; diagnosticRecord* diag = NULL; long numDiags = 0; numDocHeaders = numLongHeaders = numShortHeaders = numText = numHeadlines = numCodes = 0; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_SeedWordsUsed: buf = readString(&seedWordsUsed,buf); break; case DT_DatabaseDiagnosticRecords: if (diags == NULL) /* create a new diag list */ { diags = (diagnosticRecord**)s_malloc((size_t)sizeof(diagnosticRecord*) * 2); } else /* grow the diag list */ { diags = (diagnosticRecord**)s_realloc((char*)diags,(size_t)(sizeof(diagnosticRecord*) * (numDiags + 2))); } buf = readDiag(&diag,buf); diags[numDiags++] = diag; /* put it in the list */ diags[numDiags] = NULL; break; case DT_DocumentHeaderGroup: if (docHeaders == NULL) /* create a new header list */ { docHeaders = (WAISDocumentHeader**)s_malloc((size_t)sizeof(WAISDocumentHeader*) * 2); } else /* grow the doc list */ { docHeaders = (WAISDocumentHeader**)s_realloc((char*)docHeaders,(size_t)(sizeof(WAISDocumentHeader*) * (numDocHeaders + 2))); } buf = readWAISDocumentHeader((WAISDocumentHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); docHeaders[numDocHeaders++] = (WAISDocumentHeader*)header; /* put it in the list */ docHeaders[numDocHeaders] = NULL; break; case DT_DocumentShortHeaderGroup: if (shortHeaders == NULL) /* create a new header list */ { shortHeaders = (WAISDocumentShortHeader**)s_malloc((size_t)sizeof(WAISDocumentShortHeader*) * 2); } else /* grow the doc list */ { shortHeaders = (WAISDocumentShortHeader**)s_realloc((char*)shortHeaders,(size_t)(sizeof(WAISDocumentShortHeader*) * (numShortHeaders + 2))); } buf = readWAISDocumentShortHeader((WAISDocumentShortHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); shortHeaders[numShortHeaders++] = (WAISDocumentShortHeader*)header; /* put it in the list */ shortHeaders[numShortHeaders] = NULL; break; case DT_DocumentLongHeaderGroup: if (longHeaders == NULL) /* create a new header list */ { longHeaders = (WAISDocumentLongHeader**)s_malloc((size_t)sizeof(WAISDocumentLongHeader*) * 2); } else /* grow the doc list */ { longHeaders = (WAISDocumentLongHeader**)s_realloc((char*)longHeaders,(size_t)(sizeof(WAISDocumentLongHeader*) * (numLongHeaders + 2))); } buf = readWAISDocumentLongHeader((WAISDocumentLongHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); longHeaders[numLongHeaders++] = (WAISDocumentLongHeader*)header; /* put it in the list */ longHeaders[numLongHeaders] = NULL; break; case DT_DocumentTextGroup: if (text == NULL) /* create a new list */ { text = (WAISDocumentText**)s_malloc((size_t)sizeof(WAISDocumentText*) * 2); } else /* grow the list */ { text = (WAISDocumentText**)s_realloc((char*)text,(size_t)(sizeof(WAISDocumentText*) * (numText + 2))); } buf = readWAISDocumentText((WAISDocumentText**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); text[numText++] = (WAISDocumentText*)header; /* put it in the list */ text[numText] = NULL; break; case DT_DocumentHeadlineGroup: if (headlines == NULL) /* create a new list */ { headlines = (WAISDocumentHeadlines**)s_malloc((size_t)sizeof(WAISDocumentHeadlines*) * 2); } else /* grow the list */ { headlines = (WAISDocumentHeadlines**)s_realloc((char*)headlines,(size_t)(sizeof(WAISDocumentHeadlines*) * (numHeadlines + 2))); } buf = readWAISDocumentHeadlines((WAISDocumentHeadlines**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); headlines[numHeadlines++] = (WAISDocumentHeadlines*)header; /* put it in the list */ headlines[numHeadlines] = NULL; break; case DT_DocumentCodeGroup: if (codes == NULL) /* create a new list */ { codes = (WAISDocumentCodes**)s_malloc((size_t)sizeof(WAISDocumentCodes*) * 2); } else /* grow the list */ { codes = (WAISDocumentCodes**)s_realloc((char*)codes,(size_t)(sizeof(WAISDocumentCodes*) * (numCodes + 2))); } buf = readWAISDocumentCodes((WAISDocumentCodes**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); codes[numCodes++] = (WAISDocumentCodes*)header; /* put it in the list */ codes[numCodes] = NULL; break; default: cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISSearchResponse(seedWordsUsed,docHeaders,shortHeaders, longHeaders,text,headlines,codes,diags); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentText* makeWAISDocumentText(docID,versionNumber,documentText) any* docID; long versionNumber; any* documentText; { WAISDocumentText* docText = (WAISDocumentText*)s_malloc((size_t)sizeof(WAISDocumentText)); docText->DocumentID = docID; docText->VersionNumber = versionNumber; docText->DocumentText = documentText; return(docText); } /*----------------------------------------------------------------------*/ void freeWAISDocumentText(docText) WAISDocumentText* docText; { freeAny(docText->DocumentID); freeAny(docText->DocumentText); s_free(docText); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentText(docText,buffer,len) WAISDocumentText* docText; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentTextGroup, DefWAISDocTextSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docText->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docText->VersionNumber,DT_VersionNumber,buf,len); buf = writeAny(docText->DocumentText,DT_DocumentText,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentTextGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentText(docText,buffer) WAISDocumentText** docText; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any *docID,*documentText; long versionNumber; docID = documentText = NULL; versionNumber = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_DocumentText: buf = readAny(&documentText,buf); break; default: freeAny(docID); freeAny(documentText); REPORT_READ_ERROR(buf); break; } } *docText = makeWAISDocumentText(docID,versionNumber,documentText); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentHeadlines* makeWAISDocumentHeadlines(docID, versionNumber, source, date, headline, originCity) any* docID; long versionNumber; char* source; char* date; char* headline; char* originCity; { WAISDocumentHeadlines* docHeadline = (WAISDocumentHeadlines*)s_malloc((size_t)sizeof(WAISDocumentHeadlines)); docHeadline->DocumentID = docID; docHeadline->VersionNumber = versionNumber; docHeadline->Source = source; docHeadline->Date = date; docHeadline->Headline = headline; docHeadline->OriginCity = originCity; return(docHeadline); } /*----------------------------------------------------------------------*/ void freeWAISDocumentHeadlines(docHeadline) WAISDocumentHeadlines* docHeadline; { freeAny(docHeadline->DocumentID); s_free(docHeadline->Source); s_free(docHeadline->Date); s_free(docHeadline->Headline); s_free(docHeadline->OriginCity); s_free(docHeadline); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentHeadlines(docHeadline,buffer,len) WAISDocumentHeadlines* docHeadline; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentHeadlineGroup, DefWAISDocHeadlineSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docHeadline->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docHeadline->VersionNumber,DT_VersionNumber,buf,len); buf = writeString(docHeadline->Source,DT_Source,buf,len); buf = writeString(docHeadline->Date,DT_Date,buf,len); buf = writeString(docHeadline->Headline,DT_Headline,buf,len); buf = writeString(docHeadline->OriginCity,DT_OriginCity,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentHeadlineGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentHeadlines(docHeadline,buffer) WAISDocumentHeadlines** docHeadline; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber; char *source,*date,*headline,*originCity; docID = NULL; versionNumber = UNUSED; source = date = headline = originCity = NULL; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); REPORT_READ_ERROR(buf); break; } } *docHeadline = makeWAISDocumentHeadlines(docID,versionNumber,source,date, headline,originCity); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentCodes* makeWAISDocumentCodes(docID, versionNumber, stockCodes, companyCodes, industryCodes) any* docID; long versionNumber; char* stockCodes; char* companyCodes; char* industryCodes; { WAISDocumentCodes* docCodes = (WAISDocumentCodes*)s_malloc((size_t)sizeof(WAISDocumentCodes)); docCodes->DocumentID = docID; docCodes->VersionNumber = versionNumber; docCodes->StockCodes = stockCodes; docCodes->CompanyCodes = companyCodes; docCodes->IndustryCodes = industryCodes; return(docCodes); } /*----------------------------------------------------------------------*/ void freeWAISDocumentCodes(docCodes) WAISDocumentCodes* docCodes; { freeAny(docCodes->DocumentID); s_free(docCodes->StockCodes); s_free(docCodes->CompanyCodes); s_free(docCodes->IndustryCodes); s_free(docCodes); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentCodes(docCodes,buffer,len) WAISDocumentCodes* docCodes; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentCodeGroup , DefWAISDocCodeSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docCodes->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docCodes->VersionNumber,DT_VersionNumber,buf,len); buf = writeString(docCodes->StockCodes,DT_StockCodes,buf,len); buf = writeString(docCodes->CompanyCodes,DT_CompanyCodes,buf,len); buf = writeString(docCodes->IndustryCodes,DT_IndustryCodes,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentCodeGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentCodes(docCodes,buffer) WAISDocumentCodes** docCodes; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber; char *stockCodes,*companyCodes,*industryCodes; docID = NULL; versionNumber = UNUSED; stockCodes = companyCodes = industryCodes = NULL; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_StockCodes: buf = readString(&stockCodes,buf); break; case DT_CompanyCodes: buf = readString(&companyCodes,buf); break; case DT_IndustryCodes: buf = readString(&industryCodes,buf); break; default: freeAny(docID); s_free(stockCodes); s_free(companyCodes); s_free(industryCodes); REPORT_READ_ERROR(buf); break; } } *docCodes = makeWAISDocumentCodes(docID,versionNumber,stockCodes, companyCodes,industryCodes); return(buf); } /*----------------------------------------------------------------------*/ char* writePresentInfo(present,buffer,len) PresentAPDU* present GCC_UNUSED; char* buffer; long* len GCC_UNUSED; { /* The WAIS protocol doesn't use present info */ return(buffer); } /*----------------------------------------------------------------------*/ char* readPresentInfo(info,buffer) void** info; char* buffer; { /* The WAIS protocol doesn't use present info */ *info = NULL; return(buffer); } /*----------------------------------------------------------------------*/ char* writePresentResponseInfo(response,buffer,len) PresentResponseAPDU* response GCC_UNUSED; char* buffer; long* len GCC_UNUSED; { /* The WAIS protocol doesn't use presentResponse info */ return(buffer); } /*----------------------------------------------------------------------*/ char* readPresentResponseInfo(info,buffer) void** info; char* buffer; { /* The WAIS protocol doesn't use presentResponse info */ *info = NULL; return(buffer); } /*----------------------------------------------------------------------*/ /* support for type 1 queries */ /* new use values (for the chunk types) */ #define BYTE "wb" #define LINE "wl" #define PARAGRAPH "wp" #define DATA_TYPE "wt" /* WAIS supports the following semantics for type 1 queries: 1. retrieve the header/codes from a document: System_Control_Number = docID Data Type = type (optional) And 2. retrieve a fragment of the text of a document: System_Control_Number = docID Data Type = type (optional) And Chunk >= start And Chunk < end And Information from multiple documents may be requested by using groups of the above joined by: OR ( XXX does an OR come after every group but the first, or do they all come at the end? ) ( XXX return type could be in the element set) */ static query_term** makeWAISQueryTerms PARAMS((DocObj** docs)); static query_term** makeWAISQueryTerms(docs) DocObj** docs; /* given a null terminated list of docObjs, construct the appropriate query of the form given above */ { query_term** terms = NULL; long numTerms = 0; DocObj* doc = NULL; long i; if (docs == NULL) return((query_term**)NULL); terms = (query_term**)s_malloc((size_t)(sizeof(query_term*) * 1)); terms[numTerms] = NULL; /* loop through the docs making terms for them all */ for (i = 0,doc = docs[i]; doc != NULL; doc = docs[++i]) { any* type = NULL; if (doc->Type != NULL) type = stringToAny(doc->Type); if (doc->ChunkCode == CT_document) /* a whole document */ { terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 3 + 1))); terms[numTerms++] = makeAttributeTerm(SYSTEM_CONTROL_NUMBER, EQUAL,IGNORE,IGNORE, IGNORE,IGNORE,doc->DocumentID); if (type != NULL) { terms[numTerms++] = makeAttributeTerm(DATA_TYPE,EQUAL, IGNORE,IGNORE,IGNORE, IGNORE,type); terms[numTerms++] = makeOperatorTerm(AND); } terms[numTerms] = NULL; } else /* a document fragment */ { char chunk_att[ATTRIBUTE_SIZE]; any* startChunk = NULL; any* endChunk = NULL; terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 7 + 1))); switch (doc->ChunkCode) { case CT_byte: case CT_line: { char start[20],end[20]; (doc->ChunkCode == CT_byte) ? strncpy(chunk_att,BYTE,ATTRIBUTE_SIZE) : strncpy(chunk_att,LINE,ATTRIBUTE_SIZE); sprintf(start,"%ld",doc->ChunkStart.Pos); startChunk = stringToAny(start); sprintf(end,"%ld",doc->ChunkEnd.Pos); endChunk = stringToAny(end); } break; case CT_paragraph: strncpy(chunk_att,PARAGRAPH,ATTRIBUTE_SIZE); startChunk = doc->ChunkStart.ID; endChunk = doc->ChunkEnd.ID; break; default: /* error */ break; } terms[numTerms++] = makeAttributeTerm(SYSTEM_CONTROL_NUMBER, EQUAL,IGNORE,IGNORE, IGNORE, IGNORE,doc->DocumentID); if (type != NULL) { terms[numTerms++] = makeAttributeTerm(DATA_TYPE,EQUAL,IGNORE, IGNORE,IGNORE,IGNORE, type); terms[numTerms++] = makeOperatorTerm(AND); } terms[numTerms++] = makeAttributeTerm(chunk_att, GREATER_THAN_OR_EQUAL, IGNORE,IGNORE,IGNORE, IGNORE, startChunk); terms[numTerms++] = makeOperatorTerm(AND); terms[numTerms++] = makeAttributeTerm(chunk_att,LESS_THAN, IGNORE,IGNORE,IGNORE, IGNORE, endChunk); terms[numTerms++] = makeOperatorTerm(AND); terms[numTerms] = NULL; if (doc->ChunkCode == CT_byte || doc->ChunkCode == CT_line) { freeAny(startChunk); freeAny(endChunk); } } freeAny(type); if (i != 0) /* multiple independent queries, need a disjunction */ { terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 1 + 1))); terms[numTerms++] = makeOperatorTerm(OR); terms[numTerms] = NULL; } } return(terms); } /*----------------------------------------------------------------------*/ static DocObj** makeWAISQueryDocs PARAMS((query_term** terms)); static DocObj** makeWAISQueryDocs(terms) query_term** terms; /* given a list of terms in the form given above, convert them to DocObjs. */ { query_term* docTerm = NULL; query_term* fragmentTerm = NULL; DocObj** docs = NULL; DocObj* doc = NULL; long docNum,termNum; docNum = termNum = 0; docs = (DocObj**)s_malloc((size_t)(sizeof(DocObj*) * 1)); docs[docNum] = NULL; /* translate the terms into DocObjs */ while (true) { query_term* typeTerm = NULL; char* type = NULL; long startTermOffset; docTerm = terms[termNum]; if (docTerm == NULL) break; /* we're done converting */ typeTerm = terms[termNum + 1]; /* get the lead Term if it exists */ if (strcmp(typeTerm->Use,DATA_TYPE) == 0) /* we do have a type */ { startTermOffset = 3; type = anyToString(typeTerm->Term); } else /* no type */ { startTermOffset = 1; typeTerm = NULL; type = NULL; } /* grow the doc list */ docs = (DocObj**)s_realloc((char*)docs,(size_t)(sizeof(DocObj*) * (docNum + 1 + 1))); /* figure out what kind of docObj to build - and build it */ fragmentTerm = terms[termNum + startTermOffset]; if (fragmentTerm != NULL && fragmentTerm->TermType == TT_Attribute) { /* build a document fragment */ query_term* startTerm = fragmentTerm; query_term* endTerm = terms[termNum + startTermOffset + 2]; if (strcmp(startTerm->Use,BYTE) == 0){ /* a byte chunk */ doc = makeDocObjUsingBytes(duplicateAny(docTerm->Term), type, anyToLong(startTerm->Term), anyToLong(endTerm->Term)); log_write("byte"); }else if (strcmp(startTerm->Use,LINE) == 0){ /* a line chunk */ doc = makeDocObjUsingLines(duplicateAny(docTerm->Term), type, anyToLong(startTerm->Term), anyToLong(endTerm->Term)); log_write("line"); }else{ log_write("chunk"); /* a paragraph chunk */ doc = makeDocObjUsingParagraphs(duplicateAny(docTerm->Term), type, duplicateAny(startTerm->Term), duplicateAny(endTerm->Term)); } termNum += (startTermOffset + 4); /* point to next term */ } else /* build a full document */ { doc = makeDocObjUsingWholeDocument(duplicateAny(docTerm->Term), type); log_write("whole doc"); termNum += startTermOffset; /* point to next term */ } docs[docNum++] = doc; /* insert the new document */ docs[docNum] = NULL; /* keep the doc list terminated */ if (terms[termNum] != NULL) termNum++; /* skip the OR operator it necessary */ else break; /* we are done */ } return(docs); } /*----------------------------------------------------------------------*/ any* makeWAISTextQuery(docs) DocObj** docs; /* given a list of DocObjs, return an any whose contents is the corresponding type 1 query */ { any *buf = NULL; query_term** terms = NULL; terms = makeWAISQueryTerms(docs); buf = writeQuery(terms); doList((void**)terms,freeTerm); s_free(terms); return(buf); } /*----------------------------------------------------------------------*/ DocObj** readWAISTextQuery(buf) any* buf; /* given an any whose contents are type 1 queries of the WAIS sort, construct a list of the corresponding DocObjs */ { query_term** terms = NULL; DocObj** docs = NULL; terms = readQuery(buf); docs = makeWAISQueryDocs(terms); doList((void**)terms,freeTerm); s_free(terms); return(docs); } /*----------------------------------------------------------------------*/ /* Customized free WAIS object routines: */ /* */ /* This set of procedures is for applications to free a WAIS object */ /* which was made with makeWAISFOO. */ /* Each procedure frees only the memory that was allocated in its */ /* associated makeWAISFOO routine, thus it's not necessary for the */ /* caller to assign nulls to the pointer fields of the WAIS object. */ /*----------------------------------------------------------------------*/ void CSTFreeWAISInitResponse(init) WAISInitResponse* init; /* free an object made with makeWAISInitResponse */ { s_free(init); } /*----------------------------------------------------------------------*/ void CSTFreeWAISSearch(query) WAISSearch* query; /* destroy an object made with makeWAISSearch() */ { s_free(query); } /*----------------------------------------------------------------------*/ void CSTFreeDocObj(doc) DocObj* doc; /* free a docObj */ { s_free(doc); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentHeader(header) WAISDocumentHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentShortHeader(header) WAISDocumentShortHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentLongHeader(header) WAISDocumentLongHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISSearchResponse(response) WAISSearchResponse* response; { s_free(response); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentText(docText) WAISDocumentText* docText; { s_free(docText); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocHeadlines(docHeadline) WAISDocumentHeadlines* docHeadline; { s_free(docHeadline); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentCodes(docCodes) WAISDocumentCodes* docCodes; { s_free(docCodes); } /*----------------------------------------------------------------------*/ void CSTFreeWAISTextQuery(query) any* query; { freeAny(query); } /*----------------------------------------------------------------------*/ /* ** Routines originally from WMessage.c -- FM ** **----------------------------------------------------------------------*/ /* WIDE AREA INFORMATION SERVER SOFTWARE No guarantees or restrictions. See the readme file for the full standard disclaimer. 3.26.90 */ /* This file is for reading and writing the wais packet header. * Morris@think.com */ /* to do: * add check sum * what do you do when checksum is wrong? */ /*---------------------------------------------------------------------*/ void readWAISPacketHeader(msgBuffer,header_struct) char* msgBuffer; WAISMessage *header_struct; { /* msgBuffer is a string containing at least HEADER_LENGTH bytes. */ memmove(header_struct->msg_len,msgBuffer,(size_t)10); header_struct->msg_type = char_downcase((unsigned long)msgBuffer[10]); header_struct->hdr_vers = char_downcase((unsigned long)msgBuffer[11]); memmove(header_struct->server,(void*)(msgBuffer + 12),(size_t)10); header_struct->compression = char_downcase((unsigned long)msgBuffer[22]); header_struct->encoding = char_downcase((unsigned long)msgBuffer[23]); header_struct->msg_checksum = char_downcase((unsigned long)msgBuffer[24]); } /*---------------------------------------------------------------------*/ /* this modifies the header argument. See wais-message.h for the different * options for the arguments. */ void writeWAISPacketHeader(header, dataLen, type, server, compression, encoding, version) char* header; long dataLen; long type; char* server; long compression; long encoding; long version; /* Puts together the new wais before-the-z39-packet header. */ { char lengthBuf[11]; char serverBuf[11]; long serverLen = strlen(server); if (serverLen > 10) serverLen = 10; sprintf(lengthBuf, "%010ld", dataLen); strncpy(header,lengthBuf,10); header[10] = type & 0xFF; header[11] = version & 0xFF; strncpy(serverBuf,server,serverLen); strncpy((char*)(header + 12),serverBuf,serverLen); header[22] = compression & 0xFF; header[23] = encoding & 0xFF; header[24] = '0'; /* checkSum(header + HEADER_LENGTH,dataLen); XXX the result must be ascii */ } /*---------------------------------------------------------------------*/
avsm/openbsd-lynx
WWW/Library/Implementation/HTVMS_WaisProt.c
C
gpl-2.0
69,533
/******************************************************************************* * This file contains iSCSI extentions for RDMA (iSER) Verbs * * (c) Copyright 2013 RisingTide Systems LLC. * * Nicholas A. Bellinger <nab@linux-iscsi.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. ****************************************************************************/ #include <linux/string.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/in6.h> #include <rdma/ib_verbs.h> #include <rdma/rdma_cm.h> #include <target/target_core_base.h> #include <target/target_core_fabric.h> #include <target/iscsi/iscsi_transport.h> #include "isert_proto.h" #include "ib_isert.h" #define ISERT_MAX_CONN 8 #define ISER_MAX_RX_CQ_LEN (ISERT_QP_MAX_RECV_DTOS * ISERT_MAX_CONN) #define ISER_MAX_TX_CQ_LEN (ISERT_QP_MAX_REQ_DTOS * ISERT_MAX_CONN) static DEFINE_MUTEX(device_list_mutex); static LIST_HEAD(device_list); static struct workqueue_struct *isert_rx_wq; static struct workqueue_struct *isert_comp_wq; static struct kmem_cache *isert_cmd_cache; static void isert_release_work(struct work_struct *work); static void isert_qp_event_callback(struct ib_event *e, void *context) { struct isert_conn *isert_conn = (struct isert_conn *)context; pr_err("isert_qp_event_callback event: %d\n", e->event); switch (e->event) { case IB_EVENT_COMM_EST: rdma_notify(isert_conn->conn_cm_id, IB_EVENT_COMM_EST); break; case IB_EVENT_QP_LAST_WQE_REACHED: pr_warn("Reached TX IB_EVENT_QP_LAST_WQE_REACHED:\n"); break; default: break; } } static int isert_query_device(struct ib_device *ib_dev, struct ib_device_attr *devattr) { int ret; ret = ib_query_device(ib_dev, devattr); if (ret) { pr_err("ib_query_device() failed: %d\n", ret); return ret; } pr_debug("devattr->max_sge: %d\n", devattr->max_sge); pr_debug("devattr->max_sge_rd: %d\n", devattr->max_sge_rd); return 0; } static int isert_conn_setup_qp(struct isert_conn *isert_conn, struct rdma_cm_id *cma_id) { struct isert_device *device = isert_conn->conn_device; struct ib_qp_init_attr attr; struct ib_device_attr devattr; int ret, index, min_index = 0; memset(&devattr, 0, sizeof(struct ib_device_attr)); ret = isert_query_device(cma_id->device, &devattr); if (ret) return ret; mutex_lock(&device_list_mutex); for (index = 0; index < device->cqs_used; index++) if (device->cq_active_qps[index] < device->cq_active_qps[min_index]) min_index = index; device->cq_active_qps[min_index]++; pr_debug("isert_conn_setup_qp: Using min_index: %d\n", min_index); mutex_unlock(&device_list_mutex); memset(&attr, 0, sizeof(struct ib_qp_init_attr)); attr.event_handler = isert_qp_event_callback; attr.qp_context = isert_conn; attr.send_cq = device->dev_tx_cq[min_index]; attr.recv_cq = device->dev_rx_cq[min_index]; attr.cap.max_send_wr = ISERT_QP_MAX_REQ_DTOS; attr.cap.max_recv_wr = ISERT_QP_MAX_RECV_DTOS; /* * FIXME: Use devattr.max_sge - 2 for max_send_sge as * work-around for RDMA_READ.. */ attr.cap.max_send_sge = devattr.max_sge - 2; isert_conn->max_sge = attr.cap.max_send_sge; attr.cap.max_recv_sge = 1; attr.sq_sig_type = IB_SIGNAL_REQ_WR; attr.qp_type = IB_QPT_RC; pr_debug("isert_conn_setup_qp cma_id->device: %p\n", cma_id->device); pr_debug("isert_conn_setup_qp conn_pd->device: %p\n", isert_conn->conn_pd->device); ret = rdma_create_qp(cma_id, isert_conn->conn_pd, &attr); if (ret) { pr_err("rdma_create_qp failed for cma_id %d\n", ret); return ret; } isert_conn->conn_qp = cma_id->qp; pr_debug("rdma_create_qp() returned success >>>>>>>>>>>>>>>>>>>>>>>>>.\n"); return 0; } static void isert_cq_event_callback(struct ib_event *e, void *context) { pr_debug("isert_cq_event_callback event: %d\n", e->event); } static int isert_alloc_rx_descriptors(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iser_rx_desc *rx_desc; struct ib_sge *rx_sg; u64 dma_addr; int i, j; isert_conn->conn_rx_descs = kzalloc(ISERT_QP_MAX_RECV_DTOS * sizeof(struct iser_rx_desc), GFP_KERNEL); if (!isert_conn->conn_rx_descs) goto fail; rx_desc = isert_conn->conn_rx_descs; for (i = 0; i < ISERT_QP_MAX_RECV_DTOS; i++, rx_desc++) { dma_addr = ib_dma_map_single(ib_dev, (void *)rx_desc, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); if (ib_dma_mapping_error(ib_dev, dma_addr)) goto dma_map_fail; rx_desc->dma_addr = dma_addr; rx_sg = &rx_desc->rx_sg; rx_sg->addr = rx_desc->dma_addr; rx_sg->length = ISER_RX_PAYLOAD_SIZE; rx_sg->lkey = isert_conn->conn_mr->lkey; } isert_conn->conn_rx_desc_head = 0; return 0; dma_map_fail: rx_desc = isert_conn->conn_rx_descs; for (j = 0; j < i; j++, rx_desc++) { ib_dma_unmap_single(ib_dev, rx_desc->dma_addr, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); } kfree(isert_conn->conn_rx_descs); isert_conn->conn_rx_descs = NULL; fail: return -ENOMEM; } static void isert_free_rx_descriptors(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_device->ib_device; struct iser_rx_desc *rx_desc; int i; if (!isert_conn->conn_rx_descs) return; rx_desc = isert_conn->conn_rx_descs; for (i = 0; i < ISERT_QP_MAX_RECV_DTOS; i++, rx_desc++) { ib_dma_unmap_single(ib_dev, rx_desc->dma_addr, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); } kfree(isert_conn->conn_rx_descs); isert_conn->conn_rx_descs = NULL; } static void isert_cq_tx_callback(struct ib_cq *, void *); static void isert_cq_rx_callback(struct ib_cq *, void *); static int isert_create_device_ib_res(struct isert_device *device) { struct ib_device *ib_dev = device->ib_device; struct isert_cq_desc *cq_desc; int ret = 0, i, j; device->cqs_used = min_t(int, num_online_cpus(), device->ib_device->num_comp_vectors); device->cqs_used = min(ISERT_MAX_CQ, device->cqs_used); pr_debug("Using %d CQs, device %s supports %d vectors\n", device->cqs_used, device->ib_device->name, device->ib_device->num_comp_vectors); device->cq_desc = kzalloc(sizeof(struct isert_cq_desc) * device->cqs_used, GFP_KERNEL); if (!device->cq_desc) { pr_err("Unable to allocate device->cq_desc\n"); return -ENOMEM; } cq_desc = device->cq_desc; device->dev_pd = ib_alloc_pd(ib_dev); if (IS_ERR(device->dev_pd)) { ret = PTR_ERR(device->dev_pd); pr_err("ib_alloc_pd failed for dev_pd: %d\n", ret); goto out_cq_desc; } for (i = 0; i < device->cqs_used; i++) { cq_desc[i].device = device; cq_desc[i].cq_index = i; device->dev_rx_cq[i] = ib_create_cq(device->ib_device, isert_cq_rx_callback, isert_cq_event_callback, (void *)&cq_desc[i], ISER_MAX_RX_CQ_LEN, i); if (IS_ERR(device->dev_rx_cq[i])) { ret = PTR_ERR(device->dev_rx_cq[i]); device->dev_rx_cq[i] = NULL; goto out_cq; } device->dev_tx_cq[i] = ib_create_cq(device->ib_device, isert_cq_tx_callback, isert_cq_event_callback, (void *)&cq_desc[i], ISER_MAX_TX_CQ_LEN, i); if (IS_ERR(device->dev_tx_cq[i])) { ret = PTR_ERR(device->dev_tx_cq[i]); device->dev_tx_cq[i] = NULL; goto out_cq; } ret = ib_req_notify_cq(device->dev_rx_cq[i], IB_CQ_NEXT_COMP); if (ret) goto out_cq; ret = ib_req_notify_cq(device->dev_tx_cq[i], IB_CQ_NEXT_COMP); if (ret) goto out_cq; } device->dev_mr = ib_get_dma_mr(device->dev_pd, IB_ACCESS_LOCAL_WRITE); if (IS_ERR(device->dev_mr)) { ret = PTR_ERR(device->dev_mr); pr_err("ib_get_dma_mr failed for dev_mr: %d\n", ret); goto out_cq; } return 0; out_cq: for (j = 0; j < i; j++) { cq_desc = &device->cq_desc[j]; if (device->dev_rx_cq[j]) { cancel_work_sync(&cq_desc->cq_rx_work); ib_destroy_cq(device->dev_rx_cq[j]); } if (device->dev_tx_cq[j]) { cancel_work_sync(&cq_desc->cq_tx_work); ib_destroy_cq(device->dev_tx_cq[j]); } } ib_dealloc_pd(device->dev_pd); out_cq_desc: kfree(device->cq_desc); return ret; } static void isert_free_device_ib_res(struct isert_device *device) { struct isert_cq_desc *cq_desc; int i; for (i = 0; i < device->cqs_used; i++) { cq_desc = &device->cq_desc[i]; cancel_work_sync(&cq_desc->cq_rx_work); cancel_work_sync(&cq_desc->cq_tx_work); ib_destroy_cq(device->dev_rx_cq[i]); ib_destroy_cq(device->dev_tx_cq[i]); device->dev_rx_cq[i] = NULL; device->dev_tx_cq[i] = NULL; } ib_dereg_mr(device->dev_mr); ib_dealloc_pd(device->dev_pd); kfree(device->cq_desc); } static void isert_device_try_release(struct isert_device *device) { mutex_lock(&device_list_mutex); device->refcount--; if (!device->refcount) { isert_free_device_ib_res(device); list_del(&device->dev_node); kfree(device); } mutex_unlock(&device_list_mutex); } static struct isert_device * isert_device_find_by_ib_dev(struct rdma_cm_id *cma_id) { struct isert_device *device; int ret; mutex_lock(&device_list_mutex); list_for_each_entry(device, &device_list, dev_node) { if (device->ib_device->node_guid == cma_id->device->node_guid) { device->refcount++; mutex_unlock(&device_list_mutex); return device; } } device = kzalloc(sizeof(struct isert_device), GFP_KERNEL); if (!device) { mutex_unlock(&device_list_mutex); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&device->dev_node); device->ib_device = cma_id->device; ret = isert_create_device_ib_res(device); if (ret) { kfree(device); mutex_unlock(&device_list_mutex); return ERR_PTR(ret); } device->refcount++; list_add_tail(&device->dev_node, &device_list); mutex_unlock(&device_list_mutex); return device; } static int isert_connect_request(struct rdma_cm_id *cma_id, struct rdma_cm_event *event) { struct isert_np *isert_np = cma_id->context; struct iscsi_np *np = isert_np->np; struct isert_conn *isert_conn; struct isert_device *device; struct ib_device *ib_dev = cma_id->device; int ret = 0; spin_lock_bh(&np->np_thread_lock); if (!np->enabled) { spin_unlock_bh(&np->np_thread_lock); pr_debug("iscsi_np is not enabled, reject connect request\n"); return rdma_reject(cma_id, NULL, 0); } spin_unlock_bh(&np->np_thread_lock); pr_debug("Entering isert_connect_request cma_id: %p, context: %p\n", cma_id, cma_id->context); isert_conn = kzalloc(sizeof(struct isert_conn), GFP_KERNEL); if (!isert_conn) { pr_err("Unable to allocate isert_conn\n"); return -ENOMEM; } isert_conn->state = ISER_CONN_INIT; INIT_LIST_HEAD(&isert_conn->conn_accept_node); init_completion(&isert_conn->conn_login_comp); init_completion(&isert_conn->conn_wait); init_completion(&isert_conn->conn_wait_comp_err); kref_init(&isert_conn->conn_kref); kref_get(&isert_conn->conn_kref); mutex_init(&isert_conn->conn_mutex); INIT_WORK(&isert_conn->release_work, isert_release_work); cma_id->context = isert_conn; isert_conn->conn_cm_id = cma_id; isert_conn->responder_resources = event->param.conn.responder_resources; isert_conn->initiator_depth = event->param.conn.initiator_depth; pr_debug("Using responder_resources: %u initiator_depth: %u\n", isert_conn->responder_resources, isert_conn->initiator_depth); isert_conn->login_buf = kzalloc(ISCSI_DEF_MAX_RECV_SEG_LEN + ISER_RX_LOGIN_SIZE, GFP_KERNEL); if (!isert_conn->login_buf) { pr_err("Unable to allocate isert_conn->login_buf\n"); ret = -ENOMEM; goto out; } isert_conn->login_req_buf = isert_conn->login_buf; isert_conn->login_rsp_buf = isert_conn->login_buf + ISCSI_DEF_MAX_RECV_SEG_LEN; pr_debug("Set login_buf: %p login_req_buf: %p login_rsp_buf: %p\n", isert_conn->login_buf, isert_conn->login_req_buf, isert_conn->login_rsp_buf); isert_conn->login_req_dma = ib_dma_map_single(ib_dev, (void *)isert_conn->login_req_buf, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); ret = ib_dma_mapping_error(ib_dev, isert_conn->login_req_dma); if (ret) { pr_err("ib_dma_mapping_error failed for login_req_dma: %d\n", ret); isert_conn->login_req_dma = 0; goto out_login_buf; } isert_conn->login_rsp_dma = ib_dma_map_single(ib_dev, (void *)isert_conn->login_rsp_buf, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); ret = ib_dma_mapping_error(ib_dev, isert_conn->login_rsp_dma); if (ret) { pr_err("ib_dma_mapping_error failed for login_rsp_dma: %d\n", ret); isert_conn->login_rsp_dma = 0; goto out_req_dma_map; } device = isert_device_find_by_ib_dev(cma_id); if (IS_ERR(device)) { ret = PTR_ERR(device); goto out_rsp_dma_map; } isert_conn->conn_device = device; isert_conn->conn_pd = device->dev_pd; isert_conn->conn_mr = device->dev_mr; ret = isert_conn_setup_qp(isert_conn, cma_id); if (ret) goto out_conn_dev; mutex_lock(&isert_np->np_accept_mutex); list_add_tail(&isert_np->np_accept_list, &isert_conn->conn_accept_node); mutex_unlock(&isert_np->np_accept_mutex); pr_debug("isert_connect_request() waking up np_accept_wq: %p\n", np); wake_up(&isert_np->np_accept_wq); return 0; out_conn_dev: isert_device_try_release(device); out_rsp_dma_map: ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); out_req_dma_map: ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); out_login_buf: kfree(isert_conn->login_buf); out: kfree(isert_conn); return ret; } static void isert_connect_release(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_device *device = isert_conn->conn_device; int cq_index; pr_debug("Entering isert_connect_release(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); if (isert_conn->conn_qp) { cq_index = ((struct isert_cq_desc *) isert_conn->conn_qp->recv_cq->cq_context)->cq_index; pr_debug("isert_connect_release: cq_index: %d\n", cq_index); isert_conn->conn_device->cq_active_qps[cq_index]--; rdma_destroy_qp(isert_conn->conn_cm_id); } isert_free_rx_descriptors(isert_conn); rdma_destroy_id(isert_conn->conn_cm_id); if (isert_conn->login_buf) { ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); kfree(isert_conn->login_buf); } kfree(isert_conn); if (device) isert_device_try_release(device); pr_debug("Leaving isert_connect_release >>>>>>>>>>>>\n"); } static void isert_connected_handler(struct rdma_cm_id *cma_id) { struct isert_conn *isert_conn = cma_id->context; kref_get(&isert_conn->conn_kref); } static void isert_release_conn_kref(struct kref *kref) { struct isert_conn *isert_conn = container_of(kref, struct isert_conn, conn_kref); pr_debug("Calling isert_connect_release for final kref %s/%d\n", current->comm, current->pid); isert_connect_release(isert_conn); } static void isert_put_conn(struct isert_conn *isert_conn) { kref_put(&isert_conn->conn_kref, isert_release_conn_kref); } static void isert_disconnect_work(struct work_struct *work) { struct isert_conn *isert_conn = container_of(work, struct isert_conn, conn_logout_work); pr_debug("isert_disconnect_work(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); mutex_lock(&isert_conn->conn_mutex); if (isert_conn->state == ISER_CONN_UP) isert_conn->state = ISER_CONN_TERMINATING; if (isert_conn->post_recv_buf_count == 0 && atomic_read(&isert_conn->post_send_buf_count) == 0) { mutex_unlock(&isert_conn->conn_mutex); goto wake_up; } if (!isert_conn->conn_cm_id) { mutex_unlock(&isert_conn->conn_mutex); isert_put_conn(isert_conn); return; } if (isert_conn->disconnect) { /* Send DREQ/DREP towards our initiator */ rdma_disconnect(isert_conn->conn_cm_id); } mutex_unlock(&isert_conn->conn_mutex); wake_up: complete(&isert_conn->conn_wait); } static int isert_disconnected_handler(struct rdma_cm_id *cma_id, bool disconnect) { struct isert_conn *isert_conn; bool terminating = false; if (!cma_id->qp) { struct isert_np *isert_np = cma_id->context; isert_np->np_cm_id = NULL; break; case RDMA_CM_EVENT_ADDR_CHANGE: isert_np->np_cm_id = isert_setup_id(isert_np); if (IS_ERR(isert_np->np_cm_id)) { pr_err("isert np %p setup id failed: %ld\n", isert_np, PTR_ERR(isert_np->np_cm_id)); isert_np->np_cm_id = NULL; } break; default: pr_err("isert np %p Unexpected event %d\n", isert_np, event); } isert_conn = (struct isert_conn *)cma_id->context; isert_conn->disconnect = disconnect; INIT_WORK(&isert_conn->conn_logout_work, isert_disconnect_work); schedule_work(&isert_conn->conn_logout_work); return 0; } static int isert_cma_handler(struct rdma_cm_id *cma_id, struct rdma_cm_event *event) { int ret = 0; bool disconnect = false; pr_debug("isert_cma_handler: event %d status %d conn %p id %p\n", event->event, event->status, cma_id->context, cma_id); switch (event->event) { case RDMA_CM_EVENT_CONNECT_REQUEST: ret = isert_connect_request(cma_id, event); if (ret) pr_err("isert_cma_handler failed RDMA_CM_EVENT: 0x%08x %d\n", event->event, ret); break; case RDMA_CM_EVENT_ESTABLISHED: isert_connected_handler(cma_id); break; case RDMA_CM_EVENT_ADDR_CHANGE: /* FALLTHRU */ case RDMA_CM_EVENT_DISCONNECTED: /* FALLTHRU */ case RDMA_CM_EVENT_DEVICE_REMOVAL: /* FALLTHRU */ disconnect = true; case RDMA_CM_EVENT_TIMEWAIT_EXIT: /* FALLTHRU */ ret = isert_disconnected_handler(cma_id, disconnect); break; case RDMA_CM_EVENT_CONNECT_ERROR: default: pr_err("Unhandled RDMA CMA event: %d\n", event->event); break; } return ret; } static int isert_post_recv(struct isert_conn *isert_conn, u32 count) { struct ib_recv_wr *rx_wr, *rx_wr_failed; int i, ret; unsigned int rx_head = isert_conn->conn_rx_desc_head; struct iser_rx_desc *rx_desc; for (rx_wr = isert_conn->conn_rx_wr, i = 0; i < count; i++, rx_wr++) { rx_desc = &isert_conn->conn_rx_descs[rx_head]; rx_wr->wr_id = (unsigned long)rx_desc; rx_wr->sg_list = &rx_desc->rx_sg; rx_wr->num_sge = 1; rx_wr->next = rx_wr + 1; rx_head = (rx_head + 1) & (ISERT_QP_MAX_RECV_DTOS - 1); } rx_wr--; rx_wr->next = NULL; /* mark end of work requests list */ isert_conn->post_recv_buf_count += count; ret = ib_post_recv(isert_conn->conn_qp, isert_conn->conn_rx_wr, &rx_wr_failed); if (ret) { pr_err("ib_post_recv() failed with ret: %d\n", ret); isert_conn->post_recv_buf_count -= count; } else { pr_debug("isert_post_recv(): Posted %d RX buffers\n", count); isert_conn->conn_rx_desc_head = rx_head; } return ret; } static int isert_post_send(struct isert_conn *isert_conn, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_send_wr send_wr, *send_wr_failed; int ret; ib_dma_sync_single_for_device(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); send_wr.next = NULL; send_wr.wr_id = (unsigned long)tx_desc; send_wr.sg_list = tx_desc->tx_sg; send_wr.num_sge = tx_desc->num_sge; send_wr.opcode = IB_WR_SEND; send_wr.send_flags = IB_SEND_SIGNALED; atomic_inc(&isert_conn->post_send_buf_count); ret = ib_post_send(isert_conn->conn_qp, &send_wr, &send_wr_failed); if (ret) { pr_err("ib_post_send() failed, ret: %d\n", ret); atomic_dec(&isert_conn->post_send_buf_count); } return ret; } static void isert_create_send_desc(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; ib_dma_sync_single_for_cpu(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); memset(&tx_desc->iser_header, 0, sizeof(struct iser_hdr)); tx_desc->iser_header.flags = ISER_VER; tx_desc->num_sge = 1; tx_desc->isert_cmd = isert_cmd; if (tx_desc->tx_sg[0].lkey != isert_conn->conn_mr->lkey) { tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey; pr_debug("tx_desc %p lkey mismatch, fixing\n", tx_desc); } } static int isert_init_tx_hdrs(struct isert_conn *isert_conn, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; u64 dma_addr; dma_addr = ib_dma_map_single(ib_dev, (void *)tx_desc, ISER_HEADERS_LEN, DMA_TO_DEVICE); if (ib_dma_mapping_error(ib_dev, dma_addr)) { pr_err("ib_dma_mapping_error() failed\n"); return -ENOMEM; } tx_desc->dma_addr = dma_addr; tx_desc->tx_sg[0].addr = tx_desc->dma_addr; tx_desc->tx_sg[0].length = ISER_HEADERS_LEN; tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey; pr_debug("isert_init_tx_hdrs: Setup tx_sg[0].addr: 0x%llx length: %u" " lkey: 0x%08x\n", tx_desc->tx_sg[0].addr, tx_desc->tx_sg[0].length, tx_desc->tx_sg[0].lkey); return 0; } static void isert_init_send_wr(struct isert_cmd *isert_cmd, struct ib_send_wr *send_wr) { isert_cmd->rdma_wr.iser_ib_op = ISER_IB_SEND; send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc; send_wr->opcode = IB_WR_SEND; send_wr->send_flags = IB_SEND_SIGNALED; send_wr->sg_list = &isert_cmd->tx_desc.tx_sg[0]; send_wr->num_sge = isert_cmd->tx_desc.num_sge; } static int isert_rdma_post_recvl(struct isert_conn *isert_conn) { struct ib_recv_wr rx_wr, *rx_wr_fail; struct ib_sge sge; int ret; memset(&sge, 0, sizeof(struct ib_sge)); sge.addr = isert_conn->login_req_dma; sge.length = ISER_RX_LOGIN_SIZE; sge.lkey = isert_conn->conn_mr->lkey; pr_debug("Setup sge: addr: %llx length: %d 0x%08x\n", sge.addr, sge.length, sge.lkey); memset(&rx_wr, 0, sizeof(struct ib_recv_wr)); rx_wr.wr_id = (unsigned long)isert_conn->login_req_buf; rx_wr.sg_list = &sge; rx_wr.num_sge = 1; isert_conn->post_recv_buf_count++; ret = ib_post_recv(isert_conn->conn_qp, &rx_wr, &rx_wr_fail); if (ret) { pr_err("ib_post_recv() failed: %d\n", ret); isert_conn->post_recv_buf_count--; } pr_debug("ib_post_recv(): returned success >>>>>>>>>>>>>>>>>>>>>>>>\n"); return ret; } static int isert_put_login_tx(struct iscsi_conn *conn, struct iscsi_login *login, u32 length) { struct isert_conn *isert_conn = conn->context; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iser_tx_desc *tx_desc = &isert_conn->conn_login_tx_desc; int ret; isert_create_send_desc(isert_conn, NULL, tx_desc); memcpy(&tx_desc->iscsi_header, &login->rsp[0], sizeof(struct iscsi_hdr)); isert_init_tx_hdrs(isert_conn, tx_desc); if (length > 0) { struct ib_sge *tx_dsg = &tx_desc->tx_sg[1]; ib_dma_sync_single_for_cpu(ib_dev, isert_conn->login_rsp_dma, length, DMA_TO_DEVICE); memcpy(isert_conn->login_rsp_buf, login->rsp_buf, length); ib_dma_sync_single_for_device(ib_dev, isert_conn->login_rsp_dma, length, DMA_TO_DEVICE); tx_dsg->addr = isert_conn->login_rsp_dma; tx_dsg->length = length; tx_dsg->lkey = isert_conn->conn_mr->lkey; tx_desc->num_sge = 2; } if (!login->login_failed) { if (login->login_complete) { ret = isert_alloc_rx_descriptors(isert_conn); if (ret) return ret; ret = isert_post_recv(isert_conn, ISERT_MIN_POSTED_RX); if (ret) return ret; isert_conn->state = ISER_CONN_UP; goto post_send; } ret = isert_rdma_post_recvl(isert_conn); if (ret) return ret; } post_send: ret = isert_post_send(isert_conn, tx_desc); if (ret) return ret; return 0; } static void isert_rx_login_req(struct iser_rx_desc *rx_desc, int rx_buflen, struct isert_conn *isert_conn) { struct iscsi_conn *conn = isert_conn->conn; struct iscsi_login *login = conn->conn_login; int size; if (!login) { pr_err("conn->conn_login is NULL\n"); dump_stack(); return; } if (login->first_request) { struct iscsi_login_req *login_req = (struct iscsi_login_req *)&rx_desc->iscsi_header; /* * Setup the initial iscsi_login values from the leading * login request PDU. */ login->leading_connection = (!login_req->tsih) ? 1 : 0; login->current_stage = (login_req->flags & ISCSI_FLAG_LOGIN_CURRENT_STAGE_MASK) >> 2; login->version_min = login_req->min_version; login->version_max = login_req->max_version; memcpy(login->isid, login_req->isid, 6); login->cmd_sn = be32_to_cpu(login_req->cmdsn); login->init_task_tag = login_req->itt; login->initial_exp_statsn = be32_to_cpu(login_req->exp_statsn); login->cid = be16_to_cpu(login_req->cid); login->tsih = be16_to_cpu(login_req->tsih); } memcpy(&login->req[0], (void *)&rx_desc->iscsi_header, ISCSI_HDR_LEN); size = min(rx_buflen, MAX_KEY_VALUE_PAIRS); pr_debug("Using login payload size: %d, rx_buflen: %d MAX_KEY_VALUE_PAIRS: %d\n", size, rx_buflen, MAX_KEY_VALUE_PAIRS); memcpy(login->req_buf, &rx_desc->data[0], size); complete(&isert_conn->conn_login_comp); } static void isert_release_cmd(struct iscsi_cmd *cmd) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); pr_debug("Entering isert_release_cmd %p >>>>>>>>>>>>>>>.\n", isert_cmd); kfree(cmd->buf_ptr); kfree(cmd->tmr_req); kmem_cache_free(isert_cmd_cache, isert_cmd); } static struct iscsi_cmd *isert_alloc_cmd(struct iscsi_conn *conn, gfp_t gfp) { struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct isert_cmd *isert_cmd; isert_cmd = kmem_cache_zalloc(isert_cmd_cache, gfp); if (!isert_cmd) { pr_err("Unable to allocate isert_cmd\n"); return NULL; } isert_cmd->conn = isert_conn; isert_cmd->iscsi_cmd.release_cmd = &isert_release_cmd; return &isert_cmd->iscsi_cmd; } static int isert_handle_scsi_cmd(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct iser_rx_desc *rx_desc, unsigned char *buf) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)buf; struct scatterlist *sg; int imm_data, imm_data_len, unsol_data, sg_nents, rc; bool dump_payload = false; rc = iscsit_setup_scsi_cmd(conn, cmd, buf); if (rc < 0) return rc; imm_data = cmd->immediate_data; imm_data_len = cmd->first_burst_len; unsol_data = cmd->unsolicited_data; rc = iscsit_process_scsi_cmd(conn, cmd, hdr); if (rc < 0) { return 0; } else if (rc > 0) { dump_payload = true; goto sequence_cmd; } if (!imm_data) return 0; sg = &cmd->se_cmd.t_data_sg[0]; sg_nents = max(1UL, DIV_ROUND_UP(imm_data_len, PAGE_SIZE)); pr_debug("Copying Immediate SG: %p sg_nents: %u from %p imm_data_len: %d\n", sg, sg_nents, &rx_desc->data[0], imm_data_len); sg_copy_from_buffer(sg, sg_nents, &rx_desc->data[0], imm_data_len); cmd->write_data_done += imm_data_len; if (cmd->write_data_done == cmd->se_cmd.data_length) { spin_lock_bh(&cmd->istate_lock); cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT; cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT; spin_unlock_bh(&cmd->istate_lock); } sequence_cmd: rc = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn); if (!rc && dump_payload == false && unsol_data) iscsit_set_unsoliticed_dataout(cmd); else if (dump_payload && imm_data) target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd); return 0; } static int isert_handle_iscsi_dataout(struct isert_conn *isert_conn, struct iser_rx_desc *rx_desc, unsigned char *buf) { struct scatterlist *sg_start; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_cmd *cmd = NULL; struct iscsi_data *hdr = (struct iscsi_data *)buf; u32 unsol_data_len = ntoh24(hdr->dlength); int rc, sg_nents, sg_off, page_off; rc = iscsit_check_dataout_hdr(conn, buf, &cmd); if (rc < 0) return rc; else if (!cmd) return 0; /* * FIXME: Unexpected unsolicited_data out */ if (!cmd->unsolicited_data) { pr_err("Received unexpected solicited data payload\n"); dump_stack(); return -1; } pr_debug("Unsolicited DataOut unsol_data_len: %u, write_data_done: %u, data_length: %u\n", unsol_data_len, cmd->write_data_done, cmd->se_cmd.data_length); sg_off = cmd->write_data_done / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; sg_nents = max(1UL, DIV_ROUND_UP(unsol_data_len, PAGE_SIZE)); page_off = cmd->write_data_done % PAGE_SIZE; /* * FIXME: Non page-aligned unsolicited_data out */ if (page_off) { pr_err("Received unexpected non-page aligned data payload\n"); dump_stack(); return -1; } pr_debug("Copying DataOut: sg_start: %p, sg_off: %u sg_nents: %u from %p %u\n", sg_start, sg_off, sg_nents, &rx_desc->data[0], unsol_data_len); sg_copy_from_buffer(sg_start, sg_nents, &rx_desc->data[0], unsol_data_len); rc = iscsit_check_dataout_payload(cmd, hdr, false); if (rc < 0) return rc; return 0; } static int isert_rx_opcode(struct isert_conn *isert_conn, struct iser_rx_desc *rx_desc, uint32_t read_stag, uint64_t read_va, uint32_t write_stag, uint64_t write_va) { struct iscsi_hdr *hdr = &rx_desc->iscsi_header; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_cmd *cmd; struct isert_cmd *isert_cmd; int ret = -EINVAL; u8 opcode = (hdr->opcode & ISCSI_OPCODE_MASK); switch (opcode) { case ISCSI_OP_SCSI_CMD: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); isert_cmd->read_stag = read_stag; isert_cmd->read_va = read_va; isert_cmd->write_stag = write_stag; isert_cmd->write_va = write_va; ret = isert_handle_scsi_cmd(isert_conn, isert_cmd, rx_desc, (unsigned char *)hdr); break; case ISCSI_OP_NOOP_OUT: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_nop_out(conn, cmd, (unsigned char *)hdr); break; case ISCSI_OP_SCSI_DATA_OUT: ret = isert_handle_iscsi_dataout(isert_conn, rx_desc, (unsigned char *)hdr); break; case ISCSI_OP_SCSI_TMFUNC: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_task_mgt_cmd(conn, cmd, (unsigned char *)hdr); break; case ISCSI_OP_LOGOUT: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_logout_cmd(conn, cmd, (unsigned char *)hdr); if (ret > 0) wait_for_completion_timeout(&conn->conn_logout_comp, SECONDS_FOR_LOGOUT_COMP * HZ); break; default: pr_err("Got unknown iSCSI OpCode: 0x%02x\n", opcode); dump_stack(); break; } return ret; } static void isert_rx_do_work(struct iser_rx_desc *rx_desc, struct isert_conn *isert_conn) { struct iser_hdr *iser_hdr = &rx_desc->iser_header; uint64_t read_va = 0, write_va = 0; uint32_t read_stag = 0, write_stag = 0; int rc; switch (iser_hdr->flags & 0xF0) { case ISCSI_CTRL: if (iser_hdr->flags & ISER_RSV) { read_stag = be32_to_cpu(iser_hdr->read_stag); read_va = be64_to_cpu(iser_hdr->read_va); pr_debug("ISER_RSV: read_stag: 0x%08x read_va: 0x%16llx\n", read_stag, (unsigned long long)read_va); } if (iser_hdr->flags & ISER_WSV) { write_stag = be32_to_cpu(iser_hdr->write_stag); write_va = be64_to_cpu(iser_hdr->write_va); pr_debug("ISER_WSV: write__stag: 0x%08x write_va: 0x%16llx\n", write_stag, (unsigned long long)write_va); } pr_debug("ISER ISCSI_CTRL PDU\n"); break; case ISER_HELLO: pr_err("iSER Hello message\n"); break; default: pr_warn("Unknown iSER hdr flags: 0x%02x\n", iser_hdr->flags); break; } rc = isert_rx_opcode(isert_conn, rx_desc, read_stag, read_va, write_stag, write_va); } static void isert_rx_completion(struct iser_rx_desc *desc, struct isert_conn *isert_conn, unsigned long xfer_len) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iscsi_hdr *hdr; u64 rx_dma; int rx_buflen, outstanding; if ((char *)desc == isert_conn->login_req_buf) { rx_dma = isert_conn->login_req_dma; rx_buflen = ISER_RX_LOGIN_SIZE; pr_debug("ISER login_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n", rx_dma, rx_buflen); } else { rx_dma = desc->dma_addr; rx_buflen = ISER_RX_PAYLOAD_SIZE; pr_debug("ISER req_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n", rx_dma, rx_buflen); } ib_dma_sync_single_for_cpu(ib_dev, rx_dma, rx_buflen, DMA_FROM_DEVICE); hdr = &desc->iscsi_header; pr_debug("iSCSI opcode: 0x%02x, ITT: 0x%08x, flags: 0x%02x dlen: %d\n", hdr->opcode, hdr->itt, hdr->flags, (int)(xfer_len - ISER_HEADERS_LEN)); if ((char *)desc == isert_conn->login_req_buf) isert_rx_login_req(desc, xfer_len - ISER_HEADERS_LEN, isert_conn); else isert_rx_do_work(desc, isert_conn); ib_dma_sync_single_for_device(ib_dev, rx_dma, rx_buflen, DMA_FROM_DEVICE); isert_conn->post_recv_buf_count--; pr_debug("iSERT: Decremented post_recv_buf_count: %d\n", isert_conn->post_recv_buf_count); if ((char *)desc == isert_conn->login_req_buf) return; outstanding = isert_conn->post_recv_buf_count; if (outstanding + ISERT_MIN_POSTED_RX <= ISERT_QP_MAX_RECV_DTOS) { int err, count = min(ISERT_QP_MAX_RECV_DTOS - outstanding, ISERT_MIN_POSTED_RX); err = isert_post_recv(isert_conn, count); if (err) { pr_err("isert_post_recv() count: %d failed, %d\n", count, err); } } } static void isert_unmap_cmd(struct isert_cmd *isert_cmd, struct isert_conn *isert_conn) { struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; pr_debug("isert_unmap_cmd >>>>>>>>>>>>>>>>>>>>>>>\n"); if (wr->sge) { ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE); wr->sge = NULL; } kfree(wr->send_wr); wr->send_wr = NULL; kfree(isert_cmd->ib_sge); isert_cmd->ib_sge = NULL; } static void isert_put_cmd(struct isert_cmd *isert_cmd, bool comp_err) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct isert_conn *isert_conn = isert_cmd->conn; struct iscsi_conn *conn = isert_conn->conn; pr_debug("Entering isert_put_cmd: %p\n", isert_cmd); switch (cmd->iscsi_opcode) { case ISCSI_OP_SCSI_CMD: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); if (cmd->data_direction == DMA_TO_DEVICE) { iscsit_stop_dataout_timer(cmd); /* * Check for special case during comp_err where * WRITE_PENDING has been handed off from core, * but requires an extra target_put_sess_cmd() * before transport_generic_free_cmd() below. */ if (comp_err && cmd->se_cmd.t_state == TRANSPORT_WRITE_PENDING) { struct se_cmd *se_cmd = &cmd->se_cmd; target_put_sess_cmd(se_cmd->se_sess, se_cmd); } } isert_unmap_cmd(isert_cmd, isert_conn); transport_generic_free_cmd(&cmd->se_cmd, 0); break; case ISCSI_OP_SCSI_TMFUNC: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); transport_generic_free_cmd(&cmd->se_cmd, 0); break; case ISCSI_OP_REJECT: case ISCSI_OP_NOOP_OUT: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); /* * Handle special case for REJECT when iscsi_add_reject*() has * overwritten the original iscsi_opcode assignment, and the * associated cmd->se_cmd needs to be released. */ if (cmd->se_cmd.se_tfo != NULL) { pr_debug("Calling transport_generic_free_cmd from" " isert_put_cmd for 0x%02x\n", cmd->iscsi_opcode); transport_generic_free_cmd(&cmd->se_cmd, 0); break; } /* * Fall-through */ default: isert_release_cmd(cmd); break; } } static void isert_unmap_tx_desc(struct iser_tx_desc *tx_desc, struct ib_device *ib_dev) { if (tx_desc->dma_addr != 0) { pr_debug("Calling ib_dma_unmap_single for tx_desc->dma_addr\n"); ib_dma_unmap_single(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); tx_desc->dma_addr = 0; } } static void isert_completion_put(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd, struct ib_device *ib_dev, bool comp_err) { if (isert_cmd->sense_buf_dma != 0) { pr_debug("Calling ib_dma_unmap_single for isert_cmd->sense_buf_dma\n"); ib_dma_unmap_single(ib_dev, isert_cmd->sense_buf_dma, isert_cmd->sense_buf_len, DMA_TO_DEVICE); isert_cmd->sense_buf_dma = 0; } isert_unmap_tx_desc(tx_desc, ib_dev); isert_put_cmd(isert_cmd, comp_err); } static void isert_completion_rdma_read(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd) { struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct se_cmd *se_cmd = &cmd->se_cmd; struct ib_device *ib_dev = isert_cmd->conn->conn_cm_id->device; iscsit_stop_dataout_timer(cmd); if (wr->sge) { pr_debug("isert_do_rdma_read_comp: Unmapping wr->sge from t_data_sg\n"); ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE); wr->sge = NULL; } if (isert_cmd->ib_sge) { pr_debug("isert_do_rdma_read_comp: Freeing isert_cmd->ib_sge\n"); kfree(isert_cmd->ib_sge); isert_cmd->ib_sge = NULL; } cmd->write_data_done = se_cmd->data_length; wr->send_wr_num = 0; pr_debug("isert_do_rdma_read_comp, calling target_execute_cmd\n"); spin_lock_bh(&cmd->istate_lock); cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT; cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT; spin_unlock_bh(&cmd->istate_lock); target_execute_cmd(se_cmd); } static void isert_do_control_comp(struct work_struct *work) { struct isert_cmd *isert_cmd = container_of(work, struct isert_cmd, comp_work); struct isert_conn *isert_conn = isert_cmd->conn; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; switch (cmd->i_state) { case ISTATE_SEND_TASKMGTRSP: pr_debug("Calling iscsit_tmr_post_handler >>>>>>>>>>>>>>>>>\n"); atomic_dec(&isert_conn->post_send_buf_count); iscsit_tmr_post_handler(cmd, cmd->conn); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(&isert_cmd->tx_desc, isert_cmd, ib_dev, false); break; case ISTATE_SEND_REJECT: pr_debug("Got isert_do_control_comp ISTATE_SEND_REJECT: >>>\n"); atomic_dec(&isert_conn->post_send_buf_count); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(&isert_cmd->tx_desc, isert_cmd, ib_dev, false); break; case ISTATE_SEND_LOGOUTRSP: pr_debug("Calling iscsit_logout_post_handler >>>>>>>>>>>>>>\n"); atomic_dec(&isert_conn->post_send_buf_count); iscsit_logout_post_handler(cmd, cmd->conn); break; default: pr_err("Unknown do_control_comp i_state %d\n", cmd->i_state); dump_stack(); break; } } static void isert_response_completion(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd, struct isert_conn *isert_conn, struct ib_device *ib_dev) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; if (cmd->i_state == ISTATE_SEND_TASKMGTRSP || cmd->i_state == ISTATE_SEND_LOGOUTRSP || cmd->i_state == ISTATE_SEND_REJECT) { isert_unmap_tx_desc(tx_desc, ib_dev); INIT_WORK(&isert_cmd->comp_work, isert_do_control_comp); queue_work(isert_comp_wq, &isert_cmd->comp_work); return; } atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(tx_desc, isert_cmd, ib_dev, false); } static void isert_send_completion(struct iser_tx_desc *tx_desc, struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_cmd *isert_cmd = tx_desc->isert_cmd; struct isert_rdma_wr *wr; if (!isert_cmd) { atomic_dec(&isert_conn->post_send_buf_count); isert_unmap_tx_desc(tx_desc, ib_dev); return; } wr = &isert_cmd->rdma_wr; switch (wr->iser_ib_op) { case ISER_IB_RECV: pr_err("isert_send_completion: Got ISER_IB_RECV\n"); dump_stack(); break; case ISER_IB_SEND: pr_debug("isert_send_completion: Got ISER_IB_SEND\n"); isert_response_completion(tx_desc, isert_cmd, isert_conn, ib_dev); break; case ISER_IB_RDMA_WRITE: pr_err("isert_send_completion: Got ISER_IB_RDMA_WRITE\n"); dump_stack(); break; case ISER_IB_RDMA_READ: pr_debug("isert_send_completion: Got ISER_IB_RDMA_READ:\n"); atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count); isert_completion_rdma_read(tx_desc, isert_cmd); break; default: pr_err("Unknown wr->iser_ib_op: 0x%02x\n", wr->iser_ib_op); dump_stack(); break; } } static void isert_cq_tx_comp_err(struct iser_tx_desc *tx_desc, struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_cmd *isert_cmd = tx_desc->isert_cmd; if (!isert_cmd) isert_unmap_tx_desc(tx_desc, ib_dev); else isert_completion_put(tx_desc, isert_cmd, ib_dev, true); } static void isert_cq_rx_comp_err(struct isert_conn *isert_conn) { struct iscsi_conn *conn = isert_conn->conn; if (isert_conn->post_recv_buf_count) return; if (conn->sess) { target_sess_cmd_list_set_waiting(conn->sess->se_sess); target_wait_for_sess_cmds(conn->sess->se_sess); } while (atomic_read(&isert_conn->post_send_buf_count)) msleep(3000); mutex_lock(&isert_conn->conn_mutex); isert_conn->state = ISER_CONN_DOWN; mutex_unlock(&isert_conn->conn_mutex); iscsit_cause_connection_reinstatement(isert_conn->conn, 0); complete(&isert_conn->conn_wait_comp_err); } static void isert_cq_tx_work(struct work_struct *work) { struct isert_cq_desc *cq_desc = container_of(work, struct isert_cq_desc, cq_tx_work); struct isert_device *device = cq_desc->device; int cq_index = cq_desc->cq_index; struct ib_cq *tx_cq = device->dev_tx_cq[cq_index]; struct isert_conn *isert_conn; struct iser_tx_desc *tx_desc; struct ib_wc wc; while (ib_poll_cq(tx_cq, 1, &wc) == 1) { tx_desc = (struct iser_tx_desc *)(unsigned long)wc.wr_id; isert_conn = wc.qp->qp_context; if (wc.status == IB_WC_SUCCESS) { isert_send_completion(tx_desc, isert_conn); } else { pr_debug("TX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n"); pr_debug("TX wc.status: 0x%08x\n", wc.status); atomic_dec(&isert_conn->post_send_buf_count); isert_cq_tx_comp_err(tx_desc, isert_conn); } } ib_req_notify_cq(tx_cq, IB_CQ_NEXT_COMP); } static void isert_cq_tx_callback(struct ib_cq *cq, void *context) { struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context; INIT_WORK(&cq_desc->cq_tx_work, isert_cq_tx_work); queue_work(isert_comp_wq, &cq_desc->cq_tx_work); } static void isert_cq_rx_work(struct work_struct *work) { struct isert_cq_desc *cq_desc = container_of(work, struct isert_cq_desc, cq_rx_work); struct isert_device *device = cq_desc->device; int cq_index = cq_desc->cq_index; struct ib_cq *rx_cq = device->dev_rx_cq[cq_index]; struct isert_conn *isert_conn; struct iser_rx_desc *rx_desc; struct ib_wc wc; unsigned long xfer_len; while (ib_poll_cq(rx_cq, 1, &wc) == 1) { rx_desc = (struct iser_rx_desc *)(unsigned long)wc.wr_id; isert_conn = wc.qp->qp_context; if (wc.status == IB_WC_SUCCESS) { xfer_len = (unsigned long)wc.byte_len; isert_rx_completion(rx_desc, isert_conn, xfer_len); } else { pr_debug("RX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n"); if (wc.status != IB_WC_WR_FLUSH_ERR) pr_debug("RX wc.status: 0x%08x\n", wc.status); isert_conn->post_recv_buf_count--; isert_cq_rx_comp_err(isert_conn); } } ib_req_notify_cq(rx_cq, IB_CQ_NEXT_COMP); } static void isert_cq_rx_callback(struct ib_cq *cq, void *context) { struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context; INIT_WORK(&cq_desc->cq_rx_work, isert_cq_rx_work); queue_work(isert_rx_wq, &cq_desc->cq_rx_work); } static int isert_post_response(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd) { struct ib_send_wr *wr_failed; int ret; atomic_inc(&isert_conn->post_send_buf_count); ret = ib_post_send(isert_conn->conn_qp, &isert_cmd->tx_desc.send_wr, &wr_failed); if (ret) { pr_err("ib_post_send failed with %d\n", ret); atomic_dec(&isert_conn->post_send_buf_count); return ret; } return ret; } static int isert_put_response(struct iscsi_conn *conn, struct iscsi_cmd *cmd) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; struct iscsi_scsi_rsp *hdr = (struct iscsi_scsi_rsp *) &isert_cmd->tx_desc.iscsi_header; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_rsp_pdu(cmd, conn, true, hdr); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); /* * Attach SENSE DATA payload to iSCSI Response PDU */ if (cmd->se_cmd.sense_buffer && ((cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) || (cmd->se_cmd.se_cmd_flags & SCF_EMULATED_TASK_SENSE))) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1]; u32 padding, sense_len; put_unaligned_be16(cmd->se_cmd.scsi_sense_length, cmd->sense_buffer); cmd->se_cmd.scsi_sense_length += sizeof(__be16); padding = -(cmd->se_cmd.scsi_sense_length) & 3; hton24(hdr->dlength, (u32)cmd->se_cmd.scsi_sense_length); sense_len = cmd->se_cmd.scsi_sense_length + padding; isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev, (void *)cmd->sense_buffer, sense_len, DMA_TO_DEVICE); isert_cmd->sense_buf_len = sense_len; tx_dsg->addr = isert_cmd->sense_buf_dma; tx_dsg->length = sense_len; tx_dsg->lkey = isert_conn->conn_mr->lkey; isert_cmd->tx_desc.num_sge = 2; } isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting SCSI Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_nopin(struct iscsi_cmd *cmd, struct iscsi_conn *conn, bool nopout_response) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_nopin_rsp(cmd, conn, (struct iscsi_nopin *) &isert_cmd->tx_desc.iscsi_header, nopout_response); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting NOPIN Reponse IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_logout_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_logout_rsp(cmd, conn, (struct iscsi_logout_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Logout Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_tm_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_task_mgt_rsp(cmd, conn, (struct iscsi_tm_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Task Management Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_reject(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1]; struct iscsi_reject *hdr = (struct iscsi_reject *)&isert_cmd->tx_desc.iscsi_header; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_reject(cmd, conn, hdr); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); hton24(hdr->dlength, ISCSI_HDR_LEN); isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev, (void *)cmd->buf_ptr, ISCSI_HDR_LEN, DMA_TO_DEVICE); isert_cmd->sense_buf_len = ISCSI_HDR_LEN; tx_dsg->addr = isert_cmd->sense_buf_dma; tx_dsg->length = ISCSI_HDR_LEN; tx_dsg->lkey = isert_conn->conn_mr->lkey; isert_cmd->tx_desc.num_sge = 2; isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Reject IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_build_rdma_wr(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct ib_sge *ib_sge, struct ib_send_wr *send_wr, u32 data_left, u32 offset) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct scatterlist *sg_start, *tmp_sg; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; u32 sg_off, page_off; int i = 0, sg_nents; sg_off = offset / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; sg_nents = min(cmd->se_cmd.t_data_nents - sg_off, isert_conn->max_sge); page_off = offset % PAGE_SIZE; send_wr->sg_list = ib_sge; send_wr->num_sge = sg_nents; send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc; /* * Perform mapping of TCM scatterlist memory ib_sge dma_addr. */ for_each_sg(sg_start, tmp_sg, sg_nents, i) { pr_debug("ISER RDMA from SGL dma_addr: 0x%16llx dma_len: %u, page_off: %u\n", (unsigned long long)tmp_sg->dma_address, tmp_sg->length, page_off); ib_sge->addr = ib_sg_dma_address(ib_dev, tmp_sg) + page_off; ib_sge->length = min_t(u32, data_left, ib_sg_dma_len(ib_dev, tmp_sg) - page_off); ib_sge->lkey = isert_conn->conn_mr->lkey; pr_debug("RDMA ib_sge: addr: 0x%16llx length: %u\n", ib_sge->addr, ib_sge->length); page_off = 0; data_left -= ib_sge->length; ib_sge++; pr_debug("Incrementing ib_sge pointer to %p\n", ib_sge); } pr_debug("Set outgoing sg_list: %p num_sg: %u from TCM SGLs\n", send_wr->sg_list, send_wr->num_sge); return sg_nents; } static int isert_put_datain(struct iscsi_conn *conn, struct iscsi_cmd *cmd) { struct se_cmd *se_cmd = &cmd->se_cmd; struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *wr_failed, *send_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *ib_sge; struct scatterlist *sg; u32 offset = 0, data_len, data_left, rdma_write_max; int rc, ret = 0, count, sg_nents, i, ib_sge_cnt; pr_debug("RDMA_WRITE: data_length: %u\n", se_cmd->data_length); sg = &se_cmd->t_data_sg[0]; sg_nents = se_cmd->t_data_nents; count = ib_dma_map_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE); if (unlikely(!count)) { pr_err("Unable to map put_datain SGs\n"); return -EINVAL; } wr->sge = sg; wr->num_sge = sg_nents; pr_debug("Mapped IB count: %u sg: %p sg_nents: %u for RDMA_WRITE\n", count, sg, sg_nents); ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL); if (!ib_sge) { pr_warn("Unable to allocate datain ib_sge\n"); ret = -ENOMEM; goto unmap_sg; } isert_cmd->ib_sge = ib_sge; pr_debug("Allocated ib_sge: %p from t_data_ents: %d for RDMA_WRITE\n", ib_sge, se_cmd->t_data_nents); wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge); wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num, GFP_KERNEL); if (!wr->send_wr) { pr_err("Unable to allocate wr->send_wr\n"); ret = -ENOMEM; goto unmap_sg; } pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n", wr->send_wr, wr->send_wr_num); iscsit_increment_maxcmdsn(cmd, conn->sess); cmd->stat_sn = conn->stat_sn++; wr->isert_cmd = isert_cmd; rdma_write_max = isert_conn->max_sge * PAGE_SIZE; data_left = se_cmd->data_length; for (i = 0; i < wr->send_wr_num; i++) { send_wr = &isert_cmd->rdma_wr.send_wr[i]; data_len = min(data_left, rdma_write_max); send_wr->opcode = IB_WR_RDMA_WRITE; send_wr->send_flags = 0; send_wr->wr.rdma.remote_addr = isert_cmd->read_va + offset; send_wr->wr.rdma.rkey = isert_cmd->read_stag; ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge, send_wr, data_len, offset); ib_sge += ib_sge_cnt; if (i + 1 == wr->send_wr_num) send_wr->next = &isert_cmd->tx_desc.send_wr; else send_wr->next = &wr->send_wr[i + 1]; offset += data_len; data_left -= data_len; } /* * Build isert_conn->tx_desc for iSCSI response PDU and attach */ isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_rsp_pdu(cmd, conn, false, (struct iscsi_scsi_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, &isert_cmd->tx_desc.send_wr); atomic_add(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed); if (rc) { pr_warn("ib_post_send() failed for IB_WR_RDMA_WRITE\n"); atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); } pr_debug("Posted RDMA_WRITE + Response for iSER Data READ\n"); return 1; unmap_sg: ib_dma_unmap_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE); return ret; } static int isert_get_dataout(struct iscsi_conn *conn, struct iscsi_cmd *cmd, bool recovery) { struct se_cmd *se_cmd = &cmd->se_cmd; struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *wr_failed, *send_wr; struct ib_sge *ib_sge; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct scatterlist *sg_start; u32 sg_off, sg_nents, page_off, va_offset = 0; u32 offset = 0, data_len, data_left, rdma_write_max; int rc, ret = 0, count, i, ib_sge_cnt; pr_debug("RDMA_READ: data_length: %u write_data_done: %u\n", se_cmd->data_length, cmd->write_data_done); sg_off = cmd->write_data_done / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; page_off = cmd->write_data_done % PAGE_SIZE; pr_debug("RDMA_READ: sg_off: %d, sg_start: %p page_off: %d\n", sg_off, sg_start, page_off); data_left = se_cmd->data_length - cmd->write_data_done; sg_nents = se_cmd->t_data_nents - sg_off; pr_debug("RDMA_READ: data_left: %d, sg_nents: %d\n", data_left, sg_nents); count = ib_dma_map_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE); if (unlikely(!count)) { pr_err("Unable to map get_dataout SGs\n"); return -EINVAL; } wr->sge = sg_start; wr->num_sge = sg_nents; pr_debug("Mapped IB count: %u sg_start: %p sg_nents: %u for RDMA_READ\n", count, sg_start, sg_nents); ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL); if (!ib_sge) { pr_warn("Unable to allocate dataout ib_sge\n"); ret = -ENOMEM; goto unmap_sg; } isert_cmd->ib_sge = ib_sge; pr_debug("Using ib_sge: %p from sg_ents: %d for RDMA_READ\n", ib_sge, sg_nents); wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge); wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num, GFP_KERNEL); if (!wr->send_wr) { pr_debug("Unable to allocate wr->send_wr\n"); ret = -ENOMEM; goto unmap_sg; } pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n", wr->send_wr, wr->send_wr_num); isert_cmd->tx_desc.isert_cmd = isert_cmd; wr->iser_ib_op = ISER_IB_RDMA_READ; wr->isert_cmd = isert_cmd; rdma_write_max = isert_conn->max_sge * PAGE_SIZE; offset = cmd->write_data_done; for (i = 0; i < wr->send_wr_num; i++) { send_wr = &isert_cmd->rdma_wr.send_wr[i]; data_len = min(data_left, rdma_write_max); send_wr->opcode = IB_WR_RDMA_READ; send_wr->wr.rdma.remote_addr = isert_cmd->write_va + va_offset; send_wr->wr.rdma.rkey = isert_cmd->write_stag; ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge, send_wr, data_len, offset); ib_sge += ib_sge_cnt; if (i + 1 == wr->send_wr_num) send_wr->send_flags = IB_SEND_SIGNALED; else send_wr->next = &wr->send_wr[i + 1]; offset += data_len; va_offset += data_len; data_left -= data_len; } atomic_add(wr->send_wr_num, &isert_conn->post_send_buf_count); rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed); if (rc) { pr_warn("ib_post_send() failed for IB_WR_RDMA_READ\n"); atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count); } pr_debug("Posted RDMA_READ memory for ISER Data WRITE\n"); return 0; unmap_sg: ib_dma_unmap_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE); return ret; } static int isert_immediate_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state) { int ret; switch (state) { case ISTATE_SEND_NOPIN_WANT_RESPONSE: ret = isert_put_nopin(cmd, conn, false); break; default: pr_err("Unknown immediate state: 0x%02x\n", state); ret = -EINVAL; break; } return ret; } static int isert_response_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state) { int ret; switch (state) { case ISTATE_SEND_LOGOUTRSP: ret = isert_put_logout_rsp(cmd, conn); if (!ret) { pr_debug("Returning iSER Logout -EAGAIN\n"); ret = -EAGAIN; } break; case ISTATE_SEND_NOPIN: ret = isert_put_nopin(cmd, conn, true); break; case ISTATE_SEND_TASKMGTRSP: ret = isert_put_tm_rsp(cmd, conn); break; case ISTATE_SEND_REJECT: ret = isert_put_reject(cmd, conn); break; case ISTATE_SEND_STATUS: /* * Special case for sending non GOOD SCSI status from TX thread * context during pre se_cmd excecution failure. */ ret = isert_put_response(conn, cmd); break; default: pr_err("Unknown response state: 0x%02x\n", state); ret = -EINVAL; break; } return ret; } struct rdma_cm_id * isert_setup_id(struct isert_np *isert_np) { struct iscsi_np *np = isert_np->np; struct rdma_cm_id *id; struct sockaddr *sa; int ret; sa = (struct sockaddr *)&np->np_sockaddr; pr_debug("ksockaddr: %p, sa: %p\n", &np->np_sockaddr, sa); id = rdma_create_id(isert_cma_handler, isert_np, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(id)) { pr_err("rdma_create_id() failed: %ld\n", PTR_ERR(id)); ret = PTR_ERR(id); goto out; } pr_debug("id %p context %p\n", id, id->context); ret = rdma_bind_addr(id, sa); if (ret) { pr_err("rdma_bind_addr() failed: %d\n", ret); goto out_id; } ret = rdma_listen(id, ISERT_RDMA_LISTEN_BACKLOG); if (ret) { pr_err("rdma_listen() failed: %d\n", ret); goto out_id; } return id; out_id: rdma_destroy_id(id); out: return ERR_PTR(ret); } static int isert_setup_np(struct iscsi_np *np, struct __kernel_sockaddr_storage *ksockaddr) { struct isert_np *isert_np; struct rdma_cm_id *isert_lid; int ret; isert_np = kzalloc(sizeof(struct isert_np), GFP_KERNEL); if (!isert_np) { pr_err("Unable to allocate struct isert_np\n"); return -ENOMEM; } init_waitqueue_head(&isert_np->np_accept_wq); mutex_init(&isert_np->np_accept_mutex); INIT_LIST_HEAD(&isert_np->np_accept_list); init_completion(&isert_np->np_login_comp); isert_np->np = np; /* * Setup the np->np_sockaddr from the passed sockaddr setup * in iscsi_target_configfs.c code.. */ memcpy(&np->np_sockaddr, ksockaddr, sizeof(struct __kernel_sockaddr_storage)); isert_lid = isert_setup_id(isert_np); if (IS_ERR(isert_lid)) { ret = PTR_ERR(isert_lid); goto out; } isert_np->np_cm_id = isert_lid; np->np_context = isert_np; return 0; out: kfree(isert_np); return ret; } static int isert_check_accept_queue(struct isert_np *isert_np) { int empty; mutex_lock(&isert_np->np_accept_mutex); empty = list_empty(&isert_np->np_accept_list); mutex_unlock(&isert_np->np_accept_mutex); return empty; } static int isert_rdma_accept(struct isert_conn *isert_conn) { struct rdma_cm_id *cm_id = isert_conn->conn_cm_id; struct rdma_conn_param cp; int ret; memset(&cp, 0, sizeof(struct rdma_conn_param)); cp.responder_resources = isert_conn->responder_resources; cp.initiator_depth = isert_conn->initiator_depth; cp.retry_count = 7; cp.rnr_retry_count = 7; pr_debug("Before rdma_accept >>>>>>>>>>>>>>>>>>>>.\n"); ret = rdma_accept(cm_id, &cp); if (ret) { pr_err("rdma_accept() failed with: %d\n", ret); return ret; } pr_debug("After rdma_accept >>>>>>>>>>>>>>>>>>>>>.\n"); return 0; } static int isert_get_login_rx(struct iscsi_conn *conn, struct iscsi_login *login) { struct isert_conn *isert_conn = (struct isert_conn *)conn->context; int ret; pr_debug("isert_get_login_rx before conn_login_comp conn: %p\n", conn); ret = wait_for_completion_interruptible(&isert_conn->conn_login_comp); if (ret) return ret; pr_debug("isert_get_login_rx processing login->req: %p\n", login->req); return 0; } static void isert_set_conn_info(struct iscsi_np *np, struct iscsi_conn *conn, struct isert_conn *isert_conn) { struct rdma_cm_id *cm_id = isert_conn->conn_cm_id; struct rdma_route *cm_route = &cm_id->route; struct sockaddr_in *sock_in; struct sockaddr_in6 *sock_in6; conn->login_family = np->np_sockaddr.ss_family; if (np->np_sockaddr.ss_family == AF_INET6) { sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.dst_addr; snprintf(conn->login_ip, sizeof(conn->login_ip), "%pI6c", &sock_in6->sin6_addr.in6_u); conn->login_port = ntohs(sock_in6->sin6_port); sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.src_addr; snprintf(conn->local_ip, sizeof(conn->local_ip), "%pI6c", &sock_in6->sin6_addr.in6_u); conn->local_port = ntohs(sock_in6->sin6_port); } else { sock_in = (struct sockaddr_in *)&cm_route->addr.dst_addr; sprintf(conn->login_ip, "%pI4", &sock_in->sin_addr.s_addr); conn->login_port = ntohs(sock_in->sin_port); sock_in = (struct sockaddr_in *)&cm_route->addr.src_addr; sprintf(conn->local_ip, "%pI4", &sock_in->sin_addr.s_addr); conn->local_port = ntohs(sock_in->sin_port); } } static int isert_accept_np(struct iscsi_np *np, struct iscsi_conn *conn) { struct isert_np *isert_np = (struct isert_np *)np->np_context; struct isert_conn *isert_conn; int max_accept = 0, ret; accept_wait: ret = wait_event_interruptible(isert_np->np_accept_wq, !isert_check_accept_queue(isert_np) || np->np_thread_state == ISCSI_NP_THREAD_RESET); if (max_accept > 5) return -ENODEV; spin_lock_bh(&np->np_thread_lock); if (np->np_thread_state >= ISCSI_NP_THREAD_RESET) { spin_unlock_bh(&np->np_thread_lock); pr_debug("np_thread_state %d for isert_accept_np\n", np->np_thread_state); /** * No point in stalling here when np_thread * is in state RESET/SHUTDOWN/EXIT - bail **/ return -ENODEV; } spin_unlock_bh(&np->np_thread_lock); mutex_lock(&isert_np->np_accept_mutex); if (list_empty(&isert_np->np_accept_list)) { mutex_unlock(&isert_np->np_accept_mutex); max_accept++; goto accept_wait; } isert_conn = list_first_entry(&isert_np->np_accept_list, struct isert_conn, conn_accept_node); list_del_init(&isert_conn->conn_accept_node); mutex_unlock(&isert_np->np_accept_mutex); conn->context = isert_conn; isert_conn->conn = conn; max_accept = 0; ret = isert_rdma_post_recvl(isert_conn); if (ret) return ret; ret = isert_rdma_accept(isert_conn); if (ret) return ret; isert_set_conn_info(np, conn, isert_conn); pr_debug("Processing isert_accept_np: isert_conn: %p\n", isert_conn); return 0; } static void isert_free_np(struct iscsi_np *np) { struct isert_np *isert_np = (struct isert_np *)np->np_context; if (isert_np->np_cm_id) rdma_destroy_id(isert_np->np_cm_id); np->np_context = NULL; kfree(isert_np); } static void isert_wait_conn(struct iscsi_conn *conn) { struct isert_conn *isert_conn = conn->context; pr_debug("isert_wait_conn: Starting \n"); mutex_lock(&isert_conn->conn_mutex); if (isert_conn->conn_cm_id) { pr_debug("Calling rdma_disconnect from isert_wait_conn\n"); rdma_disconnect(isert_conn->conn_cm_id); } /* * Only wait for conn_wait_comp_err if the isert_conn made it * into full feature phase.. */ if (isert_conn->state == ISER_CONN_INIT) { mutex_unlock(&isert_conn->conn_mutex); return; } if (isert_conn->state == ISER_CONN_UP) isert_conn->state = ISER_CONN_TERMINATING; mutex_unlock(&isert_conn->conn_mutex); wait_for_completion(&isert_conn->conn_wait_comp_err); wait_for_completion(&isert_conn->conn_wait); isert_put_conn(isert_conn); } static void isert_free_conn(struct iscsi_conn *conn) { struct isert_conn *isert_conn = conn->context; isert_put_conn(isert_conn); } static struct iscsit_transport iser_target_transport = { .name = "IB/iSER", .transport_type = ISCSI_INFINIBAND, .owner = THIS_MODULE, .iscsit_setup_np = isert_setup_np, .iscsit_accept_np = isert_accept_np, .iscsit_free_np = isert_free_np, .iscsit_wait_conn = isert_wait_conn, .iscsit_free_conn = isert_free_conn, .iscsit_alloc_cmd = isert_alloc_cmd, .iscsit_get_login_rx = isert_get_login_rx, .iscsit_put_login_tx = isert_put_login_tx, .iscsit_immediate_queue = isert_immediate_queue, .iscsit_response_queue = isert_response_queue, .iscsit_get_dataout = isert_get_dataout, .iscsit_queue_data_in = isert_put_datain, .iscsit_queue_status = isert_put_response, }; static int __init isert_init(void) { int ret; isert_rx_wq = alloc_workqueue("isert_rx_wq", 0, 0); if (!isert_rx_wq) { pr_err("Unable to allocate isert_rx_wq\n"); return -ENOMEM; } isert_comp_wq = alloc_workqueue("isert_comp_wq", 0, 0); if (!isert_comp_wq) { pr_err("Unable to allocate isert_comp_wq\n"); ret = -ENOMEM; goto destroy_rx_wq; } isert_cmd_cache = kmem_cache_create("isert_cmd_cache", sizeof(struct isert_cmd), __alignof__(struct isert_cmd), 0, NULL); if (!isert_cmd_cache) { pr_err("Unable to create isert_cmd_cache\n"); ret = -ENOMEM; goto destroy_tx_cq; } iscsit_register_transport(&iser_target_transport); pr_debug("iSER_TARGET[0] - Loaded iser_target_transport\n"); return 0; destroy_tx_cq: destroy_workqueue(isert_comp_wq); destroy_rx_wq: destroy_workqueue(isert_rx_wq); return ret; } static void __exit isert_exit(void) { flush_scheduled_work(); kmem_cache_destroy(isert_cmd_cache); destroy_workqueue(isert_comp_wq); destroy_workqueue(isert_rx_wq); iscsit_unregister_transport(&iser_target_transport); pr_debug("iSER_TARGET[0] - Released iser_target_transport\n"); } MODULE_DESCRIPTION("iSER-Target for mainline target infrastructure"); MODULE_VERSION("0.1"); MODULE_AUTHOR("nab@Linux-iSCSI.org"); MODULE_LICENSE("GPL"); module_init(isert_init); module_exit(isert_exit);
crimsonthunder/kernel_samsung_trlte_5.1.1
drivers/infiniband/ulp/isert/ib_isert.c
C
gpl-2.0
67,213
/* $Id: tstCAPIGlue.c 109358 2016-07-31 17:11:31Z bird $ */ /** @file tstCAPIGlue.c * Demonstrator program to illustrate use of C bindings of Main API. * * It has sample code showing how to retrieve all available error information, * and how to handle active (event delivery through callbacks) or passive * (event delivery through a polling mechanism) event listeners. */ /* * Copyright (C) 2009-2016 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /** @todo * Our appologies for the 256+ missing return code checks in this sample file. * * We strongly recomment users of the VBoxCAPI to check all return codes! */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include "VBoxCAPIGlue.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef WIN32 # include <signal.h> # include <unistd.h> # include <sys/poll.h> #endif #ifdef ___iprt_cdefs_h # error "not supposed to involve any IPRT or VBox headers here." #endif /** * Select between active event listener (defined) and passive event listener * (undefined). The active event listener case needs much more code, and * additionally requires a lot more platform dependent code. */ #undef USE_ACTIVE_EVENT_LISTENER /********************************************************************************************************************************* * Global Variables * *********************************************************************************************************************************/ /** Set by Ctrl+C handler. */ static volatile int g_fStop = 0; #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 /** The COM type information for IEventListener, for implementing IDispatch. */ static ITypeInfo *g_pTInfoIEventListener = NULL; # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ static const char *GetStateName(MachineState_T machineState) { switch (machineState) { case MachineState_Null: return "<null>"; case MachineState_PoweredOff: return "PoweredOff"; case MachineState_Saved: return "Saved"; case MachineState_Teleported: return "Teleported"; case MachineState_Aborted: return "Aborted"; case MachineState_Running: return "Running"; case MachineState_Paused: return "Paused"; case MachineState_Stuck: return "Stuck"; case MachineState_Teleporting: return "Teleporting"; case MachineState_LiveSnapshotting: return "LiveSnapshotting"; case MachineState_Starting: return "Starting"; case MachineState_Stopping: return "Stopping"; case MachineState_Saving: return "Saving"; case MachineState_Restoring: return "Restoring"; case MachineState_TeleportingPausedVM: return "TeleportingPausedVM"; case MachineState_TeleportingIn: return "TeleportingIn"; case MachineState_FaultTolerantSyncing: return "FaultTolerantSyncing"; case MachineState_DeletingSnapshotOnline: return "DeletingSnapshotOnline"; case MachineState_DeletingSnapshotPaused: return "DeletingSnapshotPaused"; case MachineState_RestoringSnapshot: return "RestoringSnapshot"; case MachineState_DeletingSnapshot: return "DeletingSnapshot"; case MachineState_SettingUp: return "SettingUp"; default: return "no idea"; } } /** * Ctrl+C handler, terminate event listener. * * Remember that most function calls are not allowed in this context (including * printf!), so make sure that this does as little as possible. * * @param iInfo Platform dependent detail info (ignored). */ static BOOL VBOX_WINAPI ctrlCHandler(DWORD iInfo) { (void)iInfo; g_fStop = 1; return TRUE; } /** * Sample event processing function, dumping some event information. * Shared between active and passive event demo, to highlight that this part * is identical between the two. */ static HRESULT EventListenerDemoProcessEvent(IEvent *event) { VBoxEventType_T evType; HRESULT rc; if (!event) { printf("event null\n"); return S_OK; } evType = VBoxEventType_Invalid; rc = IEvent_get_Type(event, &evType); if (FAILED(rc)) { printf("cannot get event type, rc=%#x\n", rc); return S_OK; } switch (evType) { case VBoxEventType_OnMousePointerShapeChanged: printf("OnMousePointerShapeChanged\n"); break; case VBoxEventType_OnMouseCapabilityChanged: printf("OnMouseCapabilityChanged\n"); break; case VBoxEventType_OnKeyboardLedsChanged: printf("OnMouseCapabilityChanged\n"); break; case VBoxEventType_OnStateChanged: { IStateChangedEvent *ev = NULL; enum MachineState state; rc = IEvent_QueryInterface(event, &IID_IStateChangedEvent, (void **)&ev); if (FAILED(rc)) { printf("cannot get StateChangedEvent interface, rc=%#x\n", rc); return S_OK; } if (!ev) { printf("StateChangedEvent reference null\n"); return S_OK; } rc = IStateChangedEvent_get_State(ev, &state); if (FAILED(rc)) printf("warning: cannot get state, rc=%#x\n", rc); IStateChangedEvent_Release(ev); printf("OnStateChanged: %s\n", GetStateName(state)); fflush(stdout); if ( state == MachineState_PoweredOff || state == MachineState_Saved || state == MachineState_Teleported || state == MachineState_Aborted ) g_fStop = 1; break; } case VBoxEventType_OnAdditionsStateChanged: printf("OnAdditionsStateChanged\n"); break; case VBoxEventType_OnNetworkAdapterChanged: printf("OnNetworkAdapterChanged\n"); break; case VBoxEventType_OnSerialPortChanged: printf("OnSerialPortChanged\n"); break; case VBoxEventType_OnParallelPortChanged: printf("OnParallelPortChanged\n"); break; case VBoxEventType_OnStorageControllerChanged: printf("OnStorageControllerChanged\n"); break; case VBoxEventType_OnMediumChanged: printf("OnMediumChanged\n"); break; case VBoxEventType_OnVRDEServerChanged: printf("OnVRDEServerChanged\n"); break; case VBoxEventType_OnUSBControllerChanged: printf("OnUSBControllerChanged\n"); break; case VBoxEventType_OnUSBDeviceStateChanged: printf("OnUSBDeviceStateChanged\n"); break; case VBoxEventType_OnSharedFolderChanged: printf("OnSharedFolderChanged\n"); break; case VBoxEventType_OnRuntimeError: printf("OnRuntimeError\n"); break; case VBoxEventType_OnCanShowWindow: printf("OnCanShowWindow\n"); break; case VBoxEventType_OnShowWindow: printf("OnShowWindow\n"); break; default: printf("unknown event: %d\n", evType); } return S_OK; } #ifdef USE_ACTIVE_EVENT_LISTENER struct IEventListenerDemo; typedef struct IEventListenerDemo IEventListenerDemo; typedef struct IEventListenerDemoVtbl { HRESULT (*QueryInterface)(IEventListenerDemo *pThis, REFIID riid, void **ppvObject); ULONG (*AddRef)(IEventListenerDemo *pThis); ULONG (*Release)(IEventListenerDemo *pThis); #ifdef WIN32 HRESULT (*GetTypeInfoCount)(IEventListenerDemo *pThis, UINT *pctinfo); HRESULT (*GetTypeInfo)(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo); HRESULT (*GetIDsOfNames)(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); HRESULT (*Invoke)(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); #endif HRESULT (*HandleEvent)(IEventListenerDemo *pThis, IEvent *aEvent); } IEventListenerDemoVtbl; typedef struct IEventListenerDemo { struct IEventListenerDemoVtbl *lpVtbl; int cRef; #ifdef WIN32 /* Active event delivery needs a free threaded marshaler, as the default * proxy marshaling cannot deal correctly with this case. */ IUnknown *pUnkMarshaler; #endif } IEventListenerDemo; /* Defines for easily calling IEventListenerDemo functions. */ /* IUnknown functions. */ #define IEventListenerDemo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) ) #define IEventListenerDemo_AddRef(This) \ ( (This)->lpVtbl->AddRef(This) ) #define IEventListenerDemo_Release(This) \ ( (This)->lpVtbl->Release(This) ) #ifdef WIN32 /* IDispatch functions. */ #define IEventListenerDemo_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) ) #define IEventListenerDemo_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IEventListenerDemo_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IEventListenerDemo_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* IEventListener functions. */ #define IEventListenerDemo_HandleEvent(This,aEvent) \ ( (This)->lpVtbl->HandleEvent(This,aEvent) ) /** * Event handler function, for active event processing. */ static HRESULT IEventListenerDemoImpl_HandleEvent(IEventListenerDemo *pThis, IEvent *event) { return EventListenerDemoProcessEvent(event); } static HRESULT IEventListenerDemoImpl_QueryInterface(IEventListenerDemo *pThis, const IID *iid, void **resultp) { /* match iid */ if ( !memcmp(iid, &IID_IEventListener, sizeof(IID)) || !memcmp(iid, &IID_IDispatch, sizeof(IID)) || !memcmp(iid, &IID_IUnknown, sizeof(IID))) { IEventListenerDemo_AddRef(pThis); *resultp = pThis; return S_OK; } #ifdef WIN32 if (!memcmp(iid, &IID_IMarshal, sizeof(IID))) return IUnknown_QueryInterface(pThis->pUnkMarshaler, iid, resultp); #endif return E_NOINTERFACE; } static HRESULT IEventListenerDemoImpl_AddRef(IEventListenerDemo *pThis) { return ++(pThis->cRef); } static HRESULT IEventListenerDemoImpl_Release(IEventListenerDemo *pThis) { HRESULT c; c = --(pThis->cRef); if (!c) free(pThis); return c; } #ifdef WIN32 static HRESULT IEventListenerDemoImpl_GetTypeInfoCount(IEventListenerDemo *pThis, UINT *pctinfo) { if (!pctinfo) return E_POINTER; *pctinfo = 1; return S_OK; } static HRESULT IEventListenerDemoImpl_GetTypeInfo(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo) { if (!ppTInfo) return E_POINTER; ITypeInfo_AddRef(g_pTInfoIEventListener); *ppTInfo = g_pTInfoIEventListener; return S_OK; } static HRESULT IEventListenerDemoImpl_GetIDsOfNames(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { return ITypeInfo_GetIDsOfNames(g_pTInfoIEventListener, rgszNames, cNames, rgDispId); } static HRESULT IEventListenerDemoImpl_Invoke(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { return ITypeInfo_Invoke(g_pTInfoIEventListener, (IDispatch *)pThis, dispIdMember, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } static HRESULT LoadTypeInfo(REFIID riid, ITypeInfo **pTInfo) { HRESULT rc; ITypeLib *pTypeLib; rc = LoadRegTypeLib(&LIBID_VirtualBox, 1 /* major */, 0 /* minor */, 0 /* lcid */, &pTypeLib); if (FAILED(rc)) return rc; rc = ITypeLib_GetTypeInfoOfGuid(pTypeLib, riid, pTInfo); /* No longer need access to the type lib, release it. */ ITypeLib_Release(pTypeLib); return rc; } #endif #ifdef __GNUC__ typedef struct IEventListenerDemoVtblInt { ptrdiff_t offset_to_top; void *typeinfo; IEventListenerDemoVtbl lpVtbl; } IEventListenerDemoVtblInt; static IEventListenerDemoVtblInt g_IEventListenerDemoVtblInt = { 0, /* offset_to_top */ NULL, /* typeinfo, not vital */ { IEventListenerDemoImpl_QueryInterface, IEventListenerDemoImpl_AddRef, IEventListenerDemoImpl_Release, #ifdef WIN32 IEventListenerDemoImpl_GetTypeInfoCount, IEventListenerDemoImpl_GetTypeInfo, IEventListenerDemoImpl_GetIDsOfNames, IEventListenerDemoImpl_Invoke, #endif IEventListenerDemoImpl_HandleEvent } }; #elif defined(_MSC_VER) typedef struct IEventListenerDemoVtblInt { IEventListenerDemoVtbl lpVtbl; } IEventListenerDemoVtblInt; static IEventListenerDemoVtblInt g_IEventListenerDemoVtblInt = { { IEventListenerDemoImpl_QueryInterface, IEventListenerDemoImpl_AddRef, IEventListenerDemoImpl_Release, #ifdef WIN32 IEventListenerDemoImpl_GetTypeInfoCount, IEventListenerDemoImpl_GetTypeInfo, IEventListenerDemoImpl_GetIDsOfNames, IEventListenerDemoImpl_Invoke, #endif IEventListenerDemoImpl_HandleEvent } }; #else # error Port me! #endif /** * Register active event listener for the selected VM. * * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void registerActiveEventListener(IVirtualBox *virtualBox, ISession *session) { IConsole *console = NULL; HRESULT rc; rc = ISession_get_Console(session, &console); if ((SUCCEEDED(rc)) && console) { IEventSource *es = NULL; rc = IConsole_get_EventSource(console, &es); if (SUCCEEDED(rc) && es) { static const ULONG s_auInterestingEvents[] = { VBoxEventType_OnMousePointerShapeChanged, VBoxEventType_OnMouseCapabilityChanged, VBoxEventType_OnKeyboardLedsChanged, VBoxEventType_OnStateChanged, VBoxEventType_OnAdditionsStateChanged, VBoxEventType_OnNetworkAdapterChanged, VBoxEventType_OnSerialPortChanged, VBoxEventType_OnParallelPortChanged, VBoxEventType_OnStorageControllerChanged, VBoxEventType_OnMediumChanged, VBoxEventType_OnVRDEServerChanged, VBoxEventType_OnUSBControllerChanged, VBoxEventType_OnUSBDeviceStateChanged, VBoxEventType_OnSharedFolderChanged, VBoxEventType_OnRuntimeError, VBoxEventType_OnCanShowWindow, VBoxEventType_OnShowWindow }; SAFEARRAY *interestingEventsSA = NULL; IEventListenerDemo *consoleListener = NULL; /* The VirtualBox API expects enum values as VT_I4, which in the * future can be hopefully relaxed. */ interestingEventsSA = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_I4, 0, sizeof(s_auInterestingEvents) / sizeof(s_auInterestingEvents[0])); g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(interestingEventsSA, &s_auInterestingEvents, sizeof(s_auInterestingEvents)); consoleListener = calloc(1, sizeof(IEventListenerDemo)); if (consoleListener) { consoleListener->lpVtbl = &(g_IEventListenerDemoVtblInt.lpVtbl); #ifdef WIN32 CoCreateFreeThreadedMarshaler((IUnknown *)consoleListener, &consoleListener->pUnkMarshaler); #endif IEventListenerDemo_AddRef(consoleListener); rc = IEventSource_RegisterListener(es, (IEventListener *)consoleListener, ComSafeArrayAsInParam(interestingEventsSA), 1 /* active */); if (SUCCEEDED(rc)) { /* Just wait here for events, no easy way to do this better * as there's not much to do after this completes. */ printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n"); fflush(stdout); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, TRUE); #else signal(SIGINT, (void (*)(int))ctrlCHandler); #endif while (!g_fStop) g_pVBoxFuncs->pfnProcessEventQueue(250); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, FALSE); #else signal(SIGINT, SIG_DFL); #endif } else printf("Failed to register event listener.\n"); IEventSource_UnregisterListener(es, (IEventListener *)consoleListener); #ifdef WIN32 if (consoleListener->pUnkMarshaler) IUnknown_Release(consoleListener->pUnkMarshaler); #endif IEventListenerDemo_Release(consoleListener); } else printf("Failed while allocating memory for console event listener.\n"); g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA); IEventSource_Release(es); } else printf("Failed to get the event source instance.\n"); IConsole_Release(console); } } #else /* !USE_ACTIVE_EVENT_LISTENER */ /** * Register passive event listener for the selected VM. * * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void registerPassiveEventListener(ISession *session) { IConsole *console = NULL; HRESULT rc; rc = ISession_get_Console(session, &console); if (SUCCEEDED(rc) && console) { IEventSource *es = NULL; rc = IConsole_get_EventSource(console, &es); if (SUCCEEDED(rc) && es) { static const ULONG s_auInterestingEvents[] = { VBoxEventType_OnMousePointerShapeChanged, VBoxEventType_OnMouseCapabilityChanged, VBoxEventType_OnKeyboardLedsChanged, VBoxEventType_OnStateChanged, VBoxEventType_OnAdditionsStateChanged, VBoxEventType_OnNetworkAdapterChanged, VBoxEventType_OnSerialPortChanged, VBoxEventType_OnParallelPortChanged, VBoxEventType_OnStorageControllerChanged, VBoxEventType_OnMediumChanged, VBoxEventType_OnVRDEServerChanged, VBoxEventType_OnUSBControllerChanged, VBoxEventType_OnUSBDeviceStateChanged, VBoxEventType_OnSharedFolderChanged, VBoxEventType_OnRuntimeError, VBoxEventType_OnCanShowWindow, VBoxEventType_OnShowWindow }; SAFEARRAY *interestingEventsSA = NULL; IEventListener *consoleListener = NULL; /* The VirtualBox API expects enum values as VT_I4, which in the * future can be hopefully relaxed. */ interestingEventsSA = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_I4, 0, sizeof(s_auInterestingEvents) / sizeof(s_auInterestingEvents[0])); g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(interestingEventsSA, &s_auInterestingEvents, sizeof(s_auInterestingEvents)); rc = IEventSource_CreateListener(es, &consoleListener); if (SUCCEEDED(rc) && consoleListener) { rc = IEventSource_RegisterListener(es, consoleListener, ComSafeArrayAsInParam(interestingEventsSA), 0 /* passive */); if (SUCCEEDED(rc)) { /* Just wait here for events, no easy way to do this better * as there's not much to do after this completes. */ printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n"); fflush(stdout); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, TRUE); #else signal(SIGINT, (void (*)(int))ctrlCHandler); #endif while (!g_fStop) { IEvent *ev = NULL; rc = IEventSource_GetEvent(es, consoleListener, 250, &ev); if (FAILED(rc)) { printf("Failed getting event: %#x\n", rc); g_fStop = 1; continue; } /* handle timeouts, resulting in NULL events */ if (!ev) continue; rc = EventListenerDemoProcessEvent(ev); if (FAILED(rc)) { printf("Failed processing event: %#x\n", rc); g_fStop = 1; /* finish processing the event */ } rc = IEventSource_EventProcessed(es, consoleListener, ev); if (FAILED(rc)) { printf("Failed to mark event as processed: %#x\n", rc); g_fStop = 1; /* continue with event release */ } if (ev) { IEvent_Release(ev); ev = NULL; } } #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, FALSE); #else signal(SIGINT, SIG_DFL); #endif } else printf("Failed to register event listener.\n"); IEventSource_UnregisterListener(es, (IEventListener *)consoleListener); IEventListener_Release(consoleListener); } else printf("Failed to create an event listener instance.\n"); g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA); IEventSource_Release(es); } else printf("Failed to get the event source instance.\n"); IConsole_Release(console); } } #endif /* !USE_ACTIVE_EVENT_LISTENER */ /** * Print detailed error information if available. * @param pszExecutable string with the executable name * @param pszErrorMsg string containing the code location specific error message * @param rc COM/XPCOM result code */ static void PrintErrorInfo(const char *pszExecutable, const char *pszErrorMsg, HRESULT rc) { IErrorInfo *ex; HRESULT rc2; fprintf(stderr, "%s: %s (rc=%#010x)\n", pszExecutable, pszErrorMsg, (unsigned)rc); rc2 = g_pVBoxFuncs->pfnGetException(&ex); if (SUCCEEDED(rc2) && ex) { IVirtualBoxErrorInfo *ei; rc2 = IErrorInfo_QueryInterface(ex, &IID_IVirtualBoxErrorInfo, (void **)&ei); if (SUCCEEDED(rc2) && ei != NULL) { /* got extended error info, maybe multiple infos */ do { LONG resultCode = S_OK; BSTR componentUtf16 = NULL; char *component = NULL; BSTR textUtf16 = NULL; char *text = NULL; IVirtualBoxErrorInfo *ei_next = NULL; fprintf(stderr, "Extended error info (IVirtualBoxErrorInfo):\n"); IVirtualBoxErrorInfo_get_ResultCode(ei, &resultCode); fprintf(stderr, " resultCode=%#010x\n", (unsigned)resultCode); IVirtualBoxErrorInfo_get_Component(ei, &componentUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(componentUtf16, &component); g_pVBoxFuncs->pfnComUnallocString(componentUtf16); fprintf(stderr, " component=%s\n", component); g_pVBoxFuncs->pfnUtf8Free(component); IVirtualBoxErrorInfo_get_Text(ei, &textUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text); g_pVBoxFuncs->pfnComUnallocString(textUtf16); fprintf(stderr, " text=%s\n", text); g_pVBoxFuncs->pfnUtf8Free(text); rc2 = IVirtualBoxErrorInfo_get_Next(ei, &ei_next); if (FAILED(rc2)) ei_next = NULL; IVirtualBoxErrorInfo_Release(ei); ei = ei_next; } while (ei); } IErrorInfo_Release(ex); g_pVBoxFuncs->pfnClearException(); } } /** * Start a VM. * * @param argv0 executable name * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object * @param id identifies the machine to start */ static void startVM(const char *argv0, IVirtualBox *virtualBox, ISession *session, BSTR id) { HRESULT rc; IMachine *machine = NULL; IProgress *progress = NULL; BSTR env = NULL; BSTR sessionType; SAFEARRAY *groupsSA = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc(); rc = IVirtualBox_FindMachine(virtualBox, id, &machine); if (FAILED(rc) || !machine) { PrintErrorInfo(argv0, "Error: Couldn't get the Machine reference", rc); return; } rc = IMachine_get_Groups(machine, ComSafeArrayAsOutTypeParam(groupsSA, BSTR)); if (SUCCEEDED(rc)) { BSTR *groups = NULL; ULONG cbGroups = 0; ULONG i, cGroups; g_pVBoxFuncs->pfnSafeArrayCopyOutParamHelper((void **)&groups, &cbGroups, VT_BSTR, groupsSA); g_pVBoxFuncs->pfnSafeArrayDestroy(groupsSA); cGroups = cbGroups / sizeof(groups[0]); for (i = 0; i < cGroups; ++i) { /* Note that the use of %S might be tempting, but it is not * available on all platforms, and even where it is usable it * may depend on correct compiler options to make wchar_t a * 16 bit number. So better play safe and use UTF-8. */ char *group; g_pVBoxFuncs->pfnUtf16ToUtf8(groups[i], &group); printf("Groups[%d]: %s\n", i, group); g_pVBoxFuncs->pfnUtf8Free(group); } for (i = 0; i < cGroups; ++i) g_pVBoxFuncs->pfnComUnallocString(groups[i]); g_pVBoxFuncs->pfnArrayOutFree(groups); } g_pVBoxFuncs->pfnUtf8ToUtf16("gui", &sessionType); rc = IMachine_LaunchVMProcess(machine, session, sessionType, env, &progress); g_pVBoxFuncs->pfnUtf16Free(sessionType); if (SUCCEEDED(rc)) { BOOL completed; LONG resultCode; printf("Waiting for the remote session to open...\n"); IProgress_WaitForCompletion(progress, -1); rc = IProgress_get_Completed(progress, &completed); if (FAILED(rc)) fprintf(stderr, "Error: GetCompleted status failed\n"); IProgress_get_ResultCode(progress, &resultCode); if (FAILED(resultCode)) { IVirtualBoxErrorInfo *errorInfo; BSTR textUtf16; char *text; IProgress_get_ErrorInfo(progress, &errorInfo); IVirtualBoxErrorInfo_get_Text(errorInfo, &textUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text); printf("Error: %s\n", text); g_pVBoxFuncs->pfnComUnallocString(textUtf16); g_pVBoxFuncs->pfnUtf8Free(text); IVirtualBoxErrorInfo_Release(errorInfo); } else { fprintf(stderr, "VM process has been successfully started\n"); /* Kick off the event listener demo part, which is quite separate. * Ignore it if you need a more basic sample. */ #ifdef USE_ACTIVE_EVENT_LISTENER registerActiveEventListener(virtualBox, session); #else registerPassiveEventListener(session); #endif } IProgress_Release(progress); } else PrintErrorInfo(argv0, "Error: LaunchVMProcess failed", rc); /* It's important to always release resources. */ IMachine_Release(machine); } /** * List the registered VMs. * * @param argv0 executable name * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void listVMs(const char *argv0, IVirtualBox *virtualBox, ISession *session) { HRESULT rc; SAFEARRAY *machinesSA = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc(); IMachine **machines = NULL; ULONG machineCnt = 0; ULONG i; unsigned start_id; /* * Get the list of all registered VMs. */ rc = IVirtualBox_get_Machines(virtualBox, ComSafeArrayAsOutIfaceParam(machinesSA, IMachine *)); if (FAILED(rc)) { PrintErrorInfo(argv0, "could not get list of machines", rc); return; } /* * Extract interface pointers from machinesSA, and update the reference * counter of each object, as destroying machinesSA would call Release. */ g_pVBoxFuncs->pfnSafeArrayCopyOutIfaceParamHelper((IUnknown ***)&machines, &machineCnt, machinesSA); g_pVBoxFuncs->pfnSafeArrayDestroy(machinesSA); if (!machineCnt) { g_pVBoxFuncs->pfnArrayOutFree(machines); printf("\tNo VMs\n"); return; } printf("VM List:\n\n"); /* * Iterate through the collection. */ for (i = 0; i < machineCnt; ++i) { IMachine *machine = machines[i]; BOOL isAccessible = FALSE; printf("\tMachine #%u\n", (unsigned)i); if (!machine) { printf("\t(skipped, NULL)\n"); continue; } IMachine_get_Accessible(machine, &isAccessible); if (isAccessible) { BSTR machineNameUtf16; char *machineName; IMachine_get_Name(machine, &machineNameUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(machineNameUtf16,&machineName); g_pVBoxFuncs->pfnComUnallocString(machineNameUtf16); printf("\tName: %s\n", machineName); g_pVBoxFuncs->pfnUtf8Free(machineName); } else printf("\tName: <inaccessible>\n"); { BSTR uuidUtf16; char *uuidUtf8; IMachine_get_Id(machine, &uuidUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(uuidUtf16, &uuidUtf8); g_pVBoxFuncs->pfnComUnallocString(uuidUtf16); printf("\tUUID: %s\n", uuidUtf8); g_pVBoxFuncs->pfnUtf8Free(uuidUtf8); } if (isAccessible) { { BSTR configFileUtf16; char *configFileUtf8; IMachine_get_SettingsFilePath(machine, &configFileUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(configFileUtf16, &configFileUtf8); g_pVBoxFuncs->pfnComUnallocString(configFileUtf16); printf("\tConfig file: %s\n", configFileUtf8); g_pVBoxFuncs->pfnUtf8Free(configFileUtf8); } { ULONG memorySize; IMachine_get_MemorySize(machine, &memorySize); printf("\tMemory size: %uMB\n", memorySize); } { BSTR typeId; BSTR osNameUtf16; char *osName; IGuestOSType *osType = NULL; IMachine_get_OSTypeId(machine, &typeId); IVirtualBox_GetGuestOSType(virtualBox, typeId, &osType); g_pVBoxFuncs->pfnComUnallocString(typeId); IGuestOSType_get_Description(osType, &osNameUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(osNameUtf16,&osName); g_pVBoxFuncs->pfnComUnallocString(osNameUtf16); printf("\tGuest OS: %s\n\n", osName); g_pVBoxFuncs->pfnUtf8Free(osName); IGuestOSType_Release(osType); } } } /* * Let the user chose a machine to start. */ printf("Type Machine# to start (0 - %u) or 'quit' to do nothing: ", (unsigned)(machineCnt - 1)); fflush(stdout); if (scanf("%u", &start_id) == 1 && start_id < machineCnt) { IMachine *machine = machines[start_id]; if (machine) { BSTR uuidUtf16 = NULL; IMachine_get_Id(machine, &uuidUtf16); startVM(argv0, virtualBox, session, uuidUtf16); g_pVBoxFuncs->pfnComUnallocString(uuidUtf16); } } /* * Don't forget to release the objects in the array. */ for (i = 0; i < machineCnt; ++i) { IMachine *machine = machines[i]; if (machine) IMachine_Release(machine); } g_pVBoxFuncs->pfnArrayOutFree(machines); } /* Main - Start the ball rolling. */ int main(int argc, char **argv) { IVirtualBoxClient *vboxclient = NULL; IVirtualBox *vbox = NULL; ISession *session = NULL; ULONG revision = 0; BSTR versionUtf16 = NULL; BSTR homefolderUtf16 = NULL; HRESULT rc; /* Result code of various function (method) calls. */ (void)argc; printf("Starting main()\n"); if (VBoxCGlueInit()) { fprintf(stderr, "%s: FATAL: VBoxCGlueInit failed: %s\n", argv[0], g_szVBoxErrMsg); return EXIT_FAILURE; } { unsigned ver = g_pVBoxFuncs->pfnGetVersion(); printf("VirtualBox version: %u.%u.%u\n", ver / 1000000, ver / 1000 % 1000, ver % 1000); ver = g_pVBoxFuncs->pfnGetAPIVersion(); printf("VirtualBox API version: %u.%u\n", ver / 1000, ver % 1000); } g_pVBoxFuncs->pfnClientInitialize(NULL, &vboxclient); if (!vboxclient) { fprintf(stderr, "%s: FATAL: could not get VirtualBoxClient reference\n", argv[0]); return EXIT_FAILURE; } printf("----------------------------------------------------\n"); rc = IVirtualBoxClient_get_VirtualBox(vboxclient, &vbox); if (FAILED(rc) || !vbox) { PrintErrorInfo(argv[0], "FATAL: could not get VirtualBox reference", rc); return EXIT_FAILURE; } rc = IVirtualBoxClient_get_Session(vboxclient, &session); if (FAILED(rc) || !session) { PrintErrorInfo(argv[0], "FATAL: could not get Session reference", rc); return EXIT_FAILURE; } #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 rc = LoadTypeInfo(&IID_IEventListener, &g_pTInfoIEventListener); if (FAILED(rc) || !g_pTInfoIEventListener) { PrintErrorInfo(argv[0], "FATAL: could not get type information for IEventListener", rc); return EXIT_FAILURE; } # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ /* * Now ask for revision, version and home folder information of * this vbox. Were not using fancy macros here so it * remains easy to see how we access C++'s vtable. */ /* 1. Revision */ rc = IVirtualBox_get_Revision(vbox, &revision); if (SUCCEEDED(rc)) printf("\tRevision: %u\n", revision); else PrintErrorInfo(argv[0], "GetRevision() failed", rc); /* 2. Version */ rc = IVirtualBox_get_Version(vbox, &versionUtf16); if (SUCCEEDED(rc)) { char *version = NULL; g_pVBoxFuncs->pfnUtf16ToUtf8(versionUtf16, &version); printf("\tVersion: %s\n", version); g_pVBoxFuncs->pfnUtf8Free(version); g_pVBoxFuncs->pfnComUnallocString(versionUtf16); } else PrintErrorInfo(argv[0], "GetVersion() failed", rc); /* 3. Home Folder */ rc = IVirtualBox_get_HomeFolder(vbox, &homefolderUtf16); if (SUCCEEDED(rc)) { char *homefolder = NULL; g_pVBoxFuncs->pfnUtf16ToUtf8(homefolderUtf16, &homefolder); printf("\tHomeFolder: %s\n", homefolder); g_pVBoxFuncs->pfnUtf8Free(homefolder); g_pVBoxFuncs->pfnComUnallocString(homefolderUtf16); } else PrintErrorInfo(argv[0], "GetHomeFolder() failed", rc); listVMs(argv[0], vbox, session); ISession_UnlockMachine(session); printf("----------------------------------------------------\n"); /* * Do as mom told us: always clean up after yourself. */ #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 if (g_pTInfoIEventListener) { ITypeInfo_Release(g_pTInfoIEventListener); g_pTInfoIEventListener = NULL; } # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ if (session) { ISession_Release(session); session = NULL; } if (vbox) { IVirtualBox_Release(vbox); vbox = NULL; } if (vboxclient) { IVirtualBoxClient_Release(vboxclient); vboxclient = NULL; } g_pVBoxFuncs->pfnClientUninitialize(); VBoxCGlueTerm(); printf("Finished main()\n"); return 0; } /* vim: set ts=4 sw=4 et: */
ARL-UTEP-OC/emubox
workshop-manager/bin/VirtualBoxSDK-5.1.20-114628/sdk/bindings/c/samples/tstCAPIGlue.c
C
gpl-2.0
39,034
/* This file is part of ffmpeg-php Copyright (C) 2004-2008 Todd Kirby (ffmpeg.php AT gmail.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 In addition, as a special exception, the copyright holders of ffmpeg-php give you permission to combine ffmpeg-php with code included in the standard release of PHP under the PHP license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU GPL for ffmpeg-php and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU GPL requires distribution of source code. You must obey the GNU General Public License in all respects for all of the code used other than standard release of PHP. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif //#include <php.h> #include "ffmpeg_tools.h" #if LIBAVCODEC_VERSION_MAJOR >= 52 #include <swscale.h> /* {{{ ffmpeg_img_convert() * wrapper around ffmpeg image conversion routines */ int img_convert(AVPicture *dst, int dst_pix_fmt, AVPicture *src, int src_pix_fmt, int src_width, int src_height) { struct SwsContext *sws_ctx = NULL; // TODO: Try to get cached sws_context first sws_ctx = sws_getContext(src_width, src_height, 0, src_width, src_height, dst_pix_fmt, SWS_BICUBIC, NULL, NULL, NULL); if (sws_ctx == NULL){ return 2; } sws_scale(sws_ctx, src->data, src->linesize, 0, src_height, dst->data, dst->linesize); sws_freeContext(sws_ctx); return 0; } /* }}} */ void img_resample(ImgReSampleContext * context, AVPicture * pxOut, const AVPicture * pxIn) { if (context != NULL && context->context != NULL) { AVPicture shiftedInput; // = {0}; shiftedInput.data[0] = pxIn->data[0] + pxIn->linesize[0] * context->bandTop + context->bandLeft; shiftedInput.data[1] = pxIn->data[1] + (pxIn->linesize[1] * (context->bandTop / 2)) + (context->bandLeft+1) / 2; shiftedInput.data[2] = pxIn->data[2] + (pxIn->linesize[2] * (context->bandTop / 2)) + (context->bandLeft+1) / 2; shiftedInput.linesize[0] = pxIn->linesize[0]; shiftedInput.linesize[1] = pxIn->linesize[1]; shiftedInput.linesize[2] = pxIn->linesize[2]; sws_scale(context->context, (uint8_t**)shiftedInput.data, (int*)shiftedInput.linesize, 0, context->height - context->bandBottom - context->bandTop, pxOut->data, pxOut->linesize); } } ImgReSampleContext * img_resample_full_init (int owidth, int oheight, int iwidth, int iheight, int topBand, int bottomBand, int leftBand, int rightBand, int padtop, int padbottom, int padleft, int padright) { ImgReSampleContext * s = (ImgReSampleContext *)av_malloc(sizeof(ImgReSampleContext)); if (s == NULL) { return NULL; } int srcSurface = (iwidth - rightBand - leftBand)* (iheight - topBand - bottomBand); // We use bilinear when the source surface is big, and bicubic when the number of pixels to handle is less than 1 MPixels s->context = sws_getContext(iwidth - rightBand - leftBand, iheight - topBand - bottomBand, PIX_FMT_YUV420P, owidth, oheight, PIX_FMT_YUV420P, srcSurface > 1024000 ? SWS_FAST_BILINEAR : SWS_BICUBIC, NULL, NULL, NULL); if (s->context == NULL) { av_free(s); return NULL; } s->bandLeft = leftBand; s->bandRight = rightBand; s->bandTop = topBand; s->bandBottom = bottomBand; s->padLeft = padleft; s->padRight = padright; s->padTop = padtop; s->padBottom = padbottom; s->width = iwidth; s->height = iheight; s->outWidth = owidth; s->outHeight = oheight; return s; } ImgReSampleContext * img_resample_init (int owidth, int oheight, int iwidth, int iheight) { return img_resample_full_init(owidth, oheight, iwidth, iheight, 0, 0, 0, 0, 0, 0, 0, 0); } void img_resample_close(ImgReSampleContext * s) { if (s == NULL) return; sws_freeContext(s->context); av_free(s); } #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 * vim<600: noet sw=4 ts=4 */
lord2800/ffmpeg-php
ffmpeg_tools.c
C
gpl-2.0
5,212
// CHDK palette colors for the s90 // Define color values as needed in this file. #include "palette.h" #include "platform_palette.h" // Playback mode colors unsigned char ply_colors[] = { COLOR_TRANSPARENT, // Placeholder for script colors COLOR_BLACK, // Placeholder for script colors 0x01, // White 0x2B, // Red 0x29, // Dark Red 0x1E, // Light Red 0x99, // Green 0x25, // Dark Green 0x51, // Light Green 0xA1, // Blue 0xA1, // Dark Blue 0xA9, // Light Blue / Cyan 0x17, // Grey 0x61, // Dark Grey 0x16, // Light Grey 0x9A, // Yellow 0x6F, // Dark Yellow 0x66, // Light Yellow 0x61, // Transparent Dark Grey COLOR_BLACK, // Magenta }; // Record mode colors unsigned char rec_colors[] = { COLOR_TRANSPARENT, // Placeholder for script colors COLOR_BLACK, // Placeholder for script colors 0x01, // White 0x2B, // Red 0x29, // Dark Red 0x1E, // Light Red 0x99, // Green 0x25, // Dark Green 0x51, // Light Green 0xA1, // Blue 0xA1, // Dark Blue 0xA9, // Light Blue / Cyan 0x17, // Grey 0x61, // Dark Grey 0x16, // Light Grey 0x9A, // Yellow 0x6F, // Dark Yellow 0x66, // Light Yellow 0x61, // Transparent Dark Grey COLOR_BLACK, // Magenta };
c10ud/CHDK
platform/s90/platform_palette.c
C
gpl-2.0
2,303
/* * keybindings.c - this file is part of Geany, a fast and lightweight IDE * * Copyright 2006-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de> * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file keybindings.h * Configurable keyboard shortcuts. * - keybindings_send_command() mimics a built-in keybinding action. * - @ref GeanyKeyGroupID lists groups of built-in keybindings. * @see plugin_set_key_group(). **/ #include "geany.h" #include <gdk/gdkkeysyms.h> #include <string.h> #include "keybindings.h" #include "support.h" #include "utils.h" #include "ui_utils.h" #include "document.h" #include "documentprivate.h" #include "filetypes.h" #include "callbacks.h" #include "prefs.h" #include "msgwindow.h" #include "editor.h" #include "sciwrappers.h" #include "build.h" #include "tools.h" #include "navqueue.h" #include "symbols.h" #include "vte.h" #include "toolbar.h" #include "sidebar.h" #include "notebook.h" #include "geanywraplabel.h" #include "main.h" #include "search.h" #ifdef HAVE_VTE # include "vte.h" #endif GPtrArray *keybinding_groups; /* array of GeanyKeyGroup pointers, in visual order */ /* keyfile group name for non-plugin KB groups */ static const gchar keybindings_keyfile_group_name[] = "Bindings"; /* core keybindings */ static GeanyKeyBinding binding_ids[GEANY_KEYS_COUNT]; static GtkAccelGroup *kb_accel_group = NULL; static const gboolean swap_alt_tab_order = FALSE; /* central keypress event handler, almost all keypress events go to this function */ static gboolean on_key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); static gboolean check_current_word(GeanyDocument *doc, gboolean sci_word); static gboolean read_current_word(GeanyDocument *doc, gboolean sci_word); static gchar *get_current_word_or_sel(GeanyDocument *doc, gboolean sci_word); static gboolean cb_func_file_action(guint key_id); static gboolean cb_func_project_action(guint key_id); static gboolean cb_func_editor_action(guint key_id); static gboolean cb_func_select_action(guint key_id); static gboolean cb_func_format_action(guint key_id); static gboolean cb_func_insert_action(guint key_id); static gboolean cb_func_search_action(guint key_id); static gboolean cb_func_goto_action(guint key_id); static gboolean cb_func_switch_action(guint key_id); static gboolean cb_func_clipboard_action(guint key_id); static gboolean cb_func_build_action(guint key_id); static gboolean cb_func_document_action(guint key_id); static gboolean cb_func_view_action(guint key_id); /* note: new keybindings should normally use per group callbacks */ static void cb_func_menu_help(guint key_id); static void cb_func_menu_preferences(guint key_id); static void cb_func_menu_fullscreen(guint key_id); static void cb_func_menu_messagewindow(guint key_id); static void cb_func_menu_opencolorchooser(guint key_id); static void cb_func_switch_tableft(guint key_id); static void cb_func_switch_tabright(guint key_id); static void cb_func_switch_tablastused(guint key_id); static void cb_func_move_tab(guint key_id); static void add_popup_menu_accels(void); /** Looks up a keybinding item. * @param group Group. * @param key_id Keybinding index for the group. * @return The keybinding. * @since 0.19. */ GeanyKeyBinding *keybindings_get_item(GeanyKeyGroup *group, gsize key_id) { if (group->plugin) { g_assert(key_id < group->plugin_key_count); return &group->plugin_keys[key_id]; } g_assert(key_id < GEANY_KEYS_COUNT); return &binding_ids[key_id]; } /* This is used to set default keybindings on startup. * Menu accels are set in apply_kb_accel(). */ /** Fills a GeanyKeyBinding struct item. * @note Always set @a key and @a mod to 0, otherwise you will likely * cause conflicts with the user's custom, other plugin's keybindings or * future default keybindings. * @param group Group. * @param key_id Keybinding index for the group. * @param callback Function to call when activated, or @c NULL to use the group callback. * Usually it's better to use the group callback instead - see plugin_set_key_group(). * @param key (Lower case) default key, e.g. @c GDK_j, but usually 0 for unset. * @param mod Default modifier, e.g. @c GDK_CONTROL_MASK, but usually 0 for unset. * @param kf_name Key name for the configuration file, such as @c "menu_new". * @param label Label used in the preferences dialog keybindings tab. May contain * underscores - these won't be displayed. * @param menu_item Optional widget to set an accelerator for, or @c NULL. * @return The keybinding - normally this is ignored. */ GeanyKeyBinding *keybindings_set_item(GeanyKeyGroup *group, gsize key_id, GeanyKeyCallback callback, guint key, GdkModifierType mod, const gchar *kf_name, const gchar *label, GtkWidget *menu_item) { GeanyKeyBinding *kb; g_assert(group->name); kb = keybindings_get_item(group, key_id); g_assert(!kb->name); g_ptr_array_add(group->key_items, kb); if (group->plugin) { /* some plugins e.g. GeanyLua need these fields duplicated */ SETPTR(kb->name, g_strdup(kf_name)); SETPTR(kb->label, g_strdup(label)); } else { /* we don't touch these strings unless group->plugin is set, const cast is safe */ kb->name = (gchar *)kf_name; kb->label = (gchar *)label; } kb->key = key; kb->mods = mod; kb->default_key = key; kb->default_mods = mod; kb->callback = callback; kb->menu_item = menu_item; kb->id = key_id; return kb; } static void add_kb_group(GeanyKeyGroup *group, const gchar *name, const gchar *label, GeanyKeyGroupCallback callback, gboolean plugin) { g_ptr_array_add(keybinding_groups, group); group->name = name; group->label = label; group->callback = callback; group->plugin = plugin; group->key_items = g_ptr_array_new(); } GeanyKeyGroup *keybindings_get_core_group(guint id) { static GeanyKeyGroup groups[GEANY_KEY_GROUP_COUNT]; g_return_val_if_fail(id < GEANY_KEY_GROUP_COUNT, NULL); return &groups[id]; } static void add_kb(GeanyKeyGroup *group, gsize key_id, GeanyKeyCallback callback, guint key, GdkModifierType mod, const gchar *kf_name, const gchar *label, const gchar *widget_name) { GtkWidget *widget = widget_name ? ui_lookup_widget(main_widgets.window, widget_name) : NULL; keybindings_set_item(group, key_id, callback, key, mod, kf_name, label, widget); } #define ADD_KB_GROUP(group_id, label, callback) \ add_kb_group(keybindings_get_core_group(group_id),\ keybindings_keyfile_group_name, label, callback, FALSE) static void init_default_kb(void) { GeanyKeyGroup *group; /* visual group order */ ADD_KB_GROUP(GEANY_KEY_GROUP_FILE, _("File"), cb_func_file_action); ADD_KB_GROUP(GEANY_KEY_GROUP_EDITOR, _("Editor"), cb_func_editor_action); ADD_KB_GROUP(GEANY_KEY_GROUP_CLIPBOARD, _("Clipboard"), cb_func_clipboard_action); ADD_KB_GROUP(GEANY_KEY_GROUP_SELECT, _("Select"), cb_func_select_action); ADD_KB_GROUP(GEANY_KEY_GROUP_FORMAT, _("Format"), cb_func_format_action); ADD_KB_GROUP(GEANY_KEY_GROUP_INSERT, _("Insert"), cb_func_insert_action); ADD_KB_GROUP(GEANY_KEY_GROUP_SETTINGS, _("Settings"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_SEARCH, _("Search"), cb_func_search_action); ADD_KB_GROUP(GEANY_KEY_GROUP_GOTO, _("Go to"), cb_func_goto_action); ADD_KB_GROUP(GEANY_KEY_GROUP_VIEW, _("View"), cb_func_view_action); ADD_KB_GROUP(GEANY_KEY_GROUP_DOCUMENT, _("Document"), cb_func_document_action); ADD_KB_GROUP(GEANY_KEY_GROUP_PROJECT, _("Project"), cb_func_project_action); ADD_KB_GROUP(GEANY_KEY_GROUP_BUILD, _("Build"), cb_func_build_action); ADD_KB_GROUP(GEANY_KEY_GROUP_TOOLS, _("Tools"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_HELP, _("Help"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_FOCUS, _("Focus"), cb_func_switch_action); ADD_KB_GROUP(GEANY_KEY_GROUP_NOTEBOOK, _("Notebook tab"), NULL); /* Init all fields of keys with default values. * The menu_item field is always the main menu item, popup menu accelerators are * set in add_popup_menu_accels(). */ group = keybindings_get_core_group(GEANY_KEY_GROUP_FILE); add_kb(group, GEANY_KEYS_FILE_NEW, NULL, GDK_n, GDK_CONTROL_MASK, "menu_new", _("New"), NULL); add_kb(group, GEANY_KEYS_FILE_OPEN, NULL, GDK_o, GDK_CONTROL_MASK, "menu_open", _("Open"), NULL); add_kb(group, GEANY_KEYS_FILE_OPENSELECTED, NULL, GDK_o, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "menu_open_selected", _("Open selected file"), "menu_open_selected_file1"); add_kb(group, GEANY_KEYS_FILE_SAVE, NULL, GDK_s, GDK_CONTROL_MASK, "menu_save", _("Save"), NULL); add_kb(group, GEANY_KEYS_FILE_SAVEAS, NULL, 0, 0, "menu_saveas", _("Save as"), "menu_save_as1"); add_kb(group, GEANY_KEYS_FILE_SAVEALL, NULL, GDK_s, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "menu_saveall", _("Save all"), "menu_save_all1"); add_kb(group, GEANY_KEYS_FILE_PRINT, NULL, GDK_p, GDK_CONTROL_MASK, "menu_print", _("Print"), "print1"); add_kb(group, GEANY_KEYS_FILE_CLOSE, NULL, GDK_w, GDK_CONTROL_MASK, "menu_close", _("Close"), "menu_close1"); add_kb(group, GEANY_KEYS_FILE_CLOSEALL, NULL, GDK_w, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_closeall", _("Close all"), "menu_close_all1"); add_kb(group, GEANY_KEYS_FILE_RELOAD, NULL, GDK_r, GDK_CONTROL_MASK, "menu_reloadfile", _("Reload file"), "menu_reload1"); add_kb(group, GEANY_KEYS_FILE_OPENLASTTAB, NULL, 0, 0, "file_openlasttab", _("Re-open last closed tab"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_PROJECT); add_kb(group, GEANY_KEYS_PROJECT_NEW, NULL, 0, 0, "project_new", _("New"), "project_new1"); add_kb(group, GEANY_KEYS_PROJECT_OPEN, NULL, 0, 0, "project_open", _("Open"), "project_open1"); add_kb(group, GEANY_KEYS_PROJECT_PROPERTIES, NULL, 0, 0, "project_properties", ui_lookup_stock_label(GTK_STOCK_PROPERTIES), "project_properties1"); add_kb(group, GEANY_KEYS_PROJECT_CLOSE, NULL, 0, 0, "project_close", _("Close"), "project_close1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_EDITOR); add_kb(group, GEANY_KEYS_EDITOR_UNDO, NULL, GDK_z, GDK_CONTROL_MASK, "menu_undo", _("Undo"), "menu_undo2"); add_kb(group, GEANY_KEYS_EDITOR_REDO, NULL, GDK_y, GDK_CONTROL_MASK, "menu_redo", _("Redo"), "menu_redo2"); add_kb(group, GEANY_KEYS_EDITOR_DUPLICATELINE, NULL, GDK_d, GDK_CONTROL_MASK, "edit_duplicateline", _("_Duplicate Line or Selection"), "duplicate_line_or_selection1"); add_kb(group, GEANY_KEYS_EDITOR_DELETELINE, NULL, GDK_k, GDK_CONTROL_MASK, "edit_deleteline", _("_Delete Current Line(s)"), "delete_current_lines1"); add_kb(group, GEANY_KEYS_EDITOR_DELETELINETOEND, NULL, GDK_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "edit_deletelinetoend", _("Delete to line end"), NULL); /* transpose may fit better in format group */ add_kb(group, GEANY_KEYS_EDITOR_TRANSPOSELINE, NULL, 0, 0, "edit_transposeline", _("_Transpose Current Line"), "transpose_current_line1"); add_kb(group, GEANY_KEYS_EDITOR_SCROLLTOLINE, NULL, GDK_l, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "edit_scrolltoline", _("Scroll to current line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SCROLLLINEUP, NULL, GDK_Up, GDK_MOD1_MASK, "edit_scrolllineup", _("Scroll up the view by one line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SCROLLLINEDOWN, NULL, GDK_Down, GDK_MOD1_MASK, "edit_scrolllinedown", _("Scroll down the view by one line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_COMPLETESNIPPET, NULL, GDK_Tab, 0, "edit_completesnippet", _("Complete snippet"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SNIPPETNEXTCURSOR, NULL, 0, 0, "move_snippetnextcursor", _("Move cursor in snippet"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SUPPRESSSNIPPETCOMPLETION, NULL, 0, 0, "edit_suppresssnippetcompletion", _("Suppress snippet completion"), NULL); add_kb(group, GEANY_KEYS_EDITOR_CONTEXTACTION, NULL, 0, 0, "popup_contextaction", _("Context Action"), NULL); add_kb(group, GEANY_KEYS_EDITOR_AUTOCOMPLETE, NULL, GDK_space, GDK_CONTROL_MASK, "edit_autocomplete", _("Complete word"), NULL); add_kb(group, GEANY_KEYS_EDITOR_CALLTIP, NULL, GDK_space, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_calltip", _("Show calltip"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MACROLIST, NULL, GDK_Return, GDK_CONTROL_MASK, "edit_macrolist", _("Show macro list"), NULL); add_kb(group, GEANY_KEYS_EDITOR_WORDPARTCOMPLETION, NULL, GDK_Tab, 0, "edit_wordpartcompletion", _("Word part completion"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MOVELINEUP, NULL, GDK_Page_Up, GDK_MOD1_MASK, "edit_movelineup", _("Move line(s) up"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MOVELINEDOWN, NULL, GDK_Page_Down, GDK_MOD1_MASK, "edit_movelinedown", _("Move line(s) down"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_CLIPBOARD); add_kb(group, GEANY_KEYS_CLIPBOARD_CUT, NULL, GDK_x, GDK_CONTROL_MASK, "menu_cut", _("Cut"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_COPY, NULL, GDK_c, GDK_CONTROL_MASK, "menu_copy", _("Copy"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_PASTE, NULL, GDK_v, GDK_CONTROL_MASK, "menu_paste", _("Paste"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_COPYLINE, NULL, GDK_c, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_copyline", _("_Copy Current Line(s)"), "copy_current_lines1"); add_kb(group, GEANY_KEYS_CLIPBOARD_CUTLINE, NULL, GDK_x, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_cutline", _("_Cut Current Line(s)"), "cut_current_lines1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_SELECT); add_kb(group, GEANY_KEYS_SELECT_ALL, NULL, GDK_a, GDK_CONTROL_MASK, "menu_selectall", _("Select All"), "menu_select_all1"); add_kb(group, GEANY_KEYS_SELECT_WORD, NULL, GDK_w, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectword", _("Select current word"), NULL); add_kb(group, GEANY_KEYS_SELECT_LINE, NULL, GDK_l, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectline", _("_Select Current Line(s)"), "select_current_lines1"); add_kb(group, GEANY_KEYS_SELECT_PARAGRAPH, NULL, GDK_p, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectparagraph", _("_Select Current Paragraph"), "select_current_paragraph1"); add_kb(group, GEANY_KEYS_SELECT_WORDPARTLEFT, NULL, 0, 0, "edit_selectwordpartleft", _("Select to previous word part"), NULL); add_kb(group, GEANY_KEYS_SELECT_WORDPARTRIGHT, NULL, 0, 0, "edit_selectwordpartright", _("Select to next word part"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_FORMAT); add_kb(group, GEANY_KEYS_FORMAT_TOGGLECASE, NULL, GDK_u, GDK_CONTROL_MASK | GDK_MOD1_MASK, "edit_togglecase", _("T_oggle Case of Selection"), "menu_toggle_case2"); add_kb(group, GEANY_KEYS_FORMAT_COMMENTLINETOGGLE, NULL, GDK_e, GDK_CONTROL_MASK, "edit_commentlinetoggle", _("Toggle line commentation"), "menu_toggle_line_commentation1"); add_kb(group, GEANY_KEYS_FORMAT_COMMENTLINE, NULL, 0, 0, "edit_commentline", _("Comment line(s)"), "menu_comment_line1"); add_kb(group, GEANY_KEYS_FORMAT_UNCOMMENTLINE, NULL, 0, 0, "edit_uncommentline", _("Uncomment line(s)"), "menu_uncomment_line1"); add_kb(group, GEANY_KEYS_FORMAT_INCREASEINDENT, NULL, GDK_i, GDK_CONTROL_MASK, "edit_increaseindent", _("Increase indent"), "menu_increase_indent1"); add_kb(group, GEANY_KEYS_FORMAT_DECREASEINDENT, NULL, GDK_u, GDK_CONTROL_MASK, "edit_decreaseindent", _("Decrease indent"), "menu_decrease_indent1"); add_kb(group, GEANY_KEYS_FORMAT_INCREASEINDENTBYSPACE, NULL, 0, 0, "edit_increaseindentbyspace", _("Increase indent by one space"), NULL); add_kb(group, GEANY_KEYS_FORMAT_DECREASEINDENTBYSPACE, NULL, 0, 0, "edit_decreaseindentbyspace", _("Decrease indent by one space"), NULL); add_kb(group, GEANY_KEYS_FORMAT_AUTOINDENT, NULL, 0, 0, "edit_autoindent", _("_Smart Line Indent"), "smart_line_indent1"); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD1, NULL, GDK_1, GDK_CONTROL_MASK, "edit_sendtocmd1", _("Send to Custom Command 1"), NULL); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD2, NULL, GDK_2, GDK_CONTROL_MASK, "edit_sendtocmd2", _("Send to Custom Command 2"), NULL); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD3, NULL, GDK_3, GDK_CONTROL_MASK, "edit_sendtocmd3", _("Send to Custom Command 3"), NULL); /* may fit better in editor group */ add_kb(group, GEANY_KEYS_FORMAT_SENDTOVTE, NULL, 0, 0, "edit_sendtovte", _("_Send Selection to Terminal"), "send_selection_to_vte1"); add_kb(group, GEANY_KEYS_FORMAT_REFLOWPARAGRAPH, NULL, GDK_j, GDK_CONTROL_MASK, "format_reflowparagraph", _("_Reflow Lines/Block"), "reflow_lines_block1"); keybindings_set_item(group, GEANY_KEYS_FORMAT_JOINLINES, NULL, 0, 0, "edit_joinlines", _("Join lines"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_INSERT); add_kb(group, GEANY_KEYS_INSERT_DATE, NULL, GDK_d, GDK_SHIFT_MASK | GDK_MOD1_MASK, "menu_insert_date", _("Insert date"), "insert_date_custom1"); add_kb(group, GEANY_KEYS_INSERT_ALTWHITESPACE, NULL, 0, 0, "edit_insertwhitespace", _("_Insert Alternative White Space"), "insert_alternative_white_space1"); add_kb(group, GEANY_KEYS_INSERT_LINEBEFORE, NULL, 0, 0, "edit_insertlinebefore", _("Insert New Line Before Current"), NULL); add_kb(group, GEANY_KEYS_INSERT_LINEAFTER, NULL, 0, 0, "edit_insertlineafter", _("Insert New Line After Current"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_SETTINGS); add_kb(group, GEANY_KEYS_SETTINGS_PREFERENCES, cb_func_menu_preferences, GDK_p, GDK_CONTROL_MASK | GDK_MOD1_MASK, "menu_preferences", _("Preferences"), "preferences1"); add_kb(group, GEANY_KEYS_SETTINGS_PLUGINPREFERENCES, cb_func_menu_preferences, 0, 0, "menu_pluginpreferences", _("P_lugin Preferences"), "plugin_preferences1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_SEARCH); add_kb(group, GEANY_KEYS_SEARCH_FIND, NULL, GDK_f, GDK_CONTROL_MASK, "menu_find", _("Find"), "find1"); add_kb(group, GEANY_KEYS_SEARCH_FINDNEXT, NULL, GDK_g, GDK_CONTROL_MASK, "menu_findnext", _("Find Next"), "find_next1"); add_kb(group, GEANY_KEYS_SEARCH_FINDPREVIOUS, NULL, GDK_g, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_findprevious", _("Find Previous"), "find_previous1"); add_kb(group, GEANY_KEYS_SEARCH_FINDNEXTSEL, NULL, 0, 0, "menu_findnextsel", _("Find Next _Selection"), "find_nextsel1"); add_kb(group, GEANY_KEYS_SEARCH_FINDPREVSEL, NULL, 0, 0, "menu_findprevsel", _("Find Pre_vious Selection"), "find_prevsel1"); add_kb(group, GEANY_KEYS_SEARCH_REPLACE, NULL, GDK_h, GDK_CONTROL_MASK, "menu_replace", _("Replace"), "replace1"); add_kb(group, GEANY_KEYS_SEARCH_FINDINFILES, NULL, GDK_f, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_findinfiles", _("Find in Files"), "find_in_files1"); add_kb(group, GEANY_KEYS_SEARCH_NEXTMESSAGE, NULL, 0, 0, "menu_nextmessage", _("Next Message"), "next_message1"); add_kb(group, GEANY_KEYS_SEARCH_PREVIOUSMESSAGE, NULL, 0, 0, "menu_previousmessage", _("Previous Message"), "previous_message1"); add_kb(group, GEANY_KEYS_SEARCH_FINDUSAGE, NULL, GDK_e, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_findusage", _("Find Usage"), "find_usage1"); add_kb(group, GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE, NULL, GDK_d, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_finddocumentusage", _("Find Document Usage"), "find_document_usage1"); add_kb(group, GEANY_KEYS_SEARCH_MARKALL, NULL, GDK_m, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "find_markall", _("_Mark All"), "mark_all1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_GOTO); add_kb(group, GEANY_KEYS_GOTO_BACK, NULL, GDK_Left, GDK_MOD1_MASK, "nav_back", _("Navigate back a location"), NULL); add_kb(group, GEANY_KEYS_GOTO_FORWARD, NULL, GDK_Right, GDK_MOD1_MASK, "nav_forward", _("Navigate forward a location"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINE, NULL, GDK_l, GDK_CONTROL_MASK, "menu_gotoline", _("Go to Line"), "go_to_line1"); add_kb(group, GEANY_KEYS_GOTO_MATCHINGBRACE, NULL, GDK_b, GDK_CONTROL_MASK, "edit_gotomatchingbrace", _("Go to matching brace"), NULL); add_kb(group, GEANY_KEYS_GOTO_TOGGLEMARKER, NULL, GDK_m, GDK_CONTROL_MASK, "edit_togglemarker", _("Toggle marker"), NULL); add_kb(group, GEANY_KEYS_GOTO_NEXTMARKER, NULL, GDK_period, GDK_CONTROL_MASK, "edit_gotonextmarker", _("_Go to Next Marker"), "go_to_next_marker1"); add_kb(group, GEANY_KEYS_GOTO_PREVIOUSMARKER, NULL, GDK_comma, GDK_CONTROL_MASK, "edit_gotopreviousmarker", _("_Go to Previous Marker"), "go_to_previous_marker1"); add_kb(group, GEANY_KEYS_GOTO_TAGDEFINITION, NULL, GDK_t, GDK_CONTROL_MASK, "popup_gototagdefinition", _("Go to Tag Definition"), "goto_tag_definition1"); add_kb(group, GEANY_KEYS_GOTO_TAGDECLARATION, NULL, GDK_t, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_gototagdeclaration", _("Go to Tag Declaration"), "goto_tag_declaration1"); add_kb(group, GEANY_KEYS_GOTO_LINESTART, NULL, GDK_Home, 0, "edit_gotolinestart", _("Go to Start of Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINEEND, NULL, GDK_End, 0, "edit_gotolineend", _("Go to End of Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINEENDVISUAL, NULL, GDK_End, GDK_MOD1_MASK, "edit_gotolineendvisual", _("Go to End of Display Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_PREVWORDPART, NULL, GDK_slash, GDK_CONTROL_MASK, "edit_prevwordstart", _("Go to Previous Word Part"), NULL); add_kb(group, GEANY_KEYS_GOTO_NEXTWORDPART, NULL, GDK_backslash, GDK_CONTROL_MASK, "edit_nextwordstart", _("Go to Next Word Part"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_VIEW); add_kb(group, GEANY_KEYS_VIEW_TOGGLEALL, NULL, 0, 0, "menu_toggleall", _("Toggle All Additional Widgets"), "menu_toggle_all_additional_widgets1"); add_kb(group, GEANY_KEYS_VIEW_FULLSCREEN, cb_func_menu_fullscreen, GDK_F11, 0, "menu_fullscreen", _("Fullscreen"), "menu_fullscreen1"); add_kb(group, GEANY_KEYS_VIEW_MESSAGEWINDOW, cb_func_menu_messagewindow, 0, 0, "menu_messagewindow", _("Toggle Messages Window"), "menu_show_messages_window1"); add_kb(group, GEANY_KEYS_VIEW_SIDEBAR, NULL, 0, 0, "toggle_sidebar", _("Toggle Sidebar"), "menu_show_sidebar1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMIN, NULL, GDK_plus, GDK_CONTROL_MASK, "menu_zoomin", _("Zoom In"), "menu_zoom_in1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMOUT, NULL, GDK_minus, GDK_CONTROL_MASK, "menu_zoomout", _("Zoom Out"), "menu_zoom_out1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMRESET, NULL, GDK_0, GDK_CONTROL_MASK, "normal_size", _("Zoom Reset"), "normal_size1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_FOCUS); add_kb(group, GEANY_KEYS_FOCUS_EDITOR, NULL, GDK_F2, 0, "switch_editor", _("Switch to Editor"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SEARCHBAR, NULL, GDK_F7, 0, "switch_search_bar", _("Switch to Search Bar"), NULL); add_kb(group, GEANY_KEYS_FOCUS_MESSAGE_WINDOW, NULL, 0, 0, "switch_message_window", _("Switch to Message Window"), NULL); add_kb(group, GEANY_KEYS_FOCUS_COMPILER, NULL, 0, 0, "switch_compiler", _("Switch to Compiler"), NULL); add_kb(group, GEANY_KEYS_FOCUS_MESSAGES, NULL, 0, 0, "switch_messages", _("Switch to Messages"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SCRIBBLE, NULL, GDK_F6, 0, "switch_scribble", _("Switch to Scribble"), NULL); add_kb(group, GEANY_KEYS_FOCUS_VTE, NULL, GDK_F4, 0, "switch_vte", _("Switch to VTE"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR, NULL, 0, 0, "switch_sidebar", _("Switch to Sidebar"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR_SYMBOL_LIST, NULL, 0, 0, "switch_sidebar_symbol_list", _("Switch to Sidebar Symbol List"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR_DOCUMENT_LIST, NULL, 0, 0, "switch_sidebar_doc_list", _("Switch to Sidebar Document List"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_NOTEBOOK); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABLEFT, cb_func_switch_tableft, GDK_Page_Up, GDK_CONTROL_MASK, "switch_tableft", _("Switch to left document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABRIGHT, cb_func_switch_tabright, GDK_Page_Down, GDK_CONTROL_MASK, "switch_tabright", _("Switch to right document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABLASTUSED, cb_func_switch_tablastused, GDK_Tab, GDK_CONTROL_MASK, "switch_tablastused", _("Switch to last used document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABLEFT, cb_func_move_tab, GDK_Page_Up, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "move_tableft", _("Move document left"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABRIGHT, cb_func_move_tab, GDK_Page_Down, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "move_tabright", _("Move document right"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABFIRST, cb_func_move_tab, 0, 0, "move_tabfirst", _("Move document first"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABLAST, cb_func_move_tab, 0, 0, "move_tablast", _("Move document last"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_DOCUMENT); add_kb(group, GEANY_KEYS_DOCUMENT_LINEWRAP, NULL, 0, 0, "menu_linewrap", _("Toggle Line wrapping"), "menu_line_wrapping1"); add_kb(group, GEANY_KEYS_DOCUMENT_LINEBREAK, NULL, 0, 0, "menu_linebreak", _("Toggle Line breaking"), "line_breaking1"); add_kb(group, GEANY_KEYS_DOCUMENT_REPLACETABS, NULL, 0, 0, "menu_replacetabs", _("Replace tabs by space"), "menu_replace_tabs"); add_kb(group, GEANY_KEYS_DOCUMENT_REPLACESPACES, NULL, 0, 0, "menu_replacespaces", _("Replace spaces by tabs"), "menu_replace_spaces"); add_kb(group, GEANY_KEYS_DOCUMENT_TOGGLEFOLD, NULL, 0, 0, "menu_togglefold", _("Toggle current fold"), NULL); add_kb(group, GEANY_KEYS_DOCUMENT_FOLDALL, NULL, 0, 0, "menu_foldall", _("Fold all"), "menu_fold_all1"); add_kb(group, GEANY_KEYS_DOCUMENT_UNFOLDALL, NULL, 0, 0, "menu_unfoldall", _("Unfold all"), "menu_unfold_all1"); add_kb(group, GEANY_KEYS_DOCUMENT_RELOADTAGLIST, NULL, GDK_r, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "reloadtaglist", _("Reload symbol list"), NULL); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_MARKERS, NULL, 0, 0, "remove_markers", _("Remove Markers"), "remove_markers1"); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_ERROR_INDICATORS, NULL, 0, 0, "remove_error_indicators", _("Remove Error Indicators"), "menu_remove_indicators1"); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_MARKERS_INDICATORS, NULL, 0, 0, "remove_markers_and_indicators", _("Remove Markers and Error Indicators"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_BUILD); add_kb(group, GEANY_KEYS_BUILD_COMPILE, NULL, GDK_F8, 0, "build_compile", _("Compile"), NULL); add_kb(group, GEANY_KEYS_BUILD_LINK, NULL, GDK_F9, 0, "build_link", _("Build"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKE, NULL, GDK_F9, GDK_SHIFT_MASK, "build_make", _("Make all"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKEOWNTARGET, NULL, GDK_F9, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "build_makeowntarget", _("Make custom target"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKEOBJECT, NULL, GDK_F8, GDK_SHIFT_MASK, "build_makeobject", _("Make object"), NULL); add_kb(group, GEANY_KEYS_BUILD_NEXTERROR, NULL, 0, 0, "build_nexterror", _("Next error"), NULL); add_kb(group, GEANY_KEYS_BUILD_PREVIOUSERROR, NULL, 0, 0, "build_previouserror", _("Previous error"), NULL); add_kb(group, GEANY_KEYS_BUILD_RUN, NULL, GDK_F5, 0, "build_run", _("Run"), NULL); add_kb(group, GEANY_KEYS_BUILD_OPTIONS, NULL, 0, 0, "build_options", _("Build options"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_TOOLS); add_kb(group, GEANY_KEYS_TOOLS_OPENCOLORCHOOSER, cb_func_menu_opencolorchooser, 0, 0, "menu_opencolorchooser", _("Show Color Chooser"), "menu_choose_color1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_HELP); add_kb(group, GEANY_KEYS_HELP_HELP, cb_func_menu_help, GDK_F1, 0, "menu_help", _("Help"), "help1"); } void keybindings_init(void) { memset(binding_ids, 0, sizeof binding_ids); keybinding_groups = g_ptr_array_sized_new(GEANY_KEY_GROUP_COUNT); kb_accel_group = gtk_accel_group_new(); init_default_kb(); gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), kb_accel_group); g_signal_connect(main_widgets.window, "key-press-event", G_CALLBACK(on_key_press_event), NULL); } typedef void (*KBItemCallback) (GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data); static void keybindings_foreach(KBItemCallback cb, gpointer user_data) { gsize g, i; GeanyKeyGroup *group; GeanyKeyBinding *kb; foreach_ptr_array(group, g, keybinding_groups) { foreach_ptr_array(kb, i, group->key_items) cb(group, kb, user_data); } } static void load_kb(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { GKeyFile *config = user_data; gchar *val; guint key; GdkModifierType mods; val = g_key_file_get_string(config, group->name, kb->name, NULL); if (val != NULL) { gtk_accelerator_parse(val, &key, &mods); kb->key = key; kb->mods = mods; g_free(val); } } static void load_user_kb(void) { gchar *configfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "keybindings.conf", NULL); GKeyFile *config = g_key_file_new(); /* backwards compatibility with Geany 0.21 defaults */ if (!g_file_test(configfile, G_FILE_TEST_EXISTS)) { gchar *geanyconf = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "geany.conf", NULL); const gchar data[] = "[Bindings]\n" "popup_gototagdefinition=\n" "edit_transposeline=<Control>t\n" "edit_movelineup=\n" "edit_movelinedown=\n" "move_tableft=<Alt>Page_Up\n" "move_tabright=<Alt>Page_Down\n"; utils_write_file(configfile, g_file_test(geanyconf, G_FILE_TEST_EXISTS) ? data : ""); g_free(geanyconf); } /* now load user defined keys */ if (g_key_file_load_from_file(config, configfile, G_KEY_FILE_KEEP_COMMENTS, NULL)) { keybindings_foreach(load_kb, config); } g_free(configfile); g_key_file_free(config); } static void apply_kb_accel(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { if (kb->key != 0 && kb->menu_item) { gtk_widget_add_accelerator(kb->menu_item, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } } void keybindings_load_keyfile(void) { load_user_kb(); add_popup_menu_accels(); /* set menu accels now, after user keybindings have been read */ keybindings_foreach(apply_kb_accel, NULL); } static void add_menu_accel(GeanyKeyGroup *group, guint kb_id, GtkWidget *menuitem) { GeanyKeyBinding *kb = keybindings_get_item(group, kb_id); if (kb->key != 0) gtk_widget_add_accelerator(menuitem, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } #define GEANY_ADD_POPUP_ACCEL(kb_id, wid) \ add_menu_accel(group, kb_id, ui_lookup_widget(main_widgets.editor_menu, G_STRINGIFY(wid))) /* set the menu item accelerator shortcuts (just for visibility, they are handled anyway) */ static void add_popup_menu_accels(void) { GeanyKeyGroup *group; group = keybindings_get_core_group(GEANY_KEY_GROUP_EDITOR); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_UNDO, undo1); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_REDO, redo1); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_CONTEXTACTION, context_action1); group = keybindings_get_core_group(GEANY_KEY_GROUP_SELECT); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SELECT_ALL, menu_select_all2); group = keybindings_get_core_group(GEANY_KEY_GROUP_INSERT); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_INSERT_DATE, insert_date_custom2); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_INSERT_ALTWHITESPACE, insert_alternative_white_space2); group = keybindings_get_core_group(GEANY_KEY_GROUP_FILE); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_FILE_OPENSELECTED, menu_open_selected_file2); group = keybindings_get_core_group(GEANY_KEY_GROUP_SEARCH); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SEARCH_FINDUSAGE, find_usage2); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE, find_document_usage2); group = keybindings_get_core_group(GEANY_KEY_GROUP_GOTO); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_GOTO_TAGDEFINITION, goto_tag_definition2); /* Format and Commands share the menu bar submenus */ /* Build menu items are set if the build menus are created */ } static void set_keyfile_kb(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { GKeyFile *config = user_data; gchar *val; val = gtk_accelerator_name(kb->key, kb->mods); g_key_file_set_string(config, group->name, kb->name, val); g_free(val); } /* just write the content of the keys array to the config file */ void keybindings_write_to_file(void) { gchar *configfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "keybindings.conf", NULL); gchar *data; GKeyFile *config = g_key_file_new(); g_key_file_load_from_file(config, configfile, 0, NULL); keybindings_foreach(set_keyfile_kb, config); /* write the file */ data = g_key_file_to_data(config, NULL, NULL); utils_write_file(configfile, data); g_free(data); g_free(configfile); g_key_file_free(config); } void keybindings_free(void) { GeanyKeyGroup *group; gsize g; foreach_ptr_array(group, g, keybinding_groups) keybindings_free_group(group); g_ptr_array_free(keybinding_groups, TRUE); } gchar *keybindings_get_label(GeanyKeyBinding *kb) { return utils_str_remove_chars(g_strdup(kb->label), "_"); } static void fill_shortcut_labels_treeview(GtkWidget *tree) { gsize g, i; GeanyKeyBinding *kb; GeanyKeyGroup *group; GtkListStore *store; GtkTreeIter iter; store = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, PANGO_TYPE_WEIGHT); foreach_ptr_array(group, g, keybinding_groups) { if (g > 0) { gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, -1); } gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, 0, group->label, 2, PANGO_WEIGHT_BOLD, -1); foreach_ptr_array(kb, i, group->key_items) { gchar *shortcut, *label; label = keybindings_get_label(kb); shortcut = gtk_accelerator_get_label(kb->key, kb->mods); gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, 0, label, 1, shortcut, 2, PANGO_WEIGHT_NORMAL, -1); g_free(shortcut); g_free(label); } } gtk_tree_view_set_model(GTK_TREE_VIEW(tree), GTK_TREE_MODEL(store)); g_object_unref(store); } static GtkWidget *create_dialog(void) { GtkWidget *dialog, *tree, *label, *swin, *vbox; GtkCellRenderer *text_renderer; GtkTreeViewColumn *column; dialog = gtk_dialog_new_with_buttons(_("Keyboard Shortcuts"), GTK_WINDOW(main_widgets.window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_EDIT, GTK_RESPONSE_APPLY, GTK_STOCK_CLOSE, GTK_RESPONSE_CANCEL, NULL); vbox = ui_dialog_vbox_new(GTK_DIALOG(dialog)); gtk_box_set_spacing(GTK_BOX(vbox), 6); gtk_widget_set_name(dialog, "GeanyDialog"); gtk_window_set_default_size(GTK_WINDOW(dialog), -1, GEANY_DEFAULT_DIALOG_HEIGHT); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CANCEL); label = gtk_label_new(_("The following keyboard shortcuts are configurable:")); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); tree = gtk_tree_view_new(); gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(tree), TRUE); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE); text_renderer = gtk_cell_renderer_text_new(); /* we can't use "weight-set", see http://bugzilla.gnome.org/show_bug.cgi?id=355214 */ column = gtk_tree_view_column_new_with_attributes( NULL, text_renderer, "text", 0, "weight", 2, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); text_renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes(NULL, text_renderer, "text", 1, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); fill_shortcut_labels_treeview(tree); swin = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(swin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(swin), GTK_SHADOW_ETCHED_IN); gtk_container_add(GTK_CONTAINER(swin), tree); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 6); gtk_box_pack_start(GTK_BOX(vbox), swin, TRUE, TRUE, 0); return dialog; } /* non-modal keyboard shortcuts dialog, so user can edit whilst seeing the shortcuts */ static GtkWidget *key_dialog = NULL; static void on_dialog_response(GtkWidget *dialog, gint response, gpointer user_data) { if (response == GTK_RESPONSE_APPLY) { GtkWidget *wid; prefs_show_dialog(); /* select the KB page */ wid = ui_lookup_widget(ui_widgets.prefs_dialog, "frame22"); if (wid != NULL) { GtkNotebook *nb = GTK_NOTEBOOK(ui_lookup_widget(ui_widgets.prefs_dialog, "notebook2")); if (nb != NULL) gtk_notebook_set_current_page(nb, gtk_notebook_page_num(nb, wid)); } } gtk_widget_destroy(dialog); key_dialog = NULL; } void keybindings_show_shortcuts(void) { if (key_dialog) gtk_widget_destroy(key_dialog); /* in case the key_dialog is still visible */ key_dialog = create_dialog(); g_signal_connect(key_dialog, "response", G_CALLBACK(on_dialog_response), NULL); gtk_widget_show_all(key_dialog); } static gboolean check_fixed_kb(guint keyval, guint state) { /* check alt-0 to alt-9 for setting current notebook page */ if (state == GDK_MOD1_MASK && keyval >= GDK_0 && keyval <= GDK_9) { gint page = keyval - GDK_0 - 1; gint npages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)); /* alt-0 is for the rightmost tab */ if (keyval == GDK_0) page = npages - 1; /* invert the order if tabs are added on the other side */ if (swap_alt_tab_order && ! file_prefs.tab_order_ltr) page = (npages - 1) - page; gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page); return TRUE; } /* note: these are now overridden by default with move tab bindings */ if (keyval == GDK_Page_Up || keyval == GDK_Page_Down) { /* switch to first or last document */ if (state == (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) { if (keyval == GDK_Page_Up) gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), 0); if (keyval == GDK_Page_Down) gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), -1); return TRUE; } } return FALSE; } static gboolean check_snippet_completion(GeanyDocument *doc) { GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); g_return_val_if_fail(doc, FALSE); /* keybinding only valid when scintilla widget has focus */ if (focusw == GTK_WIDGET(doc->editor->sci)) { ScintillaObject *sci = doc->editor->sci; gint pos = sci_get_current_position(sci); if (editor_prefs.complete_snippets) return editor_complete_snippet(doc->editor, pos); } return FALSE; } /* Transforms a GdkEventKey event into a GdkEventButton event */ static void trigger_button_event(GtkWidget *widget, guint32 event_time) { GdkEventButton *event; gboolean ret; event = g_new0(GdkEventButton, 1); if (GTK_IS_TEXT_VIEW(widget)) event->window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget), GTK_TEXT_WINDOW_TEXT); else event->window = gtk_widget_get_window(widget); event->time = event_time; event->type = GDK_BUTTON_PRESS; event->button = 3; g_signal_emit_by_name(widget, "button-press-event", event, &ret); g_signal_emit_by_name(widget, "button-release-event", event, &ret); g_free(event); } /* Special case for the Menu key and Shift-F10 to show the right-click popup menu for various * widgets. Without this special handling, the notebook tab list of the documents' notebook * would be shown. As a very special case, we differentiate between the Menu key and Shift-F10 * if pressed in the editor widget: the Menu key opens the popup menu, Shift-F10 opens the * notebook tab list. */ static gboolean check_menu_key(GeanyDocument *doc, guint keyval, guint state, guint32 event_time) { if ((keyval == GDK_Menu && state == 0) || (keyval == GDK_F10 && state == GDK_SHIFT_MASK)) { GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); if (doc != NULL) { if (focusw == doc->priv->tag_tree) { trigger_button_event(focusw, event_time); return TRUE; } if (focusw == GTK_WIDGET(doc->editor->sci)) { if (keyval == GDK_Menu) { /* show editor popup menu */ trigger_button_event(focusw, event_time); return TRUE; } else { /* show tab bar menu */ trigger_button_event(main_widgets.notebook, event_time); return TRUE; } } } if (focusw == tv.tree_openfiles || focusw == msgwindow.tree_status || focusw == msgwindow.tree_compiler || focusw == msgwindow.tree_msg || focusw == msgwindow.scribble #ifdef HAVE_VTE || (vte_info.have_vte && focusw == vc->vte) #endif ) { trigger_button_event(focusw, event_time); return TRUE; } } return FALSE; } #ifdef HAVE_VTE static gboolean on_menu_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer user_data) { if (!GTK_WIDGET_SENSITIVE(widget)) gtk_widget_set_sensitive(GTK_WIDGET(widget), TRUE); return FALSE; } static gboolean set_sensitive(gpointer widget) { gtk_widget_set_sensitive(GTK_WIDGET(widget), TRUE); return FALSE; } static gboolean check_vte(GdkModifierType state, guint keyval) { guint i; GeanyKeyBinding *kb; GeanyKeyGroup *group; GtkWidget *widget; if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != vc->vte) return FALSE; /* let VTE copy/paste override any user keybinding */ if (state == (GDK_CONTROL_MASK | GDK_SHIFT_MASK) && (keyval == GDK_c || keyval == GDK_v)) return TRUE; if (! vc->enable_bash_keys) return FALSE; /* prevent menubar flickering: */ if (state == GDK_SHIFT_MASK && (keyval >= GDK_a && keyval <= GDK_z)) return FALSE; if (state == 0 && (keyval < GDK_F1 || keyval > GDK_F35)) /* e.g. backspace */ return FALSE; /* make focus commands override any bash commands */ group = keybindings_get_core_group(GEANY_KEY_GROUP_FOCUS); foreach_ptr_array(kb, i, group->key_items) { if (state == kb->mods && keyval == kb->key) return FALSE; } /* Temporarily disable the menus to prevent conflicting menu accelerators * from overriding the VTE bash shortcuts. * Note: maybe there's a better way of doing this ;-) */ widget = ui_lookup_widget(main_widgets.window, "menubar1"); gtk_widget_set_sensitive(widget, FALSE); { /* make the menubar sensitive before it is redrawn */ static gboolean connected = FALSE; if (!connected) g_signal_connect(widget, "expose-event", G_CALLBACK(on_menu_expose_event), NULL); } widget = main_widgets.editor_menu; gtk_widget_set_sensitive(widget, FALSE); g_idle_add(set_sensitive, widget); return TRUE; } #endif /* Map the keypad keys to their equivalent functions (taken from ScintillaGTK.cxx) */ static guint key_kp_translate(guint key_in) { switch (key_in) { case GDK_KP_Down: return GDK_Down; case GDK_KP_Up: return GDK_Up; case GDK_KP_Left: return GDK_Left; case GDK_KP_Right: return GDK_Right; case GDK_KP_Home: return GDK_Home; case GDK_KP_End: return GDK_End; case GDK_KP_Page_Up: return GDK_Page_Up; case GDK_KP_Page_Down: return GDK_Page_Down; case GDK_KP_Delete: return GDK_Delete; case GDK_KP_Insert: return GDK_Insert; default: return key_in; } } /* Check if event keypress matches keybinding combo */ gboolean keybindings_check_event(GdkEventKey *ev, GeanyKeyBinding *kb) { guint state, keyval; if (ev->keyval == 0) return FALSE; keyval = ev->keyval; state = ev->state & gtk_accelerator_get_default_mod_mask(); /* hack to get around that CTRL+Shift+r results in GDK_R not GDK_r */ if ((ev->state & GDK_SHIFT_MASK) || (ev->state & GDK_LOCK_MASK)) if (keyval >= GDK_A && keyval <= GDK_Z) keyval += GDK_a - GDK_A; if (keyval >= GDK_KP_Space && keyval < GDK_KP_Equal) keyval = key_kp_translate(keyval); return (keyval == kb->key && state == kb->mods); } void keybindings_debug_it(void) { int i; for (i = 0; i < GEANY_KEYS_COUNT; ++i) { if (binding_ids[i].id == GEANY_KEYS_CLIPBOARD_PASTE) { fprintf(stderr, "@@@ after %d\n", binding_ids[i].mods); } } } /* central keypress event handler, almost all keypress events go to this function */ static gboolean on_key_press_event(GtkWidget *widget, GdkEventKey *ev, gpointer user_data) { guint state, keyval; gsize g, i; GeanyDocument *doc; GeanyKeyGroup *group; GeanyKeyBinding *kb; if (ev->keyval == 0) return FALSE; doc = document_get_current(); if (doc) document_check_disk_status(doc, FALSE); keyval = ev->keyval; // state = ev->state & (gtk_accelerator_get_default_mod_mask() | 16); // meta bit on MacOSX state = ev->state & gtk_accelerator_get_default_mod_mask(); // geany_debug("key pressed: %d %d %d %d\n", ev->keyval, ev->state, gtk_accelerator_get_default_mod_mask(), state); /* hack to get around that CTRL+Shift+r results in GDK_R not GDK_r */ if ((ev->state & GDK_SHIFT_MASK) || (ev->state & GDK_LOCK_MASK)) if (keyval >= GDK_A && keyval <= GDK_Z) keyval += GDK_a - GDK_A; if (keyval >= GDK_KP_Space && keyval < GDK_KP_Equal) keyval = key_kp_translate(keyval); /*geany_debug("%d (%d) %d (%d)", keyval, ev->keyval, state, ev->state);*/ /* special cases */ #ifdef HAVE_VTE if (vte_info.have_vte && check_vte(state, keyval)) return FALSE; #endif if (check_menu_key(doc, keyval, state, ev->time)) return TRUE; foreach_ptr_array(group, g, keybinding_groups) { foreach_ptr_array(kb, i, group->key_items) { if (keyval == kb->key && state == kb->mods) { /* call the corresponding callback function for this shortcut */ if (kb->callback) { kb->callback(kb->id); return TRUE; } else if (group->callback) { if (group->callback(kb->id)) return TRUE; else continue; /* not handled */ } g_warning("No callback for keybinding %s: %s!", group->name, kb->name); } } } /* fixed keybindings can be overridden by user bindings, so check them last */ if (check_fixed_kb(keyval, state)) return TRUE; return FALSE; } /* group_id must be a core group, e.g. GEANY_KEY_GROUP_EDITOR * key_id e.g. GEANY_KEYS_EDITOR_CALLTIP */ GeanyKeyBinding *keybindings_lookup_item(guint group_id, guint key_id) { GeanyKeyGroup *group; g_return_val_if_fail(group_id < GEANY_KEY_GROUP_COUNT, NULL); /* can't use this for plugin groups */ group = keybindings_get_core_group(group_id); g_return_val_if_fail(group, NULL); return keybindings_get_item(group, key_id); } /** Mimics a (built-in only) keybinding action. * Example: @code keybindings_send_command(GEANY_KEY_GROUP_FILE, GEANY_KEYS_FILE_OPEN); @endcode * @param group_id @ref GeanyKeyGroupID keybinding group index that contains the @a key_id keybinding. * @param key_id @ref GeanyKeyBindingID keybinding index. */ void keybindings_send_command(guint group_id, guint key_id) { GeanyKeyBinding *kb; kb = keybindings_lookup_item(group_id, key_id); if (kb) { if (kb->callback) kb->callback(key_id); else { GeanyKeyGroup *group = keybindings_get_core_group(group_id); if (group->callback) group->callback(key_id); } } } /* These are the callback functions, either each group or each shortcut has it's * own function. */ static gboolean cb_func_file_action(guint key_id) { switch (key_id) { case GEANY_KEYS_FILE_NEW: document_new_file(NULL, NULL, NULL); break; case GEANY_KEYS_FILE_OPEN: on_open1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_OPENSELECTED: on_menu_open_selected_file1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_OPENLASTTAB: { gchar *utf8_filename = g_queue_peek_head(ui_prefs.recent_queue); gchar *locale_filename = utils_get_locale_from_utf8(utf8_filename); document_open_file(locale_filename, FALSE, NULL, NULL); g_free(locale_filename); break; } case GEANY_KEYS_FILE_SAVE: on_save1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_SAVEAS: on_save_as1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_SAVEALL: on_save_all1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_CLOSE: on_close1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_CLOSEALL: on_close_all1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_RELOAD: on_toolbutton_reload_clicked(NULL, NULL); break; case GEANY_KEYS_FILE_PRINT: on_print1_activate(NULL, NULL); break; } return TRUE; } static gboolean cb_func_project_action(guint key_id) { switch (key_id) { case GEANY_KEYS_PROJECT_NEW: on_project_new1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_OPEN: on_project_open1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_CLOSE: if (app->project) on_project_close1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_PROPERTIES: if (app->project) on_project_properties1_activate(NULL, NULL); break; } return TRUE; } static void cb_func_menu_preferences(guint key_id) { switch (key_id) { case GEANY_KEYS_SETTINGS_PREFERENCES: on_preferences1_activate(NULL, NULL); break; case GEANY_KEYS_SETTINGS_PLUGINPREFERENCES: on_plugin_preferences1_activate(NULL, NULL); break; } } static void cb_func_menu_help(G_GNUC_UNUSED guint key_id) { on_help1_activate(NULL, NULL); } static gboolean cb_func_search_action(guint key_id) { GeanyDocument *doc = document_get_current(); ScintillaObject *sci; if (key_id == GEANY_KEYS_SEARCH_FINDINFILES) { on_find_in_files1_activate(NULL, NULL); /* works without docs too */ return TRUE; } if (!doc) return TRUE; sci = doc->editor->sci; switch (key_id) { case GEANY_KEYS_SEARCH_FIND: on_find1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDNEXT: on_find_next1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDPREVIOUS: on_find_previous1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDPREVSEL: on_find_prevsel1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDNEXTSEL: on_find_nextsel1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_REPLACE: on_replace1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_NEXTMESSAGE: on_next_message1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_PREVIOUSMESSAGE: on_previous_message1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDUSAGE: on_find_usage1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE: on_find_document_usage1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_MARKALL: { gchar *text = get_current_word_or_sel(doc, TRUE); if (sci_has_selection(sci)) search_mark_all(doc, text, SCFIND_MATCHCASE); else { /* clears markers if text is null */ search_mark_all(doc, text, SCFIND_MATCHCASE | SCFIND_WHOLEWORD); } g_free(text); break; } } return TRUE; } static void cb_func_menu_opencolorchooser(G_GNUC_UNUSED guint key_id) { on_show_color_chooser1_activate(NULL, NULL); } static gboolean cb_func_view_action(guint key_id) { switch (key_id) { case GEANY_KEYS_VIEW_TOGGLEALL: on_menu_toggle_all_additional_widgets1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_SIDEBAR: on_menu_show_sidebar1_toggled(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMIN: on_zoom_in1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMOUT: on_zoom_out1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMRESET: on_normal_size1_activate(NULL, NULL); break; default: break; } return TRUE; } static void cb_func_menu_fullscreen(G_GNUC_UNUSED guint key_id) { GtkCheckMenuItem *c = GTK_CHECK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "menu_fullscreen1")); gtk_check_menu_item_set_active(c, ! gtk_check_menu_item_get_active(c)); } static void cb_func_menu_messagewindow(G_GNUC_UNUSED guint key_id) { GtkCheckMenuItem *c = GTK_CHECK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "menu_show_messages_window1")); gtk_check_menu_item_set_active(c, ! gtk_check_menu_item_get_active(c)); } static gboolean cb_func_build_action(guint key_id) { GtkWidget *item; BuildMenuItems *menu_items; GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; if (!GTK_WIDGET_IS_SENSITIVE(ui_lookup_widget(main_widgets.window, "menu_build1"))) return TRUE; menu_items = build_get_menu_items(doc->file_type->id); /* TODO make it a table??*/ switch (key_id) { case GEANY_KEYS_BUILD_COMPILE: item = menu_items->menu_item[GEANY_GBG_FT][GBO_TO_CMD(GEANY_GBO_COMPILE)]; break; case GEANY_KEYS_BUILD_LINK: item = menu_items->menu_item[GEANY_GBG_FT][GBO_TO_CMD(GEANY_GBO_BUILD)]; break; case GEANY_KEYS_BUILD_MAKE: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_MAKE_ALL)]; break; case GEANY_KEYS_BUILD_MAKEOWNTARGET: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_CUSTOM)]; break; case GEANY_KEYS_BUILD_MAKEOBJECT: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_MAKE_OBJECT)]; break; case GEANY_KEYS_BUILD_NEXTERROR: item = menu_items->menu_item[GBG_FIXED][GBF_NEXT_ERROR]; break; case GEANY_KEYS_BUILD_PREVIOUSERROR: item = menu_items->menu_item[GBG_FIXED][GBF_PREV_ERROR]; break; case GEANY_KEYS_BUILD_RUN: item = menu_items->menu_item[GEANY_GBG_EXEC][GBO_TO_CMD(GEANY_GBO_EXEC)]; break; case GEANY_KEYS_BUILD_OPTIONS: item = menu_items->menu_item[GBG_FIXED][GBF_COMMANDS]; break; default: item = NULL; } /* Note: For Build menu items it's OK (at the moment) to assume they are in the correct * sensitive state, but some other menus don't update the sensitive status until * they are redrawn. */ if (item && GTK_WIDGET_IS_SENSITIVE(item)) gtk_menu_item_activate(GTK_MENU_ITEM(item)); return TRUE; } static gboolean read_current_word(GeanyDocument *doc, gboolean sci_word) { if (doc == NULL) return FALSE; if (sci_word) { editor_find_current_word_sciwc(doc->editor, -1, editor_info.current_word, GEANY_MAX_WORD_LENGTH); } else { editor_find_current_word(doc->editor, -1, editor_info.current_word, GEANY_MAX_WORD_LENGTH, NULL); } return (*editor_info.current_word != 0); } static gboolean check_current_word(GeanyDocument *doc, gboolean sci_word) { if (! read_current_word(doc, sci_word)) { utils_beep(); return FALSE; } return TRUE; } static gchar *get_current_word_or_sel(GeanyDocument *doc, gboolean sci_word) { ScintillaObject *sci = doc->editor->sci; if (sci_has_selection(sci)) return sci_get_selection_contents(sci); return read_current_word(doc, sci_word) ? g_strdup(editor_info.current_word) : NULL; } static void focus_sidebar(void) { if (ui_prefs.sidebar_visible) { gint page_num = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.sidebar_notebook)); GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.sidebar_notebook), page_num); /* gtk_widget_grab_focus() won't work because of the scrolled window containers */ gtk_widget_child_focus(page, GTK_DIR_TAB_FORWARD); } } static void focus_msgwindow(void) { if (ui_prefs.msgwindow_visible) { gint page_num = gtk_notebook_get_current_page(GTK_NOTEBOOK(msgwindow.notebook)); GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(msgwindow.notebook), page_num); gtk_widget_grab_focus(gtk_bin_get_child(GTK_BIN(page))); } } static gboolean cb_func_switch_action(guint key_id) { switch (key_id) { case GEANY_KEYS_FOCUS_EDITOR: { GeanyDocument *doc = document_get_current(); if (doc != NULL) { GtkWidget *sci = GTK_WIDGET(doc->editor->sci); if (GTK_WIDGET_HAS_FOCUS(sci)) ui_update_statusbar(doc, -1); else gtk_widget_grab_focus(sci); } break; } case GEANY_KEYS_FOCUS_SCRIBBLE: msgwin_switch_tab(MSG_SCRATCH, TRUE); break; case GEANY_KEYS_FOCUS_SEARCHBAR: if (toolbar_prefs.visible) { GtkWidget *search_entry = toolbar_get_widget_child_by_name("SearchEntry"); if (search_entry != NULL) gtk_widget_grab_focus(search_entry); } break; case GEANY_KEYS_FOCUS_SIDEBAR: focus_sidebar(); break; case GEANY_KEYS_FOCUS_VTE: msgwin_switch_tab(MSG_VTE, TRUE); break; case GEANY_KEYS_FOCUS_COMPILER: msgwin_switch_tab(MSG_COMPILER, TRUE); break; case GEANY_KEYS_FOCUS_MESSAGES: msgwin_switch_tab(MSG_MESSAGE, TRUE); break; case GEANY_KEYS_FOCUS_MESSAGE_WINDOW: focus_msgwindow(); break; case GEANY_KEYS_FOCUS_SIDEBAR_DOCUMENT_LIST: sidebar_focus_openfiles_tab(); break; case GEANY_KEYS_FOCUS_SIDEBAR_SYMBOL_LIST: sidebar_focus_symbols_tab(); break; } return TRUE; } static void switch_notebook_page(gint direction) { gint page_count, cur_page; gboolean parent_is_notebook = FALSE; GtkNotebook *notebook; GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* check whether the current widget is a GtkNotebook or a child of a GtkNotebook */ do { parent_is_notebook = GTK_IS_NOTEBOOK(focusw); } while (! parent_is_notebook && (focusw = gtk_widget_get_parent(focusw)) != NULL); /* if we found a GtkNotebook widget, use it. Otherwise fallback to the documents notebook */ if (parent_is_notebook) notebook = GTK_NOTEBOOK(focusw); else notebook = GTK_NOTEBOOK(main_widgets.notebook); /* now switch pages */ page_count = gtk_notebook_get_n_pages(notebook); cur_page = gtk_notebook_get_current_page(notebook); if (direction == GTK_DIR_LEFT) { if (cur_page > 0) gtk_notebook_set_current_page(notebook, cur_page - 1); else gtk_notebook_set_current_page(notebook, page_count - 1); } else if (direction == GTK_DIR_RIGHT) { if (cur_page < page_count - 1) gtk_notebook_set_current_page(notebook, cur_page + 1); else gtk_notebook_set_current_page(notebook, 0); } } static void cb_func_switch_tableft(G_GNUC_UNUSED guint key_id) { switch_notebook_page(GTK_DIR_LEFT); } static void cb_func_switch_tabright(G_GNUC_UNUSED guint key_id) { switch_notebook_page(GTK_DIR_RIGHT); } static void cb_func_switch_tablastused(G_GNUC_UNUSED guint key_id) { notebook_switch_tablastused(); } /* move document left/right/first/last */ static void cb_func_move_tab(guint key_id) { GtkWidget *sci; GtkNotebook *nb = GTK_NOTEBOOK(main_widgets.notebook); gint cur_page = gtk_notebook_get_current_page(nb); GeanyDocument *doc = document_get_current(); if (doc == NULL) return; sci = GTK_WIDGET(doc->editor->sci); switch (key_id) { case GEANY_KEYS_NOTEBOOK_MOVETABLEFT: gtk_notebook_reorder_child(nb, sci, cur_page - 1); /* notebook wraps around by default */ break; case GEANY_KEYS_NOTEBOOK_MOVETABRIGHT: { gint npage = cur_page + 1; if (npage == gtk_notebook_get_n_pages(nb)) npage = 0; /* wraparound */ gtk_notebook_reorder_child(nb, sci, npage); break; } case GEANY_KEYS_NOTEBOOK_MOVETABFIRST: gtk_notebook_reorder_child(nb, sci, (file_prefs.tab_order_ltr) ? 0 : -1); break; case GEANY_KEYS_NOTEBOOK_MOVETABLAST: gtk_notebook_reorder_child(nb, sci, (file_prefs.tab_order_ltr) ? -1 : 0); break; } return; } static void goto_matching_brace(GeanyDocument *doc) { gint pos, new_pos; gint after_brace; if (doc == NULL) return; pos = sci_get_current_position(doc->editor->sci); after_brace = pos > 0 && utils_isbrace(sci_get_char_at(doc->editor->sci, pos - 1), TRUE); pos -= after_brace; /* set pos to the brace */ new_pos = sci_find_matching_brace(doc->editor->sci, pos); if (new_pos != -1) { /* set the cursor at/after the brace */ sci_set_current_position(doc->editor->sci, new_pos + (!after_brace), FALSE); editor_display_current_line(doc->editor, 0.5F); } } static gboolean cb_func_clipboard_action(guint key_id) { GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; switch (key_id) { case GEANY_KEYS_CLIPBOARD_CUT: on_cut1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_COPY: on_copy1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_PASTE: on_paste1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_COPYLINE: sci_send_command(doc->editor->sci, SCI_LINECOPY); break; case GEANY_KEYS_CLIPBOARD_CUTLINE: sci_send_command(doc->editor->sci, SCI_LINECUT); break; } return TRUE; } static void goto_tag(GeanyDocument *doc, gboolean definition) { gchar *text = get_current_word_or_sel(doc, FALSE); if (text) symbols_goto_tag(text, definition); else utils_beep(); g_free(text); } /* Common function for goto keybindings, useful even when sci doesn't have focus. */ static gboolean cb_func_goto_action(guint key_id) { gint cur_line; GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; cur_line = sci_get_current_line(doc->editor->sci); switch (key_id) { case GEANY_KEYS_GOTO_BACK: navqueue_go_back(); return TRUE; case GEANY_KEYS_GOTO_FORWARD: navqueue_go_forward(); return TRUE; case GEANY_KEYS_GOTO_LINE: { if (toolbar_prefs.visible) { GtkWidget *wid = toolbar_get_widget_child_by_name("GotoEntry"); /* use toolbar item if shown & not in the drop down overflow menu */ if (wid && GTK_WIDGET_MAPPED(wid)) { gtk_widget_grab_focus(wid); return TRUE; } } on_go_to_line_activate(NULL, NULL); return TRUE; } case GEANY_KEYS_GOTO_MATCHINGBRACE: goto_matching_brace(doc); return TRUE; case GEANY_KEYS_GOTO_TOGGLEMARKER: { sci_toggle_marker_at_line(doc->editor->sci, cur_line, 1); return TRUE; } case GEANY_KEYS_GOTO_NEXTMARKER: { gint mline = sci_marker_next(doc->editor->sci, cur_line + 1, 1 << 1, TRUE); if (mline != -1) { sci_set_current_line(doc->editor->sci, mline); editor_display_current_line(doc->editor, 0.5F); } return TRUE; } case GEANY_KEYS_GOTO_PREVIOUSMARKER: { gint mline = sci_marker_previous(doc->editor->sci, cur_line - 1, 1 << 1, TRUE); if (mline != -1) { sci_set_current_line(doc->editor->sci, mline); editor_display_current_line(doc->editor, 0.5F); } return TRUE; } case GEANY_KEYS_GOTO_TAGDEFINITION: goto_tag(doc, TRUE); return TRUE; case GEANY_KEYS_GOTO_TAGDECLARATION: goto_tag(doc, FALSE); return TRUE; } /* only check editor-sensitive keybindings when editor has focus so home,end still * work in other widgets */ if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != GTK_WIDGET(doc->editor->sci)) return FALSE; switch (key_id) { case GEANY_KEYS_GOTO_LINESTART: sci_send_command(doc->editor->sci, editor_prefs.smart_home_key ? SCI_VCHOME : SCI_HOME); break; case GEANY_KEYS_GOTO_LINEEND: sci_send_command(doc->editor->sci, SCI_LINEEND); break; case GEANY_KEYS_GOTO_LINEENDVISUAL: sci_send_command(doc->editor->sci, SCI_LINEENDDISPLAY); break; case GEANY_KEYS_GOTO_PREVWORDPART: sci_send_command(doc->editor->sci, SCI_WORDPARTLEFT); break; case GEANY_KEYS_GOTO_NEXTWORDPART: sci_send_command(doc->editor->sci, SCI_WORDPARTRIGHT); break; } return TRUE; } static void duplicate_lines(GeanyEditor *editor) { if (sci_get_lines_selected(editor->sci) > 1) { /* ignore extra_line because of selecting lines from the line number column */ editor_select_lines(editor, FALSE); sci_selection_duplicate(editor->sci); } else if (sci_has_selection(editor->sci)) sci_selection_duplicate(editor->sci); else sci_line_duplicate(editor->sci); } static void delete_lines(GeanyEditor *editor) { editor_select_lines(editor, TRUE); /* include last line (like cut lines, copy lines do) */ sci_clear(editor->sci); /* (SCI_LINEDELETE only does 1 line) */ } /* common function for editor keybindings, only valid when scintilla has focus. */ static gboolean cb_func_editor_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* edit keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return FALSE; /* also makes tab work outside editor */ switch (key_id) { case GEANY_KEYS_EDITOR_UNDO: on_undo1_activate(NULL, NULL); break; case GEANY_KEYS_EDITOR_REDO: on_redo1_activate(NULL, NULL); break; case GEANY_KEYS_EDITOR_SCROLLTOLINE: editor_scroll_to_line(doc->editor, -1, 0.5F); break; case GEANY_KEYS_EDITOR_SCROLLLINEUP: sci_send_command(doc->editor->sci, SCI_LINESCROLLUP); break; case GEANY_KEYS_EDITOR_SCROLLLINEDOWN: sci_send_command(doc->editor->sci, SCI_LINESCROLLDOWN); break; case GEANY_KEYS_EDITOR_DUPLICATELINE: duplicate_lines(doc->editor); break; case GEANY_KEYS_EDITOR_SNIPPETNEXTCURSOR: editor_goto_next_snippet_cursor(doc->editor); break; case GEANY_KEYS_EDITOR_DELETELINE: delete_lines(doc->editor); break; case GEANY_KEYS_EDITOR_DELETELINETOEND: sci_send_command(doc->editor->sci, SCI_DELLINERIGHT); break; case GEANY_KEYS_EDITOR_TRANSPOSELINE: sci_send_command(doc->editor->sci, SCI_LINETRANSPOSE); break; case GEANY_KEYS_EDITOR_AUTOCOMPLETE: editor_start_auto_complete(doc->editor, sci_get_current_position(doc->editor->sci), TRUE); break; case GEANY_KEYS_EDITOR_CALLTIP: editor_show_calltip(doc->editor, -1); break; case GEANY_KEYS_EDITOR_MACROLIST: editor_show_macro_list(doc->editor); break; case GEANY_KEYS_EDITOR_CONTEXTACTION: if (check_current_word(doc, FALSE)) on_context_action1_activate(GTK_MENU_ITEM(ui_lookup_widget(main_widgets.editor_menu, "context_action1")), NULL); break; case GEANY_KEYS_EDITOR_COMPLETESNIPPET: /* allow tab to be overloaded */ return check_snippet_completion(doc); case GEANY_KEYS_EDITOR_SUPPRESSSNIPPETCOMPLETION: { GeanyKeyBinding *kb = keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR, GEANY_KEYS_EDITOR_COMPLETESNIPPET); switch (kb->key) { case GDK_space: sci_add_text(doc->editor->sci, " "); break; case GDK_Tab: sci_send_command(doc->editor->sci, SCI_TAB); break; default: break; } break; } case GEANY_KEYS_EDITOR_WORDPARTCOMPLETION: return editor_complete_word_part(doc->editor); case GEANY_KEYS_EDITOR_MOVELINEUP: sci_move_selected_lines_up(doc->editor->sci); break; case GEANY_KEYS_EDITOR_MOVELINEDOWN: sci_move_selected_lines_down(doc->editor->sci); break; } return TRUE; } static void join_lines(GeanyEditor *editor) { gint start, end, i; start = sci_get_line_from_position(editor->sci, sci_get_selection_start(editor->sci)); end = sci_get_line_from_position(editor->sci, sci_get_selection_end(editor->sci)); /* remove spaces surrounding the lines so that these spaces * won't appear within text after joining */ for (i = start; i < end; i++) editor_strip_line_trailing_spaces(editor, i); for (i = start + 1; i <= end; i++) sci_set_line_indentation(editor->sci, i, 0); sci_set_target_start(editor->sci, sci_get_position_from_line(editor->sci, start)); sci_set_target_end(editor->sci, sci_get_position_from_line(editor->sci, end)); sci_lines_join(editor->sci); } static gint get_reflow_column(GeanyEditor *editor) { const GeanyEditorPrefs *eprefs = editor_get_prefs(editor); if (editor->line_breaking) return eprefs->line_break_column; else if (eprefs->long_line_type != 2) return eprefs->long_line_column; else return -1; /* do nothing */ } static void reflow_lines(GeanyEditor *editor, gint column) { gint start, indent, linescount, i; start = sci_get_line_from_position(editor->sci, sci_get_selection_start(editor->sci)); /* if several lines are selected, join them. */ if (sci_get_lines_selected(editor->sci) > 1) join_lines(editor); /* if this line is short enough, do nothing */ if (column > sci_get_line_end_position(editor->sci, start) - sci_get_position_from_line(editor->sci, start)) { return; } /* * We have to manipulate line indentation so that indentation * of the resulting lines would be consistent. For example, * the result of splitting "[TAB]very long content": * * +-------------+-------------+ * | proper | wrong | * +-------------+-------------+ * | [TAB]very | [TAB]very | * | [TAB]long | long | * | [TAB]content| content | * +-------------+-------------+ */ indent = sci_get_line_indentation(editor->sci, start); sci_set_line_indentation(editor->sci, start, 0); sci_target_from_selection(editor->sci); linescount = sci_get_line_count(editor->sci); sci_lines_split(editor->sci, (column - indent) * sci_text_width(editor->sci, STYLE_DEFAULT, " ")); /* use lines count to determine how many lines appeared after splitting */ linescount = sci_get_line_count(editor->sci) - linescount; /* Fix indentation. */ for (i = start; i <= start + linescount; i++) sci_set_line_indentation(editor->sci, i, indent); /* Remove trailing spaces. */ if (editor_prefs.newline_strip || file_prefs.strip_trailing_spaces) { for (i = start; i <= start + linescount; i++) editor_strip_line_trailing_spaces(editor, i); } } /* deselect last newline of selection, if any */ static void sci_deselect_last_newline(ScintillaObject *sci) { gint start, end; start = sci_get_selection_start(sci); end = sci_get_selection_end(sci); if (end > start && sci_get_col_from_position(sci, end) == 0) { end = sci_get_line_end_position(sci, sci_get_line_from_position(sci, end-1)); sci_set_selection(sci, start, end); } } static void reflow_paragraph(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gboolean sel; gint column; column = get_reflow_column(editor); if (column == -1) { utils_beep(); return; } sci_start_undo_action(sci); sel = sci_has_selection(sci); if (!sel) editor_select_indent_block(editor); sci_deselect_last_newline(sci); reflow_lines(editor, column); if (!sel) sci_set_anchor(sci, -1); sci_end_undo_action(sci); } static void join_paragraph(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gboolean sel; gint column; column = get_reflow_column(editor); if (column == -1) { utils_beep(); return; } sci_start_undo_action(sci); sel = sci_has_selection(sci); if (!sel) editor_select_indent_block(editor); sci_deselect_last_newline(sci); join_lines(editor); if (!sel) sci_set_anchor(sci, -1); sci_end_undo_action(sci); } /* common function for format keybindings, only valid when scintilla has focus. */ static gboolean cb_func_format_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; switch (key_id) { case GEANY_KEYS_FORMAT_COMMENTLINETOGGLE: on_menu_toggle_line_commentation1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_COMMENTLINE: on_menu_comment_line1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_UNCOMMENTLINE: on_menu_uncomment_line1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_INCREASEINDENT: on_menu_increase_indent1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_DECREASEINDENT: on_menu_decrease_indent1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_INCREASEINDENTBYSPACE: editor_indentation_by_one_space(doc->editor, -1, FALSE); break; case GEANY_KEYS_FORMAT_DECREASEINDENTBYSPACE: editor_indentation_by_one_space(doc->editor, -1, TRUE); break; case GEANY_KEYS_FORMAT_AUTOINDENT: editor_smart_line_indentation(doc->editor, -1); break; case GEANY_KEYS_FORMAT_TOGGLECASE: on_toggle_case1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_SENDTOCMD1: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 0) tools_execute_custom_command(doc, ui_prefs.custom_commands[0]); break; case GEANY_KEYS_FORMAT_SENDTOCMD2: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 1) tools_execute_custom_command(doc, ui_prefs.custom_commands[1]); break; case GEANY_KEYS_FORMAT_SENDTOCMD3: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 2) tools_execute_custom_command(doc, ui_prefs.custom_commands[2]); break; case GEANY_KEYS_FORMAT_SENDTOVTE: on_send_selection_to_vte1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_REFLOWPARAGRAPH: reflow_paragraph(doc->editor); break; case GEANY_KEYS_FORMAT_JOINLINES: join_paragraph(doc->editor); break; } return TRUE; } /* common function for select keybindings, only valid when scintilla has focus. */ static gboolean cb_func_select_action(guint key_id) { GeanyDocument *doc; ScintillaObject *sci; GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); GtkWidget *toolbar_search_entry = toolbar_get_widget_child_by_name("SearchEntry"); GtkWidget *toolbar_goto_entry = toolbar_get_widget_child_by_name("GotoEntry"); /* special case for Select All in the scribble widget */ if (key_id == GEANY_KEYS_SELECT_ALL && focusw == msgwindow.scribble) { g_signal_emit_by_name(msgwindow.scribble, "select-all", TRUE); return TRUE; } /* special case for Select All in the VTE widget */ #ifdef HAVE_VTE else if (key_id == GEANY_KEYS_SELECT_ALL && vte_info.have_vte && focusw == vc->vte) { vte_select_all(); return TRUE; } #endif /* special case for Select All in the toolbar search widget */ else if (key_id == GEANY_KEYS_SELECT_ALL && focusw == toolbar_search_entry) { gtk_editable_select_region(GTK_EDITABLE(toolbar_search_entry), 0, -1); return TRUE; } else if (key_id == GEANY_KEYS_SELECT_ALL && focusw == toolbar_goto_entry) { gtk_editable_select_region(GTK_EDITABLE(toolbar_goto_entry), 0, -1); return TRUE; } doc = document_get_current(); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; sci = doc->editor->sci; switch (key_id) { case GEANY_KEYS_SELECT_ALL: on_menu_select_all1_activate(NULL, NULL); break; case GEANY_KEYS_SELECT_WORD: editor_select_word(doc->editor); break; case GEANY_KEYS_SELECT_LINE: editor_select_lines(doc->editor, FALSE); break; case GEANY_KEYS_SELECT_PARAGRAPH: editor_select_paragraph(doc->editor); break; case GEANY_KEYS_SELECT_WORDPARTLEFT: sci_send_command(sci, SCI_WORDPARTLEFTEXTEND); break; case GEANY_KEYS_SELECT_WORDPARTRIGHT: sci_send_command(sci, SCI_WORDPARTRIGHTEXTEND); break; } return TRUE; } static gboolean cb_func_document_action(guint key_id) { GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; switch (key_id) { case GEANY_KEYS_DOCUMENT_REPLACETABS: on_replace_tabs_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REPLACESPACES: on_replace_spaces_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_LINEBREAK: on_line_breaking1_activate(NULL, NULL); ui_document_show_hide(doc); break; case GEANY_KEYS_DOCUMENT_LINEWRAP: on_line_wrapping1_toggled(NULL, NULL); ui_document_show_hide(doc); break; case GEANY_KEYS_DOCUMENT_RELOADTAGLIST: document_update_tags(doc); break; case GEANY_KEYS_DOCUMENT_FOLDALL: editor_fold_all(doc->editor); break; case GEANY_KEYS_DOCUMENT_UNFOLDALL: editor_unfold_all(doc->editor); break; case GEANY_KEYS_DOCUMENT_TOGGLEFOLD: if (editor_prefs.folding) { gint line = sci_get_current_line(doc->editor->sci); editor_toggle_fold(doc->editor, line, 0); break; } case GEANY_KEYS_DOCUMENT_REMOVE_MARKERS: on_remove_markers1_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REMOVE_ERROR_INDICATORS: on_menu_remove_indicators1_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REMOVE_MARKERS_INDICATORS: on_remove_markers1_activate(NULL, NULL); on_menu_remove_indicators1_activate(NULL, NULL); break; } return TRUE; } static void insert_line_after(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; sci_send_command(sci, SCI_LINEEND); sci_send_command(sci, SCI_NEWLINE); } static void insert_line_before(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gint line = sci_get_current_line(sci); gint indentpos = sci_get_line_indent_position(sci, line); sci_set_current_position(sci, indentpos, TRUE); sci_send_command(sci, SCI_NEWLINE); sci_send_command(sci, SCI_LINEUP); } /* common function for insert keybindings, only valid when scintilla has focus. */ static gboolean cb_func_insert_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; switch (key_id) { case GEANY_KEYS_INSERT_ALTWHITESPACE: editor_insert_alternative_whitespace(doc->editor); break; case GEANY_KEYS_INSERT_DATE: gtk_menu_item_activate(GTK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "insert_date_custom1"))); break; case GEANY_KEYS_INSERT_LINEAFTER: insert_line_after(doc->editor); break; case GEANY_KEYS_INSERT_LINEBEFORE: insert_line_before(doc->editor); break; } return TRUE; } /* update key combination */ void keybindings_update_combo(GeanyKeyBinding *kb, guint key, GdkModifierType mods) { GtkWidget *widget = kb->menu_item; if (widget && kb->key) gtk_widget_remove_accelerator(widget, kb_accel_group, kb->key, kb->mods); kb->key = key; kb->mods = mods; if (widget && kb->key) gtk_widget_add_accelerator(widget, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } /* used for plugins, can be called repeatedly. */ GeanyKeyGroup *keybindings_set_group(GeanyKeyGroup *group, const gchar *section_name, const gchar *label, gsize count, GeanyKeyGroupCallback callback) { g_return_val_if_fail(section_name, NULL); g_return_val_if_fail(count, NULL); /* prevent conflict with core bindings */ g_return_val_if_fail(!g_str_equal(section_name, keybindings_keyfile_group_name), NULL); if (!group) { group = g_new0(GeanyKeyGroup, 1); add_kb_group(group, section_name, label, callback, TRUE); } g_free(group->plugin_keys); group->plugin_keys = g_new0(GeanyKeyBinding, count); group->plugin_key_count = count; g_ptr_array_set_size(group->key_items, 0); return group; } void keybindings_free_group(GeanyKeyGroup *group) { GeanyKeyBinding *kb; g_ptr_array_free(group->key_items, TRUE); if (group->plugin) { foreach_c_array(kb, group->plugin_keys, group->plugin_key_count) { g_free(kb->name); g_free(kb->label); } g_free(group->plugin_keys); g_ptr_array_remove_fast(keybinding_groups, group); g_free(group); } }
ktuan89/geany-1.22
src/keybindings.c
C
gpl-2.0
79,266
/* * Synopsys DesignWare 8250 driver. * * Copyright 2011 Picochip, Jamie Iles. * Copyright 2013 Intel 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; either version 2 of the License, or * (at your option) any later version. * * The Synopsys DesignWare 8250 has an extra feature whereby it detects if the * LCR is written whilst busy. If it is, then a busy detect interrupt is * raised, the LCR needs to be rewritten and the uart status register read. */ #include <linux/device.h> #include <linux/io.h> #include <linux/module.h> #include <linux/serial_8250.h> #include <linux/serial_core.h> #include <linux/serial_reg.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/clk.h> #include <linux/reset.h> #include <linux/pm_runtime.h> #include <asm/byteorder.h> #include "8250.h" /* Offsets for the DesignWare specific registers */ #define DW_UART_USR 0x1f /* UART Status Register */ #define DW_UART_CPR 0xf4 /* Component Parameter Register */ #define DW_UART_UCV 0xf8 /* UART Component Version */ /* Component Parameter Register bits */ #define DW_UART_CPR_ABP_DATA_WIDTH (3 << 0) #define DW_UART_CPR_AFCE_MODE (1 << 4) #define DW_UART_CPR_THRE_MODE (1 << 5) #define DW_UART_CPR_SIR_MODE (1 << 6) #define DW_UART_CPR_SIR_LP_MODE (1 << 7) #define DW_UART_CPR_ADDITIONAL_FEATURES (1 << 8) #define DW_UART_CPR_FIFO_ACCESS (1 << 9) #define DW_UART_CPR_FIFO_STAT (1 << 10) #define DW_UART_CPR_SHADOW (1 << 11) #define DW_UART_CPR_ENCODED_PARMS (1 << 12) #define DW_UART_CPR_DMA_EXTRA (1 << 13) #define DW_UART_CPR_FIFO_MODE (0xff << 16) /* Helper for fifo size calculation */ #define DW_UART_CPR_FIFO_SIZE(a) (((a >> 16) & 0xff) * 16) struct dw8250_data { u8 usr_reg; int last_mcr; int line; struct clk *clk; struct reset_control *rst; struct uart_8250_dma dma; }; static inline int dw8250_modify_msr(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; /* If reading MSR, report CTS asserted when auto-CTS/RTS enabled */ if (offset == UART_MSR && d->last_mcr & UART_MCR_AFE) { value |= UART_MSR_CTS; value &= ~UART_MSR_DCTS; } return value; } static void dw8250_force_idle(struct uart_port *p) { serial8250_clear_and_reinit_fifos(container_of (p, struct uart_8250_port, port)); (void)p->serial_in(p, UART_RX); } static void dw8250_serial_out(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; if (offset == UART_MCR) d->last_mcr = value; writeb(value, p->membase + (offset << p->regshift)); /* Make sure LCR write wasn't ignored */ if (offset == UART_LCR) { int tries = 1000; while (tries--) { unsigned int lcr = p->serial_in(p, UART_LCR); if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR)) return; dw8250_force_idle(p); writeb(value, p->membase + (UART_LCR << p->regshift)); } dev_err(p->dev, "Couldn't set LCR to %d\n", value); } } static unsigned int dw8250_serial_in(struct uart_port *p, int offset) { unsigned int value = readb(p->membase + (offset << p->regshift)); return dw8250_modify_msr(p, offset, value); } /* Read Back (rb) version to ensure register access ording. */ static void dw8250_serial_out_rb(struct uart_port *p, int offset, int value) { dw8250_serial_out(p, offset, value); dw8250_serial_in(p, UART_LCR); } static void dw8250_serial_out32(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; if (offset == UART_MCR) d->last_mcr = value; writel(value, p->membase + (offset << p->regshift)); /* Make sure LCR write wasn't ignored */ if (offset == UART_LCR) { int tries = 1000; while (tries--) { unsigned int lcr = p->serial_in(p, UART_LCR); if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR)) return; dw8250_force_idle(p); writel(value, p->membase + (UART_LCR << p->regshift)); } dev_err(p->dev, "Couldn't set LCR to %d\n", value); } } static unsigned int dw8250_serial_in32(struct uart_port *p, int offset) { unsigned int value = readl(p->membase + (offset << p->regshift)); return dw8250_modify_msr(p, offset, value); } static int dw8250_handle_irq(struct uart_port *p) { struct dw8250_data *d = p->private_data; unsigned int iir = p->serial_in(p, UART_IIR); if (serial8250_handle_irq(p, iir)) { return 1; } else if ((iir & UART_IIR_BUSY) == UART_IIR_BUSY) { /* Clear the USR */ (void)p->serial_in(p, d->usr_reg); return 1; } return 0; } static void dw8250_do_pm(struct uart_port *port, unsigned int state, unsigned int old) { if (!state) pm_runtime_get_sync(port->dev); serial8250_do_pm(port, state, old); if (state) pm_runtime_put_sync_suspend(port->dev); } static bool dw8250_dma_filter(struct dma_chan *chan, void *param) { struct dw8250_data *data = param; return chan->chan_id == data->dma.tx_chan_id || chan->chan_id == data->dma.rx_chan_id; } static void dw8250_setup_port(struct uart_8250_port *up) { struct uart_port *p = &up->port; u32 reg = readl(p->membase + DW_UART_UCV); /* * If the Component Version Register returns zero, we know that * ADDITIONAL_FEATURES are not enabled. No need to go any further. */ if (!reg) return; dev_dbg_ratelimited(p->dev, "Designware UART version %c.%c%c\n", (reg >> 24) & 0xff, (reg >> 16) & 0xff, (reg >> 8) & 0xff); reg = readl(p->membase + DW_UART_CPR); if (!reg) return; /* Select the type based on fifo */ if (reg & DW_UART_CPR_FIFO_MODE) { p->type = PORT_16550A; p->flags |= UPF_FIXED_TYPE; p->fifosize = DW_UART_CPR_FIFO_SIZE(reg); up->tx_loadsz = p->fifosize; up->capabilities = UART_CAP_FIFO; } if (reg & DW_UART_CPR_AFCE_MODE) up->capabilities |= UART_CAP_AFE; } static int dw8250_probe_of(struct uart_port *p, struct dw8250_data *data) { struct device_node *np = p->dev->of_node; u32 val; bool has_ucv = true; if (of_device_is_compatible(np, "cavium,octeon-3860-uart")) { #ifdef __BIG_ENDIAN /* * Low order bits of these 64-bit registers, when * accessed as a byte, are 7 bytes further down in the * address space in big endian mode. */ p->membase += 7; #endif p->serial_out = dw8250_serial_out_rb; p->flags = ASYNC_SKIP_TEST | UPF_SHARE_IRQ | UPF_FIXED_TYPE; p->type = PORT_OCTEON; data->usr_reg = 0x27; has_ucv = false; } else if (!of_property_read_u32(np, "reg-io-width", &val)) { switch (val) { case 1: break; case 4: p->iotype = UPIO_MEM32; p->serial_in = dw8250_serial_in32; p->serial_out = dw8250_serial_out32; break; default: dev_err(p->dev, "unsupported reg-io-width (%u)\n", val); return -EINVAL; } } if (has_ucv) dw8250_setup_port(container_of(p, struct uart_8250_port, port)); if (!of_property_read_u32(np, "reg-shift", &val)) p->regshift = val; data->rst = devm_reset_control_get_optional(p->dev, NULL); /* clock got configured through clk api, all done */ if (p->uartclk) return 0; /* try to find out clock frequency from DT as fallback */ if (of_property_read_u32(np, "clock-frequency", &val)) { dev_err(p->dev, "clk or clock-frequency not defined\n"); return -EINVAL; } p->uartclk = val; return 0; } static int dw8250_probe_acpi(struct uart_8250_port *up, struct dw8250_data *data) { const struct acpi_device_id *id; struct uart_port *p = &up->port; dw8250_setup_port(up); id = acpi_match_device(p->dev->driver->acpi_match_table, p->dev); if (!id) return -ENODEV; p->iotype = UPIO_MEM32; p->serial_in = dw8250_serial_in32; p->serial_out = dw8250_serial_out32; p->regshift = 2; if (!p->uartclk) p->uartclk = (unsigned int)id->driver_data; up->dma = &data->dma; up->dma->rxconf.src_maxburst = p->fifosize / 4; up->dma->txconf.dst_maxburst = p->fifosize / 4; return 0; } static int dw8250_probe(struct platform_device *pdev) { struct uart_8250_port uart = {}; struct resource *regs = platform_get_resource(pdev, IORESOURCE_MEM, 0); struct resource *irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0); struct dw8250_data *data; int err; if (!regs || !irq) { dev_err(&pdev->dev, "no registers/irq defined\n"); return -EINVAL; } spin_lock_init(&uart.port.lock); uart.port.mapbase = regs->start; uart.port.irq = irq->start; uart.port.handle_irq = dw8250_handle_irq; uart.port.pm = dw8250_do_pm; uart.port.type = PORT_8250; uart.port.flags = UPF_SHARE_IRQ | UPF_BOOT_AUTOCONF | UPF_FIXED_PORT; uart.port.dev = &pdev->dev; uart.port.membase = devm_ioremap(&pdev->dev, regs->start, resource_size(regs)); if (!uart.port.membase) return -ENOMEM; data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->usr_reg = DW_UART_USR; data->clk = devm_clk_get(&pdev->dev, NULL); if (!IS_ERR(data->clk)) { clk_prepare_enable(data->clk); uart.port.uartclk = clk_get_rate(data->clk); } data->dma.rx_chan_id = -1; data->dma.tx_chan_id = -1; data->dma.rx_param = data; data->dma.tx_param = data; data->dma.fn = dw8250_dma_filter; uart.port.iotype = UPIO_MEM; uart.port.serial_in = dw8250_serial_in; uart.port.serial_out = dw8250_serial_out; uart.port.private_data = data; if (pdev->dev.of_node) { err = dw8250_probe_of(&uart.port, data); if (err) return err; } else if (ACPI_HANDLE(&pdev->dev)) { err = dw8250_probe_acpi(&uart, data); if (err) return err; } else { return -ENODEV; } if (!IS_ERR_OR_NULL(data->rst)) reset_control_deassert(data->rst); data->line = serial8250_register_8250_port(&uart); if (data->line < 0) return data->line; platform_set_drvdata(pdev, data); pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); return 0; } static int dw8250_remove(struct platform_device *pdev) { struct dw8250_data *data = platform_get_drvdata(pdev); pm_runtime_get_sync(&pdev->dev); serial8250_unregister_port(data->line); if (!IS_ERR_OR_NULL(data->rst)) reset_control_assert(data->rst); if (!IS_ERR(data->clk)) clk_disable_unprepare(data->clk); pm_runtime_disable(&pdev->dev); pm_runtime_put_noidle(&pdev->dev); return 0; } #ifdef CONFIG_PM_SLEEP static int dw8250_suspend(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); serial8250_suspend_port(data->line); return 0; } static int dw8250_resume(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); serial8250_resume_port(data->line); return 0; } #endif /* CONFIG_PM_SLEEP */ #ifdef CONFIG_PM_RUNTIME static int dw8250_runtime_suspend(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); if (!IS_ERR(data->clk)) clk_disable_unprepare(data->clk); return 0; } static int dw8250_runtime_resume(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); if (!IS_ERR(data->clk)) clk_prepare_enable(data->clk); return 0; } #endif static const struct dev_pm_ops dw8250_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(dw8250_suspend, dw8250_resume) SET_RUNTIME_PM_OPS(dw8250_runtime_suspend, dw8250_runtime_resume, NULL) }; static const struct of_device_id dw8250_of_match[] = { { .compatible = "snps,dw-apb-uart" }, { .compatible = "cavium,octeon-3860-uart" }, { /* Sentinel */ } }; MODULE_DEVICE_TABLE(of, dw8250_of_match); static const struct acpi_device_id dw8250_acpi_match[] = { { "INT33C4", 0 }, { "INT33C5", 0 }, { "INT3434", 0 }, { "INT3435", 0 }, { "80860F0A", 0 }, { }, }; MODULE_DEVICE_TABLE(acpi, dw8250_acpi_match); static struct platform_driver dw8250_platform_driver = { .driver = { .name = "dw-apb-uart", .owner = THIS_MODULE, .pm = &dw8250_pm_ops, .of_match_table = dw8250_of_match, .acpi_match_table = ACPI_PTR(dw8250_acpi_match), }, .probe = dw8250_probe, .remove = dw8250_remove, }; module_platform_driver(dw8250_platform_driver); MODULE_AUTHOR("Jamie Iles"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synopsys DesignWare 8250 serial port driver");
fredericgermain/linux-sunxi
drivers/tty/serial/8250/8250_dw.c
C
gpl-2.0
12,111
/***************************************************************************** * m3u.c : M3U playlist format import ***************************************************************************** * Copyright (C) 2004 VLC authors and VideoLAN * $Id: 02a95984d5fe1968163cb435268a9874f0c65eb9 $ * * Authors: Clément Stenac <zorglub@videolan.org> * Sigmund Augdal Helberg <dnumgis@videolan.org> * * 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.1 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_demux.h> #include <vlc_charset.h> #include "playlist.h" struct demux_sys_t { char *psz_prefix; char *(*pf_dup) (const char *); }; /***************************************************************************** * Local prototypes *****************************************************************************/ static int Demux( demux_t *p_demux); static void parseEXTINF( char *psz_string, char **ppsz_artist, char **ppsz_name, int *pi_duration ); static bool ContainsURL( demux_t *p_demux ); static char *GuessEncoding (const char *str) { return IsUTF8 (str) ? strdup (str) : FromLatin1 (str); } static char *CheckUnicode (const char *str) { return IsUTF8 (str) ? strdup (str): NULL; } /***************************************************************************** * Import_M3U: main import function *****************************************************************************/ int Import_M3U( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; const uint8_t *p_peek; char *(*pf_dup) (const char *) = GuessEncoding; int offset = 0; if( stream_Peek( p_demux->s, &p_peek, 3 ) == 3 && !memcmp( p_peek, "\xef\xbb\xbf", 3) ) { pf_dup = CheckUnicode; /* UTF-8 Byte Order Mark */ offset = 3; } if( demux_IsPathExtension( p_demux, ".m3u8" ) || demux_IsForced( p_demux, "m3u8" ) || CheckContentType( p_demux->s, "application/vnd.apple.mpegurl" ) ) pf_dup = CheckUnicode; /* UTF-8 file type */ else if( demux_IsPathExtension( p_demux, ".m3u" ) || demux_IsPathExtension( p_demux, ".vlc" ) || demux_IsForced( p_demux, "m3u" ) || ContainsURL( p_demux ) || CheckContentType( p_demux->s, "audio/x-mpegurl") ) ; /* Guess encoding */ else { if( stream_Peek( p_demux->s, &p_peek, 8 + offset ) < (8 + offset) ) return VLC_EGENERIC; p_peek += offset; if( !strncasecmp( (const char *)p_peek, "RTSPtext", 8 ) ) /* QuickTime */ pf_dup = CheckUnicode; /* UTF-8 */ else if( !memcmp( p_peek, "#EXTM3U", 7 ) ) ; /* Guess encoding */ else return VLC_EGENERIC; } stream_Seek( p_demux->s, offset ); STANDARD_DEMUX_INIT_MSG( "found valid M3U playlist" ); p_demux->p_sys->psz_prefix = FindPrefix( p_demux ); p_demux->p_sys->pf_dup = pf_dup; return VLC_SUCCESS; } static bool ContainsURL( demux_t *p_demux ) { const uint8_t *p_peek, *p_peek_end; int i_peek; i_peek = stream_Peek( p_demux->s, &p_peek, 1024 ); if( i_peek <= 0 ) return false; p_peek_end = p_peek + i_peek; while( p_peek + sizeof( "https://" ) < p_peek_end ) { /* One line starting with a URL is enough */ if( !strncasecmp( (const char *)p_peek, "http://", 7 ) || !strncasecmp( (const char *)p_peek, "mms://", 6 ) || !strncasecmp( (const char *)p_peek, "rtsp://", 7 ) || !strncasecmp( (const char *)p_peek, "https://", 8 ) || !strncasecmp( (const char *)p_peek, "ftp://", 6 ) || !strncasecmp( (const char *)p_peek, "ftps://", 7 ) || !strncasecmp( (const char *)p_peek, "ftpes://", 8 ) ) { return true; } /* Comments and blank lines are ignored */ else if( *p_peek != '#' && *p_peek != '\n' && *p_peek != '\r') { return false; } while( p_peek < p_peek_end && *p_peek != '\n' ) p_peek++; if ( *p_peek == '\n' ) p_peek++; } return false; } /***************************************************************************** * Deactivate: frees unused data *****************************************************************************/ void Close_M3U( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; free( p_demux->p_sys->psz_prefix ); free( p_demux->p_sys ); } static int Demux( demux_t *p_demux ) { char *psz_line; char *psz_name = NULL; char *psz_artist = NULL; char *psz_album_art = NULL; int i_parsed_duration = 0; mtime_t i_duration = -1; const char**ppsz_options = NULL; char * (*pf_dup) (const char *) = p_demux->p_sys->pf_dup; int i_options = 0; bool b_cleanup = false; input_item_t *p_input; input_item_t *p_current_input = GetCurrentItem(p_demux); input_item_node_t *p_subitems = input_item_node_Create( p_current_input ); psz_line = stream_ReadLine( p_demux->s ); while( psz_line ) { char *psz_parse = psz_line; /* Skip leading tabs and spaces */ while( *psz_parse == ' ' || *psz_parse == '\t' || *psz_parse == '\n' || *psz_parse == '\r' ) psz_parse++; if( *psz_parse == '#' ) { /* Parse extra info */ /* Skip leading tabs and spaces */ while( *psz_parse == ' ' || *psz_parse == '\t' || *psz_parse == '\n' || *psz_parse == '\r' || *psz_parse == '#' ) psz_parse++; if( !*psz_parse ) goto error; if( !strncasecmp( psz_parse, "EXTINF:", sizeof("EXTINF:") -1 ) ) { /* Extended info */ psz_parse += sizeof("EXTINF:") - 1; FREENULL( psz_name ); FREENULL( psz_artist ); parseEXTINF( psz_parse, &psz_artist, &psz_name, &i_parsed_duration ); if( i_parsed_duration >= 0 ) i_duration = i_parsed_duration * INT64_C(1000000); if( psz_name ) psz_name = pf_dup( psz_name ); if( psz_artist ) psz_artist = pf_dup( psz_artist ); } else if( !strncasecmp( psz_parse, "EXTVLCOPT:", sizeof("EXTVLCOPT:") -1 ) ) { /* VLC Option */ char *psz_option; psz_parse += sizeof("EXTVLCOPT:") -1; if( !*psz_parse ) goto error; psz_option = pf_dup( psz_parse ); if( psz_option ) INSERT_ELEM( (const char **), ppsz_options, i_options, i_options, // sunqueen modify psz_option ); } /* Special case for jamendo which provide the albumart */ else if( !strncasecmp( psz_parse, "EXTALBUMARTURL:", sizeof( "EXTALBUMARTURL:" ) -1 ) ) { psz_parse += sizeof( "EXTALBUMARTURL:" ) - 1; free( psz_album_art ); psz_album_art = pf_dup( psz_parse ); } } else if( !strncasecmp( psz_parse, "RTSPtext", sizeof("RTSPtext") -1 ) ) { ;/* special case to handle QuickTime RTSPtext redirect files */ } else if( *psz_parse ) { char *psz_mrl; psz_parse = pf_dup( psz_parse ); if( !psz_name && psz_parse ) /* Use filename as name for relative entries */ psz_name = strdup( psz_parse ); psz_mrl = ProcessMRL( psz_parse, p_demux->p_sys->psz_prefix ); b_cleanup = true; if( !psz_mrl ) { free( psz_parse ); goto error; } p_input = input_item_NewExt( psz_mrl, psz_name, i_options, ppsz_options, 0, i_duration ); free( psz_parse ); free( psz_mrl ); if ( !EMPTY_STR(psz_artist) ) input_item_SetArtist( p_input, psz_artist ); if( psz_name ) input_item_SetTitle( p_input, psz_name ); if( !EMPTY_STR(psz_album_art) ) input_item_SetArtURL( p_input, psz_album_art ); input_item_node_AppendItem( p_subitems, p_input ); vlc_gc_decref( p_input ); } error: /* Fetch another line */ free( psz_line ); psz_line = stream_ReadLine( p_demux->s ); if( !psz_line ) b_cleanup = true; if( b_cleanup ) { /* Cleanup state */ while( i_options-- ) free( (char*)ppsz_options[i_options] ); FREENULL( ppsz_options ); i_options = 0; FREENULL( psz_name ); FREENULL( psz_artist ); FREENULL( psz_album_art ); i_parsed_duration = 0; i_duration = -1; b_cleanup = false; } } input_item_node_PostAndDelete( p_subitems ); vlc_gc_decref(p_current_input); var_Destroy( p_demux, "m3u-extvlcopt" ); return 0; /* Needed for correct operation of go back */ } static void parseEXTINF(char *psz_string, char **ppsz_artist, char **ppsz_name, int *pi_duration) { char *end = NULL; char *psz_item = NULL; end = psz_string + strlen( psz_string ); /* ignore whitespaces */ for (; psz_string < end && ( *psz_string == '\t' || *psz_string == ' ' ); psz_string++ ); /* duration: read to next comma */ psz_item = psz_string; psz_string = strchr( psz_string, ',' ); if ( psz_string ) { *psz_string = '\0'; *pi_duration = atoi( psz_item ); } else { return; } if ( psz_string < end ) /* continue parsing if possible */ psz_string++; /* analyse the remaining string */ psz_item = strstr( psz_string, " - " ); /* here we have the 0.8.2+ format with artist */ if ( psz_item ) { /* *** "EXTINF:time,artist - name" */ *psz_item = '\0'; *ppsz_artist = psz_string; *ppsz_name = psz_item + 3; /* points directly after ' - ' */ return; } /* reaching this point means: 0.8.1- with artist or something without artist */ if ( *psz_string == ',' ) { /* *** "EXTINF:time,,name" */ psz_string++; *ppsz_name = psz_string; return; } psz_item = psz_string; psz_string = strchr( psz_string, ',' ); if ( psz_string ) { /* *** "EXTINF:time,artist,name" */ *psz_string = '\0'; *ppsz_artist = psz_item; *ppsz_name = psz_string+1; } else { /* *** "EXTINF:time,name" */ *ppsz_name = psz_item; } return; }
sunqueen/vlc-2.2.0-rc2.32-2013
modules/demux/playlist/m3u.c
C
gpl-2.0
11,910
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'sub_sat_char2char2.cl' */ source_code = read_buffer("sub_sat_char2char2.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "sub_sat_char2char2", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_char2 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_char2)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_char2){{2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_char2 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_char2)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_char2){{2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_char2 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_char2)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_char2)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_char2), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_char2)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
xianggong/m2c_unit_test
test/integer/sub_sat_char2char2/sub_sat_char2char2_src.c
C
gpl-2.0
10,934
/* * arch/i386/mm/ioremap.c * * Re-map IO memory to kernel address space so that we can access it. * This is needed for high PCI addresses that aren't mapped in the * 640k-1MB IO memory area on PC's * * (C) Copyright 1995 1996 Linus Torvalds */ #include <linux/vmalloc.h> #include <asm/io.h> #include <asm/pgalloc.h> static inline void remap_area_pte(pte_t * pte, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; address &= ~PMD_MASK; end = address + size; if (end > PMD_SIZE) end = PMD_SIZE; if (address >= end) BUG(); do { if (!pte_none(*pte)) { printk("remap_area_pte: page already exists\n"); BUG(); } set_pte(pte, mk_pte_phys(phys_addr, __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY | _PAGE_ACCESSED | flags))); address += PAGE_SIZE; phys_addr += PAGE_SIZE; pte++; } while (address && (address < end)); } static inline int remap_area_pmd(pmd_t * pmd, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; address &= ~PGDIR_MASK; end = address + size; if (end > PGDIR_SIZE) end = PGDIR_SIZE; phys_addr -= address; if (address >= end) BUG(); do { pte_t * pte = pte_alloc_kernel(&init_mm, pmd, address); if (!pte) return -ENOMEM; remap_area_pte(pte, address, end - address, address + phys_addr, flags); address = (address + PMD_SIZE) & PMD_MASK; pmd++; } while (address && (address < end)); return 0; } static int remap_area_pages(unsigned long address, unsigned long phys_addr, unsigned long size, unsigned long flags) { int error; pgd_t * dir; unsigned long end = address + size; phys_addr -= address; dir = pgd_offset(&init_mm, address); flush_cache_all(); if (address >= end) BUG(); spin_lock(&init_mm.page_table_lock); do { pmd_t *pmd; pmd = pmd_alloc(&init_mm, dir, address); error = -ENOMEM; if (!pmd) break; if (remap_area_pmd(pmd, address, end - address, phys_addr + address, flags)) break; error = 0; address = (address + PGDIR_SIZE) & PGDIR_MASK; dir++; } while (address && (address < end)); spin_unlock(&init_mm.page_table_lock); flush_tlb_all(); return error; } /* * Generic mapping function (not visible outside): */ /* * Remap an arbitrary physical address space into the kernel virtual * address space. Needed when the kernel wants to access high addresses * directly. * * NOTE! We need to allow non-page-aligned mappings too: we will obviously * have to convert them into an offset in a page-aligned mapping, but the * caller shouldn't need to know that small detail. */ void * __ioremap(unsigned long phys_addr, unsigned long size, unsigned long flags) { void * addr; struct vm_struct * area; unsigned long offset, last_addr; /* Don't allow wraparound or zero size */ last_addr = phys_addr + size - 1; if (!size || last_addr < phys_addr) return NULL; /* * Don't remap the low PCI/ISA area, it's always mapped.. */ if (phys_addr >= 0xA0000 && last_addr < 0x100000) return phys_to_virt(phys_addr); /* * Don't allow anybody to remap normal RAM that we're using.. */ if (phys_addr < virt_to_phys(high_memory)) { char *t_addr, *t_end; struct page *page; t_addr = __va(phys_addr); t_end = t_addr + (size - 1); for(page = virt_to_page(t_addr); page <= virt_to_page(t_end); page++) if(!PageReserved(page)) return NULL; } /* * Mappings have to be page-aligned */ offset = phys_addr & ~PAGE_MASK; phys_addr &= PAGE_MASK; size = PAGE_ALIGN(last_addr) - phys_addr; /* * Ok, go for it.. */ area = get_vm_area(size, VM_IOREMAP); if (!area) return NULL; addr = area->addr; if (remap_area_pages(VMALLOC_VMADDR(addr), phys_addr, size, flags)) { vfree(addr); return NULL; } return (void *) (offset + (char *)addr); } void iounmap(void *addr) { if (addr > high_memory) return vfree((void *) (PAGE_MASK & (unsigned long) addr)); } void __init *bt_ioremap(unsigned long phys_addr, unsigned long size) { unsigned long offset, last_addr; unsigned int nrpages; enum fixed_addresses idx; /* Don't allow wraparound or zero size */ last_addr = phys_addr + size - 1; if (!size || last_addr < phys_addr) return NULL; /* * Don't remap the low PCI/ISA area, it's always mapped.. */ if (phys_addr >= 0xA0000 && last_addr < 0x100000) return phys_to_virt(phys_addr); /* * Mappings have to be page-aligned */ offset = phys_addr & ~PAGE_MASK; phys_addr &= PAGE_MASK; size = PAGE_ALIGN(last_addr) - phys_addr; /* * Mappings have to fit in the FIX_BTMAP area. */ nrpages = size >> PAGE_SHIFT; if (nrpages > NR_FIX_BTMAPS) return NULL; /* * Ok, go for it.. */ idx = FIX_BTMAP_BEGIN; while (nrpages > 0) { set_fixmap(idx, phys_addr); phys_addr += PAGE_SIZE; --idx; --nrpages; } return (void*) (offset + fix_to_virt(FIX_BTMAP_BEGIN)); } void __init bt_iounmap(void *addr, unsigned long size) { unsigned long virt_addr; unsigned long offset; unsigned int nrpages; enum fixed_addresses idx; virt_addr = (unsigned long)addr; if (virt_addr < fix_to_virt(FIX_BTMAP_BEGIN)) return; offset = virt_addr & ~PAGE_MASK; nrpages = PAGE_ALIGN(offset + size - 1) >> PAGE_SHIFT; idx = FIX_BTMAP_BEGIN; while (nrpages > 0) { __set_fixmap(idx, 0, __pgprot(0)); --idx; --nrpages; } }
dduval/kernel-rhel3
arch/i386/mm/ioremap.c
C
gpl-2.0
5,360
/* * linux/kernel/fork.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * 'fork.c' contains the help-routines for the 'fork' system call * (see also entry.S and others). * Fork is rather simple, once you get the hang of it, but the memory * management can be a bitch. See 'mm/memory.c': 'copy_page_range()' */ #include <linux/slab.h> #include <linux/init.h> #include <linux/unistd.h> #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/completion.h> #include <linux/mnt_namespace.h> #include <linux/personality.h> #include <linux/mempolicy.h> #include <linux/sem.h> #include <linux/file.h> #include <linux/key.h> #include <linux/binfmts.h> #include <linux/mman.h> #include <linux/fs.h> #include <linux/nsproxy.h> #include <linux/capability.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/security.h> #include <linux/swap.h> #include <linux/syscalls.h> #include <linux/jiffies.h> #include <linux/futex.h> #include <linux/task_io_accounting_ops.h> #include <linux/rcupdate.h> #include <linux/ptrace.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/profile.h> #include <linux/rmap.h> #include <linux/acct.h> #include <linux/tsacct_kern.h> #include <linux/cn_proc.h> #include <linux/freezer.h> #include <linux/delayacct.h> #include <linux/taskstats_kern.h> #include <linux/random.h> #include <asm/pgtable.h> #include <asm/pgalloc.h> #include <asm/uaccess.h> #include <asm/mmu_context.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> /* * Protected counters by write_lock_irq(&tasklist_lock) */ unsigned long total_forks; /* Handle normal Linux uptimes. */ int nr_threads; /* The idle threads do not count.. */ int max_threads; /* tunable limit on nr_threads */ DEFINE_PER_CPU(unsigned long, process_counts) = 0; __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */ int nr_processes(void) { int cpu; int total = 0; for_each_online_cpu(cpu) total += per_cpu(process_counts, cpu); return total; } #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR # define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL) # define free_task_struct(tsk) kmem_cache_free(task_struct_cachep, (tsk)) static struct kmem_cache *task_struct_cachep; #endif /* SLAB cache for signal_struct structures (tsk->signal) */ static struct kmem_cache *signal_cachep; /* SLAB cache for sighand_struct structures (tsk->sighand) */ struct kmem_cache *sighand_cachep; /* SLAB cache for files_struct structures (tsk->files) */ struct kmem_cache *files_cachep; /* SLAB cache for fs_struct structures (tsk->fs) */ struct kmem_cache *fs_cachep; /* SLAB cache for vm_area_struct structures */ struct kmem_cache *vm_area_cachep; /* SLAB cache for mm_struct structures (tsk->mm) */ static struct kmem_cache *mm_cachep; void free_task(struct task_struct *tsk) { free_thread_info(tsk->stack); rt_mutex_debug_task_free(tsk); free_task_struct(tsk); } EXPORT_SYMBOL(free_task); void __put_task_struct(struct task_struct *tsk) { WARN_ON(!(tsk->exit_state & (EXIT_DEAD | EXIT_ZOMBIE))); WARN_ON(atomic_read(&tsk->usage)); WARN_ON(tsk == current); security_task_free(tsk); free_uid(tsk->user); put_group_info(tsk->group_info); delayacct_tsk_free(tsk); if (!profile_handoff_task(tsk)) free_task(tsk); } void __init fork_init(unsigned long mempages) { #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR #ifndef ARCH_MIN_TASKALIGN #define ARCH_MIN_TASKALIGN L1_CACHE_BYTES #endif /* create a slab on which task_structs can be allocated */ task_struct_cachep = kmem_cache_create("task_struct", sizeof(struct task_struct), ARCH_MIN_TASKALIGN, SLAB_PANIC, NULL, NULL); #endif /* * The default maximum number of threads is set to a safe * value: the thread structures can take up at most half * of memory. */ max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE); /* * we need to allow at least 20 threads to boot a system */ if(max_threads < 20) max_threads = 20; init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2; init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2; init_task.signal->rlim[RLIMIT_SIGPENDING] = init_task.signal->rlim[RLIMIT_NPROC]; } static struct task_struct *dup_task_struct(struct task_struct *orig) { struct task_struct *tsk; struct thread_info *ti; prepare_to_copy(orig); tsk = alloc_task_struct(); if (!tsk) return NULL; ti = alloc_thread_info(tsk); if (!ti) { free_task_struct(tsk); return NULL; } *tsk = *orig; tsk->stack = ti; setup_thread_stack(tsk, orig); #ifdef CONFIG_CC_STACKPROTECTOR tsk->stack_canary = get_random_int(); #endif /* One for us, one for whoever does the "release_task()" (usually parent) */ atomic_set(&tsk->usage,2); atomic_set(&tsk->fs_excl, 0); #ifdef CONFIG_BLK_DEV_IO_TRACE tsk->btrace_seq = 0; #endif tsk->splice_pipe = NULL; return tsk; } #ifdef CONFIG_MMU static inline int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm) { struct vm_area_struct *mpnt, *tmp, **pprev; struct rb_node **rb_link, *rb_parent; int retval; unsigned long charge; struct mempolicy *pol; down_write(&oldmm->mmap_sem); flush_cache_dup_mm(oldmm); /* * Not linked in yet - no deadlock potential: */ down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING); mm->locked_vm = 0; mm->mmap = NULL; mm->mmap_cache = NULL; mm->free_area_cache = oldmm->mmap_base; mm->cached_hole_size = ~0UL; mm->map_count = 0; cpus_clear(mm->cpu_vm_mask); mm->mm_rb = RB_ROOT; rb_link = &mm->mm_rb.rb_node; rb_parent = NULL; pprev = &mm->mmap; for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) { struct file *file; if (mpnt->vm_flags & VM_DONTCOPY) { long pages = vma_pages(mpnt); mm->total_vm -= pages; vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file, -pages); continue; } charge = 0; if (mpnt->vm_flags & VM_ACCOUNT) { unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT; if (security_vm_enough_memory(len)) goto fail_nomem; charge = len; } tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL); if (!tmp) goto fail_nomem; *tmp = *mpnt; pol = mpol_copy(vma_policy(mpnt)); retval = PTR_ERR(pol); if (IS_ERR(pol)) goto fail_nomem_policy; vma_set_policy(tmp, pol); tmp->vm_flags &= ~VM_LOCKED; tmp->vm_mm = mm; tmp->vm_next = NULL; anon_vma_link(tmp); file = tmp->vm_file; if (file) { struct inode *inode = file->f_path.dentry->d_inode; get_file(file); if (tmp->vm_flags & VM_DENYWRITE) atomic_dec(&inode->i_writecount); /* insert tmp into the share list, just after mpnt */ spin_lock(&file->f_mapping->i_mmap_lock); tmp->vm_truncate_count = mpnt->vm_truncate_count; flush_dcache_mmap_lock(file->f_mapping); vma_prio_tree_add(tmp, mpnt); flush_dcache_mmap_unlock(file->f_mapping); spin_unlock(&file->f_mapping->i_mmap_lock); } /* * Link in the new vma and copy the page table entries. */ *pprev = tmp; pprev = &tmp->vm_next; __vma_link_rb(mm, tmp, rb_link, rb_parent); rb_link = &tmp->vm_rb.rb_right; rb_parent = &tmp->vm_rb; mm->map_count++; retval = copy_page_range(mm, oldmm, mpnt); if (tmp->vm_ops && tmp->vm_ops->open) tmp->vm_ops->open(tmp); if (retval) goto out; } /* a new mm has just been created */ arch_dup_mmap(oldmm, mm); retval = 0; out: up_write(&mm->mmap_sem); flush_tlb_mm(oldmm); up_write(&oldmm->mmap_sem); return retval; fail_nomem_policy: kmem_cache_free(vm_area_cachep, tmp); fail_nomem: retval = -ENOMEM; vm_unacct_memory(charge); goto out; } static inline int mm_alloc_pgd(struct mm_struct * mm) { mm->pgd = pgd_alloc(mm); if (unlikely(!mm->pgd)) return -ENOMEM; return 0; } static inline void mm_free_pgd(struct mm_struct * mm) { pgd_free(mm->pgd); } #else #define dup_mmap(mm, oldmm) (0) #define mm_alloc_pgd(mm) (0) #define mm_free_pgd(mm) #endif /* CONFIG_MMU */ __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock); #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL)) #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm))) #include <linux/init_task.h> static struct mm_struct * mm_init(struct mm_struct * mm) { atomic_set(&mm->mm_users, 1); atomic_set(&mm->mm_count, 1); init_rwsem(&mm->mmap_sem); INIT_LIST_HEAD(&mm->mmlist); mm->core_waiters = 0; mm->nr_ptes = 0; set_mm_counter(mm, file_rss, 0); set_mm_counter(mm, anon_rss, 0); spin_lock_init(&mm->page_table_lock); rwlock_init(&mm->ioctx_list_lock); mm->ioctx_list = NULL; mm->free_area_cache = TASK_UNMAPPED_BASE; mm->cached_hole_size = ~0UL; if (likely(!mm_alloc_pgd(mm))) { mm->def_flags = 0; return mm; } free_mm(mm); return NULL; } /* * Allocate and initialize an mm_struct. */ struct mm_struct * mm_alloc(void) { struct mm_struct * mm; mm = allocate_mm(); if (mm) { memset(mm, 0, sizeof(*mm)); mm = mm_init(mm); } return mm; } /* * Called when the last reference to the mm * is dropped: either by a lazy thread or by * mmput. Free the page directory and the mm. */ void fastcall __mmdrop(struct mm_struct *mm) { BUG_ON(mm == &init_mm); mm_free_pgd(mm); destroy_context(mm); free_mm(mm); } /* * Decrement the use count and release all resources for an mm. */ void mmput(struct mm_struct *mm) { might_sleep(); if (atomic_dec_and_test(&mm->mm_users)) { exit_aio(mm); exit_mmap(mm); if (!list_empty(&mm->mmlist)) { spin_lock(&mmlist_lock); list_del(&mm->mmlist); spin_unlock(&mmlist_lock); } put_swap_token(mm); mmdrop(mm); } } EXPORT_SYMBOL_GPL(mmput); /** * get_task_mm - acquire a reference to the task's mm * * Returns %NULL if the task has no mm. Checks PF_BORROWED_MM (meaning * this kernel workthread has transiently adopted a user mm with use_mm, * to do its AIO) is not set and if so returns a reference to it, after * bumping up the use count. User must release the mm via mmput() * after use. Typically used by /proc and ptrace. */ struct mm_struct *get_task_mm(struct task_struct *task) { struct mm_struct *mm; task_lock(task); mm = task->mm; if (mm) { if (task->flags & PF_BORROWED_MM) mm = NULL; else atomic_inc(&mm->mm_users); } task_unlock(task); return mm; } EXPORT_SYMBOL_GPL(get_task_mm); /* Please note the differences between mmput and mm_release. * mmput is called whenever we stop holding onto a mm_struct, * error success whatever. * * mm_release is called after a mm_struct has been removed * from the current process. * * This difference is important for error handling, when we * only half set up a mm_struct for a new process and need to restore * the old one. Because we mmput the new mm_struct before * restoring the old one. . . * Eric Biederman 10 January 1998 */ void mm_release(struct task_struct *tsk, struct mm_struct *mm) { struct completion *vfork_done = tsk->vfork_done; /* Get rid of any cached register state */ deactivate_mm(tsk, mm); /* notify parent sleeping on vfork() */ if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } /* * If we're exiting normally, clear a user-space tid field if * requested. We leave this alone when dying by signal, to leave * the value intact in a core dump, and to save the unnecessary * trouble otherwise. Userland only wants this done for a sys_exit. */ if (tsk->clear_child_tid && !(tsk->flags & PF_SIGNALED) && atomic_read(&mm->mm_users) > 1) { u32 __user * tidptr = tsk->clear_child_tid; tsk->clear_child_tid = NULL; /* * We don't check the error code - if userspace has * not set up a proper pointer then tough luck. */ put_user(0, tidptr); sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); } } /* * Allocate a new mm structure and copy contents from the * mm structure of the passed in task structure. */ static struct mm_struct *dup_mm(struct task_struct *tsk) { struct mm_struct *mm, *oldmm = current->mm; int err; if (!oldmm) return NULL; mm = allocate_mm(); if (!mm) goto fail_nomem; memcpy(mm, oldmm, sizeof(*mm)); /* Initializing for Swap token stuff */ mm->token_priority = 0; mm->last_interval = 0; if (!mm_init(mm)) goto fail_nomem; if (init_new_context(tsk, mm)) goto fail_nocontext; err = dup_mmap(mm, oldmm); if (err) goto free_pt; mm->hiwater_rss = get_mm_rss(mm); mm->hiwater_vm = mm->total_vm; return mm; free_pt: mmput(mm); fail_nomem: return NULL; fail_nocontext: /* * If init_new_context() failed, we cannot use mmput() to free the mm * because it calls destroy_context() */ mm_free_pgd(mm); free_mm(mm); return NULL; } static int copy_mm(unsigned long clone_flags, struct task_struct * tsk) { struct mm_struct * mm, *oldmm; int retval; tsk->min_flt = tsk->maj_flt = 0; tsk->nvcsw = tsk->nivcsw = 0; tsk->mm = NULL; tsk->active_mm = NULL; /* * Are we cloning a kernel thread? * * We need to steal a active VM for that.. */ oldmm = current->mm; if (!oldmm) return 0; if (clone_flags & CLONE_VM) { atomic_inc(&oldmm->mm_users); mm = oldmm; goto good_mm; } retval = -ENOMEM; mm = dup_mm(tsk); if (!mm) goto fail_nomem; good_mm: /* Initializing for Swap token stuff */ mm->token_priority = 0; mm->last_interval = 0; tsk->mm = mm; tsk->active_mm = mm; return 0; fail_nomem: return retval; } static inline struct fs_struct *__copy_fs_struct(struct fs_struct *old) { struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL); /* We don't need to lock fs - think why ;-) */ if (fs) { atomic_set(&fs->count, 1); rwlock_init(&fs->lock); fs->umask = old->umask; read_lock(&old->lock); fs->rootmnt = mntget(old->rootmnt); fs->root = dget(old->root); fs->pwdmnt = mntget(old->pwdmnt); fs->pwd = dget(old->pwd); if (old->altroot) { fs->altrootmnt = mntget(old->altrootmnt); fs->altroot = dget(old->altroot); } else { fs->altrootmnt = NULL; fs->altroot = NULL; } read_unlock(&old->lock); } return fs; } struct fs_struct *copy_fs_struct(struct fs_struct *old) { return __copy_fs_struct(old); } EXPORT_SYMBOL_GPL(copy_fs_struct); static inline int copy_fs(unsigned long clone_flags, struct task_struct * tsk) { if (clone_flags & CLONE_FS) { atomic_inc(&current->fs->count); return 0; } tsk->fs = __copy_fs_struct(current->fs); if (!tsk->fs) return -ENOMEM; return 0; } static int count_open_files(struct fdtable *fdt) { int size = fdt->max_fds; int i; /* Find the last open fd */ for (i = size/(8*sizeof(long)); i > 0; ) { if (fdt->open_fds->fds_bits[--i]) break; } i = (i+1) * 8 * sizeof(long); return i; } static struct files_struct *alloc_files(void) { struct files_struct *newf; struct fdtable *fdt; newf = kmem_cache_alloc(files_cachep, GFP_KERNEL); if (!newf) goto out; atomic_set(&newf->count, 1); spin_lock_init(&newf->file_lock); newf->next_fd = 0; fdt = &newf->fdtab; fdt->max_fds = NR_OPEN_DEFAULT; fdt->close_on_exec = (fd_set *)&newf->close_on_exec_init; fdt->open_fds = (fd_set *)&newf->open_fds_init; fdt->fd = &newf->fd_array[0]; INIT_RCU_HEAD(&fdt->rcu); fdt->next = NULL; rcu_assign_pointer(newf->fdt, fdt); out: return newf; } /* * Allocate a new files structure and copy contents from the * passed in files structure. * errorp will be valid only when the returned files_struct is NULL. */ static struct files_struct *dup_fd(struct files_struct *oldf, int *errorp) { struct files_struct *newf; struct file **old_fds, **new_fds; int open_files, size, i; struct fdtable *old_fdt, *new_fdt; *errorp = -ENOMEM; newf = alloc_files(); if (!newf) goto out; spin_lock(&oldf->file_lock); old_fdt = files_fdtable(oldf); new_fdt = files_fdtable(newf); open_files = count_open_files(old_fdt); /* * Check whether we need to allocate a larger fd array and fd set. * Note: we're not a clone task, so the open count won't change. */ if (open_files > new_fdt->max_fds) { new_fdt->max_fds = 0; spin_unlock(&oldf->file_lock); spin_lock(&newf->file_lock); *errorp = expand_files(newf, open_files-1); spin_unlock(&newf->file_lock); if (*errorp < 0) goto out_release; new_fdt = files_fdtable(newf); /* * Reacquire the oldf lock and a pointer to its fd table * who knows it may have a new bigger fd table. We need * the latest pointer. */ spin_lock(&oldf->file_lock); old_fdt = files_fdtable(oldf); } old_fds = old_fdt->fd; new_fds = new_fdt->fd; memcpy(new_fdt->open_fds->fds_bits, old_fdt->open_fds->fds_bits, open_files/8); memcpy(new_fdt->close_on_exec->fds_bits, old_fdt->close_on_exec->fds_bits, open_files/8); for (i = open_files; i != 0; i--) { struct file *f = *old_fds++; if (f) { get_file(f); } else { /* * The fd may be claimed in the fd bitmap but not yet * instantiated in the files array if a sibling thread * is partway through open(). So make sure that this * fd is available to the new process. */ FD_CLR(open_files - i, new_fdt->open_fds); } rcu_assign_pointer(*new_fds++, f); } spin_unlock(&oldf->file_lock); /* compute the remainder to be cleared */ size = (new_fdt->max_fds - open_files) * sizeof(struct file *); /* This is long word aligned thus could use a optimized version */ memset(new_fds, 0, size); if (new_fdt->max_fds > open_files) { int left = (new_fdt->max_fds-open_files)/8; int start = open_files / (8 * sizeof(unsigned long)); memset(&new_fdt->open_fds->fds_bits[start], 0, left); memset(&new_fdt->close_on_exec->fds_bits[start], 0, left); } return newf; out_release: kmem_cache_free(files_cachep, newf); out: return NULL; } static int copy_files(unsigned long clone_flags, struct task_struct * tsk) { struct files_struct *oldf, *newf; int error = 0; /* * A background process may not have any files ... */ oldf = current->files; if (!oldf) goto out; if (clone_flags & CLONE_FILES) { atomic_inc(&oldf->count); goto out; } /* * Note: we may be using current for both targets (See exec.c) * This works because we cache current->files (old) as oldf. Don't * break this. */ tsk->files = NULL; newf = dup_fd(oldf, &error); if (!newf) goto out; tsk->files = newf; error = 0; out: return error; } /* * Helper to unshare the files of the current task. * We don't want to expose copy_files internals to * the exec layer of the kernel. */ int unshare_files(void) { struct files_struct *files = current->files; int rc; BUG_ON(!files); /* This can race but the race causes us to copy when we don't need to and drop the copy */ if(atomic_read(&files->count) == 1) { atomic_inc(&files->count); return 0; } rc = copy_files(0, current); if(rc) current->files = files; return rc; } EXPORT_SYMBOL(unshare_files); static inline int copy_sighand(unsigned long clone_flags, struct task_struct * tsk) { struct sighand_struct *sig; if (clone_flags & (CLONE_SIGHAND | CLONE_THREAD)) { atomic_inc(&current->sighand->count); return 0; } sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); rcu_assign_pointer(tsk->sighand, sig); if (!sig) return -ENOMEM; atomic_set(&sig->count, 1); memcpy(sig->action, current->sighand->action, sizeof(sig->action)); return 0; } void __cleanup_sighand(struct sighand_struct *sighand) { if (atomic_dec_and_test(&sighand->count)) kmem_cache_free(sighand_cachep, sighand); } static inline int copy_signal(unsigned long clone_flags, struct task_struct * tsk) { struct signal_struct *sig; int ret; if (clone_flags & CLONE_THREAD) { atomic_inc(&current->signal->count); atomic_inc(&current->signal->live); return 0; } sig = kmem_cache_alloc(signal_cachep, GFP_KERNEL); tsk->signal = sig; if (!sig) return -ENOMEM; ret = copy_thread_group_keys(tsk); if (ret < 0) { kmem_cache_free(signal_cachep, sig); return ret; } atomic_set(&sig->count, 1); atomic_set(&sig->live, 1); init_waitqueue_head(&sig->wait_chldexit); sig->flags = 0; sig->group_exit_code = 0; sig->group_exit_task = NULL; sig->group_stop_count = 0; sig->curr_target = NULL; init_sigpending(&sig->shared_pending); INIT_LIST_HEAD(&sig->posix_timers); hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); sig->it_real_incr.tv64 = 0; sig->real_timer.function = it_real_fn; sig->tsk = tsk; sig->it_virt_expires = cputime_zero; sig->it_virt_incr = cputime_zero; sig->it_prof_expires = cputime_zero; sig->it_prof_incr = cputime_zero; sig->leader = 0; /* session leadership doesn't inherit */ sig->tty_old_pgrp = NULL; sig->utime = sig->stime = sig->cutime = sig->cstime = cputime_zero; sig->nvcsw = sig->nivcsw = sig->cnvcsw = sig->cnivcsw = 0; sig->min_flt = sig->maj_flt = sig->cmin_flt = sig->cmaj_flt = 0; sig->inblock = sig->oublock = sig->cinblock = sig->coublock = 0; sig->sched_time = 0; INIT_LIST_HEAD(&sig->cpu_timers[0]); INIT_LIST_HEAD(&sig->cpu_timers[1]); INIT_LIST_HEAD(&sig->cpu_timers[2]); taskstats_tgid_init(sig); task_lock(current->group_leader); memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim); task_unlock(current->group_leader); if (sig->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) { /* * New sole thread in the process gets an expiry time * of the whole CPU time limit. */ tsk->it_prof_expires = secs_to_cputime(sig->rlim[RLIMIT_CPU].rlim_cur); } acct_init_pacct(&sig->pacct); return 0; } void __cleanup_signal(struct signal_struct *sig) { exit_thread_group_keys(sig); kmem_cache_free(signal_cachep, sig); } static inline void cleanup_signal(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; atomic_dec(&sig->live); if (atomic_dec_and_test(&sig->count)) __cleanup_signal(sig); } static inline void copy_flags(unsigned long clone_flags, struct task_struct *p) { unsigned long new_flags = p->flags; new_flags &= ~(PF_SUPERPRIV | PF_NOFREEZE); new_flags |= PF_FORKNOEXEC; if (!(clone_flags & CLONE_PTRACE)) p->ptrace = 0; p->flags = new_flags; } asmlinkage long sys_set_tid_address(int __user *tidptr) { current->clear_child_tid = tidptr; return current->pid; } static inline void rt_mutex_init_task(struct task_struct *p) { spin_lock_init(&p->pi_lock); #ifdef CONFIG_RT_MUTEXES plist_head_init(&p->pi_waiters, &p->pi_lock); p->pi_blocked_on = NULL; #endif } /* * This creates a new process as a copy of the old one, * but does not actually start it yet. * * It copies the registers, and all the appropriate * parts of the process environment (as per the clone * flags). The actual kick-off is left to the caller. */ static struct task_struct *copy_process(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *parent_tidptr, int __user *child_tidptr, struct pid *pid) { int retval; struct task_struct *p = NULL; if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. */ if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) return ERR_PTR(-EINVAL); /* * Shared signal handlers imply shared VM. By way of the above, * thread groups also imply shared VM. Blocking this case allows * for various simplifications in other code. */ if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) return ERR_PTR(-EINVAL); retval = security_task_create(clone_flags); if (retval) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current); if (!p) goto fork_out; rt_mutex_init_task(p); #ifdef CONFIG_TRACE_IRQFLAGS DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled); DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif retval = -EAGAIN; if (atomic_read(&p->user->processes) >= p->signal->rlim[RLIMIT_NPROC].rlim_cur) { if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) && p->user != &root_user) goto bad_fork_free; } atomic_inc(&p->user->__count); atomic_inc(&p->user->processes); get_group_info(p->group_info); /* * If multiple threads are within copy_process(), then this check * triggers too late. This doesn't hurt, the check is only there * to stop root fork bombs. */ if (nr_threads >= max_threads) goto bad_fork_cleanup_count; if (!try_module_get(task_thread_info(p)->exec_domain->module)) goto bad_fork_cleanup_count; if (p->binfmt && !try_module_get(p->binfmt->module)) goto bad_fork_cleanup_put_domain; p->did_exec = 0; delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ copy_flags(clone_flags, p); p->pid = pid_nr(pid); retval = -EFAULT; if (clone_flags & CLONE_PARENT_SETTID) if (put_user(p->pid, parent_tidptr)) goto bad_fork_cleanup_delays_binfmt; INIT_LIST_HEAD(&p->children); INIT_LIST_HEAD(&p->sibling); p->vfork_done = NULL; spin_lock_init(&p->alloc_lock); clear_tsk_thread_flag(p, TIF_SIGPENDING); init_sigpending(&p->pending); p->utime = cputime_zero; p->stime = cputime_zero; p->sched_time = 0; #ifdef CONFIG_TASK_XACCT p->rchar = 0; /* I/O counter: bytes read */ p->wchar = 0; /* I/O counter: bytes written */ p->syscr = 0; /* I/O counter: read syscalls */ p->syscw = 0; /* I/O counter: write syscalls */ #endif task_io_accounting_init(p); acct_clear_integrals(p); p->it_virt_expires = cputime_zero; p->it_prof_expires = cputime_zero; p->it_sched_expires = 0; INIT_LIST_HEAD(&p->cpu_timers[0]); INIT_LIST_HEAD(&p->cpu_timers[1]); INIT_LIST_HEAD(&p->cpu_timers[2]); p->lock_depth = -1; /* -1 = no lock */ do_posix_clock_monotonic_gettime(&p->start_time); p->security = NULL; p->io_context = NULL; p->io_wait = NULL; p->audit_context = NULL; cpuset_fork(p); #ifdef CONFIG_NUMA p->mempolicy = mpol_copy(p->mempolicy); if (IS_ERR(p->mempolicy)) { retval = PTR_ERR(p->mempolicy); p->mempolicy = NULL; goto bad_fork_cleanup_cpuset; } mpol_fix_fork_child_flag(p); #endif #ifdef CONFIG_TRACE_IRQFLAGS p->irq_events = 0; #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW p->hardirqs_enabled = 1; #else p->hardirqs_enabled = 0; #endif p->hardirq_enable_ip = 0; p->hardirq_enable_event = 0; p->hardirq_disable_ip = _THIS_IP_; p->hardirq_disable_event = 0; p->softirqs_enabled = 1; p->softirq_enable_ip = _THIS_IP_; p->softirq_enable_event = 0; p->softirq_disable_ip = 0; p->softirq_disable_event = 0; p->hardirq_context = 0; p->softirq_context = 0; #endif #ifdef CONFIG_LOCKDEP p->lockdep_depth = 0; /* no locks held yet */ p->curr_chain_key = 0; p->lockdep_recursion = 0; #endif #ifdef CONFIG_DEBUG_MUTEXES p->blocked_on = NULL; /* not blocked yet */ #endif p->tgid = p->pid; if (clone_flags & CLONE_THREAD) p->tgid = current->tgid; if ((retval = security_task_alloc(p))) goto bad_fork_cleanup_policy; if ((retval = audit_alloc(p))) goto bad_fork_cleanup_security; /* copy all the process information */ if ((retval = copy_semundo(clone_flags, p))) goto bad_fork_cleanup_audit; if ((retval = copy_files(clone_flags, p))) goto bad_fork_cleanup_semundo; if ((retval = copy_fs(clone_flags, p))) goto bad_fork_cleanup_files; if ((retval = copy_sighand(clone_flags, p))) goto bad_fork_cleanup_fs; if ((retval = copy_signal(clone_flags, p))) goto bad_fork_cleanup_sighand; if ((retval = copy_mm(clone_flags, p))) goto bad_fork_cleanup_signal; if ((retval = copy_keys(clone_flags, p))) goto bad_fork_cleanup_mm; if ((retval = copy_namespaces(clone_flags, p))) goto bad_fork_cleanup_keys; retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs); if (retval) goto bad_fork_cleanup_namespaces; p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL; /* * Clear TID on mm_release()? */ p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL; p->robust_list = NULL; #ifdef CONFIG_COMPAT p->compat_robust_list = NULL; #endif INIT_LIST_HEAD(&p->pi_state_list); p->pi_state_cache = NULL; /* * sigaltstack should be cleared when sharing the same VM */ if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) p->sas_ss_sp = p->sas_ss_size = 0; /* * Syscall tracing should be turned off in the child regardless * of CLONE_PTRACE. */ clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE); #ifdef TIF_SYSCALL_EMU clear_tsk_thread_flag(p, TIF_SYSCALL_EMU); #endif /* Our parent execution domain becomes current domain These must match for thread signalling to apply */ p->parent_exec_id = p->self_exec_id; /* ok, now we should be set up.. */ p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL); p->pdeath_signal = 0; p->exit_state = 0; /* * Ok, make it visible to the rest of the system. * We dont wake it up yet. */ p->group_leader = p; INIT_LIST_HEAD(&p->thread_group); INIT_LIST_HEAD(&p->ptrace_children); INIT_LIST_HEAD(&p->ptrace_list); /* Perform scheduler related setup. Assign this task to a CPU. */ sched_fork(p, clone_flags); /* Need tasklist lock for parent etc handling! */ write_lock_irq(&tasklist_lock); /* for sys_ioprio_set(IOPRIO_WHO_PGRP) */ p->ioprio = current->ioprio; /* * The task hasn't been attached yet, so its cpus_allowed mask will * not be changed, nor will its assigned CPU. * * The cpus_allowed mask of the parent may have changed after it was * copied first time - so re-copy it here, then check the child's CPU * to ensure it is on a valid CPU (and if not, just force it back to * parent's CPU). This avoids alot of nasty races. */ p->cpus_allowed = current->cpus_allowed; if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) || !cpu_online(task_cpu(p)))) set_task_cpu(p, smp_processor_id()); /* CLONE_PARENT re-uses the old parent */ if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) p->real_parent = current->real_parent; else p->real_parent = current; p->parent = p->real_parent; spin_lock(&current->sighand->siglock); /* * Process group and session signals need to be delivered to just the * parent before the fork or both the parent and the child after the * fork. Restart if a signal comes in before we add the new process to * it's process group. * A fatal signal pending means that current will exit, so the new * thread can't slip out of an OOM kill (or normal SIGKILL). */ recalc_sigpending(); if (signal_pending(current)) { spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); retval = -ERESTARTNOINTR; goto bad_fork_cleanup_namespaces; } if (clone_flags & CLONE_THREAD) { p->group_leader = current->group_leader; list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group); if (!cputime_eq(current->signal->it_virt_expires, cputime_zero) || !cputime_eq(current->signal->it_prof_expires, cputime_zero) || current->signal->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY || !list_empty(&current->signal->cpu_timers[0]) || !list_empty(&current->signal->cpu_timers[1]) || !list_empty(&current->signal->cpu_timers[2])) { /* * Have child wake up on its first tick to check * for process CPU timers. */ p->it_prof_expires = jiffies_to_cputime(1); } } if (likely(p->pid)) { add_parent(p); if (unlikely(p->ptrace & PT_PTRACED)) __ptrace_link(p, current->parent); if (thread_group_leader(p)) { p->signal->tty = current->signal->tty; p->signal->pgrp = process_group(current); set_signal_session(p->signal, process_session(current)); attach_pid(p, PIDTYPE_PGID, task_pgrp(current)); attach_pid(p, PIDTYPE_SID, task_session(current)); list_add_tail_rcu(&p->tasks, &init_task.tasks); __get_cpu_var(process_counts)++; } attach_pid(p, PIDTYPE_PID, pid); nr_threads++; } total_forks++; spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); proc_fork_connector(p); /** Init the wait queue we added */ init_waitqueue_head(&p->join_queue); return p; bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_keys: exit_keys(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: cleanup_signal(p); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* blocking */ bad_fork_cleanup_files: exit_files(p); /* blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_audit: audit_free(p); bad_fork_cleanup_security: security_task_free(p); bad_fork_cleanup_policy: #ifdef CONFIG_NUMA mpol_free(p->mempolicy); bad_fork_cleanup_cpuset: #endif cpuset_exit(p); bad_fork_cleanup_delays_binfmt: delayacct_tsk_free(p); if (p->binfmt) module_put(p->binfmt->module); bad_fork_cleanup_put_domain: module_put(task_thread_info(p)->exec_domain->module); bad_fork_cleanup_count: put_group_info(p->group_info); atomic_dec(&p->user->processes); free_uid(p->user); bad_fork_free: free_task(p); fork_out: return ERR_PTR(retval); } noinline struct pt_regs * __devinit __attribute__((weak)) idle_regs(struct pt_regs *regs) { memset(regs, 0, sizeof(struct pt_regs)); return regs; } struct task_struct * __cpuinit fork_idle(int cpu) { struct task_struct *task; struct pt_regs regs; task = copy_process(CLONE_VM, 0, idle_regs(&regs), 0, NULL, NULL, &init_struct_pid); if (!IS_ERR(task)) init_idle(task, cpu); return task; } static inline int fork_traceflag (unsigned clone_flags) { if (clone_flags & CLONE_UNTRACED) return 0; else if (clone_flags & CLONE_VFORK) { if (current->ptrace & PT_TRACE_VFORK) return PTRACE_EVENT_VFORK; } else if ((clone_flags & CSIGNAL) != SIGCHLD) { if (current->ptrace & PT_TRACE_CLONE) return PTRACE_EVENT_CLONE; } else if (current->ptrace & PT_TRACE_FORK) return PTRACE_EVENT_FORK; return 0; } /* * Ok, this is the main fork-routine. * * It copies the process, and if successful kick-starts * it and waits for it to finish using the VM if required. */ long do_fork(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *parent_tidptr, int __user *child_tidptr) { struct task_struct *p; int trace = 0; struct pid *pid = alloc_pid(); long nr; if (!pid) return -EAGAIN; nr = pid->nr; if (unlikely(current->ptrace)) { trace = fork_traceflag (clone_flags); if (trace) clone_flags |= CLONE_PTRACE; } p = copy_process(clone_flags, stack_start, regs, stack_size, parent_tidptr, child_tidptr, pid); /* * Do this prior waking up the new thread - the thread pointer * might get invalid after that point, if the thread exits quickly. */ if (!IS_ERR(p)) { struct completion vfork; if (clone_flags & CLONE_VFORK) { p->vfork_done = &vfork; init_completion(&vfork); } if ((p->ptrace & PT_PTRACED) || (clone_flags & CLONE_STOPPED)) { /* * We'll start up with an immediate SIGSTOP. */ sigaddset(&p->pending.signal, SIGSTOP); set_tsk_thread_flag(p, TIF_SIGPENDING); } if (!(clone_flags & CLONE_STOPPED)) wake_up_new_task(p, clone_flags); else p->state = TASK_STOPPED; if (unlikely (trace)) { current->ptrace_message = nr; ptrace_notify ((trace << 8) | SIGTRAP); } if (clone_flags & CLONE_VFORK) { freezer_do_not_count(); wait_for_completion(&vfork); freezer_count(); if (unlikely (current->ptrace & PT_TRACE_VFORK_DONE)) { current->ptrace_message = nr; ptrace_notify ((PTRACE_EVENT_VFORK_DONE << 8) | SIGTRAP); } } } else { free_pid(pid); nr = PTR_ERR(p); } return nr; } #ifndef ARCH_MIN_MMSTRUCT_ALIGN #define ARCH_MIN_MMSTRUCT_ALIGN 0 #endif static void sighand_ctor(void *data, struct kmem_cache *cachep, unsigned long flags) { struct sighand_struct *sighand = data; spin_lock_init(&sighand->siglock); INIT_LIST_HEAD(&sighand->signalfd_list); } void __init proc_caches_init(void) { sighand_cachep = kmem_cache_create("sighand_cache", sizeof(struct sighand_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU, sighand_ctor, NULL); signal_cachep = kmem_cache_create("signal_cache", sizeof(struct signal_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); files_cachep = kmem_cache_create("files_cache", sizeof(struct files_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); fs_cachep = kmem_cache_create("fs_cache", sizeof(struct fs_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); vm_area_cachep = kmem_cache_create("vm_area_struct", sizeof(struct vm_area_struct), 0, SLAB_PANIC, NULL, NULL); mm_cachep = kmem_cache_create("mm_struct", sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); } /* * Check constraints on flags passed to the unshare system call and * force unsharing of additional process context as appropriate. */ static inline void check_unshare_flags(unsigned long *flags_ptr) { /* * If unsharing a thread from a thread group, must also * unshare vm. */ if (*flags_ptr & CLONE_THREAD) *flags_ptr |= CLONE_VM; /* * If unsharing vm, must also unshare signal handlers. */ if (*flags_ptr & CLONE_VM) *flags_ptr |= CLONE_SIGHAND; /* * If unsharing signal handlers and the task was created * using CLONE_THREAD, then must unshare the thread */ if ((*flags_ptr & CLONE_SIGHAND) && (atomic_read(&current->signal->count) > 1)) *flags_ptr |= CLONE_THREAD; /* * If unsharing namespace, must also unshare filesystem information. */ if (*flags_ptr & CLONE_NEWNS) *flags_ptr |= CLONE_FS; } /* * Unsharing of tasks created with CLONE_THREAD is not supported yet */ static int unshare_thread(unsigned long unshare_flags) { if (unshare_flags & CLONE_THREAD) return -EINVAL; return 0; } /* * Unshare the filesystem structure if it is being shared */ static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp) { struct fs_struct *fs = current->fs; if ((unshare_flags & CLONE_FS) && (fs && atomic_read(&fs->count) > 1)) { *new_fsp = __copy_fs_struct(current->fs); if (!*new_fsp) return -ENOMEM; } return 0; } /* * Unsharing of sighand is not supported yet */ static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp) { struct sighand_struct *sigh = current->sighand; if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1) return -EINVAL; else return 0; } /* * Unshare vm if it is being shared */ static int unshare_vm(unsigned long unshare_flags, struct mm_struct **new_mmp) { struct mm_struct *mm = current->mm; if ((unshare_flags & CLONE_VM) && (mm && atomic_read(&mm->mm_users) > 1)) { return -EINVAL; } return 0; } /* * Unshare file descriptor table if it is being shared */ static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp) { struct files_struct *fd = current->files; int error = 0; if ((unshare_flags & CLONE_FILES) && (fd && atomic_read(&fd->count) > 1)) { *new_fdp = dup_fd(fd, &error); if (!*new_fdp) return error; } return 0; } /* * Unsharing of semundo for tasks created with CLONE_SYSVSEM is not * supported yet */ static int unshare_semundo(unsigned long unshare_flags, struct sem_undo_list **new_ulistp) { if (unshare_flags & CLONE_SYSVSEM) return -EINVAL; return 0; } /* * unshare allows a process to 'unshare' part of the process * context which was originally shared using clone. copy_* * functions used by do_fork() cannot be used here directly * because they modify an inactive task_struct that is being * constructed. Here we are modifying the current, active, * task_struct. */ asmlinkage long sys_unshare(unsigned long unshare_flags) { int err = 0; struct fs_struct *fs, *new_fs = NULL; struct sighand_struct *new_sigh = NULL; struct mm_struct *mm, *new_mm = NULL, *active_mm = NULL; struct files_struct *fd, *new_fd = NULL; struct sem_undo_list *new_ulist = NULL; struct nsproxy *new_nsproxy = NULL, *old_nsproxy = NULL; check_unshare_flags(&unshare_flags); /* Return -EINVAL for all unsupported flags */ err = -EINVAL; if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND| CLONE_VM|CLONE_FILES|CLONE_SYSVSEM| CLONE_NEWUTS|CLONE_NEWIPC)) goto bad_unshare_out; if ((err = unshare_thread(unshare_flags))) goto bad_unshare_out; if ((err = unshare_fs(unshare_flags, &new_fs))) goto bad_unshare_cleanup_thread; if ((err = unshare_sighand(unshare_flags, &new_sigh))) goto bad_unshare_cleanup_fs; if ((err = unshare_vm(unshare_flags, &new_mm))) goto bad_unshare_cleanup_sigh; if ((err = unshare_fd(unshare_flags, &new_fd))) goto bad_unshare_cleanup_vm; if ((err = unshare_semundo(unshare_flags, &new_ulist))) goto bad_unshare_cleanup_fd; if ((err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy, new_fs))) goto bad_unshare_cleanup_semundo; if (new_fs || new_mm || new_fd || new_ulist || new_nsproxy) { task_lock(current); if (new_nsproxy) { old_nsproxy = current->nsproxy; current->nsproxy = new_nsproxy; new_nsproxy = old_nsproxy; } if (new_fs) { fs = current->fs; current->fs = new_fs; new_fs = fs; } if (new_mm) { mm = current->mm; active_mm = current->active_mm; current->mm = new_mm; current->active_mm = new_mm; activate_mm(active_mm, new_mm); new_mm = mm; } if (new_fd) { fd = current->files; current->files = new_fd; new_fd = fd; } task_unlock(current); } if (new_nsproxy) put_nsproxy(new_nsproxy); bad_unshare_cleanup_semundo: bad_unshare_cleanup_fd: if (new_fd) put_files_struct(new_fd); bad_unshare_cleanup_vm: if (new_mm) mmput(new_mm); bad_unshare_cleanup_sigh: if (new_sigh) if (atomic_dec_and_test(&new_sigh->count)) kmem_cache_free(sighand_cachep, new_sigh); bad_unshare_cleanup_fs: if (new_fs) put_fs_struct(new_fs); bad_unshare_cleanup_thread: bad_unshare_out: return err; }
j0n3lson/linux-2.6.22.19-cs370
kernel/fork.c
C
gpl-2.0
41,833
/* * linux/fs/read_write.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/slab.h> #include <linux/stat.h> #include <linux/fcntl.h> #include <linux/file.h> #include <linux/uio.h> #include <linux/smp_lock.h> #include <linux/fsnotify.h> #include <linux/security.h> #include <linux/module.h> #include <linux/syscalls.h> #include <linux/pagemap.h> #include <linux/splice.h> #include <trace/fs.h> #include "read_write.h" #include <asm/uaccess.h> #include <asm/unistd.h> const struct file_operations generic_ro_fops = { .llseek = generic_file_llseek, .read = do_sync_read, .aio_read = generic_file_aio_read, .mmap = generic_file_readonly_mmap, .splice_read = generic_file_splice_read, }; EXPORT_SYMBOL(generic_ro_fops); /** * generic_file_llseek_unlocked - lockless generic llseek implementation * @file: file structure to seek on * @offset: file offset to seek to * @origin: type of seek * * Updates the file offset to the value specified by @offset and @origin. * Locking must be provided by the caller. */ loff_t generic_file_llseek_unlocked(struct file *file, loff_t offset, int origin) { struct inode *inode = file->f_mapping->host; switch (origin) { case SEEK_END: offset += inode->i_size; break; case SEEK_CUR: offset += file->f_pos; break; } if (offset < 0 || offset > inode->i_sb->s_maxbytes) return -EINVAL; /* Special lock needed here? */ if (offset != file->f_pos) { file->f_pos = offset; file->f_version = 0; } return offset; } EXPORT_SYMBOL(generic_file_llseek_unlocked); /** * generic_file_llseek - generic llseek implementation for regular files * @file: file structure to seek on * @offset: file offset to seek to * @origin: type of seek * * This is a generic implemenation of ->llseek useable for all normal local * filesystems. It just updates the file offset to the value specified by * @offset and @origin under i_mutex. */ loff_t generic_file_llseek(struct file *file, loff_t offset, int origin) { loff_t rval; mutex_lock(&file->f_dentry->d_inode->i_mutex); rval = generic_file_llseek_unlocked(file, offset, origin); mutex_unlock(&file->f_dentry->d_inode->i_mutex); return rval; } EXPORT_SYMBOL(generic_file_llseek); loff_t no_llseek(struct file *file, loff_t offset, int origin) { return -ESPIPE; } EXPORT_SYMBOL(no_llseek); loff_t default_llseek(struct file *file, loff_t offset, int origin) { loff_t retval; lock_kernel(); switch (origin) { case SEEK_END: offset += i_size_read(file->f_path.dentry->d_inode); break; case SEEK_CUR: offset += file->f_pos; } retval = -EINVAL; if (offset >= 0) { if (offset != file->f_pos) { file->f_pos = offset; file->f_version = 0; } retval = offset; } unlock_kernel(); return retval; } EXPORT_SYMBOL(default_llseek); loff_t vfs_llseek(struct file *file, loff_t offset, int origin) { loff_t (*fn)(struct file *, loff_t, int); fn = no_llseek; if (file->f_mode & FMODE_LSEEK) { fn = default_llseek; if (file->f_op && file->f_op->llseek) fn = file->f_op->llseek; } return fn(file, offset, origin); } EXPORT_SYMBOL(vfs_llseek); SYSCALL_DEFINE3(lseek, unsigned int, fd, off_t, offset, unsigned int, origin) { off_t retval; struct file * file; int fput_needed; retval = -EBADF; file = fget_light(fd, &fput_needed); if (!file) goto bad; retval = -EINVAL; if (origin <= SEEK_MAX) { loff_t res = vfs_llseek(file, offset, origin); retval = res; if (res != (loff_t)retval) retval = -EOVERFLOW; /* LFS: should only happen on 32 bit platforms */ } trace_fs_lseek(fd, offset, origin); fput_light(file, fput_needed); bad: return retval; } #ifdef __ARCH_WANT_SYS_LLSEEK SYSCALL_DEFINE5(llseek, unsigned int, fd, unsigned long, offset_high, unsigned long, offset_low, loff_t __user *, result, unsigned int, origin) { int retval; struct file * file; loff_t offset; int fput_needed; retval = -EBADF; file = fget_light(fd, &fput_needed); if (!file) goto bad; retval = -EINVAL; if (origin > SEEK_MAX) goto out_putf; offset = vfs_llseek(file, ((loff_t) offset_high << 32) | offset_low, origin); trace_fs_llseek(fd, offset, origin); retval = (int)offset; if (offset >= 0) { retval = -EFAULT; if (!copy_to_user(result, &offset, sizeof(offset))) retval = 0; } out_putf: fput_light(file, fput_needed); bad: return retval; } #endif /* * rw_verify_area doesn't like huge counts. We limit * them to something that fits in "int" so that others * won't have to do range checks all the time. */ #define MAX_RW_COUNT (INT_MAX & PAGE_CACHE_MASK) int rw_verify_area(int read_write, struct file *file, loff_t *ppos, size_t count) { struct inode *inode; loff_t pos; int retval = -EINVAL; inode = file->f_path.dentry->d_inode; if (unlikely((ssize_t) count < 0)) return retval; pos = *ppos; if (unlikely((pos < 0) || (loff_t) (pos + count) < 0)) return retval; if (unlikely(inode->i_flock && mandatory_lock(inode))) { retval = locks_mandatory_area( read_write == READ ? FLOCK_VERIFY_READ : FLOCK_VERIFY_WRITE, inode, file, pos, count); if (retval < 0) return retval; } retval = security_file_permission(file, read_write == READ ? MAY_READ : MAY_WRITE); if (retval) return retval; return count > MAX_RW_COUNT ? MAX_RW_COUNT : count; } static void wait_on_retry_sync_kiocb(struct kiocb *iocb) { set_current_state(TASK_UNINTERRUPTIBLE); if (!kiocbIsKicked(iocb)) schedule(); else kiocbClearKicked(iocb); __set_current_state(TASK_RUNNING); } ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos) { struct iovec iov = { .iov_base = buf, .iov_len = len }; struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; for (;;) { ret = filp->f_op->aio_read(&kiocb, &iov, 1, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } EXPORT_SYMBOL(do_sync_read); ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { ssize_t ret; if (!(file->f_mode & FMODE_READ)) return -EBADF; if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read)) return -EINVAL; if (unlikely(!access_ok(VERIFY_WRITE, buf, count))) return -EFAULT; ret = rw_verify_area(READ, file, pos, count); if (ret >= 0) { count = ret; if (file->f_op->read) ret = file->f_op->read(file, buf, count, pos); else ret = do_sync_read(file, buf, count, pos); if (ret > 0) { fsnotify_access(file->f_path.dentry); add_rchar(current, ret); } inc_syscr(current); } return ret; } EXPORT_SYMBOL(vfs_read); ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos) { struct iovec iov = { .iov_base = (void __user *)buf, .iov_len = len }; struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; for (;;) { ret = filp->f_op->aio_write(&kiocb, &iov, 1, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } EXPORT_SYMBOL(do_sync_write); ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos) { ssize_t ret; if (!(file->f_mode & FMODE_WRITE)) return -EBADF; if (!file->f_op || (!file->f_op->write && !file->f_op->aio_write)) return -EINVAL; if (unlikely(!access_ok(VERIFY_READ, buf, count))) return -EFAULT; ret = rw_verify_area(WRITE, file, pos, count); if (ret >= 0) { count = ret; if (file->f_op->write) ret = file->f_op->write(file, buf, count, pos); else ret = do_sync_write(file, buf, count, pos); if (ret > 0) { fsnotify_modify(file->f_path.dentry); add_wchar(current, ret); } inc_syscw(current); } return ret; } EXPORT_SYMBOL(vfs_write); static inline loff_t file_pos_read(struct file *file) { return file->f_pos; } static inline void file_pos_write(struct file *file, loff_t pos) { file->f_pos = pos; } SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_read(file, buf, count, &pos); trace_fs_read(fd, buf, count, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } return ret; } SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_write(file, buf, count, &pos); trace_fs_write(fd, buf, count, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } return ret; } SYSCALL_DEFINE(pread64)(unsigned int fd, char __user *buf, size_t count, loff_t pos) { struct file *file; ssize_t ret = -EBADF; int fput_needed; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (file) { ret = -ESPIPE; if (file->f_mode & FMODE_PREAD) { ret = vfs_read(file, buf, count, &pos); trace_fs_pread64(fd, buf, count, pos, ret); } fput_light(file, fput_needed); } return ret; } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_pread64(long fd, long buf, long count, loff_t pos) { return SYSC_pread64((unsigned int) fd, (char __user *) buf, (size_t) count, pos); } SYSCALL_ALIAS(sys_pread64, SyS_pread64); #endif SYSCALL_DEFINE(pwrite64)(unsigned int fd, const char __user *buf, size_t count, loff_t pos) { struct file *file; ssize_t ret = -EBADF; int fput_needed; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (file) { ret = -ESPIPE; if (file->f_mode & FMODE_PWRITE) { ret = vfs_write(file, buf, count, &pos); trace_fs_pwrite64(fd, buf, count, pos, ret); } fput_light(file, fput_needed); } return ret; } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_pwrite64(long fd, long buf, long count, loff_t pos) { return SYSC_pwrite64((unsigned int) fd, (const char __user *) buf, (size_t) count, pos); } SYSCALL_ALIAS(sys_pwrite64, SyS_pwrite64); #endif /* * Reduce an iovec's length in-place. Return the resulting number of segments */ unsigned long iov_shorten(struct iovec *iov, unsigned long nr_segs, size_t to) { unsigned long seg = 0; size_t len = 0; while (seg < nr_segs) { seg++; if (len + iov->iov_len >= to) { iov->iov_len = to - len; break; } len += iov->iov_len; iov++; } return seg; } EXPORT_SYMBOL(iov_shorten); ssize_t do_sync_readv_writev(struct file *filp, const struct iovec *iov, unsigned long nr_segs, size_t len, loff_t *ppos, iov_fn_t fn) { struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; kiocb.ki_nbytes = len; for (;;) { ret = fn(&kiocb, iov, nr_segs, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (ret == -EIOCBQUEUED) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } /* Do it by hand, with file-ops */ ssize_t do_loop_readv_writev(struct file *filp, struct iovec *iov, unsigned long nr_segs, loff_t *ppos, io_fn_t fn) { struct iovec *vector = iov; ssize_t ret = 0; while (nr_segs > 0) { void __user *base; size_t len; ssize_t nr; base = vector->iov_base; len = vector->iov_len; vector++; nr_segs--; nr = fn(filp, base, len, ppos); if (nr < 0) { if (!ret) ret = nr; break; } ret += nr; if (nr != len) break; } return ret; } /* A write operation does a read from user space and vice versa */ #define vrfy_dir(type) ((type) == READ ? VERIFY_WRITE : VERIFY_READ) ssize_t rw_copy_check_uvector(int type, const struct iovec __user * uvector, unsigned long nr_segs, unsigned long fast_segs, struct iovec *fast_pointer, struct iovec **ret_pointer) { unsigned long seg; ssize_t ret; struct iovec *iov = fast_pointer; /* * SuS says "The readv() function *may* fail if the iovcnt argument * was less than or equal to 0, or greater than {IOV_MAX}. Linux has * traditionally returned zero for zero segments, so... */ if (nr_segs == 0) { ret = 0; goto out; } /* * First get the "struct iovec" from user memory and * verify all the pointers */ if (nr_segs > UIO_MAXIOV) { ret = -EINVAL; goto out; } if (nr_segs > fast_segs) { iov = kmalloc(nr_segs*sizeof(struct iovec), GFP_KERNEL); if (iov == NULL) { ret = -ENOMEM; goto out; } } if (copy_from_user(iov, uvector, nr_segs*sizeof(*uvector))) { ret = -EFAULT; goto out; } /* * According to the Single Unix Specification we should return EINVAL * if an element length is < 0 when cast to ssize_t or if the * total length would overflow the ssize_t return value of the * system call. */ ret = 0; for (seg = 0; seg < nr_segs; seg++) { void __user *buf = iov[seg].iov_base; ssize_t len = (ssize_t)iov[seg].iov_len; /* see if we we're about to use an invalid len or if * it's about to overflow ssize_t */ if (len < 0 || (ret + len < ret)) { ret = -EINVAL; goto out; } if (unlikely(!access_ok(vrfy_dir(type), buf, len))) { ret = -EFAULT; goto out; } ret += len; } out: *ret_pointer = iov; return ret; } static ssize_t do_readv_writev(int type, struct file *file, const struct iovec __user * uvector, unsigned long nr_segs, loff_t *pos) { size_t tot_len; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; ssize_t ret; io_fn_t fn; iov_fn_t fnv; if (!file->f_op) { ret = -EINVAL; goto out; } ret = rw_copy_check_uvector(type, uvector, nr_segs, ARRAY_SIZE(iovstack), iovstack, &iov); if (ret <= 0) goto out; tot_len = ret; ret = rw_verify_area(type, file, pos, tot_len); if (ret < 0) goto out; fnv = NULL; if (type == READ) { fn = file->f_op->read; fnv = file->f_op->aio_read; } else { fn = (io_fn_t)file->f_op->write; fnv = file->f_op->aio_write; } if (fnv) ret = do_sync_readv_writev(file, iov, nr_segs, tot_len, pos, fnv); else ret = do_loop_readv_writev(file, iov, nr_segs, pos, fn); out: if (iov != iovstack) kfree(iov); if ((ret + (type == READ)) > 0) { if (type == READ) fsnotify_access(file->f_path.dentry); else fsnotify_modify(file->f_path.dentry); } return ret; } ssize_t vfs_readv(struct file *file, const struct iovec __user *vec, unsigned long vlen, loff_t *pos) { if (!(file->f_mode & FMODE_READ)) return -EBADF; if (!file->f_op || (!file->f_op->aio_read && !file->f_op->read)) return -EINVAL; return do_readv_writev(READ, file, vec, vlen, pos); } EXPORT_SYMBOL(vfs_readv); ssize_t vfs_writev(struct file *file, const struct iovec __user *vec, unsigned long vlen, loff_t *pos) { if (!(file->f_mode & FMODE_WRITE)) return -EBADF; if (!file->f_op || (!file->f_op->aio_write && !file->f_op->write)) return -EINVAL; return do_readv_writev(WRITE, file, vec, vlen, pos); } EXPORT_SYMBOL(vfs_writev); SYSCALL_DEFINE3(readv, unsigned long, fd, const struct iovec __user *, vec, unsigned long, vlen) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_readv(file, vec, vlen, &pos); trace_fs_readv(fd, vec, vlen, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } if (ret > 0) add_rchar(current, ret); inc_syscr(current); return ret; } SYSCALL_DEFINE3(writev, unsigned long, fd, const struct iovec __user *, vec, unsigned long, vlen) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_writev(file, vec, vlen, &pos); trace_fs_writev(fd, vec, vlen, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } if (ret > 0) add_wchar(current, ret); inc_syscw(current); return ret; } static ssize_t do_sendfile(int out_fd, int in_fd, loff_t *ppos, size_t count, loff_t max) { struct file * in_file, * out_file; struct inode * in_inode, * out_inode; loff_t pos; ssize_t retval; int fput_needed_in, fput_needed_out, fl; /* * Get input file, and verify that it is ok.. */ retval = -EBADF; in_file = fget_light(in_fd, &fput_needed_in); if (!in_file) goto out; if (!(in_file->f_mode & FMODE_READ)) goto fput_in; retval = -EINVAL; in_inode = in_file->f_path.dentry->d_inode; if (!in_inode) goto fput_in; if (!in_file->f_op || !in_file->f_op->splice_read) goto fput_in; retval = -ESPIPE; if (!ppos) ppos = &in_file->f_pos; else if (!(in_file->f_mode & FMODE_PREAD)) goto fput_in; retval = rw_verify_area(READ, in_file, ppos, count); if (retval < 0) goto fput_in; count = retval; /* * Get output file, and verify that it is ok.. */ retval = -EBADF; out_file = fget_light(out_fd, &fput_needed_out); if (!out_file) goto fput_in; if (!(out_file->f_mode & FMODE_WRITE)) goto fput_out; retval = -EINVAL; if (!out_file->f_op || !out_file->f_op->sendpage) goto fput_out; out_inode = out_file->f_path.dentry->d_inode; retval = rw_verify_area(WRITE, out_file, &out_file->f_pos, count); if (retval < 0) goto fput_out; count = retval; if (!max) max = min(in_inode->i_sb->s_maxbytes, out_inode->i_sb->s_maxbytes); pos = *ppos; retval = -EINVAL; if (unlikely(pos < 0)) goto fput_out; if (unlikely(pos + count > max)) { retval = -EOVERFLOW; if (pos >= max) goto fput_out; count = max - pos; } fl = 0; #if 0 /* * We need to debate whether we can enable this or not. The * man page documents EAGAIN return for the output at least, * and the application is arguably buggy if it doesn't expect * EAGAIN on a non-blocking file descriptor. */ if (in_file->f_flags & O_NONBLOCK) fl = SPLICE_F_NONBLOCK; #endif retval = do_splice_direct(in_file, ppos, out_file, count, fl); if (retval > 0) { add_rchar(current, retval); add_wchar(current, retval); } inc_syscr(current); inc_syscw(current); if (*ppos > max) retval = -EOVERFLOW; fput_out: fput_light(out_file, fput_needed_out); fput_in: fput_light(in_file, fput_needed_in); out: return retval; } SYSCALL_DEFINE4(sendfile, int, out_fd, int, in_fd, off_t __user *, offset, size_t, count) { loff_t pos; off_t off; ssize_t ret; if (offset) { if (unlikely(get_user(off, offset))) return -EFAULT; pos = off; ret = do_sendfile(out_fd, in_fd, &pos, count, MAX_NON_LFS); if (unlikely(put_user(pos, offset))) return -EFAULT; return ret; } return do_sendfile(out_fd, in_fd, NULL, count, 0); } SYSCALL_DEFINE4(sendfile64, int, out_fd, int, in_fd, loff_t __user *, offset, size_t, count) { loff_t pos; ssize_t ret; if (offset) { if (unlikely(copy_from_user(&pos, offset, sizeof(loff_t)))) return -EFAULT; ret = do_sendfile(out_fd, in_fd, &pos, count, 0); if (unlikely(put_user(pos, offset))) return -EFAULT; return ret; } return do_sendfile(out_fd, in_fd, NULL, count, 0); }
kzlin129/tt-gpl
go12/linux-2.6.28.10/fs/read_write.c
C
gpl-2.0
19,284
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER * DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE SOFTWARE OF * ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR SUPPLIED WITH THE * MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH THIRD PARTY FOR * ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT * IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER * LICENSES CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE * RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO RECEIVER'S * SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE * LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. */ /* * Copyright (c) 2008, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 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 <boot/boot.h> #include <msm7k/gpio.h> /* gross */ typedef struct gpioregs gpioregs; struct gpioregs { unsigned out; unsigned in; unsigned int_status; unsigned int_clear; unsigned int_en; unsigned int_edge; unsigned int_pos; unsigned oe; }; static gpioregs GPIO_REGS[] = { { .out = GPIO_OUT_0, .in = GPIO_IN_0, .int_status = GPIO_INT_STATUS_0, .int_clear = GPIO_INT_CLEAR_0, .int_en = GPIO_INT_EN_0, .int_edge = GPIO_INT_EDGE_0, .int_pos = GPIO_INT_POS_0, .oe = GPIO_OE_0, }, { .out = GPIO_OUT_1, .in = GPIO_IN_1, .int_status = GPIO_INT_STATUS_1, .int_clear = GPIO_INT_CLEAR_1, .int_en = GPIO_INT_EN_1, .int_edge = GPIO_INT_EDGE_1, .int_pos = GPIO_INT_POS_1, .oe = GPIO_OE_1, }, { .out = GPIO_OUT_2, .in = GPIO_IN_2, .int_status = GPIO_INT_STATUS_2, .int_clear = GPIO_INT_CLEAR_2, .int_en = GPIO_INT_EN_2, .int_edge = GPIO_INT_EDGE_2, .int_pos = GPIO_INT_POS_2, .oe = GPIO_OE_2, }, { .out = GPIO_OUT_3, .in = GPIO_IN_3, .int_status = GPIO_INT_STATUS_3, .int_clear = GPIO_INT_CLEAR_3, .int_en = GPIO_INT_EN_3, .int_edge = GPIO_INT_EDGE_3, .int_pos = GPIO_INT_POS_3, .oe = GPIO_OE_3, }, { .out = GPIO_OUT_4, .in = GPIO_IN_4, .int_status = GPIO_INT_STATUS_4, .int_clear = GPIO_INT_CLEAR_4, .int_en = GPIO_INT_EN_4, .int_edge = GPIO_INT_EDGE_4, .int_pos = GPIO_INT_POS_4, .oe = GPIO_OE_4, }, }; static gpioregs *find_gpio(unsigned n, unsigned *bit) { if(n > 106) return 0; if(n > 94) { *bit = 1 << (n - 95); return GPIO_REGS + 4; } if(n > 67) { *bit = 1 << (n - 68); return GPIO_REGS + 3; } if(n > 42) { *bit = 1 << (n - 43); return GPIO_REGS + 2; } if(n > 15) { *bit = 1 << (n - 16); return GPIO_REGS + 1; } *bit = 1 << n; return GPIO_REGS + 0; } void gpio_output_enable(unsigned n, unsigned out) { gpioregs *r; unsigned b; unsigned v; if((r = find_gpio(n, &b)) == 0) return; v = readl(r->oe); if(out) { writel(v | b, r->oe); } else { writel(v & (~b), r->oe); } } void gpio_write(unsigned n, unsigned on) { gpioregs *r; unsigned b; unsigned v; if((r = find_gpio(n, &b)) == 0) return; v = readl(r->out); if(on) { writel(v | b, r->out); } else { writel(v & (~b), r->out); } } int gpio_read(unsigned n) { gpioregs *r; unsigned b; if((r = find_gpio(n, &b)) == 0) return 0; return (readl(r->in) & b) ? 1 : 0; } void gpio_dir(int nr, int out) { gpio_output_enable(nr, out); } void gpio_set(int nr, int set) { gpio_write(nr, set); } int gpio_get(int nr) { return gpio_read(nr); }
luckasfb/OT_903D-kernel-2.6.35.7
bootable/bootloader/legacy/arch_msm7k/gpio.c
C
gpl-2.0
6,641
/************************************************************************* * * FILE NAME : ifxmips_pci.c * PROJECT : IFX UEIP * MODULES : PCI * * DATE : 29 June 2009 * AUTHOR : Lei Chuanhua * * DESCRIPTION : PCI Host Controller Driver * COPYRIGHT : Copyright (c) 2009 * Infineon Technologies AG * Am Campeon 1-12, 85579 Neubiberg, Germany * * 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. * * HISTORY * $Version $Date $Author $Comment * 1.0 29 Jun Lei Chuanhua First UEIP release *************************************************************************/ /*! \file ifxmips_pci.c \ingroup IFX_PCI \brief pci bus driver source file */ #include <linux/module.h> #include <linux/types.h> #include <linux/pci.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/mm.h> #include <asm/paccess.h> #include <asm/addrspace.h> #include <asm/ifx/ifx_types.h> #include <asm/ifx/ifx_regs.h> #include <asm/ifx/common_routines.h> #include <asm/ifx/ifx_gpio.h> #include <asm/ifx/irq.h> #include <asm/ifx/ifx_rcu.h> #include "ifxmips_pci_reg.h" #include "ifxmips_pci.h" #define IFX_PCI_VER_MAJOR 1 #define IFX_PCI_VER_MID 2 #define IFX_PCI_VER_MINOR 0 extern u32 max_pfn, max_low_pfn; extern struct pci_controller ifx_pci_controller; extern int ifx_pci_bus_status; extern void __iomem *ifx_pci_cfg_space; extern u32 pci_config_addr(u8 bus_num, u16 devfn, int where); /* Used by ifxmips_interrupt.c to suppress bus exception */ int pci_bus_error_flag; extern u32 ifx_pci_config_read(u32 addr); extern void ifx_pci_config_write(u32 addr, u32 data); #ifdef CONFIG_IFX_DUAL_MINI_PCI #define IFX_PCI_REQ1 29 #define IFX_PCI_GNT1 30 #endif /* CONFIG_IFX_DUAL_MINI_PCI */ static const int pci_gpio_module_id = IFX_GPIO_MODULE_PCI; #ifdef CONFIG_IFX_PCI_DANUBE_EBU_LED_RST #include <asm/ifx/ifx_ebu_led.h> static inline void ifx_pci_dev_reset_init(void) { ifx_ebu_led_enable(); ifx_ebu_led_set_data(9, 1); } static inline void ifx_pci_dev_reset(void) { ifx_ebu_led_set_data(9, 0); mdelay(5); ifx_ebu_led_set_data(9, 1); mdelay(1); ifx_ebu_led_disable(); } #else /* GPIO in global view */ #define IFX_PCI_RST 21 static inline void ifx_pci_dev_reset_init(void) { /* * PCI_RST: P1.5 used as a general GPIO, instead of PCI_RST gpio. * In Danube/AR9, it reset internal PCI core and external PCI device * However, in VR9, it only resets external PCI device. Internal core * reset by PCI software reset registers. * GPIO21 if used as PCI_RST, software can't control reset time. * Since it uses as a general GPIO, ALT should 0, 0. */ ifx_gpio_pin_reserve(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_dir_out_set(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_altsel0_clear(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_open_drain_set(IFX_PCI_RST, pci_gpio_module_id); } static inline void ifx_pci_dev_reset(void) { /* Reset external PCI device. */ ifx_gpio_output_clear(IFX_PCI_RST, pci_gpio_module_id); smp_wmb(); mdelay(5); ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id); smp_wmb(); mdelay(1); } #endif /* CONFIG_IFX_PCI_DANUBE_EBU_LED_RST */ static u32 round_up_to_next_power_of_two(u32 x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } static void ifx_pci_startup(void) { u32 reg; /* Choose reset from RCU first, then do reset */ reg = IFX_REG_R32(IFX_CGU_PCI_CR); reg |= IFX_PCI_CLK_RESET_FROM_CGU; /* XXX, Should be RCU*/ IFX_REG_W32(reg, IFX_CGU_PCI_CR); /* Secondly, RCU reset PCI domain including PCI CLK and PCI bridge */ ifx_rcu_rst(IFX_RCU_DOMAIN_PCI, IFX_RCU_MODULE_PCI); reg = IFX_REG_R32(IFX_CGU_IF_CLK); reg &= ~ IFX_PCI_CLK_MASK; /* * CGU PCI CLK is specific with platforms. Danube has four bits, * AR9 and VR9 has five bits. Their definitions are in platform header * file */ #ifdef CONFIG_IFX_PCI_EXTERNAL_CLK_SRC reg &= ~IFX_PCI_INTERNAL_CLK_SRC; /* External clk has no need to set clk in register */ #else reg |= IFX_PCI_INTERNAL_CLK_SRC; #ifdef CONFIG_IFX_PCI_INTERNAL_CLK_SRC_60 /* PCI 62.5 MHz clock */ reg |= IFX_PCI_60MHZ; #else /* PCI 33.3 MHz clock */ reg |= IFX_PCI_33MHZ; #endif /* CONFIG_IFX_PCI_INTERNAL_CLK_SRC_60 */ #endif /* CONFIG_IFX_PCI_EXTERNAL_CLK_SRC */ IFX_REG_W32(reg, IFX_CGU_IF_CLK); reg = IFX_REG_R32(IFX_CGU_PCI_CR); #ifdef CONFIG_IFX_PCI_EXTERNAL_CLK_SRC reg &= ~IFX_PCI_CLK_FROM_CGU; #else reg |= IFX_PCI_CLK_FROM_CGU; #endif /* CONFIG_IFX_PCI_EXTERNAL_CLK_SRC */ reg &= ~IFX_PCI_DELAY_MASK; #if !defined(CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS) || CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS < 0 || CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS > 7 #error "please define CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS properly" #endif reg |= (CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS << IFX_PCI_DELAY_SHIFT); #if !defined(CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND) || CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND < 0 || CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND > 5 #error "Please CONFIG_CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND properly" #endif reg |= (CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND << 18); IFX_REG_W32(reg, IFX_CGU_PCI_CR); ifx_pci_dev_reset_init(); #ifdef CONFIG_IFX_DUAL_MINI_PCI /* PCI_REQ1: P1.13 ALT 01 */ ifx_gpio_pin_reserve(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_dir_in_set(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_altsel0_set(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_REQ1, pci_gpio_module_id); /* PCI_GNT1: P1.14 ALT 01 */ ifx_gpio_pin_reserve(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_dir_out_set(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_altsel0_set(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_open_drain_set(IFX_PCI_GNT1, pci_gpio_module_id); #endif /* CONFIG_IFX_DUAL_MINI_PCI */ /* Enable auto-switching between PCI and EBU, normal ack */ reg = IFX_PCI_CLK_CTRL_EBU_PCI_SWITCH_EN | IFX_PCI_CLK_CTRL_FPI_NORMAL_ACK; IFX_REG_W32(reg, IFX_PCI_CLK_CTRL); /* Configuration mode, i.e. configuration is not done, PCI access has to be retried */ IFX_REG_CLR_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); smp_wmb(); /* Enable bus master/IO/MEM access */ reg = IFX_REG_R32(IFX_PCI_CMD); reg |= IFX_PCI_CMD_IO_EN | IFX_PCI_CMD_MEM_EN | IFX_PCI_CMD_MASTER_EN; IFX_REG_W32(reg, IFX_PCI_CMD); reg = IFX_REG_R32(IFX_PCI_ARB); #ifdef CONFIG_IFX_DUAL_MINI_PCI /* Enable external 4 PCI masters */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_PORT_ARB)); #else /* Enable external 1 PCI masters */ reg &= ~(SM(1, IFX_PCI_ARB_PCI_PORT_ARB)); #endif /* Enable internal arbiter */ reg |= IFX_PCI_ARB_INTERNAL_EN; /* Enable internal PCI master reqest */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ0)); /* Enable EBU reqest */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ1)); /* Enable all external masters request */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ2)); IFX_REG_W32(reg, IFX_PCI_ARB); smp_wmb(); /* * FPI ==> PCI MEM address mapping * base: 0xb8000000 == > 0x18000000 * size: 8x4M = 32M */ reg = IFX_PCI_MEM_PHY_BASE; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP0); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP1); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP2); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP3); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP4); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP5); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP6); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP7); /* FPI ==> PCI IO address mapping * base: 0xbAE00000 == > 0xbAE00000 * size: 2M */ IFX_REG_W32(IFX_PCI_IO_PHY_BASE, IFX_PCI_FPI_ADDR_MAP11_HIGH); /* PCI ==> FPI address mapping * base: 0x0 ==> 0x0 * size: 32M */ /* At least 16M. Otherwise there will be discontiguous memory region. */ reg = IFX_PCI_BAR_PREFETCH; reg |= ((-round_up_to_next_power_of_two((max_low_pfn << PAGE_SHIFT))) & 0x0F000000); IFX_REG_W32(reg, IFX_PCI_BAR11MASK); IFX_REG_W32(0x0, IFX_PCI_ADDR_MAP11); IFX_REG_W32(0x0, IFX_PCI_BAR1); #ifdef CONFIG_IFX_PCI_HW_SWAP /* both TX and RX endian swap are enabled */ reg = IFX_PCI_SWAP_RX | IFX_PCI_SWAP_TX; IFX_REG_W32(reg, IFX_PCI_SWAP); smp_wmb(); #endif reg = IFX_REG_R32(IFX_PCI_BAR12MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR12MASK); reg = IFX_REG_R32(IFX_PCI_BAR13MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR13MASK); reg = IFX_REG_R32(IFX_PCI_BAR14MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR14MASK); reg = IFX_REG_R32(IFX_PCI_BAR15MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR15MASK); reg = IFX_REG_R32(IFX_PCI_BAR16MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR16MASK); /* Use 4 dw burse length, XXX 8 dw will cause PCI timeout */ reg = SM(IFX_PCI_FPI_BURST_LEN4, IFX_PCI_FPI_RD_BURST_LEN) | SM(IFX_PCI_FPI_BURST_LEN4, IFX_PCI_FPI_WR_BURST_LEN); IFX_REG_W32(reg, IFX_PCI_FPI_BURST_LENGTH); /* Configuration OK. */ IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); smp_wmb(); mdelay(1); ifx_pci_dev_reset(); } /* Brief: disable external pci aribtor request * Details: * blocking call, i.e. only return when there is no external PCI bus activities */ void ifx_disable_external_pci(void) { IFX_REG_RMW32_FILED(IFX_PCI_ARB_PCI_MASTER_REQ2, 3, IFX_PCI_ARB); smp_wmb(); /* make sure EBUSY is low && Frame Ird is high) */ while ((IFX_REG_R32(IFX_PCI_ARB) & (IFX_PCI_ARB_PCI_NOT_READY | IFX_PCI_ARB_PCI_NO_FRM | IFX_PCI_ARB_EBU_IDLE)) != (IFX_PCI_ARB_PCI_NOT_READY | IFX_PCI_ARB_PCI_NO_FRM)); } /* Brief: enable external pci aribtor request * Details: * non-blocking call */ void ifx_enable_external_pci(void) { /* Clear means enabling all external masters request */ IFX_REG_CLR_BIT(IFX_PCI_ARB_PCI_MASTER_REQ2, IFX_PCI_ARB); smp_wmb(); } #ifdef CONFIG_DANUBE_EBU_PCI_SW_ARBITOR void ifx_enable_ebu(void) { u32 reg; /* Delay before enabling ebu ??? */ /* Disable int/ext pci request */ reg = IFX_REG_R32(IFX_PCI_ARB); reg &= ~(IFX_PCI_ARB_PCI_MASTER_REQ1); reg |= (IFX_PCI_ARB_PCI_MASTER_REQ0 | IFX_PCI_ARB_PCI_MASTER_REQ2); IFX_REG_W32(reg, IFX_PCI_ARB); /* Poll for pci bus idle */ reg = IFX_REG_R32(IFX_PCI_ARB); while ((reg & IFX_PCI_ART_PCI_IDLE) != IFX_PCI_ART_PCI_IDLE) { reg = IFX_REG_R32(IFX_PCI_ARB); }; /* EBU only, Arbitor fix*/ IFX_REG_W32(0, IFX_PCI_CLK_CTRL); /* * Unmask CFRAME_MASK changing PCI's Config Space via internal path * might need to change to external path */ /* Start configuration, one burst read is allowed */ reg = IFX_REG_R32(IFX_PCI_MOD); reg &= ~IFX_PCI_MOD_CFG_OK; reg |= IFX_PCI_MOD_TWO_IRQ_INTA_AND_INTB | SM(1, IFX_PCI_MOD_READ_BURST_THRESHOLD); IFX_REG_W32(reg, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); reg &= ~IFX_PCI_CARDBUS_FRAME_MASK_EN; IFX_REG_W32(reg, IFX_PCI_CARDBUS_FRAME_MASK); IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); } EXPORT_SYMBOL(ifx_enable_ebu); void ifx_disable_ebu(void) { u32 reg; /* Delay before enabling ebu ??? */ /* Restore EBU and PCI auto switch */ IFX_REG_W32(IFX_PCI_CLK_CTRL_EBU_PCI_SWITCH_EN, IFX_PCI_CLK_CTRL); /* * unmask CFRAME_MASK changing PCI's Config Space via internal path * might need to change to external path */ reg = IFX_REG_R32(IFX_PCI_MOD); /* Start configuration, one burst read is allowed */ reg &= ~IFX_PCI_MOD_CFG_OK; reg |= IFX_PCI_MOD_TWO_IRQ_INTA_AND_INTB | SM(1, IFX_PCI_MOD_READ_BURST_THRESHOLD); IFX_REG_W32(reg, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); reg |= IFX_PCI_CARDBUS_FRAME_MASK_EN; IFX_REG_W32(reg, IFX_PCI_CARDBUS_FRAME_MASK); IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); /* Enable int/ext pci request */ reg = IFX_REG_R32(IFX_PCI_ARB); reg &= ~(IFX_PCI_ARB_PCI_MASTER_REQ0 | IFX_PCI_ARB_PCI_MASTER_REQ2); reg |= IFX_PCI_ARB_PCI_MASTER_REQ1; IFX_REG_W32(reg, IFX_PCI_ARB); } EXPORT_SYMBOL(ifx_disable_ebu); #endif /* CONFIG_DANUBE_EBU_PCI_SW_ARBITOR */ static void __devinit pcibios_fixup_resources(struct pci_dev *dev) { struct pci_controller* hose = (struct pci_controller *)dev->sysdata; int i; unsigned long offset; if (!hose) { printk(KERN_ERR "No hose for PCI dev %s!\n", pci_name(dev)); return; } for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) { struct resource *res = dev->resource + i; if (!res->flags) continue; if (res->end == 0xffffffff) { printk(KERN_INFO "PCI:%s Resource %d [%016llx-%016llx] is unassigned\n", pci_name(dev), i, (u64)res->start, (u64)res->end); res->end -= res->start; res->start = 0; res->flags |= IORESOURCE_UNSET; continue; } offset = 0; if (res->flags & IORESOURCE_MEM) { offset = hose->mem_offset; } else if (res->flags & IORESOURCE_IO) { offset = hose->io_offset; } if (offset != 0) { res->start += offset; res->end += offset; printk(KERN_INFO "Fixup res %d (%lx) of dev %s: %llx -> %llx\n", i, res->flags, pci_name(dev), (u64)res->start - offset, (u64)res->start); } } IFX_PCI_PRINT("[%s %s %d]: %s\n", __FILE__, __func__, __LINE__, pci_name(dev)); /* Enable I/O, MEM, Bus Master, Special Cycles SERR, Fast back-to-back */ pci_write_config_word(dev, PCI_COMMAND, PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_SPECIAL | PCI_COMMAND_SERR | PCI_COMMAND_FAST_BACK); } DECLARE_PCI_FIXUP_EARLY(PCI_ANY_ID, PCI_ANY_ID, pcibios_fixup_resources); /** * \fn int ifx_pci_bios_map_irq(struct pci_dev *dev, u8 slot, u8 pin) * \brief Map a PCI device to the appropriate interrupt line * * \param[in] dev The Linux PCI device structure for the device to map * \param[in] slot The slot number for this device on __BUS 0__. Linux * enumerates through all the bridges and figures out the * slot on Bus 0 where this device eventually hooks to. * \param[in] pin The PCI interrupt pin read from the device, then swizzled * as it goes through each bridge. * \return Interrupt number for the device * \ingroup IFX_PCI_OS */ int ifx_pci_bios_map_irq(IFX_PCI_CONST struct pci_dev *dev, u8 slot, u8 pin) { int irq = -1; IFX_PCI_PRINT("%s dev %s slot %d pin %d \n", __func__, pci_name(dev), slot, pin); switch (pin) { case 0: break; case 1: IFX_PCI_PRINT("%s dev %s: interrupt pin 1\n", __func__, pci_name(dev)); /* * PCI_INTA--shared with EBU * falling edge level triggered:0x4, low level:0xc, rising edge:0x2 */ IFX_REG_W32(IFX_EBU_PCC_CON_IREQ_LOW_LEVEL_DETECT, IFX_EBU_PCC_CON); /* enable interrupt only */ IFX_REG_W32(IFX_EBU_PCC_IEN_PCI_EN, IFX_EBU_PCC_IEN); irq = INT_NUM_IM0_IRL22; break; case 2: case 3: break; default: printk(KERN_WARNING "WARNING: %s dev %s: invalid interrupt pin %d\n", __func__, pci_name(dev), pin); break; } return irq; } /** * \fn int ifx_pci_bios_plat_dev_init(struct pci_dev *dev) * \brief Called to perform platform specific PCI setup * * \param[in] dev The Linux PCI device structure for the device to map * \return OK * \ingroup IFX_PCI_OS */ int ifx_pci_bios_plat_dev_init(struct pci_dev *dev) { return 0; } static void inline ifx_pci_core_rst(void) { u32 reg; unsigned long flags; volatile int i; local_irq_save(flags); /* Ack the interrupt */ IFX_REG_W32(IFX_REG_R32(IFX_PCI_IRA), IFX_PCI_IRA); /* Disable external masters */ ifx_disable_external_pci(); /* PCI core reset start */ reg = IFX_REG_R32(IFX_PCI_SFT_RST); reg |= IFX_PCI_SFT_RST_REQ; IFX_REG_W32(reg, IFX_PCI_SFT_RST); for (i = 0; i < 100; i++); /* Wait for PCI core reset to be finished */ while ((IFX_REG_R32(IFX_PCI_SFT_RST) & IFX_PCI_SFT_RST_ACKING)); /* Out of reset to normal operation */ reg = IFX_REG_R32(IFX_PCI_SFT_RST); reg &= ~IFX_PCI_SFT_RST_REQ; IFX_REG_W32(reg, IFX_PCI_SFT_RST); for (i = 0; i < 50; i++); /* Enable external masters */ ifx_enable_external_pci(); local_irq_restore(flags); } static irqreturn_t #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19) ifx_pci_core_int_isr(int irq, void *dev_id) #else ifx_pci_core_int_isr(int irq, void *dev_id, struct pt_regs *regs) #endif { /* Only care about Timeout interrupt */ if ((IFX_REG_R32(IFX_PCI_IRR) & IFX_PCI_IR_TIMEOUT) == IFX_PCI_IR_TIMEOUT) { printk(KERN_ERR "%s: PCI timeout occurred\n", __func__); ifx_pci_core_rst(); } return IRQ_HANDLED; } static void ifx_pci_ir_irq_init(void) { int ret; /* Clear the interrupt first */ IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRA); ret = request_irq(IFX_PCI_IR, ifx_pci_core_int_isr, IRQF_DISABLED, "ifx_pci_ir", NULL); if (ret) { printk("%s:request irq %d failed with %d \n", __func__, IFX_PCI_IR, ret); return; } /* Unmask Timeout interrupt */ IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRM); } /*! * \fn static int __init ifx_pci_init(void) * \brief Initialize the IFX PCI host controller, register with PCI * bus subsystem. * * \return -ENOMEM configuration/io space mapping failed. * \return -EIO pci bus not initialized * \return 0 OK * \ingroup IFX_PCI_OS */ static int __init ifx_pci_init(void) { u32 cmdreg; void __iomem *io_map_base; char ver_str[128] = {0}; pci_bus_error_flag = 1; ifx_pci_startup(); ifx_pci_cfg_space = ioremap_nocache(IFX_PCI_CFG_PHY_BASE, IFX_PCI_CFG_SIZE); if (ifx_pci_cfg_space == NULL) { printk(KERN_ERR "%s configuration space ioremap failed\n", __func__); return -ENOMEM; } IFX_PCI_PRINT("[%s %s %d]: ifx_pci_cfg_space %p\n", __FILE__, __func__, __LINE__, ifx_pci_cfg_space); /* Otherwise, warning will pop up */ io_map_base = ioremap(IFX_PCI_IO_PHY_BASE, IFX_PCI_IO_SIZE); if (io_map_base == NULL) { iounmap(ifx_pci_cfg_space); IFX_PCI_PRINT("%s io space ioremap failed\n", __func__); return -ENOMEM; } ifx_pci_controller.io_map_base = (unsigned long)io_map_base; cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), PCI_COMMAND)); if (!(cmdreg & PCI_COMMAND_MASTER)) { printk(KERN_INFO "PCI: Skipping PCI probe. Bus is not initialized.\n"); iounmap(ifx_pci_cfg_space); return -EIO; } ifx_pci_bus_status |= PCI_BUS_ENABLED; /* Turn on ExpMemEn */ cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40)); ifx_pci_config_write(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40), cmdreg | 0x10); cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40)); /* Enable normal FPI bus exception after we configured everything */ IFX_REG_CLR_BIT(IFX_PCI_CLK_CTRL_FPI_NORMAL_ACK, IFX_PCI_CLK_CTRL); IFX_PCI_PRINT("[%s %s %d]: mem_resource @%p, io_resource @%p\n", __FILE__, __func__, __LINE__, &ifx_pci_controller.mem_resource, &ifx_pci_controller.io_resource); register_pci_controller(&ifx_pci_controller); ifx_pci_ir_irq_init(); ifx_drv_ver(ver_str, "PCI host controller", IFX_PCI_VER_MAJOR, IFX_PCI_VER_MID, IFX_PCI_VER_MINOR); printk(KERN_INFO "%s", ver_str); return 0; } arch_initcall(ifx_pci_init); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Lei Chuanhua, chuanhua.lei@infineon.com"); MODULE_SUPPORTED_DEVICE("Infineon builtin PCI module for Danube AR9 and VR9"); MODULE_DESCRIPTION("Infineon builtin PCI host controller driver");
kbridgers/VOLTE4GFAX
target/linux/ltqcpe/files-2.6.32/arch/mips/pci/ifxmips_pci.c
C
gpl-2.0
21,354
/* * Copyright (c) 2010, Google, Inc. * * This file is part of Libav. * * Libav 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. * * Libav 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * VP8 decoder support via libvpx */ #define VPX_CODEC_DISABLE_COMPAT 1 #include <vpx/vpx_decoder.h> #include <vpx/vp8dx.h> #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "internal.h" typedef struct VP8DecoderContext { struct vpx_codec_ctx decoder; } VP8Context; static av_cold int vpx_init(AVCodecContext *avctx, const struct vpx_codec_iface *iface) { VP8Context *ctx = avctx->priv_data; struct vpx_codec_dec_cfg deccfg = { /* token partitions+1 would be a decent choice */ .threads = FFMIN(avctx->thread_count, 16) }; av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str()); av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config()); if (vpx_codec_dec_init(&ctx->decoder, iface, &deccfg, 0) != VPX_CODEC_OK) { const char *error = vpx_codec_error(&ctx->decoder); av_log(avctx, AV_LOG_ERROR, "Failed to initialize decoder: %s\n", error); return AVERROR(EINVAL); } avctx->pix_fmt = AV_PIX_FMT_YUV420P; return 0; } static int vp8_decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { VP8Context *ctx = avctx->priv_data; AVFrame *picture = data; const void *iter = NULL; struct vpx_image *img; int ret; if (vpx_codec_decode(&ctx->decoder, avpkt->data, avpkt->size, NULL, 0) != VPX_CODEC_OK) { const char *error = vpx_codec_error(&ctx->decoder); const char *detail = vpx_codec_error_detail(&ctx->decoder); av_log(avctx, AV_LOG_ERROR, "Failed to decode frame: %s\n", error); if (detail) av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail); return AVERROR_INVALIDDATA; } if ((img = vpx_codec_get_frame(&ctx->decoder, &iter))) { if (img->fmt != VPX_IMG_FMT_I420) { av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d)\n", img->fmt); return AVERROR_INVALIDDATA; } if ((int) img->d_w != avctx->width || (int) img->d_h != avctx->height) { av_log(avctx, AV_LOG_INFO, "dimension change! %dx%d -> %dx%d\n", avctx->width, avctx->height, img->d_w, img->d_h); if (av_image_check_size(img->d_w, img->d_h, 0, avctx)) return AVERROR_INVALIDDATA; avcodec_set_dimensions(avctx, img->d_w, img->d_h); } if ((ret = ff_get_buffer(avctx, picture, 0)) < 0) return ret; av_image_copy(picture->data, picture->linesize, img->planes, img->stride, avctx->pix_fmt, img->d_w, img->d_h); *got_frame = 1; } return avpkt->size; } static av_cold int vp8_free(AVCodecContext *avctx) { VP8Context *ctx = avctx->priv_data; vpx_codec_destroy(&ctx->decoder); return 0; } #if CONFIG_LIBVPX_VP8_DECODER static av_cold int vp8_init(AVCodecContext *avctx) { return vpx_init(avctx, &vpx_codec_vp8_dx_algo); } AVCodec ff_libvpx_vp8_decoder = { .name = "libvpx", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP8, .priv_data_size = sizeof(VP8Context), .init = vp8_init, .close = vp8_free, .decode = vp8_decode, .capabilities = CODEC_CAP_AUTO_THREADS | CODEC_CAP_DR1, .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"), }; #endif /* CONFIG_LIBVPX_VP8_DECODER */ #if CONFIG_LIBVPX_VP9_DECODER static av_cold int vp9_init(AVCodecContext *avctx) { return vpx_init(avctx, &vpx_codec_vp9_dx_algo); } AVCodec ff_libvpx_vp9_decoder = { .name = "libvpx-vp9", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP9, .priv_data_size = sizeof(VP8Context), .init = vp9_init, .close = vp8_free, .decode = vp8_decode, .capabilities = CODEC_CAP_AUTO_THREADS | CODEC_CAP_EXPERIMENTAL, .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"), }; #endif /* CONFIG_LIBVPX_VP9_DECODER */
DDTChen/CookieVLC
vlc/contrib/android/ffmpeg/libavcodec/libvpxdec.c
C
gpl-2.0
4,941
/* * Driver for the SGS-Thomson M48T35 Timekeeper RAM chip * * Real Time Clock interface for Linux * * TODO: Implement periodic interrupts. * * Copyright (C) 2000 Silicon Graphics, Inc. * Written by Ulf Carlsson (ulfc@engr.sgi.com) * * Based on code written by Paul Gortmaker. * * This driver allows use of the real time clock (built into * nearly all computers) from user space. It exports the /dev/rtc * interface supporting various ioctl() and also the /proc/rtc * pseudo-file for status information. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #define RTC_VERSION "1.09b" #include <linux/bcd.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/smp_lock.h> #include <linux/types.h> #include <linux/miscdevice.h> #include <linux/ioport.h> #include <linux/fcntl.h> #include <linux/rtc.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/proc_fs.h> #include <asm/m48t35.h> #include <asm/sn/ioc3.h> #include <asm/io.h> #include <asm/uaccess.h> #include <asm/system.h> #include <asm/sn/klconfig.h> #include <asm/sn/sn0/ip27.h> #include <asm/sn/sn0/hub.h> #include <asm/sn/sn_private.h> static long rtc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); static int rtc_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data); static void get_rtc_time(struct rtc_time *rtc_tm); /* * Bits in rtc_status. (6 bits of room for future expansion) */ #define RTC_IS_OPEN 0x01 /* means /dev/rtc is in use */ #define RTC_TIMER_ON 0x02 /* missed irq timer active */ static unsigned char rtc_status; /* bitmapped status byte. */ static unsigned long rtc_freq; /* Current periodic IRQ rate */ static struct m48t35_rtc *rtc; /* * If this driver ever becomes modularised, it will be really nice * to make the epoch retain its value across module reload... */ static unsigned long epoch = 1970; /* year corresponding to 0x00 */ static const unsigned char days_in_mo[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; static long rtc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct rtc_time wtime; switch (cmd) { case RTC_RD_TIME: /* Read the time/date from RTC */ { get_rtc_time(&wtime); break; } case RTC_SET_TIME: /* Set the RTC */ { struct rtc_time rtc_tm; unsigned char mon, day, hrs, min, sec, leap_yr; unsigned int yrs; if (!capable(CAP_SYS_TIME)) return -EACCES; if (copy_from_user(&rtc_tm, (struct rtc_time*)arg, sizeof(struct rtc_time))) return -EFAULT; yrs = rtc_tm.tm_year + 1900; mon = rtc_tm.tm_mon + 1; /* tm_mon starts at zero */ day = rtc_tm.tm_mday; hrs = rtc_tm.tm_hour; min = rtc_tm.tm_min; sec = rtc_tm.tm_sec; if (yrs < 1970) return -EINVAL; leap_yr = ((!(yrs % 4) && (yrs % 100)) || !(yrs % 400)); if ((mon > 12) || (day == 0)) return -EINVAL; if (day > (days_in_mo[mon] + ((mon == 2) && leap_yr))) return -EINVAL; if ((hrs >= 24) || (min >= 60) || (sec >= 60)) return -EINVAL; if ((yrs -= epoch) > 255) /* They are unsigned */ return -EINVAL; if (yrs > 169) return -EINVAL; if (yrs >= 100) yrs -= 100; sec = bin2bcd(sec); min = bin2bcd(min); hrs = bin2bcd(hrs); day = bin2bcd(day); mon = bin2bcd(mon); yrs = bin2bcd(yrs); spin_lock_irq(&rtc_lock); rtc->control |= M48T35_RTC_SET; rtc->year = yrs; rtc->month = mon; rtc->date = day; rtc->hour = hrs; rtc->min = min; rtc->sec = sec; rtc->control &= ~M48T35_RTC_SET; spin_unlock_irq(&rtc_lock); return 0; } default: return -EINVAL; } return copy_to_user((void *)arg, &wtime, sizeof wtime) ? -EFAULT : 0; } /* * We enforce only one user at a time here with the open/close. * Also clear the previous interrupt data on an open, and clean * up things on a close. */ static int rtc_open(struct inode *inode, struct file *file) { lock_kernel(); spin_lock_irq(&rtc_lock); if (rtc_status & RTC_IS_OPEN) { spin_unlock_irq(&rtc_lock); unlock_kernel(); return -EBUSY; } rtc_status |= RTC_IS_OPEN; spin_unlock_irq(&rtc_lock); unlock_kernel(); return 0; } static int rtc_release(struct inode *inode, struct file *file) { /* * Turn off all interrupts once the device is no longer * in use, and clear the data. */ spin_lock_irq(&rtc_lock); rtc_status &= ~RTC_IS_OPEN; spin_unlock_irq(&rtc_lock); return 0; } /* * The various file operations we support. */ static const struct file_operations rtc_fops = { .owner = THIS_MODULE, .unlocked_ioctl = rtc_ioctl, .open = rtc_open, .release = rtc_release, }; static struct miscdevice rtc_dev= { RTC_MINOR, "rtc", &rtc_fops }; static int __init rtc_init(void) { rtc = (struct m48t35_rtc *) (KL_CONFIG_CH_CONS_INFO(master_nasid)->memory_base + IOC3_BYTEBUS_DEV0); printk(KERN_INFO "Real Time Clock Driver v%s\n", RTC_VERSION); if (misc_register(&rtc_dev)) { printk(KERN_ERR "rtc: cannot register misc device.\n"); return -ENODEV; } if (!create_proc_read_entry("driver/rtc", 0, NULL, rtc_read_proc, NULL)) { printk(KERN_ERR "rtc: cannot create /proc/rtc.\n"); misc_deregister(&rtc_dev); return -ENOENT; } rtc_freq = 1024; return 0; } static void __exit rtc_exit (void) { /* interrupts and timer disabled at this point by rtc_release */ remove_proc_entry ("rtc", NULL); misc_deregister(&rtc_dev); } module_init(rtc_init); module_exit(rtc_exit); /* * Info exported via "/proc/rtc". */ static int rtc_get_status(char *buf) { char *p; struct rtc_time tm; /* * Just emulate the standard /proc/rtc */ p = buf; get_rtc_time(&tm); /* * There is no way to tell if the luser has the RTC set for local * time or for Universal Standard Time (GMT). Probably local though. */ p += sprintf(p, "rtc_time\t: %02d:%02d:%02d\n" "rtc_date\t: %04d-%02d-%02d\n" "rtc_epoch\t: %04lu\n" "24hr\t\t: yes\n", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, epoch); return p - buf; } static int rtc_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data) { int len = rtc_get_status(page); if (len <= off+count) *eof = 1; *start = page + off; len -= off; if (len>count) len = count; if (len<0) len = 0; return len; } static void get_rtc_time(struct rtc_time *rtc_tm) { /* * Do we need to wait for the last update to finish? */ /* * Only the values that we read from the RTC are set. We leave * tm_wday, tm_yday and tm_isdst untouched. Even though the * RTC has RTC_DAY_OF_WEEK, we ignore it, as it is only updated * by the RTC when initially set to a non-zero value. */ spin_lock_irq(&rtc_lock); rtc->control |= M48T35_RTC_READ; rtc_tm->tm_sec = rtc->sec; rtc_tm->tm_min = rtc->min; rtc_tm->tm_hour = rtc->hour; rtc_tm->tm_mday = rtc->date; rtc_tm->tm_mon = rtc->month; rtc_tm->tm_year = rtc->year; rtc->control &= ~M48T35_RTC_READ; spin_unlock_irq(&rtc_lock); rtc_tm->tm_sec = bcd2bin(rtc_tm->tm_sec); rtc_tm->tm_min = bcd2bin(rtc_tm->tm_min); rtc_tm->tm_hour = bcd2bin(rtc_tm->tm_hour); rtc_tm->tm_mday = bcd2bin(rtc_tm->tm_mday); rtc_tm->tm_mon = bcd2bin(rtc_tm->tm_mon); rtc_tm->tm_year = bcd2bin(rtc_tm->tm_year); /* * Account for differences between how the RTC uses the values * and how they are defined in a struct rtc_time; */ if ((rtc_tm->tm_year += (epoch - 1900)) <= 69) rtc_tm->tm_year += 100; rtc_tm->tm_mon--; }
mpalmer/linux-2.6
drivers/char/ip27-rtc.c
C
gpl-2.0
7,743
/* dnsmasq is Copyright (c) 2000-2015 Simon Kelley 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 dated June, 1991, or (at your option) version 3 dated 29 June, 2007. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dnsmasq.h" #ifdef HAVE_LOOP static ssize_t loop_make_probe(u32 uid); void loop_send_probes() { struct server *serv; if (!option_bool(OPT_LOOP_DETECT)) return; /* Loop through all upstream servers not for particular domains, and send a query to that server which is identifiable, via the uid. If we see that query back again, then the server is looping, and we should not use it. */ for (serv = daemon->servers; serv; serv = serv->next) if (!(serv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND | SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_LOOP))) { ssize_t len = loop_make_probe(serv->uid); int fd; struct randfd *rfd = NULL; if (serv->sfd) fd = serv->sfd->fd; else { if (!(rfd = allocate_rfd(serv->addr.sa.sa_family))) continue; fd = rfd->fd; } while (retry_send(sendto(fd, daemon->packet, len, 0, &serv->addr.sa, sa_len(&serv->addr)))); free_rfd(rfd); } } static ssize_t loop_make_probe(u32 uid) { struct dns_header *header = (struct dns_header *)daemon->packet; unsigned char *p = (unsigned char *)(header+1); /* packet buffer overwritten */ daemon->srv_save = NULL; header->id = rand16(); header->ancount = header->nscount = header->arcount = htons(0); header->qdcount = htons(1); header->hb3 = HB3_RD; header->hb4 = 0; SET_OPCODE(header, QUERY); *p++ = 8; sprintf((char *)p, "%.8x", uid); p += 8; *p++ = strlen(LOOP_TEST_DOMAIN); strcpy((char *)p, LOOP_TEST_DOMAIN); /* Add terminating zero */ p += strlen(LOOP_TEST_DOMAIN) + 1; PUTSHORT(LOOP_TEST_TYPE, p); PUTSHORT(C_IN, p); return p - (unsigned char *)header; } int detect_loop(char *query, int type) { int i; u32 uid; struct server *serv; if (!option_bool(OPT_LOOP_DETECT)) return 0; if (type != LOOP_TEST_TYPE || strlen(LOOP_TEST_DOMAIN) + 9 != strlen(query) || strstr(query, LOOP_TEST_DOMAIN) != query + 9) return 0; for (i = 0; i < 8; i++) if (!isxdigit(query[i])) return 0; uid = strtol(query, NULL, 16); for (serv = daemon->servers; serv; serv = serv->next) if (!(serv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND | SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_LOOP)) && uid == serv->uid) { serv->flags |= SERV_LOOP; check_servers(); /* log new state */ return 1; } return 0; } #endif
ghmajx/asuswrt-merlin
release/src/router/dnsmasq/src/loop.c
C
gpl-2.0
3,165
/* * Copyright 2002-2005, Instant802 Networks, Inc. * Copyright 2005-2006, Devicescape Software, Inc. * Copyright 2007 Johannes Berg <johannes@sipsolutions.net> * Copyright 2008 Luis R. Rodriguez <lrodriguz@atheros.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /** * DOC: Wireless regulatory infrastructure * * The usual implementation is for a driver to read a device EEPROM to * determine which regulatory domain it should be operating under, then * looking up the allowable channels in a driver-local table and finally * registering those channels in the wiphy structure. * * Another set of compliance enforcement is for drivers to use their * own compliance limits which can be stored on the EEPROM. The host * driver or firmware may ensure these are used. * * In addition to all this we provide an extra layer of regulatory * conformance. For drivers which do not have any regulatory * information CRDA provides the complete regulatory solution. * For others it provides a community effort on further restrictions * to enhance compliance. * * Note: When number of rules --> infinity we will not be able to * index on alpha2 any more, instead we'll probably have to * rely on some SHA1 checksum of the regdomain for example. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/slab.h> #include <linux/list.h> #include <linux/random.h> #include <linux/ctype.h> #include <linux/nl80211.h> #include <linux/platform_device.h> #include <net/cfg80211.h> #include "core.h" #include "reg.h" #include "regdb.h" #include "nl80211.h" #ifdef CONFIG_CFG80211_REG_DEBUG #define REG_DBG_PRINT(format, args...) \ do { \ printk(KERN_DEBUG pr_fmt(format), ##args); \ } while (0) #else #define REG_DBG_PRINT(args...) #endif /* Receipt of information from last regulatory request */ static struct regulatory_request *last_request; /* To trigger userspace events */ static struct platform_device *reg_pdev; static struct device_type reg_device_type = { .uevent = reg_device_uevent, }; /* * Central wireless core regulatory domains, we only need two, * the current one and a world regulatory domain in case we have no * information to give us an alpha2 */ const struct ieee80211_regdomain *cfg80211_regdomain; /* * Protects static reg.c components: * - cfg80211_world_regdom * - cfg80211_regdom * - last_request */ static DEFINE_MUTEX(reg_mutex); static inline void assert_reg_lock(void) { lockdep_assert_held(&reg_mutex); } /* Used to queue up regulatory hints */ static LIST_HEAD(reg_requests_list); static spinlock_t reg_requests_lock; /* Used to queue up beacon hints for review */ static LIST_HEAD(reg_pending_beacons); static spinlock_t reg_pending_beacons_lock; /* Used to keep track of processed beacon hints */ static LIST_HEAD(reg_beacon_list); struct reg_beacon { struct list_head list; struct ieee80211_channel chan; }; static void reg_todo(struct work_struct *work); static DECLARE_WORK(reg_work, reg_todo); static void reg_timeout_work(struct work_struct *work); static DECLARE_DELAYED_WORK(reg_timeout, reg_timeout_work); /* We keep a static world regulatory domain in case of the absence of CRDA */ static const struct ieee80211_regdomain world_regdom = { .n_reg_rules = 5, .alpha2 = "00", .reg_rules = { /* IEEE 802.11b/g, channels 1..11 */ REG_RULE(2412-10, 2462+10, 40, 6, 20, 0), /* IEEE 802.11b/g, channels 12..13. No HT40 * channel fits here. */ REG_RULE(2467-10, 2472+10, 20, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), /* IEEE 802.11 channel 14 - Only JP enables * this and for 802.11b only */ REG_RULE(2484-10, 2484+10, 20, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS | NL80211_RRF_NO_OFDM), /* IEEE 802.11a, channel 36..48 */ REG_RULE(5180-10, 5240+10, 40, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), /* NB: 5260 MHz - 5700 MHz requies DFS */ /* IEEE 802.11a, channel 149..165 */ REG_RULE(5745-10, 5825+10, 40, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), } }; static const struct ieee80211_regdomain *cfg80211_world_regdom = &world_regdom; static char *ieee80211_regdom = "00"; static char user_alpha2[2]; module_param(ieee80211_regdom, charp, 0444); MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code"); static void reset_regdomains(void) { /* avoid freeing static information or freeing something twice */ if (cfg80211_regdomain == cfg80211_world_regdom) cfg80211_regdomain = NULL; if (cfg80211_world_regdom == &world_regdom) cfg80211_world_regdom = NULL; if (cfg80211_regdomain == &world_regdom) cfg80211_regdomain = NULL; kfree(cfg80211_regdomain); kfree(cfg80211_world_regdom); cfg80211_world_regdom = &world_regdom; cfg80211_regdomain = NULL; } /* * Dynamic world regulatory domain requested by the wireless * core upon initialization */ static void update_world_regdomain(const struct ieee80211_regdomain *rd) { BUG_ON(!last_request); reset_regdomains(); cfg80211_world_regdom = rd; cfg80211_regdomain = rd; } bool is_world_regdom(const char *alpha2) { if (!alpha2) return false; if (alpha2[0] == '0' && alpha2[1] == '0') return true; return false; } static bool is_alpha2_set(const char *alpha2) { if (!alpha2) return false; if (alpha2[0] != 0 && alpha2[1] != 0) return true; return false; } static bool is_unknown_alpha2(const char *alpha2) { if (!alpha2) return false; /* * Special case where regulatory domain was built by driver * but a specific alpha2 cannot be determined */ if (alpha2[0] == '9' && alpha2[1] == '9') return true; return false; } static bool is_intersected_alpha2(const char *alpha2) { if (!alpha2) return false; /* * Special case where regulatory domain is the * result of an intersection between two regulatory domain * structures */ if (alpha2[0] == '9' && alpha2[1] == '8') return true; return false; } static bool is_an_alpha2(const char *alpha2) { if (!alpha2) return false; if (isalpha(alpha2[0]) && isalpha(alpha2[1])) return true; return false; } static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y) { if (!alpha2_x || !alpha2_y) return false; if (alpha2_x[0] == alpha2_y[0] && alpha2_x[1] == alpha2_y[1]) return true; return false; } static bool regdom_changes(const char *alpha2) { assert_cfg80211_lock(); if (!cfg80211_regdomain) return true; if (alpha2_equal(cfg80211_regdomain->alpha2, alpha2)) return false; return true; } /* * The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets * you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER * has ever been issued. */ static bool is_user_regdom_saved(void) { if (user_alpha2[0] == '9' && user_alpha2[1] == '7') return false; /* This would indicate a mistake on the design */ if (WARN((!is_world_regdom(user_alpha2) && !is_an_alpha2(user_alpha2)), "Unexpected user alpha2: %c%c\n", user_alpha2[0], user_alpha2[1])) return false; return true; } static int reg_copy_regd(const struct ieee80211_regdomain **dst_regd, const struct ieee80211_regdomain *src_regd) { struct ieee80211_regdomain *regd; int size_of_regd = 0; unsigned int i; size_of_regd = sizeof(struct ieee80211_regdomain) + ((src_regd->n_reg_rules + 1) * sizeof(struct ieee80211_reg_rule)); regd = kzalloc(size_of_regd, GFP_KERNEL); if (!regd) return -ENOMEM; memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain)); for (i = 0; i < src_regd->n_reg_rules; i++) memcpy(&regd->reg_rules[i], &src_regd->reg_rules[i], sizeof(struct ieee80211_reg_rule)); *dst_regd = regd; return 0; } #ifdef CONFIG_CFG80211_INTERNAL_REGDB struct reg_regdb_search_request { char alpha2[2]; struct list_head list; }; static LIST_HEAD(reg_regdb_search_list); static DEFINE_MUTEX(reg_regdb_search_mutex); static void reg_regdb_search(struct work_struct *work) { struct reg_regdb_search_request *request; const struct ieee80211_regdomain *curdom, *regdom; int i, r; mutex_lock(&reg_regdb_search_mutex); while (!list_empty(&reg_regdb_search_list)) { request = list_first_entry(&reg_regdb_search_list, struct reg_regdb_search_request, list); list_del(&request->list); for (i=0; i<reg_regdb_size; i++) { curdom = reg_regdb[i]; if (!memcmp(request->alpha2, curdom->alpha2, 2)) { r = reg_copy_regd(&regdom, curdom); if (r) break; mutex_lock(&cfg80211_mutex); set_regdom(regdom); mutex_unlock(&cfg80211_mutex); break; } } kfree(request); } mutex_unlock(&reg_regdb_search_mutex); } static DECLARE_WORK(reg_regdb_work, reg_regdb_search); static void reg_regdb_query(const char *alpha2) { struct reg_regdb_search_request *request; if (!alpha2) return; request = kzalloc(sizeof(struct reg_regdb_search_request), GFP_KERNEL); if (!request) return; memcpy(request->alpha2, alpha2, 2); mutex_lock(&reg_regdb_search_mutex); list_add_tail(&request->list, &reg_regdb_search_list); mutex_unlock(&reg_regdb_search_mutex); schedule_work(&reg_regdb_work); } #else static inline void reg_regdb_query(const char *alpha2) {} #endif /* CONFIG_CFG80211_INTERNAL_REGDB */ /* * This lets us keep regulatory code which is updated on a regulatory * basis in userspace. Country information is filled in by * reg_device_uevent */ static int call_crda(const char *alpha2) { if (!is_world_regdom((char *) alpha2)) pr_info("Calling CRDA for country: %c%c\n", alpha2[0], alpha2[1]); else pr_info("Calling CRDA to update world regulatory domain\n"); /* query internal regulatory database (if it exists) */ reg_regdb_query(alpha2); return kobject_uevent(&reg_pdev->dev.kobj, KOBJ_CHANGE); } /* Used by nl80211 before kmalloc'ing our regulatory domain */ bool reg_is_valid_request(const char *alpha2) { assert_cfg80211_lock(); if (!last_request) return false; return alpha2_equal(last_request->alpha2, alpha2); } /* Sanity check on a regulatory rule */ static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule) { const struct ieee80211_freq_range *freq_range = &rule->freq_range; u32 freq_diff; if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0) return false; if (freq_range->start_freq_khz > freq_range->end_freq_khz) return false; freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz; if (freq_range->end_freq_khz <= freq_range->start_freq_khz || freq_range->max_bandwidth_khz > freq_diff) return false; return true; } static bool is_valid_rd(const struct ieee80211_regdomain *rd) { const struct ieee80211_reg_rule *reg_rule = NULL; unsigned int i; if (!rd->n_reg_rules) return false; if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES)) return false; for (i = 0; i < rd->n_reg_rules; i++) { reg_rule = &rd->reg_rules[i]; if (!is_valid_reg_rule(reg_rule)) return false; } return true; } static bool reg_does_bw_fit(const struct ieee80211_freq_range *freq_range, u32 center_freq_khz, u32 bw_khz) { u32 start_freq_khz, end_freq_khz; start_freq_khz = center_freq_khz - (bw_khz/2); end_freq_khz = center_freq_khz + (bw_khz/2); if (start_freq_khz >= freq_range->start_freq_khz && end_freq_khz <= freq_range->end_freq_khz) return true; return false; } /** * freq_in_rule_band - tells us if a frequency is in a frequency band * @freq_range: frequency rule we want to query * @freq_khz: frequency we are inquiring about * * This lets us know if a specific frequency rule is or is not relevant to * a specific frequency's band. Bands are device specific and artificial * definitions (the "2.4 GHz band" and the "5 GHz band"), however it is * safe for now to assume that a frequency rule should not be part of a * frequency's band if the start freq or end freq are off by more than 2 GHz. * This resolution can be lowered and should be considered as we add * regulatory rule support for other "bands". **/ static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range, u32 freq_khz) { #define ONE_GHZ_IN_KHZ 1000000 if (abs(freq_khz - freq_range->start_freq_khz) <= (2 * ONE_GHZ_IN_KHZ)) return true; if (abs(freq_khz - freq_range->end_freq_khz) <= (2 * ONE_GHZ_IN_KHZ)) return true; return false; #undef ONE_GHZ_IN_KHZ } /* * Helper for regdom_intersect(), this does the real * mathematical intersection fun */ static int reg_rules_intersect( const struct ieee80211_reg_rule *rule1, const struct ieee80211_reg_rule *rule2, struct ieee80211_reg_rule *intersected_rule) { const struct ieee80211_freq_range *freq_range1, *freq_range2; struct ieee80211_freq_range *freq_range; const struct ieee80211_power_rule *power_rule1, *power_rule2; struct ieee80211_power_rule *power_rule; u32 freq_diff; freq_range1 = &rule1->freq_range; freq_range2 = &rule2->freq_range; freq_range = &intersected_rule->freq_range; power_rule1 = &rule1->power_rule; power_rule2 = &rule2->power_rule; power_rule = &intersected_rule->power_rule; freq_range->start_freq_khz = max(freq_range1->start_freq_khz, freq_range2->start_freq_khz); freq_range->end_freq_khz = min(freq_range1->end_freq_khz, freq_range2->end_freq_khz); freq_range->max_bandwidth_khz = min(freq_range1->max_bandwidth_khz, freq_range2->max_bandwidth_khz); freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz; if (freq_range->max_bandwidth_khz > freq_diff) freq_range->max_bandwidth_khz = freq_diff; power_rule->max_eirp = min(power_rule1->max_eirp, power_rule2->max_eirp); power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain, power_rule2->max_antenna_gain); intersected_rule->flags = (rule1->flags | rule2->flags); if (!is_valid_reg_rule(intersected_rule)) return -EINVAL; return 0; } /** * regdom_intersect - do the intersection between two regulatory domains * @rd1: first regulatory domain * @rd2: second regulatory domain * * Use this function to get the intersection between two regulatory domains. * Once completed we will mark the alpha2 for the rd as intersected, "98", * as no one single alpha2 can represent this regulatory domain. * * Returns a pointer to the regulatory domain structure which will hold the * resulting intersection of rules between rd1 and rd2. We will * kzalloc() this structure for you. */ static struct ieee80211_regdomain *regdom_intersect( const struct ieee80211_regdomain *rd1, const struct ieee80211_regdomain *rd2) { int r, size_of_regd; unsigned int x, y; unsigned int num_rules = 0, rule_idx = 0; const struct ieee80211_reg_rule *rule1, *rule2; struct ieee80211_reg_rule *intersected_rule; struct ieee80211_regdomain *rd; /* This is just a dummy holder to help us count */ struct ieee80211_reg_rule irule; /* Uses the stack temporarily for counter arithmetic */ intersected_rule = &irule; memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule)); if (!rd1 || !rd2) return NULL; /* * First we get a count of the rules we'll need, then we actually * build them. This is to so we can malloc() and free() a * regdomain once. The reason we use reg_rules_intersect() here * is it will return -EINVAL if the rule computed makes no sense. * All rules that do check out OK are valid. */ for (x = 0; x < rd1->n_reg_rules; x++) { rule1 = &rd1->reg_rules[x]; for (y = 0; y < rd2->n_reg_rules; y++) { rule2 = &rd2->reg_rules[y]; if (!reg_rules_intersect(rule1, rule2, intersected_rule)) num_rules++; memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule)); } } if (!num_rules) return NULL; size_of_regd = sizeof(struct ieee80211_regdomain) + ((num_rules + 1) * sizeof(struct ieee80211_reg_rule)); rd = kzalloc(size_of_regd, GFP_KERNEL); if (!rd) return NULL; for (x = 0; x < rd1->n_reg_rules; x++) { rule1 = &rd1->reg_rules[x]; for (y = 0; y < rd2->n_reg_rules; y++) { rule2 = &rd2->reg_rules[y]; /* * This time around instead of using the stack lets * write to the target rule directly saving ourselves * a memcpy() */ intersected_rule = &rd->reg_rules[rule_idx]; r = reg_rules_intersect(rule1, rule2, intersected_rule); /* * No need to memset here the intersected rule here as * we're not using the stack anymore */ if (r) continue; rule_idx++; } } if (rule_idx != num_rules) { kfree(rd); return NULL; } rd->n_reg_rules = num_rules; rd->alpha2[0] = '9'; rd->alpha2[1] = '8'; return rd; } /* * XXX: add support for the rest of enum nl80211_reg_rule_flags, we may * want to just have the channel structure use these */ static u32 map_regdom_flags(u32 rd_flags) { u32 channel_flags = 0; if (rd_flags & NL80211_RRF_PASSIVE_SCAN) channel_flags |= IEEE80211_CHAN_PASSIVE_SCAN; if (rd_flags & NL80211_RRF_NO_IBSS) channel_flags |= IEEE80211_CHAN_NO_IBSS; if (rd_flags & NL80211_RRF_DFS) channel_flags |= IEEE80211_CHAN_RADAR; return channel_flags; } static int freq_reg_info_regd(struct wiphy *wiphy, u32 center_freq, u32 desired_bw_khz, const struct ieee80211_reg_rule **reg_rule, const struct ieee80211_regdomain *custom_regd) { int i; bool band_rule_found = false; const struct ieee80211_regdomain *regd; bool bw_fits = false; if (!desired_bw_khz) desired_bw_khz = MHZ_TO_KHZ(20); regd = custom_regd ? custom_regd : cfg80211_regdomain; /* * Follow the driver's regulatory domain, if present, unless a country * IE has been processed or a user wants to help complaince further */ if (!custom_regd && last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && last_request->initiator != NL80211_REGDOM_SET_BY_USER && wiphy->regd) regd = wiphy->regd; if (!regd) return -EINVAL; for (i = 0; i < regd->n_reg_rules; i++) { const struct ieee80211_reg_rule *rr; const struct ieee80211_freq_range *fr = NULL; rr = &regd->reg_rules[i]; fr = &rr->freq_range; /* * We only need to know if one frequency rule was * was in center_freq's band, that's enough, so lets * not overwrite it once found */ if (!band_rule_found) band_rule_found = freq_in_rule_band(fr, center_freq); bw_fits = reg_does_bw_fit(fr, center_freq, desired_bw_khz); if (band_rule_found && bw_fits) { *reg_rule = rr; return 0; } } if (!band_rule_found) return -ERANGE; return -EINVAL; } int freq_reg_info(struct wiphy *wiphy, u32 center_freq, u32 desired_bw_khz, const struct ieee80211_reg_rule **reg_rule) { assert_cfg80211_lock(); return freq_reg_info_regd(wiphy, center_freq, desired_bw_khz, reg_rule, NULL); } EXPORT_SYMBOL(freq_reg_info); #ifdef CONFIG_CFG80211_REG_DEBUG static const char *reg_initiator_name(enum nl80211_reg_initiator initiator) { switch (initiator) { case NL80211_REGDOM_SET_BY_CORE: return "Set by core"; case NL80211_REGDOM_SET_BY_USER: return "Set by user"; case NL80211_REGDOM_SET_BY_DRIVER: return "Set by driver"; case NL80211_REGDOM_SET_BY_COUNTRY_IE: return "Set by country IE"; default: WARN_ON(1); return "Set by bug"; } } static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan, u32 desired_bw_khz, const struct ieee80211_reg_rule *reg_rule) { const struct ieee80211_power_rule *power_rule; const struct ieee80211_freq_range *freq_range; char max_antenna_gain[32]; power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (!power_rule->max_antenna_gain) snprintf(max_antenna_gain, 32, "N/A"); else snprintf(max_antenna_gain, 32, "%d", power_rule->max_antenna_gain); REG_DBG_PRINT("Updating information on frequency %d MHz " "for a %d MHz width channel with regulatory rule:\n", chan->center_freq, KHZ_TO_MHZ(desired_bw_khz)); REG_DBG_PRINT("%d KHz - %d KHz @ KHz), (%s mBi, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, max_antenna_gain, power_rule->max_eirp); } #else static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan, u32 desired_bw_khz, const struct ieee80211_reg_rule *reg_rule) { return; } #endif /* * Note that right now we assume the desired channel bandwidth * is always 20 MHz for each individual channel (HT40 uses 20 MHz * per channel, the primary and the extension channel). To support * smaller custom bandwidths such as 5 MHz or 10 MHz we'll need a * new ieee80211_channel.target_bw and re run the regulatory check * on the wiphy with the target_bw specified. Then we can simply use * that below for the desired_bw_khz below. */ static void handle_channel(struct wiphy *wiphy, enum nl80211_reg_initiator initiator, enum ieee80211_band band, unsigned int chan_idx) { int r; u32 flags, bw_flags = 0; u32 desired_bw_khz = MHZ_TO_KHZ(20); const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_power_rule *power_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; struct wiphy *request_wiphy = NULL; assert_cfg80211_lock(); request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); chan = &sband->channels[chan_idx]; flags = chan->orig_flags; r = freq_reg_info(wiphy, MHZ_TO_KHZ(chan->center_freq), desired_bw_khz, &reg_rule); if (r) { /* * We will disable all channels that do not match our * received regulatory rule unless the hint is coming * from a Country IE and the Country IE had no information * about a band. The IEEE 802.11 spec allows for an AP * to send only a subset of the regulatory rules allowed, * so an AP in the US that only supports 2.4 GHz may only send * a country IE with information for the 2.4 GHz band * while 5 GHz is still supported. */ if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && r == -ERANGE) return; REG_DBG_PRINT("Disabling freq %d MHz\n", chan->center_freq); chan->flags = IEEE80211_CHAN_DISABLED; return; } chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule); power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40)) bw_flags = IEEE80211_CHAN_NO_HT40; if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && request_wiphy && request_wiphy == wiphy && request_wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { /* * This guarantees the driver's requested regulatory domain * will always be used as a base for further regulatory * settings */ chan->flags = chan->orig_flags = map_regdom_flags(reg_rule->flags) | bw_flags; chan->max_antenna_gain = chan->orig_mag = (int) MBI_TO_DBI(power_rule->max_antenna_gain); chan->max_power = chan->orig_mpwr = (int) MBM_TO_DBM(power_rule->max_eirp); return; } chan->beacon_found = false; chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags); chan->max_antenna_gain = min(chan->orig_mag, (int) MBI_TO_DBI(power_rule->max_antenna_gain)); if (chan->orig_mpwr) { /* * Devices that have their own custom regulatory domain * but also use WIPHY_FLAG_STRICT_REGULATORY will follow the * passed country IE power settings. */ if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY && wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { chan->max_power = MBM_TO_DBM(power_rule->max_eirp); } else { chan->max_power = min(chan->orig_mpwr, (int) MBM_TO_DBM(power_rule->max_eirp)); } } else chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp); } static void handle_band(struct wiphy *wiphy, enum ieee80211_band band, enum nl80211_reg_initiator initiator) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) handle_channel(wiphy, initiator, band, i); } static bool ignore_reg_update(struct wiphy *wiphy, enum nl80211_reg_initiator initiator) { if (!last_request) { REG_DBG_PRINT("Ignoring regulatory request %s since " "last_request is not set\n", reg_initiator_name(initiator)); return true; } if (initiator == NL80211_REGDOM_SET_BY_CORE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) { REG_DBG_PRINT("Ignoring regulatory request %s " "since the driver uses its own custom " "regulatory domain ", reg_initiator_name(initiator)); return true; } /* * wiphy->regd will be set once the device has its own * desired regulatory domain set */ if (wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY && !wiphy->regd && initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && !is_world_regdom(last_request->alpha2)) { REG_DBG_PRINT("Ignoring regulatory request %s " "since the driver requires its own regulaotry " "domain to be set first", reg_initiator_name(initiator)); return true; } return false; } static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator) { struct cfg80211_registered_device *rdev; struct wiphy *wiphy; list_for_each_entry(rdev, &cfg80211_rdev_list, list) { wiphy = &rdev->wiphy; wiphy_update_regulatory(wiphy, initiator); /* * Regulatory updates set by CORE are ignored for custom * regulatory cards. Let us notify the changes to the driver, * as some drivers used this to restore its orig_* reg domain. */ if (initiator == NL80211_REGDOM_SET_BY_CORE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY && wiphy->reg_notifier) wiphy->reg_notifier(wiphy, last_request); } } static void handle_reg_beacon(struct wiphy *wiphy, unsigned int chan_idx, struct reg_beacon *reg_beacon) { struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; bool channel_changed = false; struct ieee80211_channel chan_before; assert_cfg80211_lock(); sband = wiphy->bands[reg_beacon->chan.band]; chan = &sband->channels[chan_idx]; if (likely(chan->center_freq != reg_beacon->chan.center_freq)) return; if (chan->beacon_found) return; chan->beacon_found = true; if (wiphy->flags & WIPHY_FLAG_DISABLE_BEACON_HINTS) return; chan_before.center_freq = chan->center_freq; chan_before.flags = chan->flags; if (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN) { chan->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN; channel_changed = true; } if (chan->flags & IEEE80211_CHAN_NO_IBSS) { chan->flags &= ~IEEE80211_CHAN_NO_IBSS; channel_changed = true; } if (channel_changed) nl80211_send_beacon_hint_event(wiphy, &chan_before, chan); } /* * Called when a scan on a wiphy finds a beacon on * new channel */ static void wiphy_update_new_beacon(struct wiphy *wiphy, struct reg_beacon *reg_beacon) { unsigned int i; struct ieee80211_supported_band *sband; assert_cfg80211_lock(); if (!wiphy->bands[reg_beacon->chan.band]) return; sband = wiphy->bands[reg_beacon->chan.band]; for (i = 0; i < sband->n_channels; i++) handle_reg_beacon(wiphy, i, reg_beacon); } /* * Called upon reg changes or a new wiphy is added */ static void wiphy_update_beacon_reg(struct wiphy *wiphy) { unsigned int i; struct ieee80211_supported_band *sband; struct reg_beacon *reg_beacon; assert_cfg80211_lock(); if (list_empty(&reg_beacon_list)) return; list_for_each_entry(reg_beacon, &reg_beacon_list, list) { if (!wiphy->bands[reg_beacon->chan.band]) continue; sband = wiphy->bands[reg_beacon->chan.band]; for (i = 0; i < sband->n_channels; i++) handle_reg_beacon(wiphy, i, reg_beacon); } } static bool reg_is_world_roaming(struct wiphy *wiphy) { if (is_world_regdom(cfg80211_regdomain->alpha2) || (wiphy->regd && is_world_regdom(wiphy->regd->alpha2))) return true; if (last_request && last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) return true; return false; } /* Reap the advantages of previously found beacons */ static void reg_process_beacons(struct wiphy *wiphy) { /* * Means we are just firing up cfg80211, so no beacons would * have been processed yet. */ if (!last_request) return; if (!reg_is_world_roaming(wiphy)) return; wiphy_update_beacon_reg(wiphy); } static bool is_ht40_not_allowed(struct ieee80211_channel *chan) { if (!chan) return true; if (chan->flags & IEEE80211_CHAN_DISABLED) return true; /* This would happen when regulatory rules disallow HT40 completely */ if (IEEE80211_CHAN_NO_HT40 == (chan->flags & (IEEE80211_CHAN_NO_HT40))) return true; return false; } static void reg_process_ht_flags_channel(struct wiphy *wiphy, enum ieee80211_band band, unsigned int chan_idx) { struct ieee80211_supported_band *sband; struct ieee80211_channel *channel; struct ieee80211_channel *channel_before = NULL, *channel_after = NULL; unsigned int i; assert_cfg80211_lock(); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); channel = &sband->channels[chan_idx]; if (is_ht40_not_allowed(channel)) { channel->flags |= IEEE80211_CHAN_NO_HT40; return; } /* * We need to ensure the extension channels exist to * be able to use HT40- or HT40+, this finds them (or not) */ for (i = 0; i < sband->n_channels; i++) { struct ieee80211_channel *c = &sband->channels[i]; if (c->center_freq == (channel->center_freq - 20)) channel_before = c; if (c->center_freq == (channel->center_freq + 20)) channel_after = c; } /* * Please note that this assumes target bandwidth is 20 MHz, * if that ever changes we also need to change the below logic * to include that as well. */ if (is_ht40_not_allowed(channel_before)) channel->flags |= IEEE80211_CHAN_NO_HT40MINUS; else channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS; if (is_ht40_not_allowed(channel_after)) channel->flags |= IEEE80211_CHAN_NO_HT40PLUS; else channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS; } static void reg_process_ht_flags_band(struct wiphy *wiphy, enum ieee80211_band band) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) reg_process_ht_flags_channel(wiphy, band, i); } static void reg_process_ht_flags(struct wiphy *wiphy) { enum ieee80211_band band; if (!wiphy) return; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (wiphy->bands[band]) reg_process_ht_flags_band(wiphy, band); } } void wiphy_update_regulatory(struct wiphy *wiphy, enum nl80211_reg_initiator initiator) { enum ieee80211_band band; if (ignore_reg_update(wiphy, initiator)) return; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (wiphy->bands[band]) handle_band(wiphy, band, initiator); } reg_process_beacons(wiphy); reg_process_ht_flags(wiphy); if (wiphy->reg_notifier) wiphy->reg_notifier(wiphy, last_request); } static void handle_channel_custom(struct wiphy *wiphy, enum ieee80211_band band, unsigned int chan_idx, const struct ieee80211_regdomain *regd) { int r; u32 desired_bw_khz = MHZ_TO_KHZ(20); u32 bw_flags = 0; const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_power_rule *power_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; assert_reg_lock(); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); chan = &sband->channels[chan_idx]; r = freq_reg_info_regd(wiphy, MHZ_TO_KHZ(chan->center_freq), desired_bw_khz, &reg_rule, regd); if (r) { REG_DBG_PRINT("Disabling freq %d MHz as custom " "regd has no rule that fits a %d MHz " "wide channel\n", chan->center_freq, KHZ_TO_MHZ(desired_bw_khz)); chan->flags = IEEE80211_CHAN_DISABLED; return; } chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule); power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40)) bw_flags = IEEE80211_CHAN_NO_HT40; chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags; chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain); chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp); } static void handle_band_custom(struct wiphy *wiphy, enum ieee80211_band band, const struct ieee80211_regdomain *regd) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) handle_channel_custom(wiphy, band, i, regd); } /* Used by drivers prior to wiphy registration */ void wiphy_apply_custom_regulatory(struct wiphy *wiphy, const struct ieee80211_regdomain *regd) { enum ieee80211_band band; unsigned int bands_set = 0; mutex_lock(&reg_mutex); for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (!wiphy->bands[band]) continue; handle_band_custom(wiphy, band, regd); bands_set++; } mutex_unlock(&reg_mutex); /* * no point in calling this if it won't have any effect * on your device's supportd bands. */ WARN_ON(!bands_set); } EXPORT_SYMBOL(wiphy_apply_custom_regulatory); /* * Return value which can be used by ignore_request() to indicate * it has been determined we should intersect two regulatory domains */ #define REG_INTERSECT 1 /* This has the logic which determines when a new request * should be ignored. */ static int ignore_request(struct wiphy *wiphy, struct regulatory_request *pending_request) { struct wiphy *last_wiphy = NULL; assert_cfg80211_lock(); /* All initial requests are respected */ if (!last_request) return 0; switch (pending_request->initiator) { case NL80211_REGDOM_SET_BY_CORE: return 0; case NL80211_REGDOM_SET_BY_COUNTRY_IE: last_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (unlikely(!is_an_alpha2(pending_request->alpha2))) return -EINVAL; if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) { if (last_wiphy != wiphy) { /* * Two cards with two APs claiming different * Country IE alpha2s. We could * intersect them, but that seems unlikely * to be correct. Reject second one for now. */ if (regdom_changes(pending_request->alpha2)) return -EOPNOTSUPP; return -EALREADY; } /* * Two consecutive Country IE hints on the same wiphy. * This should be picked up early by the driver/stack */ if (WARN_ON(regdom_changes(pending_request->alpha2))) return 0; return -EALREADY; } return 0; case NL80211_REGDOM_SET_BY_DRIVER: if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE) { if (regdom_changes(pending_request->alpha2)) return 0; return -EALREADY; } /* * This would happen if you unplug and plug your card * back in or if you add a new device for which the previously * loaded card also agrees on the regulatory domain. */ if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && !regdom_changes(pending_request->alpha2)) return -EALREADY; return REG_INTERSECT; case NL80211_REGDOM_SET_BY_USER: if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) return REG_INTERSECT; /* * If the user knows better the user should set the regdom * to their country before the IE is picked up */ if (last_request->initiator == NL80211_REGDOM_SET_BY_USER && last_request->intersect) return -EOPNOTSUPP; /* * Process user requests only after previous user/driver/core * requests have been processed */ if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE || last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER || last_request->initiator == NL80211_REGDOM_SET_BY_USER) { if (regdom_changes(last_request->alpha2)) return -EAGAIN; } if (!regdom_changes(pending_request->alpha2)) return -EALREADY; return 0; } return -EINVAL; } static void reg_set_request_processed(void) { bool need_more_processing = false; last_request->processed = true; spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) need_more_processing = true; spin_unlock(&reg_requests_lock); if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) cancel_delayed_work_sync(&reg_timeout); if (need_more_processing) schedule_work(&reg_work); } /** * __regulatory_hint - hint to the wireless core a regulatory domain * @wiphy: if the hint comes from country information from an AP, this * is required to be set to the wiphy that received the information * @pending_request: the regulatory request currently being processed * * The Wireless subsystem can use this function to hint to the wireless core * what it believes should be the current regulatory domain. * * Returns zero if all went fine, %-EALREADY if a regulatory domain had * already been set or other standard error codes. * * Caller must hold &cfg80211_mutex and &reg_mutex */ static int __regulatory_hint(struct wiphy *wiphy, struct regulatory_request *pending_request) { bool intersect = false; int r = 0; assert_cfg80211_lock(); r = ignore_request(wiphy, pending_request); if (r == REG_INTERSECT) { if (pending_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) { r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain); if (r) { kfree(pending_request); return r; } } intersect = true; } else if (r) { /* * If the regulatory domain being requested by the * driver has already been set just copy it to the * wiphy */ if (r == -EALREADY && pending_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) { r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain); if (r) { kfree(pending_request); return r; } r = -EALREADY; goto new_request; } kfree(pending_request); return r; } new_request: kfree(last_request); last_request = pending_request; last_request->intersect = intersect; pending_request = NULL; if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) { user_alpha2[0] = last_request->alpha2[0]; user_alpha2[1] = last_request->alpha2[1]; } /* When r == REG_INTERSECT we do need to call CRDA */ if (r < 0) { /* * Since CRDA will not be called in this case as we already * have applied the requested regulatory domain before we just * inform userspace we have processed the request */ if (r == -EALREADY) { nl80211_send_reg_change_event(last_request); reg_set_request_processed(); } return r; } return call_crda(last_request->alpha2); } /* This processes *all* regulatory hints */ static void reg_process_hint(struct regulatory_request *reg_request) { int r = 0; struct wiphy *wiphy = NULL; enum nl80211_reg_initiator initiator = reg_request->initiator; BUG_ON(!reg_request->alpha2); if (wiphy_idx_valid(reg_request->wiphy_idx)) wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx); if (reg_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && !wiphy) { kfree(reg_request); return; } r = __regulatory_hint(wiphy, reg_request); /* This is required so that the orig_* parameters are saved */ if (r == -EALREADY && wiphy && wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { wiphy_update_regulatory(wiphy, initiator); return; } /* * We only time out user hints, given that they should be the only * source of bogus requests. */ if (r != -EALREADY && reg_request->initiator == NL80211_REGDOM_SET_BY_USER) schedule_delayed_work(&reg_timeout, msecs_to_jiffies(3142)); } /* * Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_* * Regulatory hints come on a first come first serve basis and we * must process each one atomically. */ static void reg_process_pending_hints(void) { struct regulatory_request *reg_request; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); /* When last_request->processed becomes true this will be rescheduled */ if (last_request && !last_request->processed) { REG_DBG_PRINT("Pending regulatory request, waiting " "for it to be processed..."); goto out; } spin_lock(&reg_requests_lock); if (list_empty(&reg_requests_list)) { spin_unlock(&reg_requests_lock); goto out; } reg_request = list_first_entry(&reg_requests_list, struct regulatory_request, list); list_del_init(&reg_request->list); spin_unlock(&reg_requests_lock); reg_process_hint(reg_request); out: mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); } /* Processes beacon hints -- this has nothing to do with country IEs */ static void reg_process_pending_beacon_hints(void) { struct cfg80211_registered_device *rdev; struct reg_beacon *pending_beacon, *tmp; /* * No need to hold the reg_mutex here as we just touch wiphys * and do not read or access regulatory variables. */ mutex_lock(&cfg80211_mutex); /* This goes through the _pending_ beacon list */ spin_lock_bh(&reg_pending_beacons_lock); if (list_empty(&reg_pending_beacons)) { spin_unlock_bh(&reg_pending_beacons_lock); goto out; } list_for_each_entry_safe(pending_beacon, tmp, &reg_pending_beacons, list) { list_del_init(&pending_beacon->list); /* Applies the beacon hint to current wiphys */ list_for_each_entry(rdev, &cfg80211_rdev_list, list) wiphy_update_new_beacon(&rdev->wiphy, pending_beacon); /* Remembers the beacon hint for new wiphys or reg changes */ list_add_tail(&pending_beacon->list, &reg_beacon_list); } spin_unlock_bh(&reg_pending_beacons_lock); out: mutex_unlock(&cfg80211_mutex); } static void reg_todo(struct work_struct *work) { reg_process_pending_hints(); reg_process_pending_beacon_hints(); } static void queue_regulatory_request(struct regulatory_request *request) { if (isalpha(request->alpha2[0])) request->alpha2[0] = toupper(request->alpha2[0]); if (isalpha(request->alpha2[1])) request->alpha2[1] = toupper(request->alpha2[1]); spin_lock(&reg_requests_lock); list_add_tail(&request->list, &reg_requests_list); spin_unlock(&reg_requests_lock); schedule_work(&reg_work); } /* * Core regulatory hint -- happens during cfg80211_init() * and when we restore regulatory settings. */ static int regulatory_hint_core(const char *alpha2) { struct regulatory_request *request; kfree(last_request); last_request = NULL; request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_CORE; queue_regulatory_request(request); return 0; } /* User hints */ int regulatory_hint_user(const char *alpha2) { struct regulatory_request *request; BUG_ON(!alpha2); request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->wiphy_idx = WIPHY_IDX_STALE; request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_USER; queue_regulatory_request(request); return 0; } /* Driver hints */ int regulatory_hint(struct wiphy *wiphy, const char *alpha2) { struct regulatory_request *request; BUG_ON(!alpha2); BUG_ON(!wiphy); request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->wiphy_idx = get_wiphy_idx(wiphy); /* Must have registered wiphy first */ BUG_ON(!wiphy_idx_valid(request->wiphy_idx)); request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_DRIVER; queue_regulatory_request(request); return 0; } EXPORT_SYMBOL(regulatory_hint); /* * We hold wdev_lock() here so we cannot hold cfg80211_mutex() and * therefore cannot iterate over the rdev list here. */ void regulatory_hint_11d(struct wiphy *wiphy, enum ieee80211_band band, u8 *country_ie, u8 country_ie_len) { char alpha2[2]; enum environment_cap env = ENVIRON_ANY; struct regulatory_request *request; mutex_lock(&reg_mutex); if (unlikely(!last_request)) goto out; /* IE len must be evenly divisible by 2 */ if (country_ie_len & 0x01) goto out; if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN) goto out; alpha2[0] = country_ie[0]; alpha2[1] = country_ie[1]; if (country_ie[2] == 'I') env = ENVIRON_INDOOR; else if (country_ie[2] == 'O') env = ENVIRON_OUTDOOR; /* * We will run this only upon a successful connection on cfg80211. * We leave conflict resolution to the workqueue, where can hold * cfg80211_mutex. */ if (likely(last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy_idx_valid(last_request->wiphy_idx))) goto out; request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) goto out; request->wiphy_idx = get_wiphy_idx(wiphy); request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE; request->country_ie_env = env; mutex_unlock(&reg_mutex); queue_regulatory_request(request); return; out: mutex_unlock(&reg_mutex); } static void restore_alpha2(char *alpha2, bool reset_user) { /* indicates there is no alpha2 to consider for restoration */ alpha2[0] = '9'; alpha2[1] = '7'; /* The user setting has precedence over the module parameter */ if (is_user_regdom_saved()) { /* Unless we're asked to ignore it and reset it */ if (reset_user) { REG_DBG_PRINT("Restoring regulatory settings " "including user preference\n"); user_alpha2[0] = '9'; user_alpha2[1] = '7'; /* * If we're ignoring user settings, we still need to * check the module parameter to ensure we put things * back as they were for a full restore. */ if (!is_world_regdom(ieee80211_regdom)) { REG_DBG_PRINT("Keeping preference on " "module parameter ieee80211_regdom: %c%c\n", ieee80211_regdom[0], ieee80211_regdom[1]); alpha2[0] = ieee80211_regdom[0]; alpha2[1] = ieee80211_regdom[1]; } } else { REG_DBG_PRINT("Restoring regulatory settings " "while preserving user preference for: %c%c\n", user_alpha2[0], user_alpha2[1]); alpha2[0] = user_alpha2[0]; alpha2[1] = user_alpha2[1]; } } else if (!is_world_regdom(ieee80211_regdom)) { REG_DBG_PRINT("Keeping preference on " "module parameter ieee80211_regdom: %c%c\n", ieee80211_regdom[0], ieee80211_regdom[1]); alpha2[0] = ieee80211_regdom[0]; alpha2[1] = ieee80211_regdom[1]; } else REG_DBG_PRINT("Restoring regulatory settings\n"); } static void restore_custom_reg_settings(struct wiphy *wiphy) { struct ieee80211_supported_band *sband; enum ieee80211_band band; struct ieee80211_channel *chan; int i; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { sband = wiphy->bands[band]; if (!sband) continue; for (i = 0; i < sband->n_channels; i++) { chan = &sband->channels[i]; chan->flags = chan->orig_flags; chan->max_antenna_gain = chan->orig_mag; chan->max_power = chan->orig_mpwr; } } } /* * Restoring regulatory settings involves ingoring any * possibly stale country IE information and user regulatory * settings if so desired, this includes any beacon hints * learned as we could have traveled outside to another country * after disconnection. To restore regulatory settings we do * exactly what we did at bootup: * * - send a core regulatory hint * - send a user regulatory hint if applicable * * Device drivers that send a regulatory hint for a specific country * keep their own regulatory domain on wiphy->regd so that does does * not need to be remembered. */ static void restore_regulatory_settings(bool reset_user) { char alpha2[2]; struct reg_beacon *reg_beacon, *btmp; struct regulatory_request *reg_request, *tmp; LIST_HEAD(tmp_reg_req_list); struct cfg80211_registered_device *rdev; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); reset_regdomains(); restore_alpha2(alpha2, reset_user); /* * If there's any pending requests we simply * stash them to a temporary pending queue and * add then after we've restored regulatory * settings. */ spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) { list_for_each_entry_safe(reg_request, tmp, &reg_requests_list, list) { if (reg_request->initiator != NL80211_REGDOM_SET_BY_USER) continue; list_del(&reg_request->list); list_add_tail(&reg_request->list, &tmp_reg_req_list); } } spin_unlock(&reg_requests_lock); /* Clear beacon hints */ spin_lock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_pending_beacons)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_unlock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_beacon_list)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } /* First restore to the basic regulatory settings */ cfg80211_regdomain = cfg80211_world_regdom; list_for_each_entry(rdev, &cfg80211_rdev_list, list) { if (rdev->wiphy.flags & WIPHY_FLAG_CUSTOM_REGULATORY) restore_custom_reg_settings(&rdev->wiphy); } mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); regulatory_hint_core(cfg80211_regdomain->alpha2); /* * This restores the ieee80211_regdom module parameter * preference or the last user requested regulatory * settings, user regulatory settings takes precedence. */ if (is_an_alpha2(alpha2)) regulatory_hint_user(user_alpha2); if (list_empty(&tmp_reg_req_list)) return; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); spin_lock(&reg_requests_lock); list_for_each_entry_safe(reg_request, tmp, &tmp_reg_req_list, list) { REG_DBG_PRINT("Adding request for country %c%c back " "into the queue\n", reg_request->alpha2[0], reg_request->alpha2[1]); list_del(&reg_request->list); list_add_tail(&reg_request->list, &reg_requests_list); } spin_unlock(&reg_requests_lock); mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); REG_DBG_PRINT("Kicking the queue\n"); schedule_work(&reg_work); } void regulatory_hint_disconnect(void) { REG_DBG_PRINT("All devices are disconnected, going to " "restore regulatory settings\n"); restore_regulatory_settings(false); } static bool freq_is_chan_12_13_14(u16 freq) { if (freq == ieee80211_channel_to_frequency(12, IEEE80211_BAND_2GHZ) || freq == ieee80211_channel_to_frequency(13, IEEE80211_BAND_2GHZ) || freq == ieee80211_channel_to_frequency(14, IEEE80211_BAND_2GHZ)) return true; return false; } int regulatory_hint_found_beacon(struct wiphy *wiphy, struct ieee80211_channel *beacon_chan, gfp_t gfp) { struct reg_beacon *reg_beacon; if (likely((beacon_chan->beacon_found || (beacon_chan->flags & IEEE80211_CHAN_RADAR) || (beacon_chan->band == IEEE80211_BAND_2GHZ && !freq_is_chan_12_13_14(beacon_chan->center_freq))))) return 0; reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp); if (!reg_beacon) return -ENOMEM; REG_DBG_PRINT("Found new beacon on " "frequency: %d MHz (Ch %d) on %s\n", beacon_chan->center_freq, ieee80211_frequency_to_channel(beacon_chan->center_freq), wiphy_name(wiphy)); memcpy(&reg_beacon->chan, beacon_chan, sizeof(struct ieee80211_channel)); /* * Since we can be called from BH or and non-BH context * we must use spin_lock_bh() */ spin_lock_bh(&reg_pending_beacons_lock); list_add_tail(&reg_beacon->list, &reg_pending_beacons); spin_unlock_bh(&reg_pending_beacons_lock); schedule_work(&reg_work); return 0; } static void print_rd_rules(const struct ieee80211_regdomain *rd) { unsigned int i; const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; const struct ieee80211_power_rule *power_rule = NULL; pr_info(" (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)\n"); for (i = 0; i < rd->n_reg_rules; i++) { reg_rule = &rd->reg_rules[i]; freq_range = &reg_rule->freq_range; power_rule = &reg_rule->power_rule; /* * There may not be documentation for max antenna gain * in certain regions */ if (power_rule->max_antenna_gain) pr_info(" (%d KHz - %d KHz @ %d KHz), (%d mBi, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, freq_range->max_bandwidth_khz, power_rule->max_antenna_gain, power_rule->max_eirp); else pr_info(" (%d KHz - %d KHz @ %d KHz), (N/A, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, freq_range->max_bandwidth_khz, power_rule->max_eirp); } } static void print_regdomain(const struct ieee80211_regdomain *rd) { if (is_intersected_alpha2(rd->alpha2)) { if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) { struct cfg80211_registered_device *rdev; rdev = cfg80211_rdev_by_wiphy_idx( last_request->wiphy_idx); if (rdev) { pr_info("Current regulatory domain updated by AP to: %c%c\n", rdev->country_ie_alpha2[0], rdev->country_ie_alpha2[1]); } else pr_info("Current regulatory domain intersected:\n"); } else pr_info("Current regulatory domain intersected:\n"); } else if (is_world_regdom(rd->alpha2)) pr_info("World regulatory domain updated:\n"); else { if (is_unknown_alpha2(rd->alpha2)) pr_info("Regulatory domain changed to driver built-in settings (unknown country)\n"); else pr_info("Regulatory domain changed to country: %c%c\n", rd->alpha2[0], rd->alpha2[1]); } print_rd_rules(rd); } static void print_regdomain_info(const struct ieee80211_regdomain *rd) { pr_info("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]); print_rd_rules(rd); } /* Takes ownership of rd only if it doesn't fail */ static int __set_regdom(const struct ieee80211_regdomain *rd) { const struct ieee80211_regdomain *intersected_rd = NULL; struct cfg80211_registered_device *rdev = NULL; struct wiphy *request_wiphy; /* Some basic sanity checks first */ if (is_world_regdom(rd->alpha2)) { if (WARN_ON(!reg_is_valid_request(rd->alpha2))) return -EINVAL; update_world_regdomain(rd); return 0; } if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) && !is_unknown_alpha2(rd->alpha2)) return -EINVAL; if (!last_request) return -EINVAL; /* * Lets only bother proceeding on the same alpha2 if the current * rd is non static (it means CRDA was present and was used last) * and the pending request came in from a country IE */ if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) { /* * If someone else asked us to change the rd lets only bother * checking if the alpha2 changes if CRDA was already called */ if (!regdom_changes(rd->alpha2)) return -EINVAL; } /* * Now lets set the regulatory domain, update all driver channels * and finally inform them of what we have done, in case they want * to review or adjust their own settings based on their own * internal EEPROM data */ if (WARN_ON(!reg_is_valid_request(rd->alpha2))) return -EINVAL; if (!is_valid_rd(rd)) { pr_err("Invalid regulatory domain detected:\n"); print_regdomain_info(rd); return -EINVAL; } request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (!last_request->intersect) { int r; if (last_request->initiator != NL80211_REGDOM_SET_BY_DRIVER) { reset_regdomains(); cfg80211_regdomain = rd; return 0; } /* * For a driver hint, lets copy the regulatory domain the * driver wanted to the wiphy to deal with conflicts */ /* * Userspace could have sent two replies with only * one kernel request. */ if (request_wiphy->regd) return -EALREADY; r = reg_copy_regd(&request_wiphy->regd, rd); if (r) return r; reset_regdomains(); cfg80211_regdomain = rd; return 0; } /* Intersection requires a bit more work */ if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) { intersected_rd = regdom_intersect(rd, cfg80211_regdomain); if (!intersected_rd) return -EINVAL; /* * We can trash what CRDA provided now. * However if a driver requested this specific regulatory * domain we keep it for its private use */ if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) request_wiphy->regd = rd; else kfree(rd); rd = NULL; reset_regdomains(); cfg80211_regdomain = intersected_rd; return 0; } if (!intersected_rd) return -EINVAL; rdev = wiphy_to_dev(request_wiphy); rdev->country_ie_alpha2[0] = rd->alpha2[0]; rdev->country_ie_alpha2[1] = rd->alpha2[1]; rdev->env = last_request->country_ie_env; BUG_ON(intersected_rd == rd); kfree(rd); rd = NULL; reset_regdomains(); cfg80211_regdomain = intersected_rd; return 0; } /* * Use this call to set the current regulatory domain. Conflicts with * multiple drivers can be ironed out later. Caller must've already * kmalloc'd the rd structure. Caller must hold cfg80211_mutex */ int set_regdom(const struct ieee80211_regdomain *rd) { int r; assert_cfg80211_lock(); mutex_lock(&reg_mutex); /* Note that this doesn't update the wiphys, this is done below */ r = __set_regdom(rd); if (r) { kfree(rd); mutex_unlock(&reg_mutex); return r; } /* This would make this whole thing pointless */ if (!last_request->intersect) BUG_ON(rd != cfg80211_regdomain); /* update all wiphys now with the new established regulatory domain */ update_all_wiphy_regulatory(last_request->initiator); print_regdomain(cfg80211_regdomain); nl80211_send_reg_change_event(last_request); reg_set_request_processed(); mutex_unlock(&reg_mutex); return r; } #ifdef CONFIG_HOTPLUG int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env) { if (last_request && !last_request->processed) { if (add_uevent_var(env, "COUNTRY=%c%c", last_request->alpha2[0], last_request->alpha2[1])) return -ENOMEM; } return 0; } #else int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env) { return -ENODEV; } #endif /* CONFIG_HOTPLUG */ /* Caller must hold cfg80211_mutex */ void reg_device_remove(struct wiphy *wiphy) { struct wiphy *request_wiphy = NULL; assert_cfg80211_lock(); mutex_lock(&reg_mutex); kfree(wiphy->regd); if (last_request) request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (!request_wiphy || request_wiphy != wiphy) goto out; last_request->wiphy_idx = WIPHY_IDX_STALE; last_request->country_ie_env = ENVIRON_ANY; out: mutex_unlock(&reg_mutex); } static void reg_timeout_work(struct work_struct *work) { REG_DBG_PRINT("Timeout while waiting for CRDA to reply, " "restoring regulatory settings"); restore_regulatory_settings(true); } int __init regulatory_init(void) { int err = 0; reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0); if (IS_ERR(reg_pdev)) return PTR_ERR(reg_pdev); reg_pdev->dev.type = &reg_device_type; spin_lock_init(&reg_requests_lock); spin_lock_init(&reg_pending_beacons_lock); cfg80211_regdomain = cfg80211_world_regdom; user_alpha2[0] = '9'; user_alpha2[1] = '7'; /* We always try to get an update for the static regdomain */ err = regulatory_hint_core(cfg80211_regdomain->alpha2); if (err) { if (err == -ENOMEM) return err; /* * N.B. kobject_uevent_env() can fail mainly for when we're out * memory which is handled and propagated appropriately above * but it can also fail during a netlink_broadcast() or during * early boot for call_usermodehelper(). For now treat these * errors as non-fatal. */ pr_err("kobject_uevent_env() was unable to call CRDA during init\n"); #ifdef CONFIG_CFG80211_REG_DEBUG /* We want to find out exactly why when debugging */ WARN_ON(err); #endif } /* * Finally, if the user set the module parameter treat it * as a user hint. */ if (!is_world_regdom(ieee80211_regdom)) regulatory_hint_user(ieee80211_regdom); return 0; } void /* __init_or_exit */ regulatory_exit(void) { struct regulatory_request *reg_request, *tmp; struct reg_beacon *reg_beacon, *btmp; cancel_work_sync(&reg_work); cancel_delayed_work_sync(&reg_timeout); mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); reset_regdomains(); kfree(last_request); platform_device_unregister(reg_pdev); spin_lock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_pending_beacons)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_unlock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_beacon_list)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) { list_for_each_entry_safe(reg_request, tmp, &reg_requests_list, list) { list_del(&reg_request->list); kfree(reg_request); } } spin_unlock(&reg_requests_lock); mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); }
vSlipenchuk/ac100hd
net/wireless/reg.c
C
gpl-2.0
61,693
/* * pcm audio input device * * Copyright (C) 2008 Google, Inc. * Copyright (C) 2008 HTC Corporation * Copyright (c) 2009-2010, Code Aurora Forum. All rights reserved. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <mach/debug_audio_mm.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/miscdevice.h> #include <linux/uaccess.h> #include <linux/sched.h> #include <linux/wait.h> #include <linux/dma-mapping.h> #include <linux/msm_audio.h> #include <asm/atomic.h> #include <asm/ioctls.h> #include <mach/msm_adsp.h> #include <mach/qdsp5v2/qdsp5audreccmdi.h> #include <mach/qdsp5v2/qdsp5audrecmsg.h> #include <mach/qdsp5v2/audpreproc.h> #include <mach/qdsp5v2/audio_dev_ctl.h> /* FRAME_NUM must be a power of two */ #define FRAME_NUM (8) #define FRAME_SIZE (2052 * 2) #define MONO_DATA_SIZE (2048) #define STEREO_DATA_SIZE (MONO_DATA_SIZE * 2) #define DMASZ (FRAME_SIZE * FRAME_NUM) struct buffer { void *data; uint32_t size; uint32_t read; uint32_t addr; }; struct audio_in { struct buffer in[FRAME_NUM]; spinlock_t dsp_lock; atomic_t in_bytes; atomic_t in_samples; struct mutex lock; struct mutex read_lock; wait_queue_head_t wait; wait_queue_head_t wait_enable; struct msm_adsp_module *audrec; /* configuration to use on next enable */ uint32_t samp_rate; uint32_t channel_mode; uint32_t buffer_size; /* 2048 for mono, 4096 for stereo */ uint32_t enc_type; uint32_t dsp_cnt; uint32_t in_head; /* next buffer dsp will write */ uint32_t in_tail; /* next buffer read() will read */ uint32_t in_count; /* number of buffers available to read() */ const char *module_name; unsigned queue_ids; uint16_t enc_id; /* Session Id */ uint16_t source; /* Encoding source bit mask */ uint32_t device_events; /* device events interested in */ uint32_t dev_cnt; spinlock_t dev_lock; /* data allocated for various buffers */ char *data; dma_addr_t phys; int opened; int enabled; int running; int stopped; /* set when stopped, cleared on flush */ int abort; /* set when error, like sample rate mismatch */ }; static struct audio_in the_audio_in; struct audio_frame { uint16_t frame_count_lsw; uint16_t frame_count_msw; uint16_t frame_length; uint16_t erased_pcm; unsigned char raw_bitstream[]; /* samples */ } __attribute__((packed)); /* Audrec Queue command sent macro's */ #define audrec_send_bitstreamqueue(audio, cmd, len) \ msm_adsp_write(audio->audrec, ((audio->queue_ids & 0xFFFF0000) >> 16),\ cmd, len) #define audrec_send_audrecqueue(audio, cmd, len) \ msm_adsp_write(audio->audrec, (audio->queue_ids & 0x0000FFFF),\ cmd, len) /* DSP command send functions */ static int audpcm_in_enc_config(struct audio_in *audio, int enable); static int audpcm_in_param_config(struct audio_in *audio); static int audpcm_in_mem_config(struct audio_in *audio); static int audpcm_in_record_config(struct audio_in *audio, int enable); static int audpcm_dsp_read_buffer(struct audio_in *audio, uint32_t read_cnt); static void audpcm_in_get_dsp_frames(struct audio_in *audio); static void audpcm_in_flush(struct audio_in *audio); static void pcm_in_listener(u32 evt_id, union auddev_evt_data *evt_payload, void *private_data) { struct audio_in *audio = (struct audio_in *) private_data; unsigned long flags; MM_DBG("evt_id = 0x%8x\n", evt_id); switch (evt_id) { case AUDDEV_EVT_DEV_RDY: { MM_DBG("AUDDEV_EVT_DEV_RDY\n"); spin_lock_irqsave(&audio->dev_lock, flags); audio->dev_cnt++; audio->source |= (0x1 << evt_payload->routing_id); spin_unlock_irqrestore(&audio->dev_lock, flags); if ((audio->running == 1) && (audio->enabled == 1)) audpcm_in_record_config(audio, 1); break; } case AUDDEV_EVT_DEV_RLS: { MM_DBG("AUDDEV_EVT_DEV_RLS\n"); spin_lock_irqsave(&audio->dev_lock, flags); audio->dev_cnt--; audio->source &= ~(0x1 << evt_payload->routing_id); spin_unlock_irqrestore(&audio->dev_lock, flags); if (!audio->running || !audio->enabled) break; /* Turn of as per source */ if (audio->source) audpcm_in_record_config(audio, 1); else /* Turn off all */ audpcm_in_record_config(audio, 0); break; } case AUDDEV_EVT_FREQ_CHG: { MM_DBG("Encoder Driver got sample rate change event\n"); MM_DBG("sample rate %d\n", evt_payload->freq_info.sample_rate); MM_DBG("dev_type %d\n", evt_payload->freq_info.dev_type); MM_DBG("acdb_dev_id %d\n", evt_payload->freq_info.acdb_dev_id); if (audio->running == 1) { /* Stop Recording sample rate does not match with device sample rate */ if (evt_payload->freq_info.sample_rate != audio->samp_rate) { audpcm_in_record_config(audio, 0); audio->abort = 1; wake_up(&audio->wait); } } break; } default: MM_ERR("wrong event %d\n", evt_id); break; } } /* ------------------- dsp preproc event handler--------------------- */ static void audpreproc_dsp_event(void *data, unsigned id, void *msg) { struct audio_in *audio = data; switch (id) { case AUDPREPROC_ERROR_MSG: { struct audpreproc_err_msg *err_msg = msg; MM_ERR("ERROR_MSG: stream id %d err idx %d\n", err_msg->stream_id, err_msg->aud_preproc_err_idx); /* Error case */ wake_up(&audio->wait_enable); break; } case AUDPREPROC_CMD_CFG_DONE_MSG: { MM_DBG("CMD_CFG_DONE_MSG \n"); break; } case AUDPREPROC_CMD_ENC_CFG_DONE_MSG: { struct audpreproc_cmd_enc_cfg_done_msg *enc_cfg_msg = msg; MM_DBG("CMD_ENC_CFG_DONE_MSG: stream id %d enc type \ 0x%8x\n", enc_cfg_msg->stream_id, enc_cfg_msg->rec_enc_type); /* Encoder enable success */ if (enc_cfg_msg->rec_enc_type & ENCODE_ENABLE) audpcm_in_param_config(audio); else { /* Encoder disable success */ audio->running = 0; audpcm_in_record_config(audio, 0); } break; } case AUDPREPROC_CMD_ENC_PARAM_CFG_DONE_MSG: { MM_DBG("CMD_ENC_PARAM_CFG_DONE_MSG \n"); audpcm_in_mem_config(audio); break; } case AUDPREPROC_AFE_CMD_AUDIO_RECORD_CFG_DONE_MSG: { MM_DBG("AFE_CMD_AUDIO_RECORD_CFG_DONE_MSG \n"); wake_up(&audio->wait_enable); break; } default: MM_ERR("Unknown Event id %d\n", id); } } /* ------------------- dsp audrec event handler--------------------- */ static void audrec_dsp_event(void *data, unsigned id, size_t len, void (*getevent)(void *ptr, size_t len)) { struct audio_in *audio = data; switch (id) { case AUDREC_CMD_MEM_CFG_DONE_MSG: { MM_DBG("CMD_MEM_CFG_DONE MSG DONE\n"); audio->running = 1; if (audio->dev_cnt > 0) audpcm_in_record_config(audio, 1); break; } case AUDREC_FATAL_ERR_MSG: { struct audrec_fatal_err_msg fatal_err_msg; getevent(&fatal_err_msg, AUDREC_FATAL_ERR_MSG_LEN); MM_ERR("FATAL_ERR_MSG: err id %d\n", fatal_err_msg.audrec_err_id); /* Error stop the encoder */ audio->stopped = 1; wake_up(&audio->wait); break; } case AUDREC_UP_PACKET_READY_MSG: { struct audrec_up_pkt_ready_msg pkt_ready_msg; getevent(&pkt_ready_msg, AUDREC_UP_PACKET_READY_MSG_LEN); MM_DBG("UP_PACKET_READY_MSG: write cnt lsw %d \ write cnt msw %d read cnt lsw %d read cnt msw %d \n",\ pkt_ready_msg.audrec_packet_write_cnt_lsw, \ pkt_ready_msg.audrec_packet_write_cnt_msw, \ pkt_ready_msg.audrec_up_prev_read_cnt_lsw, \ pkt_ready_msg.audrec_up_prev_read_cnt_msw); audpcm_in_get_dsp_frames(audio); break; } default: MM_ERR("Unknown Event id %d\n", id); } } static void audpcm_in_get_dsp_frames(struct audio_in *audio) { struct audio_frame *frame; uint32_t index; unsigned long flags; index = audio->in_head; frame = (void *) (((char *)audio->in[index].data) - \ sizeof(*frame)); spin_lock_irqsave(&audio->dsp_lock, flags); audio->in[index].size = frame->frame_length; /* statistics of read */ atomic_add(audio->in[index].size, &audio->in_bytes); atomic_add(1, &audio->in_samples); audio->in_head = (audio->in_head + 1) & (FRAME_NUM - 1); /* If overflow, move the tail index foward. */ if (audio->in_head == audio->in_tail) audio->in_tail = (audio->in_tail + 1) & (FRAME_NUM - 1); else audio->in_count++; audpcm_dsp_read_buffer(audio, audio->dsp_cnt++); spin_unlock_irqrestore(&audio->dsp_lock, flags); wake_up(&audio->wait); } struct msm_adsp_ops audrec_adsp_ops = { .event = audrec_dsp_event, }; static int audpcm_in_enc_config(struct audio_in *audio, int enable) { struct audpreproc_audrec_cmd_enc_cfg cmd; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = AUDPREPROC_AUDREC_CMD_ENC_CFG; cmd.stream_id = audio->enc_id; if (enable) cmd.audrec_enc_type = audio->enc_type | ENCODE_ENABLE; else cmd.audrec_enc_type &= ~(ENCODE_ENABLE); return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd)); } static int audpcm_in_param_config(struct audio_in *audio) { struct audpreproc_audrec_cmd_parm_cfg_wav cmd; memset(&cmd, 0, sizeof(cmd)); cmd.common.cmd_id = AUDPREPROC_AUDREC_CMD_PARAM_CFG; cmd.common.stream_id = audio->enc_id; cmd.aud_rec_samplerate_idx = audio->samp_rate; cmd.aud_rec_stereo_mode = audio->channel_mode; return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd)); } /* To Do: msm_snddev_route_enc(audio->enc_id); */ static int audpcm_in_record_config(struct audio_in *audio, int enable) { struct audpreproc_afe_cmd_audio_record_cfg cmd; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = AUDPREPROC_AFE_CMD_AUDIO_RECORD_CFG; cmd.stream_id = audio->enc_id; if (enable) cmd.destination_activity = AUDIO_RECORDING_TURN_ON; else cmd.destination_activity = AUDIO_RECORDING_TURN_OFF; cmd.source_mix_mask = audio->source; return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd)); } static int audpcm_in_mem_config(struct audio_in *audio) { struct audrec_cmd_arecmem_cfg cmd; uint16_t *data = (void *) audio->data; int n; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = AUDREC_CMD_MEM_CFG_CMD; cmd.audrec_up_pkt_intm_count = 1; cmd.audrec_ext_pkt_start_addr_msw = audio->phys >> 16; cmd.audrec_ext_pkt_start_addr_lsw = audio->phys; cmd.audrec_ext_pkt_buf_number = FRAME_NUM; /* prepare buffer pointers: * Mono: 1024 samples + 4 halfword header * Stereo: 2048 samples + 4 halfword header */ for (n = 0; n < FRAME_NUM; n++) { audio->in[n].data = data + 4; data += (4 + (audio->channel_mode ? 2048 : 1024)); MM_DBG("0x%8x\n", (int)(audio->in[n].data - 8)); } return audrec_send_audrecqueue(audio, &cmd, sizeof(cmd)); } static int audpcm_dsp_read_buffer(struct audio_in *audio, uint32_t read_cnt) { struct up_audrec_packet_ext_ptr cmd; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = UP_AUDREC_PACKET_EXT_PTR; cmd.audrec_up_curr_read_count_msw = read_cnt >> 16; cmd.audrec_up_curr_read_count_lsw = read_cnt; return audrec_send_bitstreamqueue(audio, &cmd, sizeof(cmd)); } /* must be called with audio->lock held */ static int audpcm_in_enable(struct audio_in *audio) { if (audio->enabled) return 0; if (audpreproc_enable(audio->enc_id, &audpreproc_dsp_event, audio)) { MM_ERR("msm_adsp_enable(audpreproc) failed\n"); return -ENODEV; } if (msm_adsp_enable(audio->audrec)) { MM_ERR("msm_adsp_enable(audrec) failed\n"); audpreproc_disable(audio->enc_id, audio); return -ENODEV; } audio->enabled = 1; audpcm_in_enc_config(audio, 1); return 0; } /* must be called with audio->lock held */ static int audpcm_in_disable(struct audio_in *audio) { if (audio->enabled) { audio->enabled = 0; audpcm_in_enc_config(audio, 0); wake_up(&audio->wait); wait_event_interruptible_timeout(audio->wait_enable, audio->running == 0, 1*HZ); msm_adsp_disable(audio->audrec); audpreproc_disable(audio->enc_id, audio); } return 0; } static void audpcm_in_flush(struct audio_in *audio) { int i; audio->dsp_cnt = 0; audio->in_head = 0; audio->in_tail = 0; audio->in_count = 0; for (i = 0; i < FRAME_NUM; i++) { audio->in[i].size = 0; audio->in[i].read = 0; } MM_DBG("in_bytes %d\n", atomic_read(&audio->in_bytes)); MM_DBG("in_samples %d\n", atomic_read(&audio->in_samples)); atomic_set(&audio->in_bytes, 0); atomic_set(&audio->in_samples, 0); } /* ------------------- device --------------------- */ static long audpcm_in_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct audio_in *audio = file->private_data; int rc = 0; if (cmd == AUDIO_GET_STATS) { struct msm_audio_stats stats; stats.byte_count = atomic_read(&audio->in_bytes); stats.sample_count = atomic_read(&audio->in_samples); if (copy_to_user((void *) arg, &stats, sizeof(stats))) return -EFAULT; return rc; } mutex_lock(&audio->lock); switch (cmd) { case AUDIO_START: { uint32_t freq; /* Poll at 48KHz always */ freq = 48000; MM_DBG("AUDIO_START\n"); rc = msm_snddev_request_freq(&freq, audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); MM_DBG("sample rate configured %d sample rate requested %d\n", freq, audio->samp_rate); if (rc < 0) { MM_DBG("sample rate can not be set, return code %d\n",\ rc); msm_snddev_withdraw_freq(audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); MM_DBG("msm_snddev_withdraw_freq\n"); break; } rc = audpcm_in_enable(audio); if (!rc) { rc = wait_event_interruptible_timeout(audio->wait_enable, audio->running != 0, 1*HZ); MM_DBG("state %d rc = %d\n", audio->running, rc); if (audio->running == 0) rc = -ENODEV; else rc = 0; } break; } case AUDIO_STOP: { rc = audpcm_in_disable(audio); rc = msm_snddev_withdraw_freq(audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); MM_DBG("msm_snddev_withdraw_freq\n"); audio->stopped = 1; audio->abort = 0; break; } case AUDIO_FLUSH: { if (audio->stopped) { /* Make sure we're stopped and we wake any threads * that might be blocked holding the read_lock. * While audio->stopped read threads will always * exit immediately. */ wake_up(&audio->wait); mutex_lock(&audio->read_lock); audpcm_in_flush(audio); mutex_unlock(&audio->read_lock); } break; } case AUDIO_SET_CONFIG: { struct msm_audio_config cfg; if (copy_from_user(&cfg, (void *) arg, sizeof(cfg))) { rc = -EFAULT; break; } if (cfg.channel_count == 1) { cfg.channel_count = AUDREC_CMD_MODE_MONO; } else if (cfg.channel_count == 2) { cfg.channel_count = AUDREC_CMD_MODE_STEREO; } else { rc = -EINVAL; break; } audio->samp_rate = cfg.sample_rate; audio->channel_mode = cfg.channel_count; audio->buffer_size = audio->channel_mode ? STEREO_DATA_SIZE : \ MONO_DATA_SIZE; break; } case AUDIO_GET_CONFIG: { struct msm_audio_config cfg; memset(&cfg, 0, sizeof(cfg)); cfg.buffer_size = audio->buffer_size; cfg.buffer_count = FRAME_NUM; cfg.sample_rate = audio->samp_rate; if (audio->channel_mode == AUDREC_CMD_MODE_MONO) cfg.channel_count = 1; else cfg.channel_count = 2; if (copy_to_user((void *) arg, &cfg, sizeof(cfg))) rc = -EFAULT; break; } case AUDIO_GET_SESSION_ID: { if (copy_to_user((void *) arg, &audio->enc_id, sizeof(unsigned short))) { rc = -EFAULT; } break; } default: rc = -EINVAL; } mutex_unlock(&audio->lock); return rc; } static ssize_t audpcm_in_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { struct audio_in *audio = file->private_data; unsigned long flags; const char __user *start = buf; void *data; uint32_t index; uint32_t size; int rc = 0; mutex_lock(&audio->read_lock); while (count > 0) { rc = wait_event_interruptible( audio->wait, (audio->in_count > 0) || audio->stopped || audio->abort); if (rc < 0) break; if (audio->stopped && !audio->in_count) { MM_DBG("Driver in stop state, No more buffer to read"); rc = 0;/* End of File */ break; } if (audio->abort) { rc = -EPERM; /* Not permitted due to abort */ break; } index = audio->in_tail; data = (uint8_t *) audio->in[index].data; size = audio->in[index].size; if (count >= size) { if (copy_to_user(buf, data, size)) { rc = -EFAULT; break; } spin_lock_irqsave(&audio->dsp_lock, flags); if (index != audio->in_tail) { /* overrun -- data is * invalid and we need to retry */ spin_unlock_irqrestore(&audio->dsp_lock, flags); continue; } audio->in[index].size = 0; audio->in_tail = (audio->in_tail + 1) & (FRAME_NUM - 1); audio->in_count--; spin_unlock_irqrestore(&audio->dsp_lock, flags); count -= size; buf += size; } else { MM_ERR("short read\n"); break; } } mutex_unlock(&audio->read_lock); if (buf > start) return buf - start; return rc; } static ssize_t audpcm_in_write(struct file *file, const char __user *buf, size_t count, loff_t *pos) { return -EINVAL; } static int audpcm_in_release(struct inode *inode, struct file *file) { struct audio_in *audio = file->private_data; mutex_lock(&audio->lock); /* with draw frequency for session incase not stopped the driver */ msm_snddev_withdraw_freq(audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); auddev_unregister_evt_listner(AUDDEV_CLNT_ENC, audio->enc_id); audpcm_in_disable(audio); audpcm_in_flush(audio); msm_adsp_put(audio->audrec); audpreproc_aenc_free(audio->enc_id); audio->audrec = NULL; audio->opened = 0; mutex_unlock(&audio->lock); return 0; } static int audpcm_in_open(struct inode *inode, struct file *file) { struct audio_in *audio = &the_audio_in; int rc; int encid; mutex_lock(&audio->lock); if (audio->opened) { rc = -EBUSY; goto done; } /* Settings will be re-config at AUDIO_SET_CONFIG, * but at least we need to have initial config */ audio->channel_mode = AUDREC_CMD_MODE_MONO; audio->buffer_size = MONO_DATA_SIZE; audio->samp_rate = 8000; audio->enc_type = ENC_TYPE_WAV; audio->source = INTERNAL_CODEC_TX_SOURCE_MIX_MASK; encid = audpreproc_aenc_alloc(audio->enc_type, &audio->module_name, &audio->queue_ids); if (encid < 0) { MM_ERR("No free encoder available\n"); rc = -ENODEV; goto done; } audio->enc_id = encid; rc = msm_adsp_get(audio->module_name, &audio->audrec, &audrec_adsp_ops, audio); if (rc) { audpreproc_aenc_free(audio->enc_id); goto done; } audio->stopped = 0; audio->source = 0; audio->abort = 0; audpcm_in_flush(audio); audio->device_events = AUDDEV_EVT_DEV_RDY | AUDDEV_EVT_DEV_RLS | AUDDEV_EVT_FREQ_CHG; rc = auddev_register_evt_listner(audio->device_events, AUDDEV_CLNT_ENC, audio->enc_id, pcm_in_listener, (void *) audio); if (rc) { MM_ERR("failed to register device event listener\n"); goto evt_error; } file->private_data = audio; audio->opened = 1; rc = 0; done: mutex_unlock(&audio->lock); return rc; evt_error: msm_adsp_put(audio->audrec); audpreproc_aenc_free(audio->enc_id); mutex_unlock(&audio->lock); return rc; } static const struct file_operations audio_in_fops = { .owner = THIS_MODULE, .open = audpcm_in_open, .release = audpcm_in_release, .read = audpcm_in_read, .write = audpcm_in_write, .unlocked_ioctl = audpcm_in_ioctl, }; struct miscdevice audio_in_misc = { .minor = MISC_DYNAMIC_MINOR, .name = "msm_pcm_in", .fops = &audio_in_fops, }; static int __init audpcm_in_init(void) { the_audio_in.data = dma_alloc_coherent(NULL, DMASZ, &the_audio_in.phys, GFP_KERNEL); MM_DBG("Memory addr = 0x%8x phy addr = 0x%8x ---- \n", \ (int) the_audio_in.data, (int) the_audio_in.phys); if (!the_audio_in.data) { MM_ERR("Unable to allocate DMA buffer\n"); return -ENOMEM; } mutex_init(&the_audio_in.lock); mutex_init(&the_audio_in.read_lock); spin_lock_init(&the_audio_in.dsp_lock); spin_lock_init(&the_audio_in.dev_lock); init_waitqueue_head(&the_audio_in.wait); init_waitqueue_head(&the_audio_in.wait_enable); return misc_register(&audio_in_misc); } device_initcall(audpcm_in_init);
marcOcram/Acer-Liquid-MT-Kernel
arch/arm/mach-msm/qdsp5v2/audio_pcm_in.c
C
gpl-2.0
20,064
/* linux/arch/arm/mach-s3c2410/mach-bast.c * * Copyright 2003-2008 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * * http://www.simtec.co.uk/products/EB2410ITX/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/interrupt.h> #include <linux/list.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/gpio.h> #include <linux/syscore_ops.h> #include <linux/serial_core.h> #include <linux/platform_device.h> #include <linux/dm9000.h> #include <linux/ata_platform.h> #include <linux/i2c.h> #include <linux/io.h> #include <linux/serial_8250.h> #include <linux/mtd/mtd.h> #include <linux/mtd/nand.h> #include <linux/mtd/nand_ecc.h> #include <linux/mtd/partitions.h> #include <linux/platform_data/asoc-s3c24xx_simtec.h> #include <linux/platform_data/hwmon-s3c.h> #include <linux/platform_data/i2c-s3c2410.h> #include <linux/platform_data/mtd-nand-s3c2410.h> #include <net/ax88796.h> #include <asm/irq.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <asm/mach/irq.h> #include <asm/mach-types.h> #include <mach/fb.h> #include <mach/hardware.h> #include <mach/regs-gpio.h> #include <mach/regs-lcd.h> #include <mach/regs-mem.h> #include <plat/clock.h> #include <plat/cpu.h> #include <plat/cpu-freq.h> #include <plat/devs.h> #include <plat/gpio-cfg.h> #include <plat/regs-serial.h> #include "bast.h" #include "common.h" #include "simtec.h" #define COPYRIGHT ", Copyright 2004-2008 Simtec Electronics" /* macros for virtual address mods for the io space entries */ #define VA_C5(item) ((unsigned long)(item) + BAST_VAM_CS5) #define VA_C4(item) ((unsigned long)(item) + BAST_VAM_CS4) #define VA_C3(item) ((unsigned long)(item) + BAST_VAM_CS3) #define VA_C2(item) ((unsigned long)(item) + BAST_VAM_CS2) /* macros to modify the physical addresses for io space */ #define PA_CS2(item) (__phys_to_pfn((item) + S3C2410_CS2)) #define PA_CS3(item) (__phys_to_pfn((item) + S3C2410_CS3)) #define PA_CS4(item) (__phys_to_pfn((item) + S3C2410_CS4)) #define PA_CS5(item) (__phys_to_pfn((item) + S3C2410_CS5)) static struct map_desc bast_iodesc[] __initdata = { /* ISA IO areas */ { .virtual = (u32)S3C24XX_VA_ISA_BYTE, .pfn = PA_CS2(BAST_PA_ISAIO), .length = SZ_16M, .type = MT_DEVICE, }, { .virtual = (u32)S3C24XX_VA_ISA_WORD, .pfn = PA_CS3(BAST_PA_ISAIO), .length = SZ_16M, .type = MT_DEVICE, }, /* bast CPLD control registers, and external interrupt controls */ { .virtual = (u32)BAST_VA_CTRL1, .pfn = __phys_to_pfn(BAST_PA_CTRL1), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_CTRL2, .pfn = __phys_to_pfn(BAST_PA_CTRL2), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_CTRL3, .pfn = __phys_to_pfn(BAST_PA_CTRL3), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_CTRL4, .pfn = __phys_to_pfn(BAST_PA_CTRL4), .length = SZ_1M, .type = MT_DEVICE, }, /* PC104 IRQ mux */ { .virtual = (u32)BAST_VA_PC104_IRQREQ, .pfn = __phys_to_pfn(BAST_PA_PC104_IRQREQ), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_PC104_IRQRAW, .pfn = __phys_to_pfn(BAST_PA_PC104_IRQRAW), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_PC104_IRQMASK, .pfn = __phys_to_pfn(BAST_PA_PC104_IRQMASK), .length = SZ_1M, .type = MT_DEVICE, }, /* peripheral space... one for each of fast/slow/byte/16bit */ /* note, ide is only decoded in word space, even though some registers * are only 8bit */ /* slow, byte */ { VA_C2(BAST_VA_ISAIO), PA_CS2(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C2(BAST_VA_ISAMEM), PA_CS2(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C2(BAST_VA_SUPERIO), PA_CS2(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, /* slow, word */ { VA_C3(BAST_VA_ISAIO), PA_CS3(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C3(BAST_VA_ISAMEM), PA_CS3(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C3(BAST_VA_SUPERIO), PA_CS3(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, /* fast, byte */ { VA_C4(BAST_VA_ISAIO), PA_CS4(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C4(BAST_VA_ISAMEM), PA_CS4(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C4(BAST_VA_SUPERIO), PA_CS4(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, /* fast, word */ { VA_C5(BAST_VA_ISAIO), PA_CS5(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C5(BAST_VA_ISAMEM), PA_CS5(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C5(BAST_VA_SUPERIO), PA_CS5(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, }; #define UCON S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK #define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB #define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE static struct s3c2410_uartcfg bast_uartcfgs[] __initdata = { [0] = { .hwport = 0, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, }, [1] = { .hwport = 1, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, }, /* port 2 is not actually used */ [2] = { .hwport = 2, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, } }; /* NAND Flash on BAST board */ #ifdef CONFIG_PM static int bast_pm_suspend(void) { /* ensure that an nRESET is not generated on resume. */ gpio_direction_output(S3C2410_GPA(21), 1); return 0; } static void bast_pm_resume(void) { s3c_gpio_cfgpin(S3C2410_GPA(21), S3C2410_GPA21_nRSTOUT); } #else #define bast_pm_suspend NULL #define bast_pm_resume NULL #endif static struct syscore_ops bast_pm_syscore_ops = { .suspend = bast_pm_suspend, .resume = bast_pm_resume, }; static int smartmedia_map[] = { 0 }; static int chip0_map[] = { 1 }; static int chip1_map[] = { 2 }; static int chip2_map[] = { 3 }; static struct mtd_partition __initdata bast_default_nand_part[] = { [0] = { .name = "Boot Agent", .size = SZ_16K, .offset = 0, }, [1] = { .name = "/boot", .size = SZ_4M - SZ_16K, .offset = SZ_16K, }, [2] = { .name = "user", .offset = SZ_4M, .size = MTDPART_SIZ_FULL, } }; /* the bast has 4 selectable slots for nand-flash, the three * on-board chip areas, as well as the external SmartMedia * slot. * * Note, there is no current hot-plug support for the SmartMedia * socket. */ static struct s3c2410_nand_set __initdata bast_nand_sets[] = { [0] = { .name = "SmartMedia", .nr_chips = 1, .nr_map = smartmedia_map, .options = NAND_SCAN_SILENT_NODEV, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, }, [1] = { .name = "chip0", .nr_chips = 1, .nr_map = chip0_map, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, }, [2] = { .name = "chip1", .nr_chips = 1, .nr_map = chip1_map, .options = NAND_SCAN_SILENT_NODEV, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, }, [3] = { .name = "chip2", .nr_chips = 1, .nr_map = chip2_map, .options = NAND_SCAN_SILENT_NODEV, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, } }; static void bast_nand_select(struct s3c2410_nand_set *set, int slot) { unsigned int tmp; slot = set->nr_map[slot] & 3; pr_debug("bast_nand: selecting slot %d (set %p,%p)\n", slot, set, set->nr_map); tmp = __raw_readb(BAST_VA_CTRL2); tmp &= BAST_CPLD_CTLR2_IDERST; tmp |= slot; tmp |= BAST_CPLD_CTRL2_WNAND; pr_debug("bast_nand: ctrl2 now %02x\n", tmp); __raw_writeb(tmp, BAST_VA_CTRL2); } static struct s3c2410_platform_nand __initdata bast_nand_info = { .tacls = 30, .twrph0 = 60, .twrph1 = 60, .nr_sets = ARRAY_SIZE(bast_nand_sets), .sets = bast_nand_sets, .select_chip = bast_nand_select, }; /* DM9000 */ static struct resource bast_dm9k_resource[] = { [0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_DM9000, 4), [1] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_DM9000 + 0x40, 0x40), [2] = DEFINE_RES_NAMED(BAST_IRQ_DM9000 , 1, NULL, IORESOURCE_IRQ \ | IORESOURCE_IRQ_HIGHLEVEL), }; /* for the moment we limit ourselves to 16bit IO until some * better IO routines can be written and tested */ static struct dm9000_plat_data bast_dm9k_platdata = { .flags = DM9000_PLATF_16BITONLY, }; static struct platform_device bast_device_dm9k = { .name = "dm9000", .id = 0, .num_resources = ARRAY_SIZE(bast_dm9k_resource), .resource = bast_dm9k_resource, .dev = { .platform_data = &bast_dm9k_platdata, } }; /* serial devices */ #define SERIAL_BASE (S3C2410_CS2 + BAST_PA_SUPERIO) #define SERIAL_FLAGS (UPF_BOOT_AUTOCONF | UPF_IOREMAP | UPF_SHARE_IRQ) #define SERIAL_CLK (1843200) static struct plat_serial8250_port bast_sio_data[] = { [0] = { .mapbase = SERIAL_BASE + 0x2f8, .irq = BAST_IRQ_PCSERIAL1, .flags = SERIAL_FLAGS, .iotype = UPIO_MEM, .regshift = 0, .uartclk = SERIAL_CLK, }, [1] = { .mapbase = SERIAL_BASE + 0x3f8, .irq = BAST_IRQ_PCSERIAL2, .flags = SERIAL_FLAGS, .iotype = UPIO_MEM, .regshift = 0, .uartclk = SERIAL_CLK, }, { } }; static struct platform_device bast_sio = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = &bast_sio_data, }, }; /* we have devices on the bus which cannot work much over the * standard 100KHz i2c bus frequency */ static struct s3c2410_platform_i2c __initdata bast_i2c_info = { .flags = 0, .slave_addr = 0x10, .frequency = 100*1000, }; /* Asix AX88796 10/100 ethernet controller */ static struct ax_plat_data bast_asix_platdata = { .flags = AXFLG_MAC_FROMDEV, .wordlength = 2, .dcr_val = 0x48, .rcr_val = 0x40, }; static struct resource bast_asix_resource[] = { [0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET, 0x18 * 0x20), [1] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET + (0x1f * 0x20), 1), [2] = DEFINE_RES_IRQ(BAST_IRQ_ASIX), }; static struct platform_device bast_device_asix = { .name = "ax88796", .id = 0, .num_resources = ARRAY_SIZE(bast_asix_resource), .resource = bast_asix_resource, .dev = { .platform_data = &bast_asix_platdata } }; /* Asix AX88796 10/100 ethernet controller parallel port */ static struct resource bast_asixpp_resource[] = { [0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET + (0x18 * 0x20), \ 0x30 * 0x20), }; static struct platform_device bast_device_axpp = { .name = "ax88796-pp", .id = 0, .num_resources = ARRAY_SIZE(bast_asixpp_resource), .resource = bast_asixpp_resource, }; /* LCD/VGA controller */ static struct s3c2410fb_display __initdata bast_lcd_info[] = { { .type = S3C2410_LCDCON1_TFT, .width = 640, .height = 480, .pixclock = 33333, .xres = 640, .yres = 480, .bpp = 4, .left_margin = 40, .right_margin = 20, .hsync_len = 88, .upper_margin = 30, .lower_margin = 32, .vsync_len = 3, .lcdcon5 = 0x00014b02, }, { .type = S3C2410_LCDCON1_TFT, .width = 640, .height = 480, .pixclock = 33333, .xres = 640, .yres = 480, .bpp = 8, .left_margin = 40, .right_margin = 20, .hsync_len = 88, .upper_margin = 30, .lower_margin = 32, .vsync_len = 3, .lcdcon5 = 0x00014b02, }, { .type = S3C2410_LCDCON1_TFT, .width = 640, .height = 480, .pixclock = 33333, .xres = 640, .yres = 480, .bpp = 16, .left_margin = 40, .right_margin = 20, .hsync_len = 88, .upper_margin = 30, .lower_margin = 32, .vsync_len = 3, .lcdcon5 = 0x00014b02, }, }; /* LCD/VGA controller */ static struct s3c2410fb_mach_info __initdata bast_fb_info = { .displays = bast_lcd_info, .num_displays = ARRAY_SIZE(bast_lcd_info), .default_display = 1, }; /* I2C devices fitted. */ static struct i2c_board_info bast_i2c_devs[] __initdata = { { I2C_BOARD_INFO("tlv320aic23", 0x1a), }, { I2C_BOARD_INFO("simtec-pmu", 0x6b), }, { I2C_BOARD_INFO("ch7013", 0x75), }, }; static struct s3c_hwmon_pdata bast_hwmon_info = { /* LCD contrast (0-6.6V) */ .in[0] = &(struct s3c_hwmon_chcfg) { .name = "lcd-contrast", .mult = 3300, .div = 512, }, /* LED current feedback */ .in[1] = &(struct s3c_hwmon_chcfg) { .name = "led-feedback", .mult = 3300, .div = 1024, }, /* LCD feedback (0-6.6V) */ .in[2] = &(struct s3c_hwmon_chcfg) { .name = "lcd-feedback", .mult = 3300, .div = 512, }, /* Vcore (1.8-2.0V), Vref 3.3V */ .in[3] = &(struct s3c_hwmon_chcfg) { .name = "vcore", .mult = 3300, .div = 1024, }, }; /* Standard BAST devices */ // cat /sys/devices/platform/s3c24xx-adc/s3c-hwmon/in_0 static struct platform_device *bast_devices[] __initdata = { &s3c_device_ohci, &s3c_device_lcd, &s3c_device_wdt, &s3c_device_i2c0, &s3c_device_rtc, &s3c_device_nand, &s3c_device_adc, &s3c_device_hwmon, &bast_device_dm9k, &bast_device_asix, &bast_device_axpp, &bast_sio, }; static struct clk *bast_clocks[] __initdata = { &s3c24xx_dclk0, &s3c24xx_dclk1, &s3c24xx_clkout0, &s3c24xx_clkout1, &s3c24xx_uclk, }; static struct s3c_cpufreq_board __initdata bast_cpufreq = { .refresh = 7800, /* 7.8usec */ .auto_io = 1, .need_io = 1, }; static struct s3c24xx_audio_simtec_pdata __initdata bast_audio = { .have_mic = 1, .have_lout = 1, }; static void __init bast_map_io(void) { /* initialise the clocks */ s3c24xx_dclk0.parent = &clk_upll; s3c24xx_dclk0.rate = 12*1000*1000; s3c24xx_dclk1.parent = &clk_upll; s3c24xx_dclk1.rate = 24*1000*1000; s3c24xx_clkout0.parent = &s3c24xx_dclk0; s3c24xx_clkout1.parent = &s3c24xx_dclk1; s3c24xx_uclk.parent = &s3c24xx_clkout1; s3c24xx_register_clocks(bast_clocks, ARRAY_SIZE(bast_clocks)); s3c_hwmon_set_platdata(&bast_hwmon_info); s3c24xx_init_io(bast_iodesc, ARRAY_SIZE(bast_iodesc)); s3c24xx_init_clocks(0); s3c24xx_init_uarts(bast_uartcfgs, ARRAY_SIZE(bast_uartcfgs)); } static void __init bast_init(void) { register_syscore_ops(&bast_pm_syscore_ops); s3c_i2c0_set_platdata(&bast_i2c_info); s3c_nand_set_platdata(&bast_nand_info); s3c24xx_fb_set_platdata(&bast_fb_info); platform_add_devices(bast_devices, ARRAY_SIZE(bast_devices)); i2c_register_board_info(0, bast_i2c_devs, ARRAY_SIZE(bast_i2c_devs)); usb_simtec_init(); nor_simtec_init(); simtec_audio_add(NULL, true, &bast_audio); WARN_ON(gpio_request(S3C2410_GPA(21), "bast nreset")); s3c_cpufreq_setboard(&bast_cpufreq); } MACHINE_START(BAST, "Simtec-BAST") /* Maintainer: Ben Dooks <ben@simtec.co.uk> */ .atag_offset = 0x100, .map_io = bast_map_io, .init_irq = s3c24xx_init_irq, .init_machine = bast_init, .init_time = s3c24xx_timer_init, .restart = s3c2410_restart, MACHINE_END
Oleh-Kravchenko/asusp535
arch/arm/mach-s3c24xx/mach-bast.c
C
gpl-2.0
14,795
/* * Copyright (c) 2011-2012, The Linux Foundation. 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. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/io.h> #include <linux/delay.h> #include <linux/mutex.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/cpufreq.h> #include <linux/cpu.h> #include <linux/console.h> #include <linux/regulator/consumer.h> #include <asm/mach-types.h> #include <asm/cpu.h> #include <mach/board.h> #include <mach/msm_iomap.h> #include <mach/socinfo.h> #include <mach/msm-krait-l2-accessors.h> #include <mach/rpm-regulator.h> #include <mach/rpm-regulator-smd.h> #include <mach/msm_bus.h> #include <mach/msm_dcvs.h> #include "acpuclock.h" #include "acpuclock-krait.h" #include "avs.h" #ifdef CONFIG_SEC_DEBUG_DCVS_LOG #include <mach/sec_debug.h> #endif /* MUX source selects. */ #define PRI_SRC_SEL_SEC_SRC 0 #define PRI_SRC_SEL_HFPLL 1 #define PRI_SRC_SEL_HFPLL_DIV2 2 #define SECCLKAGD BIT(4) #ifdef CONFIG_SEC_DEBUG_SUBSYS int boost_uv; int speed_bin; int pvs_bin; #endif static DEFINE_MUTEX(driver_lock); static DEFINE_SPINLOCK(l2_lock); static struct drv_data { struct acpu_level *acpu_freq_tbl; const struct l2_level *l2_freq_tbl; struct scalable *scalable; struct hfpll_data *hfpll_data; u32 bus_perf_client; struct msm_bus_scale_pdata *bus_scale; int boost_uv; struct device *dev; } drv; static unsigned long acpuclk_krait_get_rate(int cpu) { return drv.scalable[cpu].cur_speed->khz; } /* Select a source on the primary MUX. */ static void set_pri_clk_src(struct scalable *sc, u32 pri_src_sel) { u32 regval; regval = get_l2_indirect_reg(sc->l2cpmr_iaddr); regval &= ~0x3; regval |= (pri_src_sel & 0x3); set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Wait for switch to complete. */ mb(); udelay(1); } /* Select a source on the secondary MUX. */ static void __cpuinit set_sec_clk_src(struct scalable *sc, u32 sec_src_sel) { u32 regval; /* 8064 Errata: disable sec_src clock gating during switch. */ regval = get_l2_indirect_reg(sc->l2cpmr_iaddr); regval |= SECCLKAGD; set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Program the MUX */ regval &= ~(0x3 << 2); regval |= ((sec_src_sel & 0x3) << 2); set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* 8064 Errata: re-enabled sec_src clock gating. */ regval &= ~SECCLKAGD; set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Wait for switch to complete. */ mb(); udelay(1); } static int enable_rpm_vreg(struct vreg *vreg) { int ret = 0; if (vreg->rpm_reg) { ret = rpm_regulator_enable(vreg->rpm_reg); if (ret) dev_err(drv.dev, "%s regulator enable failed (%d)\n", vreg->name, ret); } return ret; } static void disable_rpm_vreg(struct vreg *vreg) { int rc; if (vreg->rpm_reg) { rc = rpm_regulator_disable(vreg->rpm_reg); if (rc) dev_err(drv.dev, "%s regulator disable failed (%d)\n", vreg->name, rc); } } /* Enable an already-configured HFPLL. */ static void hfpll_enable(struct scalable *sc, bool skip_regulators) { if (!skip_regulators) { /* Enable regulators required by the HFPLL. */ enable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]); enable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]); } /* Disable PLL bypass mode. */ writel_relaxed(0x2, sc->hfpll_base + drv.hfpll_data->mode_offset); /* * H/W requires a 5us delay between disabling the bypass and * de-asserting the reset. Delay 10us just to be safe. */ mb(); udelay(10); /* De-assert active-low PLL reset. */ writel_relaxed(0x6, sc->hfpll_base + drv.hfpll_data->mode_offset); /* Wait for PLL to lock. */ mb(); udelay(60); /* Enable PLL output. */ writel_relaxed(0x7, sc->hfpll_base + drv.hfpll_data->mode_offset); } /* Disable a HFPLL for power-savings or while it's being reprogrammed. */ static void hfpll_disable(struct scalable *sc, bool skip_regulators) { /* * Disable the PLL output, disable test mode, enable the bypass mode, * and assert the reset. */ writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->mode_offset); if (!skip_regulators) { /* Remove voltage votes required by the HFPLL. */ disable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]); disable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]); } } /* Program the HFPLL rate. Assumes HFPLL is already disabled. */ static void hfpll_set_rate(struct scalable *sc, const struct core_speed *tgt_s) { void __iomem *base = sc->hfpll_base; u32 regval; writel_relaxed(tgt_s->pll_l_val, base + drv.hfpll_data->l_offset); if (drv.hfpll_data->has_user_reg) { regval = readl_relaxed(base + drv.hfpll_data->user_offset); if (tgt_s->pll_l_val <= drv.hfpll_data->low_vco_l_max) regval &= ~drv.hfpll_data->user_vco_mask; else regval |= drv.hfpll_data->user_vco_mask; writel_relaxed(regval, base + drv.hfpll_data->user_offset); } } /* Return the L2 speed that should be applied. */ static unsigned int compute_l2_level(struct scalable *sc, unsigned int vote_l) { unsigned int new_l = 0; int cpu; /* Find max L2 speed vote. */ sc->l2_vote = vote_l; for_each_present_cpu(cpu) new_l = max(new_l, drv.scalable[cpu].l2_vote); return new_l; } /* Update the bus bandwidth request. */ static void set_bus_bw(unsigned int bw) { int ret; /* Update bandwidth if request has changed. This may sleep. */ ret = msm_bus_scale_client_update_request(drv.bus_perf_client, bw); if (ret) dev_err(drv.dev, "bandwidth request failed (%d)\n", ret); } /* Set the CPU or L2 clock speed. */ static void set_speed(struct scalable *sc, const struct core_speed *tgt_s, bool skip_regulators) { const struct core_speed *strt_s = sc->cur_speed; if (strt_s == tgt_s) return; if (strt_s->src == HFPLL && tgt_s->src == HFPLL) { /* * Move to an always-on source running at a frequency * that does not require an elevated CPU voltage. */ set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC); /* Re-program HFPLL. */ hfpll_disable(sc, true); hfpll_set_rate(sc, tgt_s); hfpll_enable(sc, true); /* Move to HFPLL. */ set_pri_clk_src(sc, tgt_s->pri_src_sel); } else if (strt_s->src == HFPLL && tgt_s->src != HFPLL) { set_pri_clk_src(sc, tgt_s->pri_src_sel); hfpll_disable(sc, skip_regulators); } else if (strt_s->src != HFPLL && tgt_s->src == HFPLL) { hfpll_set_rate(sc, tgt_s); hfpll_enable(sc, skip_regulators); set_pri_clk_src(sc, tgt_s->pri_src_sel); } sc->cur_speed = tgt_s; } struct vdd_data { int vdd_mem; int vdd_dig; int vdd_core; int ua_core; }; /* Apply any per-cpu voltage increases. */ static int increase_vdd(int cpu, struct vdd_data *data, enum setrate_reason reason) { struct scalable *sc = &drv.scalable[cpu]; int rc; /* * Increase vdd_mem active-set before vdd_dig. * vdd_mem should be >= vdd_dig. */ if (data->vdd_mem > sc->vreg[VREG_MEM].cur_vdd) { rc = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg, data->vdd_mem, sc->vreg[VREG_MEM].max_vdd); if (rc) { dev_err(drv.dev, "vdd_mem (cpu%d) increase failed (%d)\n", cpu, rc); return rc; } sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem; } /* Increase vdd_dig active-set vote. */ if (data->vdd_dig > sc->vreg[VREG_DIG].cur_vdd) { rc = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg, data->vdd_dig, sc->vreg[VREG_DIG].max_vdd); if (rc) { dev_err(drv.dev, "vdd_dig (cpu%d) increase failed (%d)\n", cpu, rc); return rc; } sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig; } /* Increase current request. */ if (data->ua_core > sc->vreg[VREG_CORE].cur_ua) { rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, data->ua_core); if (rc < 0) { dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, rc); return rc; } sc->vreg[VREG_CORE].cur_ua = data->ua_core; } /* * Update per-CPU core voltage. Don't do this for the hotplug path for * which it should already be correct. Attempting to set it is bad * because we don't know what CPU we are running on at this point, but * the CPU regulator API requires we call it from the affected CPU. */ if (data->vdd_core > sc->vreg[VREG_CORE].cur_vdd && reason != SETRATE_HOTPLUG) { rc = regulator_set_voltage(sc->vreg[VREG_CORE].reg, data->vdd_core, sc->vreg[VREG_CORE].max_vdd); if (rc) { dev_err(drv.dev, "vdd_core (cpu%d) increase failed (%d)\n", cpu, rc); return rc; } sc->vreg[VREG_CORE].cur_vdd = data->vdd_core; } return 0; } /* Apply any per-cpu voltage decreases. */ static void decrease_vdd(int cpu, struct vdd_data *data, enum setrate_reason reason) { struct scalable *sc = &drv.scalable[cpu]; int ret; /* * Update per-CPU core voltage. This must be called on the CPU * that's being affected. Don't do this in the hotplug remove path, * where the rail is off and we're executing on the other CPU. */ if (data->vdd_core < sc->vreg[VREG_CORE].cur_vdd && reason != SETRATE_HOTPLUG) { ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg, data->vdd_core, sc->vreg[VREG_CORE].max_vdd); if (ret) { dev_err(drv.dev, "vdd_core (cpu%d) decrease failed (%d)\n", cpu, ret); return; } sc->vreg[VREG_CORE].cur_vdd = data->vdd_core; } /* Decrease current request. */ if (data->ua_core < sc->vreg[VREG_CORE].cur_ua) { ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, data->ua_core); if (ret < 0) { dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); return; } sc->vreg[VREG_CORE].cur_ua = data->ua_core; } /* Decrease vdd_dig active-set vote. */ if (data->vdd_dig < sc->vreg[VREG_DIG].cur_vdd) { ret = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg, data->vdd_dig, sc->vreg[VREG_DIG].max_vdd); if (ret) { dev_err(drv.dev, "vdd_dig (cpu%d) decrease failed (%d)\n", cpu, ret); return; } sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig; } /* * Decrease vdd_mem active-set after vdd_dig. * vdd_mem should be >= vdd_dig. */ if (data->vdd_mem < sc->vreg[VREG_MEM].cur_vdd) { ret = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg, data->vdd_mem, sc->vreg[VREG_MEM].max_vdd); if (ret) { dev_err(drv.dev, "vdd_mem (cpu%d) decrease failed (%d)\n", cpu, ret); return; } sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem; } } static int calculate_vdd_mem(const struct acpu_level *tgt) { return drv.l2_freq_tbl[tgt->l2_level].vdd_mem; } static int get_src_dig(const struct core_speed *s) { const int *hfpll_vdd = drv.hfpll_data->vdd; const u32 low_vdd_l_max = drv.hfpll_data->low_vdd_l_max; const u32 nom_vdd_l_max = drv.hfpll_data->nom_vdd_l_max; if (s->src != HFPLL) return hfpll_vdd[HFPLL_VDD_NONE]; else if (s->pll_l_val > nom_vdd_l_max) return hfpll_vdd[HFPLL_VDD_HIGH]; else if (s->pll_l_val > low_vdd_l_max) return hfpll_vdd[HFPLL_VDD_NOM]; else return hfpll_vdd[HFPLL_VDD_LOW]; } static int calculate_vdd_dig(const struct acpu_level *tgt) { int l2_pll_vdd_dig, cpu_pll_vdd_dig; l2_pll_vdd_dig = get_src_dig(&drv.l2_freq_tbl[tgt->l2_level].speed); cpu_pll_vdd_dig = get_src_dig(&tgt->speed); return max(drv.l2_freq_tbl[tgt->l2_level].vdd_dig, max(l2_pll_vdd_dig, cpu_pll_vdd_dig)); } static bool enable_boost = true; module_param_named(boost, enable_boost, bool, S_IRUGO | S_IWUSR); static int calculate_vdd_core(const struct acpu_level *tgt) { return tgt->vdd_core + (enable_boost ? drv.boost_uv : 0); } static DEFINE_MUTEX(l2_regulator_lock); static int l2_vreg_count; static int enable_l2_regulators(void) { int ret = 0; mutex_lock(&l2_regulator_lock); if (l2_vreg_count == 0) { ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]); if (ret) goto out; ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]); if (ret) { disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]); goto out; } } l2_vreg_count++; out: mutex_unlock(&l2_regulator_lock); return ret; } static void disable_l2_regulators(void) { mutex_lock(&l2_regulator_lock); if (WARN(!l2_vreg_count, "L2 regulator votes are unbalanced!")) goto out; if (l2_vreg_count == 1) { disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]); disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]); } l2_vreg_count--; out: mutex_unlock(&l2_regulator_lock); } static int minus_vc; module_param_named( mclk, minus_vc, int, S_IRUGO | S_IWUSR | S_IWGRP ); /* Set the CPU's clock rate and adjust the L2 rate, voltage and BW requests. */ static int acpuclk_krait_set_rate(int cpu, unsigned long rate, enum setrate_reason reason) { const struct core_speed *strt_acpu_s, *tgt_acpu_s; const struct acpu_level *tgt; int tgt_l2_l; enum src_id prev_l2_src = NUM_SRC_ID; struct vdd_data vdd_data; bool skip_regulators; int rc = 0; if (cpu > num_possible_cpus()) return -EINVAL; if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) mutex_lock(&driver_lock); strt_acpu_s = drv.scalable[cpu].cur_speed; /* Return early if rate didn't change. */ if (rate == strt_acpu_s->khz) goto out; /* Find target frequency. */ for (tgt = drv.acpu_freq_tbl; tgt->speed.khz != 0; tgt++) { if (tgt->speed.khz == rate) { tgt_acpu_s = &tgt->speed; break; } } if (tgt->speed.khz == 0) { rc = -EINVAL; goto out; } /* Calculate voltage requirements for the current CPU. */ vdd_data.vdd_mem = calculate_vdd_mem(tgt); vdd_data.vdd_dig = calculate_vdd_dig(tgt); vdd_data.vdd_core = calculate_vdd_core(tgt) + minus_vc; vdd_data.ua_core = tgt->ua_core; /* Disable AVS before voltage switch */ if (reason == SETRATE_CPUFREQ && drv.scalable[cpu].avs_enabled) { AVS_DISABLE(cpu); drv.scalable[cpu].avs_enabled = false; } /* Increase VDD levels if needed. */ if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) { rc = increase_vdd(cpu, &vdd_data, reason); if (rc) goto out; prev_l2_src = drv.l2_freq_tbl[drv.scalable[cpu].l2_vote].speed.src; /* Vote for the L2 regulators here if necessary. */ if (drv.l2_freq_tbl[tgt->l2_level].speed.src == HFPLL) { rc = enable_l2_regulators(); if (rc) goto out; } } dev_dbg(drv.dev, "Switching from ACPU%d rate %lu KHz -> %lu KHz\n", cpu, strt_acpu_s->khz, tgt_acpu_s->khz); /* * If we are setting the rate as part of power collapse or in the resume * path after power collapse, skip the vote for the HFPLL regulators, * which are active-set-only votes that will be removed when apps enters * its sleep set. This is needed to avoid voting for regulators with * sleeping APIs from an atomic context. */ skip_regulators = (reason == SETRATE_PC); #ifdef CONFIG_SEC_DEBUG_DCVS_LOG sec_debug_dcvs_log(cpu, strt_acpu_s->khz, tgt_acpu_s->khz); #endif /* Set the new CPU speed. */ set_speed(&drv.scalable[cpu], tgt_acpu_s, skip_regulators); /* * Update the L2 vote and apply the rate change. A spinlock is * necessary to ensure L2 rate is calculated and set atomically * with the CPU frequency, even if acpuclk_krait_set_rate() is * called from an atomic context and the driver_lock mutex is not * acquired. */ spin_lock(&l2_lock); tgt_l2_l = compute_l2_level(&drv.scalable[cpu], tgt->l2_level); set_speed(&drv.scalable[L2], &drv.l2_freq_tbl[tgt_l2_l].speed, true); spin_unlock(&l2_lock); /* Nothing else to do for power collapse or SWFI. */ if (reason == SETRATE_PC || reason == SETRATE_SWFI) goto out; /* * Remove the vote for the L2 HFPLL regulators only if the L2 * was already on an HFPLL source. */ if (prev_l2_src == HFPLL) disable_l2_regulators(); /* Update bus bandwith request. */ set_bus_bw(drv.l2_freq_tbl[tgt_l2_l].bw_level); /* Drop VDD levels if we can. */ decrease_vdd(cpu, &vdd_data, reason); /* Re-enable AVS */ if (reason == SETRATE_CPUFREQ && tgt->avsdscr_setting) { AVS_ENABLE(cpu, tgt->avsdscr_setting); drv.scalable[cpu].avs_enabled = true; } dev_dbg(drv.dev, "ACPU%d speed change complete\n", cpu); out: if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) mutex_unlock(&driver_lock); return rc; } static struct acpuclk_data acpuclk_krait_data = { .set_rate = acpuclk_krait_set_rate, .get_rate = acpuclk_krait_get_rate, }; /* Initialize a HFPLL at a given rate and enable it. */ static void __cpuinit hfpll_init(struct scalable *sc, const struct core_speed *tgt_s) { dev_dbg(drv.dev, "Initializing HFPLL%d\n", sc - drv.scalable); /* Disable the PLL for re-programming. */ hfpll_disable(sc, true); /* Configure PLL parameters for integer mode. */ writel_relaxed(drv.hfpll_data->config_val, sc->hfpll_base + drv.hfpll_data->config_offset); writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->m_offset); writel_relaxed(1, sc->hfpll_base + drv.hfpll_data->n_offset); if (drv.hfpll_data->has_user_reg) writel_relaxed(drv.hfpll_data->user_val, sc->hfpll_base + drv.hfpll_data->user_offset); /* Program droop controller, if supported */ if (drv.hfpll_data->has_droop_ctl) writel_relaxed(drv.hfpll_data->droop_val, sc->hfpll_base + drv.hfpll_data->droop_offset); /* Set an initial PLL rate. */ hfpll_set_rate(sc, tgt_s); } static int __cpuinit rpm_regulator_init(struct scalable *sc, enum vregs vreg, int vdd, bool enable) { int ret; if (!sc->vreg[vreg].name) return 0; sc->vreg[vreg].rpm_reg = rpm_regulator_get(drv.dev, sc->vreg[vreg].name); if (IS_ERR(sc->vreg[vreg].rpm_reg)) { ret = PTR_ERR(sc->vreg[vreg].rpm_reg); dev_err(drv.dev, "rpm_regulator_get(%s) failed (%d)\n", sc->vreg[vreg].name, ret); goto err_get; } ret = rpm_regulator_set_voltage(sc->vreg[vreg].rpm_reg, vdd, sc->vreg[vreg].max_vdd); if (ret) { dev_err(drv.dev, "%s initialization failed (%d)\n", sc->vreg[vreg].name, ret); goto err_conf; } sc->vreg[vreg].cur_vdd = vdd; if (enable) { ret = enable_rpm_vreg(&sc->vreg[vreg]); if (ret) goto err_conf; } return 0; err_conf: rpm_regulator_put(sc->vreg[vreg].rpm_reg); err_get: return ret; } static void __cpuinit rpm_regulator_cleanup(struct scalable *sc, enum vregs vreg) { if (!sc->vreg[vreg].rpm_reg) return; disable_rpm_vreg(&sc->vreg[vreg]); rpm_regulator_put(sc->vreg[vreg].rpm_reg); } /* Voltage regulator initialization. */ static int __cpuinit regulator_init(struct scalable *sc, const struct acpu_level *acpu_level) { int ret, vdd_mem, vdd_dig, vdd_core; vdd_mem = calculate_vdd_mem(acpu_level); ret = rpm_regulator_init(sc, VREG_MEM, vdd_mem, true); if (ret) goto err_mem; vdd_dig = calculate_vdd_dig(acpu_level); ret = rpm_regulator_init(sc, VREG_DIG, vdd_dig, true); if (ret) goto err_dig; ret = rpm_regulator_init(sc, VREG_HFPLL_A, sc->vreg[VREG_HFPLL_A].max_vdd, false); if (ret) goto err_hfpll_a; ret = rpm_regulator_init(sc, VREG_HFPLL_B, sc->vreg[VREG_HFPLL_B].max_vdd, false); if (ret) goto err_hfpll_b; /* Setup Krait CPU regulators and initial core voltage. */ sc->vreg[VREG_CORE].reg = regulator_get(drv.dev, sc->vreg[VREG_CORE].name); if (IS_ERR(sc->vreg[VREG_CORE].reg)) { ret = PTR_ERR(sc->vreg[VREG_CORE].reg); dev_err(drv.dev, "regulator_get(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_get; } ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, acpu_level->ua_core); if (ret < 0) { dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_conf; } sc->vreg[VREG_CORE].cur_ua = acpu_level->ua_core; vdd_core = calculate_vdd_core(acpu_level); ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg, vdd_core, sc->vreg[VREG_CORE].max_vdd); if (ret) { dev_err(drv.dev, "regulator_set_voltage(%s) (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_conf; } sc->vreg[VREG_CORE].cur_vdd = vdd_core; ret = regulator_enable(sc->vreg[VREG_CORE].reg); if (ret) { dev_err(drv.dev, "regulator_enable(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_conf; } /* * Increment the L2 HFPLL regulator refcount if _this_ CPU's frequency * requires a corresponding target L2 frequency that needs the L2 to * run off of an HFPLL. */ if (drv.l2_freq_tbl[acpu_level->l2_level].speed.src == HFPLL) l2_vreg_count++; return 0; err_core_conf: regulator_put(sc->vreg[VREG_CORE].reg); err_core_get: rpm_regulator_cleanup(sc, VREG_HFPLL_B); err_hfpll_b: rpm_regulator_cleanup(sc, VREG_HFPLL_A); err_hfpll_a: rpm_regulator_cleanup(sc, VREG_DIG); err_dig: rpm_regulator_cleanup(sc, VREG_MEM); err_mem: return ret; } static void __cpuinit regulator_cleanup(struct scalable *sc) { regulator_disable(sc->vreg[VREG_CORE].reg); regulator_put(sc->vreg[VREG_CORE].reg); rpm_regulator_cleanup(sc, VREG_HFPLL_B); rpm_regulator_cleanup(sc, VREG_HFPLL_A); rpm_regulator_cleanup(sc, VREG_DIG); rpm_regulator_cleanup(sc, VREG_MEM); } /* Set initial rate for a given core. */ static int __cpuinit init_clock_sources(struct scalable *sc, const struct core_speed *tgt_s) { u32 regval; void __iomem *aux_reg; /* Program AUX source input to the secondary MUX. */ if (sc->aux_clk_sel_phys) { aux_reg = ioremap(sc->aux_clk_sel_phys, 4); if (!aux_reg) return -ENOMEM; writel_relaxed(sc->aux_clk_sel, aux_reg); iounmap(aux_reg); } /* Switch away from the HFPLL while it's re-initialized. */ set_sec_clk_src(sc, sc->sec_clk_sel); set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC); hfpll_init(sc, tgt_s); /* Set PRI_SRC_SEL_HFPLL_DIV2 divider to div-2. */ regval = get_l2_indirect_reg(sc->l2cpmr_iaddr); regval &= ~(0x3 << 6); set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Enable and switch to the target clock source. */ if (tgt_s->src == HFPLL) hfpll_enable(sc, false); set_pri_clk_src(sc, tgt_s->pri_src_sel); sc->cur_speed = tgt_s; return 0; } static void __cpuinit fill_cur_core_speed(struct core_speed *s, struct scalable *sc) { s->pri_src_sel = get_l2_indirect_reg(sc->l2cpmr_iaddr) & 0x3; s->pll_l_val = readl_relaxed(sc->hfpll_base + drv.hfpll_data->l_offset); } static bool __cpuinit speed_equal(const struct core_speed *s1, const struct core_speed *s2) { return (s1->pri_src_sel == s2->pri_src_sel && s1->pll_l_val == s2->pll_l_val); } static const struct acpu_level __cpuinit *find_cur_acpu_level(int cpu) { struct scalable *sc = &drv.scalable[cpu]; const struct acpu_level *l; struct core_speed cur_speed; fill_cur_core_speed(&cur_speed, sc); for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++) if (speed_equal(&l->speed, &cur_speed)) return l; return NULL; } static const struct l2_level __init *find_cur_l2_level(void) { struct scalable *sc = &drv.scalable[L2]; const struct l2_level *l; struct core_speed cur_speed; fill_cur_core_speed(&cur_speed, sc); for (l = drv.l2_freq_tbl; l->speed.khz != 0; l++) if (speed_equal(&l->speed, &cur_speed)) return l; return NULL; } static const struct acpu_level __cpuinit *find_min_acpu_level(void) { struct acpu_level *l; for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++) if (l->use_for_scaling) return l; return NULL; } static int __cpuinit per_cpu_init(int cpu) { struct scalable *sc = &drv.scalable[cpu]; const struct acpu_level *acpu_level; int ret; sc->hfpll_base = ioremap(sc->hfpll_phys_base, SZ_32); if (!sc->hfpll_base) { ret = -ENOMEM; goto err_ioremap; } acpu_level = find_cur_acpu_level(cpu); if (!acpu_level) { acpu_level = find_min_acpu_level(); if (!acpu_level) { ret = -ENODEV; goto err_table; } dev_dbg(drv.dev, "CPU%d is running at an unknown rate. Defaulting to %lu KHz.\n", cpu, acpu_level->speed.khz); } else { dev_dbg(drv.dev, "CPU%d is running at %lu KHz\n", cpu, acpu_level->speed.khz); } ret = regulator_init(sc, acpu_level); if (ret) goto err_regulators; ret = init_clock_sources(sc, &acpu_level->speed); if (ret) goto err_clocks; sc->l2_vote = acpu_level->l2_level; sc->initialized = true; return 0; err_clocks: regulator_cleanup(sc); err_regulators: err_table: iounmap(sc->hfpll_base); err_ioremap: return ret; } /* Register with bus driver. */ static void __init bus_init(const struct l2_level *l2_level) { int ret; drv.bus_perf_client = msm_bus_scale_register_client(drv.bus_scale); if (!drv.bus_perf_client) { dev_err(drv.dev, "unable to register bus client\n"); BUG(); } ret = msm_bus_scale_client_update_request(drv.bus_perf_client, l2_level->bw_level); if (ret) dev_err(drv.dev, "initial bandwidth req failed (%d)\n", ret); } #ifdef CONFIG_CPU_FREQ_MSM static struct cpufreq_frequency_table freq_table[NR_CPUS][35]; extern int console_batt_stat; static void __init cpufreq_table_init(void) { int cpu; for_each_possible_cpu(cpu) { int i, freq_cnt = 0; /* Construct the freq_table tables from acpu_freq_tbl. */ for (i = 0; drv.acpu_freq_tbl[i].speed.khz != 0 && freq_cnt < ARRAY_SIZE(*freq_table); i++) { if (drv.acpu_freq_tbl[i].use_for_scaling) { #ifdef CONFIG_SEC_FACTORY // if factory_condition, set the core freq limit. //QMCK if (console_set_on_cmdline && drv.acpu_freq_tbl[i].speed.khz > 1000000) { if(console_batt_stat == 1) { continue; } } //QMCK #endif freq_table[cpu][freq_cnt].index = freq_cnt; freq_table[cpu][freq_cnt].frequency = drv.acpu_freq_tbl[i].speed.khz; freq_cnt++; } } /* freq_table not big enough to store all usable freqs. */ BUG_ON(drv.acpu_freq_tbl[i].speed.khz != 0); freq_table[cpu][freq_cnt].index = freq_cnt; freq_table[cpu][freq_cnt].frequency = CPUFREQ_TABLE_END; dev_info(drv.dev, "CPU%d: %d frequencies supported\n", cpu, freq_cnt); /* Register table with CPUFreq. */ cpufreq_frequency_table_get_attr(freq_table[cpu], cpu); } } #else static void __init cpufreq_table_init(void) {} #endif static void __init dcvs_freq_init(void) { int i; for (i = 0; drv.acpu_freq_tbl[i].speed.khz != 0; i++) if (drv.acpu_freq_tbl[i].use_for_scaling) msm_dcvs_register_cpu_freq( drv.acpu_freq_tbl[i].speed.khz, drv.acpu_freq_tbl[i].vdd_core / 1000); } static int __cpuinit acpuclk_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { static int prev_khz[NR_CPUS]; int rc, cpu = (int)hcpu; struct scalable *sc = &drv.scalable[cpu]; unsigned long hot_unplug_khz = acpuclk_krait_data.power_collapse_khz; switch (action & ~CPU_TASKS_FROZEN) { case CPU_DEAD: prev_khz[cpu] = acpuclk_krait_get_rate(cpu); /* Fall through. */ case CPU_UP_CANCELED: acpuclk_krait_set_rate(cpu, hot_unplug_khz, SETRATE_HOTPLUG); regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, 0); break; case CPU_UP_PREPARE: if (!sc->initialized) { rc = per_cpu_init(cpu); if (rc) return NOTIFY_BAD; break; } if (WARN_ON(!prev_khz[cpu])) return NOTIFY_BAD; rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, sc->vreg[VREG_CORE].cur_ua); if (rc < 0) return NOTIFY_BAD; acpuclk_krait_set_rate(cpu, prev_khz[cpu], SETRATE_HOTPLUG); break; default: break; } return NOTIFY_OK; } static struct notifier_block __cpuinitdata acpuclk_cpu_notifier = { .notifier_call = acpuclk_cpu_callback, }; static const int krait_needs_vmin(void) { switch (read_cpuid_id()) { case 0x511F04D0: /* KR28M2A20 */ case 0x511F04D1: /* KR28M2A21 */ case 0x510F06F0: /* KR28M4A10 */ return 1; default: return 0; }; } static void krait_apply_vmin(struct acpu_level *tbl) { for (; tbl->speed.khz != 0; tbl++) { if (tbl->vdd_core < 1150000) tbl->vdd_core = 1150000; tbl->avsdscr_setting = 0; } } static int __init get_speed_bin(u32 pte_efuse) { uint32_t speed_bin; speed_bin = pte_efuse & 0xF; if (speed_bin == 0xF) speed_bin = (pte_efuse >> 4) & 0xF; if (speed_bin == 0xF) { speed_bin = 0; dev_warn(drv.dev, "SPEED BIN: Defaulting to %d\n", speed_bin); } else { dev_info(drv.dev, "SPEED BIN: %d\n", speed_bin); } return speed_bin; } static int __init get_pvs_bin(u32 pte_efuse) { uint32_t pvs_bin; pvs_bin = (pte_efuse >> 10) & 0x7; if (pvs_bin == 0x7) pvs_bin = (pte_efuse >> 13) & 0x7; if (pvs_bin == 0x7) { pvs_bin = 0; dev_warn(drv.dev, "ACPU PVS: Defaulting to %d\n", pvs_bin); } else { dev_info(drv.dev, "ACPU PVS: %d\n", pvs_bin); } return pvs_bin; } static struct pvs_table * __init select_freq_plan(u32 pte_efuse_phys, struct pvs_table (*pvs_tables)[NUM_PVS]) { void __iomem *pte_efuse; u32 pte_efuse_val, tbl_idx, bin_idx; pte_efuse = ioremap(pte_efuse_phys, 4); if (!pte_efuse) { dev_err(drv.dev, "Unable to map QFPROM base\n"); return NULL; } pte_efuse_val = readl_relaxed(pte_efuse); iounmap(pte_efuse); /* Select frequency tables. */ bin_idx = get_speed_bin(pte_efuse_val); tbl_idx = get_pvs_bin(pte_efuse_val); #ifdef CONFIG_SEC_DEBUG_SUBSYS speed_bin = bin_idx; pvs_bin = tbl_idx; #endif return &pvs_tables[bin_idx][tbl_idx]; } static void __init drv_data_init(struct device *dev, const struct acpuclk_krait_params *params) { struct pvs_table *pvs; drv.dev = dev; drv.scalable = kmemdup(params->scalable, params->scalable_size, GFP_KERNEL); BUG_ON(!drv.scalable); drv.hfpll_data = kmemdup(params->hfpll_data, sizeof(*drv.hfpll_data), GFP_KERNEL); BUG_ON(!drv.hfpll_data); drv.l2_freq_tbl = kmemdup(params->l2_freq_tbl, params->l2_freq_tbl_size, GFP_KERNEL); BUG_ON(!drv.l2_freq_tbl); drv.bus_scale = kmemdup(params->bus_scale, sizeof(*drv.bus_scale), GFP_KERNEL); BUG_ON(!drv.bus_scale); drv.bus_scale->usecase = kmemdup(drv.bus_scale->usecase, drv.bus_scale->num_usecases * sizeof(*drv.bus_scale->usecase), GFP_KERNEL); BUG_ON(!drv.bus_scale->usecase); pvs = select_freq_plan(params->pte_efuse_phys, params->pvs_tables); BUG_ON(!pvs->table); drv.acpu_freq_tbl = kmemdup(pvs->table, pvs->size, GFP_KERNEL); BUG_ON(!drv.acpu_freq_tbl); drv.boost_uv = pvs->boost_uv; #ifdef CONFIG_SEC_DEBUG_SUBSYS boost_uv = drv.boost_uv; #endif acpuclk_krait_data.power_collapse_khz = params->stby_khz; acpuclk_krait_data.wait_for_irq_khz = params->stby_khz; } static void __init hw_init(void) { struct scalable *l2 = &drv.scalable[L2]; const struct l2_level *l2_level; int cpu, rc; if (krait_needs_vmin()) krait_apply_vmin(drv.acpu_freq_tbl); l2->hfpll_base = ioremap(l2->hfpll_phys_base, SZ_32); BUG_ON(!l2->hfpll_base); rc = rpm_regulator_init(l2, VREG_HFPLL_A, l2->vreg[VREG_HFPLL_A].max_vdd, false); BUG_ON(rc); rc = rpm_regulator_init(l2, VREG_HFPLL_B, l2->vreg[VREG_HFPLL_B].max_vdd, false); BUG_ON(rc); l2_level = find_cur_l2_level(); if (!l2_level) { l2_level = drv.l2_freq_tbl; dev_dbg(drv.dev, "L2 is running at an unknown rate. Defaulting to %lu KHz.\n", l2_level->speed.khz); } else { dev_dbg(drv.dev, "L2 is running at %lu KHz\n", l2_level->speed.khz); } rc = init_clock_sources(l2, &l2_level->speed); BUG_ON(rc); for_each_online_cpu(cpu) { rc = per_cpu_init(cpu); BUG_ON(rc); } bus_init(l2_level); } int __init acpuclk_krait_init(struct device *dev, const struct acpuclk_krait_params *params) { drv_data_init(dev, params); hw_init(); cpufreq_table_init(); dcvs_freq_init(); acpuclk_register(&acpuclk_krait_data); register_hotcpu_notifier(&acpuclk_cpu_notifier); return 0; }
cnexus/NexTKernel-d2spr
arch/arm/mach-msm/acpuclock-krait.c
C
gpl-2.0
31,611
/* Copyright (c) 2012-2014, The Linux Foundation. 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. */ #include <linux/slab.h> #include <linux/wait.h> #include <linux/sched.h> #include <linux/jiffies.h> #include <linux/uaccess.h> #include <linux/atomic.h> #include <linux/wait.h> #include <sound/apr_audio-v2.h> #include <linux/qdsp6v2/apr.h> #include <sound/q6adm-v2.h> #include <sound/q6audio-v2.h> #include <sound/q6afe-v2.h> #include <sound/hw_audio_log.h> #include "audio_acdb.h" #define TIMEOUT_MS 1000 #define RESET_COPP_ID 99 #define INVALID_COPP_ID 0xFF /* Used for inband payload copy, max size is 4k */ /* 2 is to account for module & param ID in payload */ #define ADM_GET_PARAMETER_LENGTH (4096 - APR_HDR_SIZE - 2 * sizeof(uint32_t)) #define ULL_SUPPORTED_SAMPLE_RATE 48000 enum { ADM_RX_AUDPROC_CAL, ADM_TX_AUDPROC_CAL, ADM_RX_AUDVOL_CAL, ADM_TX_AUDVOL_CAL, ADM_CUSTOM_TOP_CAL, ADM_RTAC, ADM_MAX_CAL_TYPES }; struct adm_ctl { void *apr; atomic_t copp_id[AFE_MAX_PORTS]; atomic_t copp_cnt[AFE_MAX_PORTS]; atomic_t copp_low_latency_id[AFE_MAX_PORTS]; atomic_t copp_low_latency_cnt[AFE_MAX_PORTS]; atomic_t copp_perf_mode[AFE_MAX_PORTS]; atomic_t copp_stat[AFE_MAX_PORTS]; wait_queue_head_t wait[AFE_MAX_PORTS]; struct acdb_cal_block mem_addr_audproc[MAX_AUDPROC_TYPES]; struct acdb_cal_block mem_addr_audvol[MAX_AUDPROC_TYPES]; atomic_t mem_map_cal_handles[ADM_MAX_CAL_TYPES]; atomic_t mem_map_cal_index; int set_custom_topology; int ec_ref_rx; }; static struct adm_ctl this_adm; struct adm_multi_ch_map { bool set_channel_map; char channel_mapping[PCM_FORMAT_MAX_NUM_CHANNEL]; }; static struct adm_multi_ch_map multi_ch_map = { false, {0, 0, 0, 0, 0, 0, 0, 0} }; static int adm_get_parameters[ADM_GET_PARAMETER_LENGTH]; int srs_trumedia_open(int port_id, int srs_tech_id, void *srs_params) { struct adm_cmd_set_pp_params_inband_v5 *adm_params = NULL; int ret = 0, sz = 0; int index; ad_logd("SRS - %s", __func__); switch (srs_tech_id) { case SRS_ID_GLOBAL: { struct srs_trumedia_params_GLOBAL *glb_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_GLOBAL); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_GLOBAL) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS; adm_params->params.param_size = sizeof(struct srs_trumedia_params_GLOBAL); glb_params = (struct srs_trumedia_params_GLOBAL *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(glb_params, srs_params, sizeof(struct srs_trumedia_params_GLOBAL)); ad_logd("SRS - %s: Global params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x\n", __func__, (int)glb_params->v1, (int)glb_params->v2, (int)glb_params->v3, (int)glb_params->v4, (int)glb_params->v5, (int)glb_params->v6, (int)glb_params->v7, (int)glb_params->v8); break; } case SRS_ID_WOWHD: { struct srs_trumedia_params_WOWHD *whd_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_WOWHD); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_WOWHD) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_WOWHD; adm_params->params.param_size = sizeof(struct srs_trumedia_params_WOWHD); whd_params = (struct srs_trumedia_params_WOWHD *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(whd_params, srs_params, sizeof(struct srs_trumedia_params_WOWHD)); ad_logd("SRS - %s: WOWHD params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x, 9 = %x, 10 = %x, 11 = %x\n", __func__, (int)whd_params->v1, (int)whd_params->v2, (int)whd_params->v3, (int)whd_params->v4, (int)whd_params->v5, (int)whd_params->v6, (int)whd_params->v7, (int)whd_params->v8, (int)whd_params->v9, (int)whd_params->v10, (int)whd_params->v11); break; } case SRS_ID_CSHP: { struct srs_trumedia_params_CSHP *chp_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_CSHP); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_CSHP) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_CSHP; adm_params->params.param_size = sizeof(struct srs_trumedia_params_CSHP); chp_params = (struct srs_trumedia_params_CSHP *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(chp_params, srs_params, sizeof(struct srs_trumedia_params_CSHP)); ad_logd("SRS - %s: CSHP params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x, 9 = %x\n", __func__, (int)chp_params->v1, (int)chp_params->v2, (int)chp_params->v3, (int)chp_params->v4, (int)chp_params->v5, (int)chp_params->v6, (int)chp_params->v7, (int)chp_params->v8, (int)chp_params->v9); break; } case SRS_ID_HPF: { struct srs_trumedia_params_HPF *hpf_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_HPF); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_HPF) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_HPF; adm_params->params.param_size = sizeof(struct srs_trumedia_params_HPF); hpf_params = (struct srs_trumedia_params_HPF *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(hpf_params, srs_params, sizeof(struct srs_trumedia_params_HPF)); ad_logd("SRS - %s: HPF params - 1 = %x\n", __func__, (int)hpf_params->v1); break; } case SRS_ID_PEQ: { struct srs_trumedia_params_PEQ *peq_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_PEQ); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_PEQ) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_PEQ; adm_params->params.param_size = sizeof(struct srs_trumedia_params_PEQ); peq_params = (struct srs_trumedia_params_PEQ *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(peq_params, srs_params, sizeof(struct srs_trumedia_params_PEQ)); ad_logd("SRS - %s: PEQ params - 1 = %x 2 = %x, 3 = %x, 4 = %x\n", __func__, (int)peq_params->v1, (int)peq_params->v2, (int)peq_params->v3, (int)peq_params->v4); break; } case SRS_ID_HL: { struct srs_trumedia_params_HL *hl_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_HL); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_HL) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_HL; adm_params->params.param_size = sizeof(struct srs_trumedia_params_HL); hl_params = (struct srs_trumedia_params_HL *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(hl_params, srs_params, sizeof(struct srs_trumedia_params_HL)); ad_logd("SRS - %s: HL params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x\n", __func__, (int)hl_params->v1, (int)hl_params->v2, (int)hl_params->v3, (int)hl_params->v4, (int)hl_params->v5, (int)hl_params->v6, (int)hl_params->v7); break; } default: goto fail_cmd; } adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; index = afe_get_port_index(port_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); ret = -EINVAL; goto fail_cmd; } adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5; adm_params->payload_addr_lsw = 0; adm_params->payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->params.module_id = SRS_TRUMEDIA_MODULE_ID; adm_params->params.reserved = 0; ad_logd("SRS - %s: Command was sent now check Q6 - port id = %d, size %d, module id %x, param id %x.\n", __func__, adm_params->hdr.dest_port, adm_params->payload_size, adm_params->params.module_id, adm_params->params.param_id); ret = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (ret < 0) { ad_loge("SRS - %s: ADM enable for port %d failed\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } /* Wait for the callback with copp id */ ret = wait_event_timeout(this_adm.wait[index], 1, msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s: SRS set params timed out port = %d\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } fail_cmd: kfree(adm_params); return ret; } int adm_set_stereo_to_custom_stereo(int port_id, unsigned int session_id, char *params, uint32_t params_length) { struct adm_cmd_set_pspd_mtmx_strtr_params_v5 *adm_params = NULL; int sz, rc = 0, index = afe_get_port_index(port_id); ad_logd("%s\n", __func__); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d port_id %#x\n", __func__, index, port_id); return -EINVAL; } sz = sizeof(struct adm_cmd_set_pspd_mtmx_strtr_params_v5) + params_length; adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_set_pspd_mtmx_strtr_params_v5)), params, params_length); adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5; adm_params->payload_addr_lsw = 0; adm_params->payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->payload_size = params_length; /* direction RX as 0 */ adm_params->direction = 0; /* session id for this cmd to be applied on */ adm_params->sessionid = session_id; /* valid COPP id for LPCM */ adm_params->deviceid = atomic_read(&this_adm.copp_id[index]); adm_params->reserved = 0; ad_logd("%s: deviceid %d, session_id %d, src_port %d, dest_port %d\n", __func__, adm_params->deviceid, adm_params->sessionid, adm_params->hdr.src_port, adm_params->hdr.dest_port); atomic_set(&this_adm.copp_stat[index], 0); rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (rc < 0) { ad_loge("%s: Set params failed port = %#x\n", __func__, port_id); rc = -EINVAL; goto set_stereo_to_custom_stereo_return; } /* Wait for the callback */ rc = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!rc) { ad_loge("%s: Set params timed out port = %#x\n", __func__, port_id); rc = -EINVAL; goto set_stereo_to_custom_stereo_return; } rc = 0; set_stereo_to_custom_stereo_return: kfree(adm_params); return rc; } int adm_dolby_dap_send_params(int port_id, char *params, uint32_t params_length) { struct adm_cmd_set_pp_params_v5 *adm_params = NULL; int sz, rc = 0, index = afe_get_port_index(port_id); ad_logd("%s\n", __func__); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); return -EINVAL; } sz = sizeof(struct adm_cmd_set_pp_params_v5) + params_length; adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed", __func__); return -ENOMEM; } memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_v5)), params, params_length); adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5; adm_params->payload_addr_lsw = 0; adm_params->payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->payload_size = params_length; atomic_set(&this_adm.copp_stat[index], 0); rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (rc < 0) { ad_loge("%s: Set params failed port = %#x\n", __func__, port_id); rc = -EINVAL; goto dolby_dap_send_param_return; } /* Wait for the callback */ rc = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!rc) { ad_loge("%s: Set params timed out port = %#x\n", __func__, port_id); rc = -EINVAL; goto dolby_dap_send_param_return; } rc = 0; dolby_dap_send_param_return: kfree(adm_params); return rc; } int adm_get_params(int port_id, uint32_t module_id, uint32_t param_id, uint32_t params_length, char *params) { struct adm_cmd_get_pp_params_v5 *adm_params = NULL; int sz, rc = 0, i = 0, index = afe_get_port_index(port_id); int *params_data = (int *)params; if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); return -EINVAL; } sz = sizeof(struct adm_cmd_get_pp_params_v5) + params_length; adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed", __func__); return -ENOMEM; } memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_get_pp_params_v5)), params, params_length); adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_GET_PP_PARAMS_V5; adm_params->data_payload_addr_lsw = 0; adm_params->data_payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->module_id = module_id; adm_params->param_id = param_id; adm_params->param_max_size = params_length; adm_params->reserved = 0; atomic_set(&this_adm.copp_stat[index], 0); rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (rc < 0) { ad_loge("%s: Failed to Get Params on port %d\n", __func__, port_id); rc = -EINVAL; goto adm_get_param_return; } /* Wait for the callback with copp id */ rc = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!rc) { ad_loge("%s: get params timed out port = %d\n", __func__, port_id); rc = -EINVAL; goto adm_get_param_return; } if ((params_data) && (ARRAY_SIZE(adm_get_parameters) >= (1+adm_get_parameters[0])) && (params_length/sizeof(int) >= adm_get_parameters[0])) { for (i = 0; i < adm_get_parameters[0]; i++) params_data[i] = adm_get_parameters[1+i]; } else { pr_err("%s: Get param data not copied! get_param array size %zd, index %d, params array size %zd, index %d\n", __func__, ARRAY_SIZE(adm_get_parameters), (1+adm_get_parameters[0]), params_length/sizeof(int), adm_get_parameters[0]); } rc = 0; adm_get_param_return: kfree(adm_params); return rc; } static void adm_callback_debug_print(struct apr_client_data *data) { uint32_t *payload; payload = data->payload; if (data->payload_size >= 8) ad_logd("%s: code = 0x%x PL#0[%x], PL#1[%x], size = %d\n", __func__, data->opcode, payload[0], payload[1], data->payload_size); else if (data->payload_size >= 4) ad_logd("%s: code = 0x%x PL#0[%x], size = %d\n", __func__, data->opcode, payload[0], data->payload_size); else ad_logd("%s: code = 0x%x, size = %d\n", __func__, data->opcode, data->payload_size); } void adm_set_multi_ch_map(char *channel_map) { memcpy(multi_ch_map.channel_mapping, channel_map, PCM_FORMAT_MAX_NUM_CHANNEL); multi_ch_map.set_channel_map = true; } void adm_get_multi_ch_map(char *channel_map) { if (multi_ch_map.set_channel_map) { memcpy(channel_map, multi_ch_map.channel_mapping, PCM_FORMAT_MAX_NUM_CHANNEL); } } static int32_t adm_callback(struct apr_client_data *data, void *priv) { uint32_t *payload; int i, index; if (data == NULL) { ad_loge("%s: data paramter is null\n", __func__); return -EINVAL; } payload = data->payload; if (data->opcode == RESET_EVENTS) { ad_logd("adm_callback: Reset event is received: %d %d apr[%p]\n", data->reset_event, data->reset_proc, this_adm.apr); if (this_adm.apr) { apr_reset(this_adm.apr); for (i = 0; i < AFE_MAX_PORTS; i++) { atomic_set(&this_adm.copp_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_low_latency_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_cnt[i], 0); atomic_set(&this_adm.copp_low_latency_cnt[i], 0); atomic_set(&this_adm.copp_perf_mode[i], 0); atomic_set(&this_adm.copp_stat[i], 0); } this_adm.apr = NULL; reset_custom_topology_flags(); this_adm.set_custom_topology = 1; for (i = 0; i < ADM_MAX_CAL_TYPES; i++) atomic_set(&this_adm.mem_map_cal_handles[i], 0); rtac_clear_mapping(ADM_RTAC_CAL); } ad_logd("Resetting calibration blocks"); for (i = 0; i < MAX_AUDPROC_TYPES; i++) { /* Device calibration */ this_adm.mem_addr_audproc[i].cal_size = 0; this_adm.mem_addr_audproc[i].cal_kvaddr = 0; this_adm.mem_addr_audproc[i].cal_paddr = 0; /* Volume calibration */ this_adm.mem_addr_audvol[i].cal_size = 0; this_adm.mem_addr_audvol[i].cal_kvaddr = 0; this_adm.mem_addr_audvol[i].cal_paddr = 0; } return 0; } adm_callback_debug_print(data); if (data->payload_size) { index = q6audio_get_port_index(data->token); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d token %d\n", __func__, index, data->token); return 0; } if (data->opcode == APR_BASIC_RSP_RESULT) { ad_logd("APR_BASIC_RSP_RESULT id %x\n", payload[0]); if (payload[1] != 0) { ad_loge("%s: cmd = 0x%x returned error = 0x%x\n", __func__, payload[0], payload[1]); } switch (payload[0]) { case ADM_CMD_SET_PP_PARAMS_V5: ad_logd("%s: ADM_CMD_SET_PP_PARAMS_V5\n", __func__); if (rtac_make_adm_callback( payload, data->payload_size)) { break; } case ADM_CMD_DEVICE_CLOSE_V5: case ADM_CMD_SHARED_MEM_UNMAP_REGIONS: case ADM_CMD_MATRIX_MAP_ROUTINGS_V5: case ADM_CMD_ADD_TOPOLOGIES: ad_logd("%s: Basic callback received, wake up.\n", __func__); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; case ADM_CMD_SHARED_MEM_MAP_REGIONS: ad_logd("%s: ADM_CMD_SHARED_MEM_MAP_REGIONS\n", __func__); /* Should only come here if there is an APR */ /* error or malformed APR packet. Otherwise */ /* response will be returned as */ if (payload[1] != 0) { ad_loge("%s: ADM map error, resuming\n", __func__); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); } break; case ADM_CMD_GET_PP_PARAMS_V5: ad_logd("%s: ADM_CMD_GET_PP_PARAMS_V5\n", __func__); /* Should only come here if there is an APR */ /* error or malformed APR packet. Otherwise */ /* response will be returned as */ /* ADM_CMDRSP_GET_PP_PARAMS_V5 */ if (payload[1] != 0) { ad_loge("%s: ADM get param error = %d, resuming\n", __func__, payload[1]); rtac_make_adm_callback(payload, data->payload_size); } break; case ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5: ad_logd("%s:ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5\n", __func__); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; default: ad_loge("%s: Unknown Cmd: 0x%x\n", __func__, payload[0]); break; } return 0; } switch (data->opcode) { case ADM_CMDRSP_DEVICE_OPEN_V5: { struct adm_cmd_rsp_device_open_v5 *open = (struct adm_cmd_rsp_device_open_v5 *)data->payload; if (open->copp_id == INVALID_COPP_ID) { ad_loge("%s: invalid coppid rxed %d\n", __func__, open->copp_id); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; } if (atomic_read(&this_adm.copp_perf_mode[index])) { atomic_set(&this_adm.copp_low_latency_id[index], open->copp_id); } else { atomic_set(&this_adm.copp_id[index], open->copp_id); } atomic_set(&this_adm.copp_stat[index], 1); ad_logd("%s: coppid rxed=%d\n", __func__, open->copp_id); wake_up(&this_adm.wait[index]); } break; case ADM_CMDRSP_GET_PP_PARAMS_V5: ad_logd("%s: ADM_CMDRSP_GET_PP_PARAMS_V5\n", __func__); if (payload[0] != 0) ad_loge("%s: ADM_CMDRSP_GET_PP_PARAMS_V5 returned error = 0x%x\n", __func__, payload[0]); if (rtac_make_adm_callback(payload, data->payload_size)) break; if ((payload[0] == 0) && (data->payload_size > (4 * sizeof(*payload))) && (data->payload_size/sizeof(*payload)-4 >= payload[3]) && (ARRAY_SIZE(adm_get_parameters)-1 >= payload[3])) { adm_get_parameters[0] = payload[3]; pr_debug("%s: GET_PP PARAM:received parameter length: 0x%x\n", __func__, adm_get_parameters[0]); /* storing param size then params */ for (i = 0; i < payload[3]; i++) adm_get_parameters[1+i] = payload[4+i]; } else { adm_get_parameters[0] = -1; pr_err("%s: GET_PP_PARAMS failed, setting size to %d\n", __func__, adm_get_parameters[0]); } atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; case ADM_CMDRSP_SHARED_MEM_MAP_REGIONS: ad_logd("%s: ADM_CMDRSP_SHARED_MEM_MAP_REGIONS\n", __func__); atomic_set(&this_adm.mem_map_cal_handles[ atomic_read(&this_adm.mem_map_cal_index)], *payload); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; default: ad_loge("%s: Unknown cmd:0x%x\n", __func__, data->opcode); break; } } return 0; } void send_adm_custom_topology(int port_id) { struct acdb_cal_block cal_block; struct cmd_set_topologies adm_top; int index; int result; int size = 4096; get_adm_custom_topology(&cal_block); if (cal_block.cal_size == 0) { ad_logd("%s: no cal to send addr= 0x%pa\n", __func__, &cal_block.cal_paddr); goto done; } index = afe_get_port_index(port_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); goto done; } if (this_adm.set_custom_topology) { /* specific index 4 for adm topology memory */ atomic_set(&this_adm.mem_map_cal_index, ADM_CUSTOM_TOP_CAL); /* Only call this once */ this_adm.set_custom_topology = 0; result = adm_memory_map_regions(port_id, &cal_block.cal_paddr, 0, &size, 1); if (result < 0) { ad_loge("%s: mmap did not work! addr = 0x%pa, size = %zd\n", __func__, &cal_block.cal_paddr, cal_block.cal_size); goto done; } } adm_top.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(20), APR_PKT_VER); adm_top.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(adm_top)); adm_top.hdr.src_svc = APR_SVC_ADM; adm_top.hdr.src_domain = APR_DOMAIN_APPS; adm_top.hdr.src_port = port_id; adm_top.hdr.dest_svc = APR_SVC_ADM; adm_top.hdr.dest_domain = APR_DOMAIN_ADSP; adm_top.hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_top.hdr.token = port_id; adm_top.hdr.opcode = ADM_CMD_ADD_TOPOLOGIES; adm_top.payload_addr_lsw = lower_32_bits(cal_block.cal_paddr); adm_top.payload_addr_msw = upper_32_bits(cal_block.cal_paddr); adm_top.mem_map_handle = atomic_read(&this_adm.mem_map_cal_handles[ADM_CUSTOM_TOP_CAL]); adm_top.payload_size = cal_block.cal_size; atomic_set(&this_adm.copp_stat[index], 0); ad_logd("%s: Sending ADM_CMD_ADD_TOPOLOGIES payload = 0x%x, size = %d\n", __func__, adm_top.payload_addr_lsw, adm_top.payload_size); result = apr_send_pkt(this_adm.apr, (uint32_t *)&adm_top); if (result < 0) { ad_loge("%s: Set topologies failed port = 0x%x payload = 0x%pa\n", __func__, port_id, &cal_block.cal_paddr); goto done; } /* Wait for the callback */ result = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!result) { ad_loge("%s: Set topologies timed out port = 0x%x, payload = 0x%pa\n", __func__, port_id, &cal_block.cal_paddr); goto done; } done: return; } static int send_adm_cal_block(int port_id, struct acdb_cal_block *aud_cal, int perf_mode) { s32 result = 0; struct adm_cmd_set_pp_params_v5 adm_params; int index = afe_get_port_index(port_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); return 0; } ad_logd("%s: Port id %#x, index %d\n", __func__, port_id, index); if (!aud_cal || aud_cal->cal_size == 0) { ad_logd("%s: No ADM cal to send for port_id = %#x!\n", __func__, port_id); result = -EINVAL; goto done; } adm_params.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(20), APR_PKT_VER); adm_params.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(adm_params)); adm_params.hdr.src_svc = APR_SVC_ADM; adm_params.hdr.src_domain = APR_DOMAIN_APPS; adm_params.hdr.src_port = port_id; adm_params.hdr.dest_svc = APR_SVC_ADM; adm_params.hdr.dest_domain = APR_DOMAIN_ADSP; if (perf_mode == LEGACY_PCM_MODE) adm_params.hdr.dest_port = atomic_read(&this_adm.copp_id[index]); else adm_params.hdr.dest_port = atomic_read(&this_adm.copp_low_latency_id[index]); adm_params.hdr.token = port_id; adm_params.hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5; adm_params.payload_addr_lsw = lower_32_bits(aud_cal->cal_paddr); adm_params.payload_addr_msw = upper_32_bits(aud_cal->cal_paddr); adm_params.mem_map_handle = atomic_read(&this_adm.mem_map_cal_handles[ atomic_read(&this_adm.mem_map_cal_index)]); adm_params.payload_size = aud_cal->cal_size; atomic_set(&this_adm.copp_stat[index], 0); ad_logd("%s: Sending SET_PARAMS payload = 0x%x, size = %d\n", __func__, adm_params.payload_addr_lsw, adm_params.payload_size); result = apr_send_pkt(this_adm.apr, (uint32_t *)&adm_params); if (result < 0) { ad_loge("%s: Set params failed port = %#x payload = 0x%pa\n", __func__, port_id, &aud_cal->cal_paddr); result = -EINVAL; goto done; } /* Wait for the callback */ result = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!result) { ad_loge("%s: Set params timed out port = %#x, payload = 0x%pa\n", __func__, port_id, &aud_cal->cal_paddr); result = -EINVAL; goto done; } result = 0; done: return result; } static void send_adm_cal(int port_id, int path, int perf_mode) { int result = 0; s32 acdb_path; struct acdb_cal_block aud_cal; int size; ad_logd("%s\n", __func__); /* Maps audio_dev_ctrl path definition to ACDB definition */ acdb_path = path - 1; if (acdb_path == TX_CAL) size = 4096 * 4; else size = 4096; ad_logd("%s: Sending audproc cal\n", __func__); get_audproc_cal(acdb_path, &aud_cal); /* map & cache buffers used */ atomic_set(&this_adm.mem_map_cal_index, acdb_path); if (((this_adm.mem_addr_audproc[acdb_path].cal_paddr != aud_cal.cal_paddr) && (aud_cal.cal_size > 0)) || (aud_cal.cal_size > this_adm.mem_addr_audproc[acdb_path].cal_size)) { if (this_adm.mem_addr_audproc[acdb_path].cal_paddr != 0) adm_memory_unmap_regions(port_id); result = adm_memory_map_regions(port_id, &aud_cal.cal_paddr, 0, &size, 1); if (result < 0) { ad_loge("ADM audproc mmap did not work! path = %d, addr = 0x%pa, size = %zd\n", acdb_path, &aud_cal.cal_paddr, aud_cal.cal_size); } else { this_adm.mem_addr_audproc[acdb_path].cal_paddr = aud_cal.cal_paddr; this_adm.mem_addr_audproc[acdb_path].cal_size = size; } } if (!send_adm_cal_block(port_id, &aud_cal, perf_mode)) ad_logd("%s: Audproc cal sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); else ad_logd("%s: Audproc cal not sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); ad_logd("%s: Sending audvol cal\n", __func__); get_audvol_cal(acdb_path, &aud_cal); /* map & cache buffers used */ atomic_set(&this_adm.mem_map_cal_index, (acdb_path + MAX_AUDPROC_TYPES)); if (((this_adm.mem_addr_audvol[acdb_path].cal_paddr != aud_cal.cal_paddr) && (aud_cal.cal_size > 0)) || (aud_cal.cal_size > this_adm.mem_addr_audvol[acdb_path].cal_size)) { if (this_adm.mem_addr_audvol[acdb_path].cal_paddr != 0) adm_memory_unmap_regions(port_id); result = adm_memory_map_regions(port_id, &aud_cal.cal_paddr, 0, &size, 1); if (result < 0) { ad_loge("ADM audvol mmap did not work! path = %d, addr = 0x%pa, size = %zd\n", acdb_path, &aud_cal.cal_paddr, aud_cal.cal_size); } else { this_adm.mem_addr_audvol[acdb_path].cal_paddr = aud_cal.cal_paddr; this_adm.mem_addr_audvol[acdb_path].cal_size = size; } } if (!send_adm_cal_block(port_id, &aud_cal, perf_mode)) ad_logd("%s: Audvol cal sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); else ad_logd("%s: Audvol cal not sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); } int adm_map_rtac_block(struct rtac_cal_block_data *cal_block) { int result = 0; ad_logd("%s\n", __func__); if (cal_block == NULL) { ad_loge("%s: cal_block is NULL!\n", __func__); result = -EINVAL; goto done; } if (cal_block->cal_data.paddr == 0) { ad_logd("%s: No address to map!\n", __func__); result = -EINVAL; goto done; } if (cal_block->map_data.map_size == 0) { ad_logd("%s: map size is 0!\n", __func__); result = -EINVAL; goto done; } /* valid port ID needed for callback use primary I2S */ atomic_set(&this_adm.mem_map_cal_index, ADM_RTAC); result = adm_memory_map_regions(PRIMARY_I2S_RX, &cal_block->cal_data.paddr, 0, &cal_block->map_data.map_size, 1); if (result < 0) { ad_loge("%s: RTAC mmap did not work! addr = 0x%pa, size = %d\n", __func__, &cal_block->cal_data.paddr, cal_block->map_data.map_size); goto done; } cal_block->map_data.map_handle = atomic_read( &this_adm.mem_map_cal_handles[ADM_RTAC]); done: return result; } int adm_unmap_rtac_block(uint32_t *mem_map_handle) { int result = 0; ad_logd("%s\n", __func__); if (mem_map_handle == NULL) { ad_logd("%s: Map handle is NULL, nothing to unmap\n", __func__); goto done; } if (*mem_map_handle == 0) { ad_logd("%s: Map handle is 0, nothing to unmap\n", __func__); goto done; } if (*mem_map_handle != atomic_read( &this_adm.mem_map_cal_handles[ADM_RTAC])) { ad_loge("%s: Map handles do not match! Unmapping RTAC, RTAC map 0x%x, ADM map 0x%x\n", __func__, *mem_map_handle, atomic_read( &this_adm.mem_map_cal_handles[ADM_RTAC])); /* if mismatch use handle passed in to unmap */ atomic_set(&this_adm.mem_map_cal_handles[ADM_RTAC], *mem_map_handle); } /* valid port ID needed for callback use primary I2S */ atomic_set(&this_adm.mem_map_cal_index, ADM_RTAC); result = adm_memory_unmap_regions(PRIMARY_I2S_RX); if (result < 0) { ad_logd("%s: adm_memory_unmap_regions failed, error %d\n", __func__, result); } else { atomic_set(&this_adm.mem_map_cal_handles[ADM_RTAC], 0); *mem_map_handle = 0; } done: return result; } int adm_unmap_cal_blocks(void) { int i; int result = 0; int result2 = 0; for (i = 0; i < ADM_MAX_CAL_TYPES; i++) { if (atomic_read(&this_adm.mem_map_cal_handles[i]) != 0) { if (i <= ADM_TX_AUDPROC_CAL) { this_adm.mem_addr_audproc[i].cal_paddr = 0; this_adm.mem_addr_audproc[i].cal_size = 0; } else if (i <= ADM_TX_AUDVOL_CAL) { this_adm.mem_addr_audvol [(i - ADM_RX_AUDVOL_CAL)].cal_paddr = 0; this_adm.mem_addr_audvol [(i - ADM_RX_AUDVOL_CAL)].cal_size = 0; } else if (i == ADM_CUSTOM_TOP_CAL) { this_adm.set_custom_topology = 1; } else { continue; } /* valid port ID needed for callback use primary I2S */ atomic_set(&this_adm.mem_map_cal_index, i); result2 = adm_memory_unmap_regions(PRIMARY_I2S_RX); if (result2 < 0) { ad_loge("%s: adm_memory_unmap_regions failed, err %d\n", __func__, result2); result = result2; } else { atomic_set(&this_adm.mem_map_cal_handles[i], 0); } } } return result; } int adm_connect_afe_port(int mode, int session_id, int port_id) { struct adm_cmd_connect_afe_port_v5 cmd; int ret = 0; int index; ad_logd("%s: port %d session id:%d mode:%d\n", __func__, port_id, session_id, mode); port_id = afe_convert_virtual_to_portid(port_id); if (afe_validate_port(port_id) < 0) { ad_loge("%s port idi[%d] is invalid\n", __func__, port_id); return -ENODEV; } if (this_adm.apr == NULL) { this_adm.apr = apr_register("ADSP", "ADM", adm_callback, 0xFFFFFFFF, &this_adm); if (this_adm.apr == NULL) { ad_loge("%s: Unable to register ADM\n", __func__); ret = -ENODEV; return ret; } rtac_set_adm_handle(this_adm.apr); } index = afe_get_port_index(port_id); ad_logd("%s: Port ID %#x, index %d\n", __func__, port_id, index); cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cmd.hdr.pkt_size = sizeof(cmd); cmd.hdr.src_svc = APR_SVC_ADM; cmd.hdr.src_domain = APR_DOMAIN_APPS; cmd.hdr.src_port = port_id; cmd.hdr.dest_svc = APR_SVC_ADM; cmd.hdr.dest_domain = APR_DOMAIN_ADSP; cmd.hdr.dest_port = port_id; cmd.hdr.token = port_id; cmd.hdr.opcode = ADM_CMD_CONNECT_AFE_PORT_V5; cmd.mode = mode; cmd.session_id = session_id; cmd.afe_port_id = port_id; atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *)&cmd); if (ret < 0) { ad_loge("%s:ADM enable for port %#x failed\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } /* Wait for the callback with copp id */ ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s ADM connect AFE failed for port %#x\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } atomic_inc(&this_adm.copp_cnt[index]); return 0; fail_cmd: return ret; } int adm_open(int port_id, int path, int rate, int channel_mode, int topology, int perf_mode, uint16_t bits_per_sample) { struct adm_cmd_device_open_v5 open; int ret = 0; int index; int tmp_port = q6audio_get_port_id(port_id); ad_logd("%s: port %#x path:%d rate:%d mode:%d perf_mode:%d\n", __func__, port_id, path, rate, channel_mode, perf_mode); port_id = q6audio_convert_virtual_to_portid(port_id); if (q6audio_validate_port(port_id) < 0) { ad_loge("%s port idi[%#x] is invalid\n", __func__, port_id); return -ENODEV; } index = q6audio_get_port_index(port_id); ad_logd("%s: Port ID %#x, index %d\n", __func__, port_id, index); if (this_adm.apr == NULL) { this_adm.apr = apr_register("ADSP", "ADM", adm_callback, 0xFFFFFFFF, &this_adm); if (this_adm.apr == NULL) { ad_loge("%s: Unable to register ADM\n", __func__); ret = -ENODEV; return ret; } rtac_set_adm_handle(this_adm.apr); } if (perf_mode == LEGACY_PCM_MODE) { atomic_set(&this_adm.copp_perf_mode[index], 0); send_adm_custom_topology(port_id); } else { atomic_set(&this_adm.copp_perf_mode[index], 1); } /* Create a COPP if port id are not enabled */ if ((perf_mode == LEGACY_PCM_MODE && (atomic_read(&this_adm.copp_cnt[index]) == 0)) || (perf_mode != LEGACY_PCM_MODE && (atomic_read(&this_adm.copp_low_latency_cnt[index]) == 0))) { ad_logd("%s:opening ADM: perf_mode: %d\n", __func__, perf_mode); open.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); open.hdr.pkt_size = sizeof(open); open.hdr.src_svc = APR_SVC_ADM; open.hdr.src_domain = APR_DOMAIN_APPS; open.hdr.src_port = tmp_port; open.hdr.dest_svc = APR_SVC_ADM; open.hdr.dest_domain = APR_DOMAIN_ADSP; open.hdr.dest_port = tmp_port; open.hdr.token = port_id; open.hdr.opcode = ADM_CMD_DEVICE_OPEN_V5; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE) open.flags = ADM_ULTRA_LOW_LATENCY_DEVICE_SESSION; else if (perf_mode == LOW_LATENCY_PCM_MODE) open.flags = ADM_LOW_LATENCY_DEVICE_SESSION; else open.flags = ADM_LEGACY_DEVICE_SESSION; open.mode_of_operation = path; open.endpoint_id_1 = tmp_port; if (this_adm.ec_ref_rx == -1) { open.endpoint_id_2 = 0xFFFF; } else if (this_adm.ec_ref_rx && (path != 1)) { open.endpoint_id_2 = this_adm.ec_ref_rx; this_adm.ec_ref_rx = -1; } open.topology_id = topology; if ((open.topology_id == VPM_TX_SM_ECNS_COPP_TOPOLOGY) || (open.topology_id == VPM_TX_DM_FLUENCE_COPP_TOPOLOGY) || (open.topology_id == VPM_TX_DM_RFECNS_COPP_TOPOLOGY)) rate = 16000; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE) { open.topology_id = NULL_COPP_TOPOLOGY; rate = ULL_SUPPORTED_SAMPLE_RATE; } else if (perf_mode == LOW_LATENCY_PCM_MODE) { if ((open.topology_id == DOLBY_ADM_COPP_TOPOLOGY_ID) || (open.topology_id == SRS_TRUMEDIA_TOPOLOGY_ID)) open.topology_id = DEFAULT_COPP_TOPOLOGY; } open.dev_num_channel = channel_mode & 0x00FF; open.bit_width = bits_per_sample; WARN_ON(perf_mode == ULTRA_LOW_LATENCY_PCM_MODE && (rate != 48000)); open.sample_rate = rate; memset(open.dev_channel_mapping, 0, 8); if (channel_mode == 1) { open.dev_channel_mapping[0] = PCM_CHANNEL_FC; } else if (channel_mode == 2) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; } else if (channel_mode == 3) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_FC; } else if (channel_mode == 4) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_RB; open.dev_channel_mapping[3] = PCM_CHANNEL_LB; } else if (channel_mode == 5) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_FC; open.dev_channel_mapping[3] = PCM_CHANNEL_LB; open.dev_channel_mapping[4] = PCM_CHANNEL_RB; } else if (channel_mode == 6) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_LFE; open.dev_channel_mapping[3] = PCM_CHANNEL_FC; open.dev_channel_mapping[4] = PCM_CHANNEL_LS; open.dev_channel_mapping[5] = PCM_CHANNEL_RS; } else if (channel_mode == 8) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_LFE; open.dev_channel_mapping[3] = PCM_CHANNEL_FC; open.dev_channel_mapping[4] = PCM_CHANNEL_LB; open.dev_channel_mapping[5] = PCM_CHANNEL_RB; open.dev_channel_mapping[6] = PCM_CHANNEL_FLC; open.dev_channel_mapping[7] = PCM_CHANNEL_FRC; } else { ad_loge("%s invalid num_chan %d\n", __func__, channel_mode); return -EINVAL; } if ((open.dev_num_channel > 2) && multi_ch_map.set_channel_map) memcpy(open.dev_channel_mapping, multi_ch_map.channel_mapping, PCM_FORMAT_MAX_NUM_CHANNEL); ad_logd("%s: port_id=%#x rate=%d topology_id=0x%X\n", __func__, open.endpoint_id_1, open.sample_rate, open.topology_id); atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *)&open); if (ret < 0) { ad_loge("%s:ADM enable for port %#x for[%d] failed\n", __func__, tmp_port, port_id); ret = -EINVAL; goto fail_cmd; } /* Wait for the callback with copp id */ ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s ADM open failed for port %#x for [%d]\n", __func__, tmp_port, port_id); ret = -EINVAL; goto fail_cmd; } } if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { atomic_inc(&this_adm.copp_low_latency_cnt[index]); ad_logd("%s: index: %d coppid: %d", __func__, index, atomic_read(&this_adm.copp_low_latency_id[index])); } else { atomic_inc(&this_adm.copp_cnt[index]); ad_logd("%s: index: %d coppid: %d", __func__, index, atomic_read(&this_adm.copp_id[index])); } return 0; fail_cmd: return ret; } int adm_multi_ch_copp_open(int port_id, int path, int rate, int channel_mode, int topology, int perf_mode, uint16_t bits_per_sample) { int ret = 0; ret = adm_open(port_id, path, rate, channel_mode, topology, perf_mode, bits_per_sample); return ret; } int adm_matrix_map(int session_id, int path, int num_copps, unsigned int *port_id, int copp_id, int perf_mode) { struct adm_cmd_matrix_map_routings_v5 *route; struct adm_session_map_node_v5 *node; uint16_t *copps_list; int cmd_size = 0; int ret = 0, i = 0; void *payload = NULL; void *matrix_map = NULL; /* Assumes port_ids have already been validated during adm_open */ int index = q6audio_get_port_index(copp_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d token %d\n", __func__, index, copp_id); return 0; } cmd_size = (sizeof(struct adm_cmd_matrix_map_routings_v5) + sizeof(struct adm_session_map_node_v5) + (sizeof(uint32_t) * num_copps)); matrix_map = kzalloc(cmd_size, GFP_KERNEL); if (matrix_map == NULL) { ad_loge("%s: Mem alloc failed\n", __func__); ret = -EINVAL; return ret; } route = (struct adm_cmd_matrix_map_routings_v5 *)matrix_map; ad_logd("%s: session 0x%x path:%d num_copps:%d port_id[0]:%#x coppid[%d]\n", __func__, session_id, path, num_copps, port_id[0], copp_id); route->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); route->hdr.pkt_size = cmd_size; route->hdr.src_svc = 0; route->hdr.src_domain = APR_DOMAIN_APPS; route->hdr.src_port = copp_id; route->hdr.dest_svc = APR_SVC_ADM; route->hdr.dest_domain = APR_DOMAIN_ADSP; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { route->hdr.dest_port = atomic_read(&this_adm.copp_low_latency_id[index]); } else { route->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); } route->hdr.token = copp_id; route->hdr.opcode = ADM_CMD_MATRIX_MAP_ROUTINGS_V5; route->num_sessions = 1; switch (path) { case 0x1: route->matrix_id = ADM_MATRIX_ID_AUDIO_RX; break; case 0x2: case 0x3: route->matrix_id = ADM_MATRIX_ID_AUDIO_TX; break; default: ad_loge("%s: Wrong path set[%d]\n", __func__, path); break; } payload = ((u8 *)matrix_map + sizeof(struct adm_cmd_matrix_map_routings_v5)); node = (struct adm_session_map_node_v5 *)payload; node->session_id = session_id; node->num_copps = num_copps; payload = (u8 *)node + sizeof(struct adm_session_map_node_v5); copps_list = (uint16_t *)payload; for (i = 0; i < num_copps; i++) { int tmp; port_id[i] = q6audio_convert_virtual_to_portid(port_id[i]); tmp = q6audio_get_port_index(port_id[i]); if (tmp >= 0 && tmp < AFE_MAX_PORTS) { if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) copps_list[i] = atomic_read(&this_adm.copp_low_latency_id[tmp]); else copps_list[i] = atomic_read(&this_adm.copp_id[tmp]); } else continue; ad_logd("%s: port_id[%#x]: %d, index: %d act coppid[0x%x]\n", __func__, i, port_id[i], tmp, copps_list[i]); } atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *)matrix_map); if (ret < 0) { ad_loge("%s: ADM routing for port %#x failed\n", __func__, port_id[0]); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s: ADM cmd Route failed for port %#x\n", __func__, port_id[0]); ret = -EINVAL; goto fail_cmd; } if (perf_mode != ULTRA_LOW_LATENCY_PCM_MODE) { for (i = 0; i < num_copps; i++) send_adm_cal(port_id[i], path, perf_mode); for (i = 0; i < num_copps; i++) { int tmp, copp_id; tmp = afe_get_port_index(port_id[i]); if (tmp >= 0 && tmp < AFE_MAX_PORTS) { if (perf_mode == LEGACY_PCM_MODE) copp_id = atomic_read( &this_adm.copp_id[tmp]); else copp_id = atomic_read( &this_adm.copp_low_latency_id[tmp]); rtac_add_adm_device(port_id[i], copp_id, path, session_id); ad_logd("%s, copp_id: %d\n", __func__, copp_id); } else ad_logd("%s: Invalid port index %d", __func__, tmp); } } fail_cmd: kfree(matrix_map); return ret; } int adm_memory_map_regions(int port_id, phys_addr_t *buf_add, uint32_t mempool_id, uint32_t *bufsz, uint32_t bufcnt) { struct avs_cmd_shared_mem_map_regions *mmap_regions = NULL; struct avs_shared_map_region_payload *mregions = NULL; void *mmap_region_cmd = NULL; void *payload = NULL; int ret = 0; int i = 0; int cmd_size = 0; int index = 0; ad_logd("%s\n", __func__); if (this_adm.apr == NULL) { this_adm.apr = apr_register("ADSP", "ADM", adm_callback, 0xFFFFFFFF, &this_adm); if (this_adm.apr == NULL) { ad_loge("%s: Unable to register ADM\n", __func__); ret = -ENODEV; return ret; } rtac_set_adm_handle(this_adm.apr); } port_id = q6audio_convert_virtual_to_portid(port_id); if (q6audio_validate_port(port_id) < 0) { ad_loge("%s port id[%#x] is invalid\n", __func__, port_id); return -ENODEV; } index = q6audio_get_port_index(port_id); cmd_size = sizeof(struct avs_cmd_shared_mem_map_regions) + sizeof(struct avs_shared_map_region_payload) * bufcnt; mmap_region_cmd = kzalloc(cmd_size, GFP_KERNEL); if (!mmap_region_cmd) { ad_loge("%s: allocate mmap_region_cmd failed\n", __func__); return -ENOMEM; } mmap_regions = (struct avs_cmd_shared_mem_map_regions *)mmap_region_cmd; mmap_regions->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mmap_regions->hdr.pkt_size = cmd_size; mmap_regions->hdr.src_port = 0; mmap_regions->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); mmap_regions->hdr.token = port_id; mmap_regions->hdr.opcode = ADM_CMD_SHARED_MEM_MAP_REGIONS; mmap_regions->mem_pool_id = ADSP_MEMORY_MAP_SHMEM8_4K_POOL & 0x00ff; mmap_regions->num_regions = bufcnt & 0x00ff; mmap_regions->property_flag = 0x00; ad_logd("%s: map_regions->num_regions = %d\n", __func__, mmap_regions->num_regions); payload = ((u8 *) mmap_region_cmd + sizeof(struct avs_cmd_shared_mem_map_regions)); mregions = (struct avs_shared_map_region_payload *)payload; for (i = 0; i < bufcnt; i++) { mregions->shm_addr_lsw = lower_32_bits(buf_add[i]); mregions->shm_addr_msw = upper_32_bits(buf_add[i]); mregions->mem_size_bytes = bufsz[i]; ++mregions; } atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *) mmap_region_cmd); if (ret < 0) { ad_loge("%s: mmap_regions op[0x%x]rc[%d]\n", __func__, mmap_regions->hdr.opcode, ret); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), 5 * HZ); if (!ret) { ad_loge("%s: timeout. waited for memory_map\n", __func__); ret = -EINVAL; goto fail_cmd; } fail_cmd: kfree(mmap_region_cmd); return ret; } int adm_memory_unmap_regions(int32_t port_id) { struct avs_cmd_shared_mem_unmap_regions unmap_regions; int ret = 0; int index = 0; ad_logd("%s\n", __func__); if (this_adm.apr == NULL) { ad_loge("%s APR handle NULL\n", __func__); return -EINVAL; } port_id = q6audio_convert_virtual_to_portid(port_id); if (q6audio_validate_port(port_id) < 0) { ad_loge("%s port idi[%d] is invalid\n", __func__, port_id); return -ENODEV; } index = q6audio_get_port_index(port_id); unmap_regions.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); unmap_regions.hdr.pkt_size = sizeof(unmap_regions); unmap_regions.hdr.src_port = 0; unmap_regions.hdr.dest_port = atomic_read(&this_adm.copp_id[index]); unmap_regions.hdr.token = port_id; unmap_regions.hdr.opcode = ADM_CMD_SHARED_MEM_UNMAP_REGIONS; unmap_regions.mem_map_handle = atomic_read(&this_adm. mem_map_cal_handles[atomic_read(&this_adm.mem_map_cal_index)]); atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *) &unmap_regions); if (ret < 0) { ad_loge("%s: mmap_regions op[0x%x]rc[%d]\n", __func__, unmap_regions.hdr.opcode, ret); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), 5 * HZ); if (!ret) { ad_loge("%s: timeout. waited for memory_unmap index %d\n", __func__, index); ret = -EINVAL; goto fail_cmd; } else { ad_logd("%s: Unmap handle 0x%x succeeded\n", __func__, unmap_regions.mem_map_handle); } fail_cmd: return ret; } #ifdef CONFIG_RTAC int adm_get_copp_id(int port_index) { int copp_id; ad_logd("%s\n", __func__); if (port_index < 0) { ad_loge("%s: invalid port_id = %d\n", __func__, port_index); return -EINVAL; } copp_id = atomic_read(&this_adm.copp_id[port_index]); if (copp_id == RESET_COPP_ID) copp_id = atomic_read( &this_adm.copp_low_latency_id[port_index]); return copp_id; } int adm_get_lowlatency_copp_id(int port_index) { ad_logd("%s\n", __func__); if (port_index < 0) { ad_loge("%s: invalid port_id = %d\n", __func__, port_index); return -EINVAL; } return atomic_read(&this_adm.copp_low_latency_id[port_index]); } #else int adm_get_copp_id(int port_index) { return -EINVAL; } int adm_get_lowlatency_copp_id(int port_index) { return -EINVAL; } #endif /* #ifdef CONFIG_RTAC */ void adm_ec_ref_rx_id(int port_id) { this_adm.ec_ref_rx = port_id; ad_logd("%s ec_ref_rx:%d", __func__, this_adm.ec_ref_rx); } int adm_close(int port_id, int perf_mode) { struct apr_hdr close; int ret = 0; int index = 0; int copp_id = RESET_COPP_ID; port_id = q6audio_convert_virtual_to_portid(port_id); index = q6audio_get_port_index(port_id); if (q6audio_validate_port(port_id) < 0) return -EINVAL; ad_logd("%s port_id=%#x index %d perf_mode: %d\n", __func__, port_id, index, perf_mode); if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { if (!(atomic_read(&this_adm.copp_low_latency_cnt[index]))) { ad_loge("%s: copp count for port[%#x]is 0\n", __func__, port_id); goto fail_cmd; } atomic_dec(&this_adm.copp_low_latency_cnt[index]); } else { if (!(atomic_read(&this_adm.copp_cnt[index]))) { ad_loge("%s: copp count for port[%#x]is 0\n", __func__, port_id); goto fail_cmd; } atomic_dec(&this_adm.copp_cnt[index]); } if ((perf_mode == LEGACY_PCM_MODE && !(atomic_read(&this_adm.copp_cnt[index]))) || ((perf_mode != LEGACY_PCM_MODE) && !(atomic_read(&this_adm.copp_low_latency_cnt[index])))) { ad_logd("%s:Closing ADM: perf_mode: %d\n", __func__, perf_mode); close.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); close.pkt_size = sizeof(close); close.src_svc = APR_SVC_ADM; close.src_domain = APR_DOMAIN_APPS; close.src_port = port_id; close.dest_svc = APR_SVC_ADM; close.dest_domain = APR_DOMAIN_ADSP; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) close.dest_port = atomic_read(&this_adm.copp_low_latency_id[index]); else close.dest_port = atomic_read(&this_adm.copp_id[index]); close.token = port_id; close.opcode = ADM_CMD_DEVICE_CLOSE_V5; atomic_set(&this_adm.copp_stat[index], 0); if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { copp_id = atomic_read( &this_adm.copp_low_latency_id[index]); ad_logd("%s:coppid %d portid=%#x index=%d coppcnt=%d\n", __func__, copp_id, port_id, index, atomic_read( &this_adm.copp_low_latency_cnt[index])); atomic_set(&this_adm.copp_low_latency_id[index], RESET_COPP_ID); } else { copp_id = atomic_read(&this_adm.copp_id[index]); ad_logd("%s:coppid %d portid=%#x index=%d coppcnt=%d\n", __func__, copp_id, port_id, index, atomic_read(&this_adm.copp_cnt[index])); atomic_set(&this_adm.copp_id[index], RESET_COPP_ID); } ret = apr_send_pkt(this_adm.apr, (uint32_t *)&close); if (ret < 0) { ad_loge("%s ADM close failed\n", __func__); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s: ADM cmd Route failed for port %#x\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } } if (perf_mode != ULTRA_LOW_LATENCY_PCM_MODE) { ad_logd("%s: remove adm device from rtac\n", __func__); rtac_remove_adm_device(port_id, copp_id); } fail_cmd: return ret; } static int __init adm_init(void) { int i = 0; this_adm.apr = NULL; this_adm.set_custom_topology = 1; this_adm.ec_ref_rx = -1; for (i = 0; i < AFE_MAX_PORTS; i++) { atomic_set(&this_adm.copp_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_low_latency_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_cnt[i], 0); atomic_set(&this_adm.copp_low_latency_cnt[i], 0); atomic_set(&this_adm.copp_stat[i], 0); atomic_set(&this_adm.copp_perf_mode[i], 0); init_waitqueue_head(&this_adm.wait[i]); } return 0; } device_initcall(adm_init);
EloYGomeZ/test_kernel_g620s
sound/soc/msm/qdsp6v2/q6adm.c
C
gpl-2.0
55,954
/* * PROJECT: ReactOS i8042 (ps/2 keyboard-mouse controller) driver * LICENSE: GPL - See COPYING in the top level directory * FILE: drivers/input/i8042prt/pnp.c * PURPOSE: IRP_MJ_PNP operations * PROGRAMMERS: Copyright 2006-2007 Hervé Poussineau (hpoussin@reactos.org) * Copyright 2008 Colin Finck (mail@colinfinck.de) */ /* INCLUDES ******************************************************************/ #include "i8042prt.h" #include <debug.h> /* FUNCTIONS *****************************************************************/ /* This is all pretty confusing. There's more than one way to * disable/enable the keyboard. You can send KBD_ENABLE to the * keyboard, and it will start scanning keys. Sending KBD_DISABLE * will disable the key scanning but also reset the parameters to * defaults. * * You can also send 0xAE to the controller for enabling the * keyboard clock line and 0xAD for disabling it. Then it'll * automatically get turned on at the next command. The last * way is by modifying the bit that drives the clock line in the * 'command byte' of the controller. This is almost, but not quite, * the same as the AE/AD thing. The difference can be used to detect * some really old broken keyboard controllers which I hope won't be * necessary. * * We change the command byte, sending KBD_ENABLE/DISABLE seems to confuse * some kvm switches. */ BOOLEAN i8042ChangeMode( IN PPORT_DEVICE_EXTENSION DeviceExtension, IN UCHAR FlagsToDisable, IN UCHAR FlagsToEnable) { UCHAR Value; NTSTATUS Status; if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, KBD_READ_MODE)) { WARN_(I8042PRT, "Can't read i8042 mode\n"); return FALSE; } Status = i8042ReadDataWait(DeviceExtension, &Value); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "No response after read i8042 mode\n"); return FALSE; } Value &= ~FlagsToDisable; Value |= FlagsToEnable; if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, KBD_WRITE_MODE)) { WARN_(I8042PRT, "Can't set i8042 mode\n"); return FALSE; } if (!i8042Write(DeviceExtension, DeviceExtension->DataPort, Value)) { WARN_(I8042PRT, "Can't send i8042 mode\n"); return FALSE; } return TRUE; } static NTSTATUS i8042BasicDetect( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status; ULONG ResendIterations; UCHAR Value = 0; /* Don't enable keyboard and mouse interrupts, disable keyboard/mouse */ i8042Flush(DeviceExtension); if (!i8042ChangeMode(DeviceExtension, CCB_KBD_INT_ENAB | CCB_MOUSE_INT_ENAB, CCB_KBD_DISAB | CCB_MOUSE_DISAB)) return STATUS_IO_DEVICE_ERROR; i8042Flush(DeviceExtension); /* Issue a CTRL_SELF_TEST command to check if this is really an i8042 controller */ ResendIterations = DeviceExtension->Settings.ResendIterations + 1; while (ResendIterations--) { if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, CTRL_SELF_TEST)) { WARN_(I8042PRT, "Writing CTRL_SELF_TEST command failed\n"); return STATUS_IO_TIMEOUT; } Status = i8042ReadDataWait(DeviceExtension, &Value); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "Failed to read CTRL_SELF_TEST response, status 0x%08lx\n", Status); return Status; } if (Value == KBD_SELF_TEST_OK) { INFO_(I8042PRT, "CTRL_SELF_TEST completed successfully!\n"); break; } else if (Value == KBD_RESEND) { TRACE_(I8042PRT, "Resending...\n"); KeStallExecutionProcessor(50); } else { WARN_(I8042PRT, "Got 0x%02x instead of 0x55\n", Value); return STATUS_IO_DEVICE_ERROR; } } return STATUS_SUCCESS; } static VOID i8042DetectKeyboard( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status; /* Set LEDs (that is not fatal if some error occurs) */ Status = i8042SynchWritePort(DeviceExtension, 0, KBD_CMD_SET_LEDS, TRUE); if (NT_SUCCESS(Status)) { Status = i8042SynchWritePort(DeviceExtension, 0, 0, TRUE); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "Can't finish SET_LEDS (0x%08lx)\n", Status); return; } } else { WARN_(I8042PRT, "Warning: can't write SET_LEDS (0x%08lx)\n", Status); } /* Turn on translation and SF (Some machines don't reboot if SF is not set, see ReactOS bug CORE-1713) */ if (!i8042ChangeMode(DeviceExtension, 0, CCB_TRANSLATE | CCB_SYSTEM_FLAG)) return; /* * We used to send a KBD_LINE_TEST (0xAB) command, but on at least HP * Pavilion notebooks the response to that command was incorrect. * So now we just assume that a keyboard is attached. */ DeviceExtension->Flags |= KEYBOARD_PRESENT; INFO_(I8042PRT, "Keyboard detected\n"); } static VOID i8042DetectMouse( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status; UCHAR Value; UCHAR ExpectedReply[] = { MOUSE_ACK, 0xAA }; UCHAR ReplyByte; /* First do a mouse line test */ if (i8042Write(DeviceExtension, DeviceExtension->ControlPort, MOUSE_LINE_TEST)) { Status = i8042ReadDataWait(DeviceExtension, &Value); if (!NT_SUCCESS(Status) || Value != 0) { WARN_(I8042PRT, "Mouse line test failed\n"); goto failure; } } /* Now reset the mouse */ i8042Flush(DeviceExtension); if(!i8042IsrWritePort(DeviceExtension, MOU_CMD_RESET, CTRL_WRITE_MOUSE)) { WARN_(I8042PRT, "Failed to write reset command to mouse\n"); goto failure; } /* The implementation of the "Mouse Reset" command differs much from chip to chip. By default, the first byte is an ACK, when the mouse is plugged in and working and NACK when it's not. On success, the next bytes are 0xAA and 0x00. But on some systems (like ECS K7S5A Pro, SiS 735 chipset), we always get an ACK and 0xAA. Only the last byte indicates, whether a mouse is plugged in. It is either sent or not, so there is no byte, which indicates a failure here. After the Mouse Reset command was issued, it usually takes some time until we get a response. So get the first two bytes in a loop. */ for (ReplyByte = 0; ReplyByte < sizeof(ExpectedReply) / sizeof(ExpectedReply[0]); ReplyByte++) { ULONG Counter = 500; do { Status = i8042ReadDataWait(DeviceExtension, &Value); if(!NT_SUCCESS(Status)) { /* Wait some time before trying again */ KeStallExecutionProcessor(50); } } while (Status == STATUS_IO_TIMEOUT && Counter--); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "No ACK after mouse reset, status 0x%08lx\n", Status); goto failure; } else if (Value != ExpectedReply[ReplyByte]) { WARN_(I8042PRT, "Unexpected reply: 0x%02x (expected 0x%02x)\n", Value, ExpectedReply[ReplyByte]); goto failure; } } /* Finally get the third byte, but only try it one time (see above). Otherwise this takes around 45 seconds on a K7S5A Pro, when no mouse is plugged in. */ Status = i8042ReadDataWait(DeviceExtension, &Value); if(!NT_SUCCESS(Status)) { WARN_(I8042PRT, "Last byte was not transmitted after mouse reset, status 0x%08lx\n", Status); goto failure; } else if(Value != 0x00) { WARN_(I8042PRT, "Last byte after mouse reset was not 0x00, but 0x%02x\n", Value); goto failure; } DeviceExtension->Flags |= MOUSE_PRESENT; INFO_(I8042PRT, "Mouse detected\n"); return; failure: /* There is probably no mouse present. On some systems, the probe locks the entire keyboard controller. Let's try to get access to the keyboard again by sending a reset */ i8042Flush(DeviceExtension); i8042Write(DeviceExtension, DeviceExtension->ControlPort, CTRL_SELF_TEST); i8042ReadDataWait(DeviceExtension, &Value); i8042Flush(DeviceExtension); INFO_(I8042PRT, "Mouse not detected\n"); } static NTSTATUS i8042ConnectKeyboardInterrupt( IN PI8042_KEYBOARD_EXTENSION DeviceExtension) { PPORT_DEVICE_EXTENSION PortDeviceExtension; KIRQL DirqlMax; NTSTATUS Status; TRACE_(I8042PRT, "i8042ConnectKeyboardInterrupt()\n"); PortDeviceExtension = DeviceExtension->Common.PortDeviceExtension; DirqlMax = MAX( PortDeviceExtension->KeyboardInterrupt.Dirql, PortDeviceExtension->MouseInterrupt.Dirql); INFO_(I8042PRT, "KeyboardInterrupt.Vector %lu\n", PortDeviceExtension->KeyboardInterrupt.Vector); INFO_(I8042PRT, "KeyboardInterrupt.Dirql %lu\n", PortDeviceExtension->KeyboardInterrupt.Dirql); INFO_(I8042PRT, "KeyboardInterrupt.DirqlMax %lu\n", DirqlMax); INFO_(I8042PRT, "KeyboardInterrupt.InterruptMode %s\n", PortDeviceExtension->KeyboardInterrupt.InterruptMode == LevelSensitive ? "LevelSensitive" : "Latched"); INFO_(I8042PRT, "KeyboardInterrupt.ShareInterrupt %s\n", PortDeviceExtension->KeyboardInterrupt.ShareInterrupt ? "yes" : "no"); INFO_(I8042PRT, "KeyboardInterrupt.Affinity 0x%lx\n", PortDeviceExtension->KeyboardInterrupt.Affinity); Status = IoConnectInterrupt( &PortDeviceExtension->KeyboardInterrupt.Object, i8042KbdInterruptService, DeviceExtension, &PortDeviceExtension->SpinLock, PortDeviceExtension->KeyboardInterrupt.Vector, PortDeviceExtension->KeyboardInterrupt.Dirql, DirqlMax, PortDeviceExtension->KeyboardInterrupt.InterruptMode, PortDeviceExtension->KeyboardInterrupt.ShareInterrupt, PortDeviceExtension->KeyboardInterrupt.Affinity, FALSE); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "IoConnectInterrupt() failed with status 0x%08x\n", Status); return Status; } if (DirqlMax == PortDeviceExtension->KeyboardInterrupt.Dirql) PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->KeyboardInterrupt.Object; PortDeviceExtension->Flags |= KEYBOARD_INITIALIZED; return STATUS_SUCCESS; } static NTSTATUS i8042ConnectMouseInterrupt( IN PI8042_MOUSE_EXTENSION DeviceExtension) { PPORT_DEVICE_EXTENSION PortDeviceExtension; KIRQL DirqlMax; NTSTATUS Status; TRACE_(I8042PRT, "i8042ConnectMouseInterrupt()\n"); Status = i8042MouInitialize(DeviceExtension); if (!NT_SUCCESS(Status)) return Status; PortDeviceExtension = DeviceExtension->Common.PortDeviceExtension; DirqlMax = MAX( PortDeviceExtension->KeyboardInterrupt.Dirql, PortDeviceExtension->MouseInterrupt.Dirql); INFO_(I8042PRT, "MouseInterrupt.Vector %lu\n", PortDeviceExtension->MouseInterrupt.Vector); INFO_(I8042PRT, "MouseInterrupt.Dirql %lu\n", PortDeviceExtension->MouseInterrupt.Dirql); INFO_(I8042PRT, "MouseInterrupt.DirqlMax %lu\n", DirqlMax); INFO_(I8042PRT, "MouseInterrupt.InterruptMode %s\n", PortDeviceExtension->MouseInterrupt.InterruptMode == LevelSensitive ? "LevelSensitive" : "Latched"); INFO_(I8042PRT, "MouseInterrupt.ShareInterrupt %s\n", PortDeviceExtension->MouseInterrupt.ShareInterrupt ? "yes" : "no"); INFO_(I8042PRT, "MouseInterrupt.Affinity 0x%lx\n", PortDeviceExtension->MouseInterrupt.Affinity); Status = IoConnectInterrupt( &PortDeviceExtension->MouseInterrupt.Object, i8042MouInterruptService, DeviceExtension, &PortDeviceExtension->SpinLock, PortDeviceExtension->MouseInterrupt.Vector, PortDeviceExtension->MouseInterrupt.Dirql, DirqlMax, PortDeviceExtension->MouseInterrupt.InterruptMode, PortDeviceExtension->MouseInterrupt.ShareInterrupt, PortDeviceExtension->MouseInterrupt.Affinity, FALSE); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "IoConnectInterrupt() failed with status 0x%08x\n", Status); goto cleanup; } if (DirqlMax == PortDeviceExtension->MouseInterrupt.Dirql) PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->MouseInterrupt.Object; PortDeviceExtension->Flags |= MOUSE_INITIALIZED; Status = STATUS_SUCCESS; cleanup: if (!NT_SUCCESS(Status)) { PortDeviceExtension->Flags &= ~MOUSE_INITIALIZED; if (PortDeviceExtension->MouseInterrupt.Object) { IoDisconnectInterrupt(PortDeviceExtension->MouseInterrupt.Object); PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->KeyboardInterrupt.Object; } } return Status; } static NTSTATUS EnableInterrupts( IN PPORT_DEVICE_EXTENSION DeviceExtension, IN UCHAR FlagsToDisable, IN UCHAR FlagsToEnable) { i8042Flush(DeviceExtension); if (!i8042ChangeMode(DeviceExtension, FlagsToDisable, FlagsToEnable)) return STATUS_UNSUCCESSFUL; return STATUS_SUCCESS; } static NTSTATUS StartProcedure( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status = STATUS_UNSUCCESSFUL; UCHAR FlagsToDisable = 0; UCHAR FlagsToEnable = 0; KIRQL Irql; if (DeviceExtension->DataPort == 0) { /* Unable to do something at the moment */ return STATUS_SUCCESS; } if (!(DeviceExtension->Flags & (KEYBOARD_PRESENT | MOUSE_PRESENT))) { /* Try to detect them */ TRACE_(I8042PRT, "Check if the controller is really a i8042\n"); Status = i8042BasicDetect(DeviceExtension); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "i8042BasicDetect() failed with status 0x%08lx\n", Status); return STATUS_UNSUCCESSFUL; } /* First detect the mouse and then the keyboard! If we do it the other way round, some systems throw away settings like the keyboard translation, when detecting the mouse. */ TRACE_(I8042PRT, "Detecting mouse\n"); i8042DetectMouse(DeviceExtension); TRACE_(I8042PRT, "Detecting keyboard\n"); i8042DetectKeyboard(DeviceExtension); INFO_(I8042PRT, "Keyboard present: %s\n", DeviceExtension->Flags & KEYBOARD_PRESENT ? "YES" : "NO"); INFO_(I8042PRT, "Mouse present : %s\n", DeviceExtension->Flags & MOUSE_PRESENT ? "YES" : "NO"); TRACE_(I8042PRT, "Enabling i8042 interrupts\n"); if (DeviceExtension->Flags & KEYBOARD_PRESENT) { FlagsToDisable |= CCB_KBD_DISAB; FlagsToEnable |= CCB_KBD_INT_ENAB; } if (DeviceExtension->Flags & MOUSE_PRESENT) { FlagsToDisable |= CCB_MOUSE_DISAB; FlagsToEnable |= CCB_MOUSE_INT_ENAB; } Status = EnableInterrupts(DeviceExtension, FlagsToDisable, FlagsToEnable); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "EnableInterrupts failed: %lx\n", Status); DeviceExtension->Flags &= ~(KEYBOARD_PRESENT | MOUSE_PRESENT); return Status; } } /* Connect interrupts */ if (DeviceExtension->Flags & KEYBOARD_PRESENT && DeviceExtension->Flags & KEYBOARD_CONNECTED && DeviceExtension->Flags & KEYBOARD_STARTED && !(DeviceExtension->Flags & KEYBOARD_INITIALIZED)) { /* Keyboard is ready to be initialized */ Status = i8042ConnectKeyboardInterrupt(DeviceExtension->KeyboardExtension); if (NT_SUCCESS(Status)) { DeviceExtension->Flags |= KEYBOARD_INITIALIZED; } else { WARN_(I8042PRT, "i8042ConnectKeyboardInterrupt failed: %lx\n", Status); } } if (DeviceExtension->Flags & MOUSE_PRESENT && DeviceExtension->Flags & MOUSE_CONNECTED && DeviceExtension->Flags & MOUSE_STARTED && !(DeviceExtension->Flags & MOUSE_INITIALIZED)) { /* Mouse is ready to be initialized */ Status = i8042ConnectMouseInterrupt(DeviceExtension->MouseExtension); if (NT_SUCCESS(Status)) { DeviceExtension->Flags |= MOUSE_INITIALIZED; } else { WARN_(I8042PRT, "i8042ConnectMouseInterrupt failed: %lx\n", Status); } /* Start the mouse */ Irql = KeAcquireInterruptSpinLock(DeviceExtension->HighestDIRQLInterrupt); /* HACK: the mouse has already been reset in i8042DetectMouse. This second reset prevents some touchpads/mice from working (Dell D531, D600). See CORE-6901 */ if (!(i8042HwFlags & FL_INITHACK)) { i8042IsrWritePort(DeviceExtension, MOU_CMD_RESET, CTRL_WRITE_MOUSE); } KeReleaseInterruptSpinLock(DeviceExtension->HighestDIRQLInterrupt, Irql); } return Status; } static NTSTATUS i8042PnpStartDevice( IN PDEVICE_OBJECT DeviceObject, IN PCM_RESOURCE_LIST AllocatedResources, IN PCM_RESOURCE_LIST AllocatedResourcesTranslated) { PFDO_DEVICE_EXTENSION DeviceExtension; PPORT_DEVICE_EXTENSION PortDeviceExtension; PCM_PARTIAL_RESOURCE_DESCRIPTOR ResourceDescriptor, ResourceDescriptorTranslated; INTERRUPT_DATA InterruptData = { NULL }; BOOLEAN FoundDataPort = FALSE; BOOLEAN FoundControlPort = FALSE; BOOLEAN FoundIrq = FALSE; ULONG i; NTSTATUS Status; TRACE_(I8042PRT, "i8042PnpStartDevice(%p)\n", DeviceObject); DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension; PortDeviceExtension = DeviceExtension->PortDeviceExtension; ASSERT(DeviceExtension->PnpState == dsStopped); if (!AllocatedResources) { WARN_(I8042PRT, "No allocated resources sent to driver\n"); return STATUS_INSUFFICIENT_RESOURCES; } if (AllocatedResources->Count != 1) { WARN_(I8042PRT, "Wrong number of allocated resources sent to driver\n"); return STATUS_INSUFFICIENT_RESOURCES; } if (AllocatedResources->List[0].PartialResourceList.Version != 1 || AllocatedResources->List[0].PartialResourceList.Revision != 1 || AllocatedResourcesTranslated->List[0].PartialResourceList.Version != 1 || AllocatedResourcesTranslated->List[0].PartialResourceList.Revision != 1) { WARN_(I8042PRT, "Revision mismatch: %u.%u != 1.1 or %u.%u != 1.1\n", AllocatedResources->List[0].PartialResourceList.Version, AllocatedResources->List[0].PartialResourceList.Revision, AllocatedResourcesTranslated->List[0].PartialResourceList.Version, AllocatedResourcesTranslated->List[0].PartialResourceList.Revision); return STATUS_REVISION_MISMATCH; } /* Get Irq and optionally control port and data port */ for (i = 0; i < AllocatedResources->List[0].PartialResourceList.Count; i++) { ResourceDescriptor = &AllocatedResources->List[0].PartialResourceList.PartialDescriptors[i]; ResourceDescriptorTranslated = &AllocatedResourcesTranslated->List[0].PartialResourceList.PartialDescriptors[i]; switch (ResourceDescriptor->Type) { case CmResourceTypePort: { if (ResourceDescriptor->u.Port.Length == 1) { /* We assume that the first resource will * be the control port and the second one * will be the data port... */ if (!FoundDataPort) { PortDeviceExtension->DataPort = ULongToPtr(ResourceDescriptor->u.Port.Start.u.LowPart); INFO_(I8042PRT, "Found data port: %p\n", PortDeviceExtension->DataPort); FoundDataPort = TRUE; } else if (!FoundControlPort) { PortDeviceExtension->ControlPort = ULongToPtr(ResourceDescriptor->u.Port.Start.u.LowPart); INFO_(I8042PRT, "Found control port: %p\n", PortDeviceExtension->ControlPort); FoundControlPort = TRUE; } else { /* FIXME: implement PS/2 Active Multiplexing */ ERR_(I8042PRT, "Unhandled I/O ranges provided: 0x%lx\n", ResourceDescriptor->u.Port.Length); } } else WARN_(I8042PRT, "Invalid I/O range length: 0x%lx\n", ResourceDescriptor->u.Port.Length); break; } case CmResourceTypeInterrupt: { if (FoundIrq) return STATUS_INVALID_PARAMETER; InterruptData.Dirql = (KIRQL)ResourceDescriptorTranslated->u.Interrupt.Level; InterruptData.Vector = ResourceDescriptorTranslated->u.Interrupt.Vector; InterruptData.Affinity = ResourceDescriptorTranslated->u.Interrupt.Affinity; if (ResourceDescriptorTranslated->Flags & CM_RESOURCE_INTERRUPT_LATCHED) InterruptData.InterruptMode = Latched; else InterruptData.InterruptMode = LevelSensitive; InterruptData.ShareInterrupt = (ResourceDescriptorTranslated->ShareDisposition == CmResourceShareShared); INFO_(I8042PRT, "Found irq resource: %lu\n", ResourceDescriptor->u.Interrupt.Level); FoundIrq = TRUE; break; } default: WARN_(I8042PRT, "Unknown resource descriptor type 0x%x\n", ResourceDescriptor->Type); } } if (!FoundIrq) { WARN_(I8042PRT, "Interrupt resource was not found in allocated resources list\n"); return STATUS_INSUFFICIENT_RESOURCES; } else if (DeviceExtension->Type == Keyboard && (!FoundDataPort || !FoundControlPort)) { WARN_(I8042PRT, "Some required resources were not found in allocated resources list\n"); return STATUS_INSUFFICIENT_RESOURCES; } else if (DeviceExtension->Type == Mouse && (FoundDataPort || FoundControlPort)) { WARN_(I8042PRT, "Too much resources were provided in allocated resources list\n"); return STATUS_INVALID_PARAMETER; } switch (DeviceExtension->Type) { case Keyboard: { RtlCopyMemory( &PortDeviceExtension->KeyboardInterrupt, &InterruptData, sizeof(INTERRUPT_DATA)); PortDeviceExtension->Flags |= KEYBOARD_STARTED; Status = StartProcedure(PortDeviceExtension); break; } case Mouse: { RtlCopyMemory( &PortDeviceExtension->MouseInterrupt, &InterruptData, sizeof(INTERRUPT_DATA)); PortDeviceExtension->Flags |= MOUSE_STARTED; Status = StartProcedure(PortDeviceExtension); break; } default: { WARN_(I8042PRT, "Unknown FDO type %u\n", DeviceExtension->Type); ASSERT(!(PortDeviceExtension->Flags & KEYBOARD_CONNECTED) || !(PortDeviceExtension->Flags & MOUSE_CONNECTED)); Status = STATUS_INVALID_DEVICE_REQUEST; } } if (NT_SUCCESS(Status)) DeviceExtension->PnpState = dsStarted; return Status; } static VOID i8042RemoveDevice( IN PDEVICE_OBJECT DeviceObject) { PI8042_DRIVER_EXTENSION DriverExtension; KIRQL OldIrql; PFDO_DEVICE_EXTENSION DeviceExtension; DriverExtension = (PI8042_DRIVER_EXTENSION)IoGetDriverObjectExtension(DeviceObject->DriverObject, DeviceObject->DriverObject); DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension; KeAcquireSpinLock(&DriverExtension->DeviceListLock, &OldIrql); RemoveEntryList(&DeviceExtension->ListEntry); KeReleaseSpinLock(&DriverExtension->DeviceListLock, OldIrql); IoDetachDevice(DeviceExtension->LowerDevice); IoDeleteDevice(DeviceObject); } NTSTATUS NTAPI i8042Pnp( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { PIO_STACK_LOCATION Stack; ULONG MinorFunction; I8042_DEVICE_TYPE DeviceType; ULONG_PTR Information = 0; NTSTATUS Status; Stack = IoGetCurrentIrpStackLocation(Irp); MinorFunction = Stack->MinorFunction; DeviceType = ((PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->Type; switch (MinorFunction) { case IRP_MN_START_DEVICE: /* 0x00 */ { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_START_DEVICE\n"); /* Call lower driver (if any) */ if (DeviceType != PhysicalDeviceObject) { Status = ForwardIrpAndWait(DeviceObject, Irp); if (NT_SUCCESS(Status)) Status = i8042PnpStartDevice( DeviceObject, Stack->Parameters.StartDevice.AllocatedResources, Stack->Parameters.StartDevice.AllocatedResourcesTranslated); } else Status = STATUS_SUCCESS; break; } case IRP_MN_QUERY_DEVICE_RELATIONS: /* (optional) 0x07 */ { switch (Stack->Parameters.QueryDeviceRelations.Type) { case BusRelations: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / BusRelations\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case RemovalRelations: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / RemovalRelations\n"); return ForwardIrpAndForget(DeviceObject, Irp); } default: ERR_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unknown type 0x%lx\n", Stack->Parameters.QueryDeviceRelations.Type); return ForwardIrpAndForget(DeviceObject, Irp); } break; } case IRP_MN_FILTER_RESOURCE_REQUIREMENTS: /* (optional) 0x0d */ { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_FILTER_RESOURCE_REQUIREMENTS\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_QUERY_PNP_DEVICE_STATE: /* 0x14 */ { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_PNP_DEVICE_STATE\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_QUERY_REMOVE_DEVICE: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_REMOVE_DEVICE\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_CANCEL_REMOVE_DEVICE: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_CANCEL_REMOVE_DEVICE\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_REMOVE_DEVICE: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_REMOVE_DEVICE\n"); Status = ForwardIrpAndForget(DeviceObject, Irp); i8042RemoveDevice(DeviceObject); return Status; } default: { ERR_(I8042PRT, "IRP_MJ_PNP / unknown minor function 0x%x\n", MinorFunction); return ForwardIrpAndForget(DeviceObject, Irp); } } Irp->IoStatus.Information = Information; Irp->IoStatus.Status = Status; IoCompleteRequest(Irp, IO_NO_INCREMENT); return Status; }
sunnyden/reactos
drivers/input/i8042prt/pnp.c
C
gpl-2.0
27,818
/* * Compiler error handler * Copyright * (C) 1992 Joseph H. Allen * * This file is part of JOE (Joe's Own Editor) */ #include "types.h" /* Error database */ typedef struct error ERROR; struct error { LINK(ERROR) link; /* Linked list of errors */ long line; /* Target line number */ long org; /* Original target line number */ unsigned char *file; /* Target file name */ long src; /* Error-file line number */ unsigned char *msg; /* The message */ } errors = { { &errors, &errors} }; ERROR *errptr = &errors; /* Current error row */ B *errbuf = NULL; /* Buffer with error messages */ /* Function which allows stepping through all error buffers, for multi-file search and replace. Give it a buffer. It finds next buffer in error list. Look at 'berror' for error information. */ /* This is made to work like bafter: it does not increment refcount of buffer */ B *beafter(B *b) { struct error *e; unsigned char *name = b->name; if (!name) name = USTR ""; for (e = errors.link.next; e != &errors; e = e->link.next) if (!zcmp(name, e->file)) break; if (e == &errors) { /* Given buffer is not in list? Return first buffer in list. */ e = errors.link.next; } while (e != &errors && !zcmp(name, e->file)) e = e->link.next; berror = 0; if (e != &errors) { B *b = bfind(e->file); /* bfind bumps refcount, so we have to unbump it */ if (b->count == 1) b->orphan = 1; /* Oops */ else --b->count; return b; } return 0; } /* Insert and delete notices */ void inserr(unsigned char *name, long int where, long int n, int bol) { ERROR *e; if (!n) return; if (name) { for (e = errors.link.next; e != &errors; e = e->link.next) { if (!zcmp(e->file, name)) { if (e->line > where) e->line += n; else if (e->line == where && bol) e->line += n; } } } } void delerr(unsigned char *name, long int where, long int n) { ERROR *e; if (!n) return; if (name) { for (e = errors.link.next; e != &errors; e = e->link.next) { if (!zcmp(e->file, name)) { if (e->line > where + n) e->line -= n; else if (e->line > where) e->line = where; } } } } /* Abort notice */ void abrerr(unsigned char *name) { ERROR *e; if (name) for (e = errors.link.next; e != &errors; e = e->link.next) if (!zcmp(e->file, name)) e->line = e->org; } /* Save notice */ void saverr(unsigned char *name) { ERROR *e; if (name) for (e = errors.link.next; e != &errors; e = e->link.next) if (!zcmp(e->file, name)) e->org = e->line; } /* Pool of free error nodes */ ERROR errnodes = { {&errnodes, &errnodes} }; /* Free an error node */ static void freeerr(ERROR *n) { vsrm(n->file); vsrm(n->msg); enquef(ERROR, link, &errnodes, n); } /* Free all errors */ static int freeall(void) { int count = 0; while (!qempty(ERROR, link, &errors)) { freeerr(deque_f(ERROR, link, errors.link.next)); ++count; } errptr = &errors; return count; } /* Parse error messages into database */ /* From joe's joe 2.9 */ /* First word (allowing ., /, _ and -) with a . is the file name. Next number is line number. Then there should be a ':' */ static void parseone(struct charmap *map,unsigned char *s,unsigned char **rtn_name,long *rtn_line) { int x, y, flg; unsigned char *name = NULL; long line = -1; y=0; flg=0; if (s[0] == 'J' && s[1] == 'O' && s[2] == 'E' && s[3] == ':') goto bye; do { /* Skip to first word */ for (x = y; s[x] && !(joe_isalnum_(map,s[x]) || s[x] == '.' || s[x] == '/'); ++x) ; /* Skip to end of first word */ for (y = x; joe_isalnum_(map,s[y]) || s[y] == '.' || s[y] == '/' || s[y]=='-'; ++y) if (s[y] == '.') flg = 1; } while (!flg && x!=y); /* Save file name */ if (x != y) name = vsncpy(NULL, 0, s + x, y - x); /* Skip to first number */ for (x = y; s[x] && (s[x] < '0' || s[x] > '9'); ++x) ; /* Skip to end of first number */ for (y = x; s[y] >= '0' && s[y] <= '9'; ++y) ; /* Save line number */ if (x != y) sscanf((char *)(s + x), "%ld", &line); if (line != -1) --line; /* Look for ':' */ flg = 0; while (s[y]) { /* Allow : anywhere on line: works for MIPS C compiler */ /* for (y = 0; s[y];) */ if (s[y]==':') { flg = 1; break; } ++y; } bye: if (!flg) line = -1; *rtn_name = name; *rtn_line = line; } /* Parser for file name lists from grep, find and ls. * * filename * filename:* * filename:line-number:* */ void parseone_grep(struct charmap *map,unsigned char *s,unsigned char **rtn_name,long *rtn_line) { int y; unsigned char *name = NULL; long line = -1; if (s[0] == 'J' && s[1] == 'O' && s[2] == 'E' && s[3] == ':') goto bye; /* Skip to first : or end of line */ for (y = 0;s[y] && s[y] != ':';++y); if (y) { /* This should be the file name */ name = vsncpy(NULL,0,s,y); line = 0; if (s[y] == ':') { /* Maybe there's a line number */ ++y; while (s[y] >= '0' && s[y] <= '9') line = line * 10 + (s[y++] - '0'); --line; if (line < 0 || s[y] != ':') { /* Line number is only valid if there's a second : */ line = 0; } } } bye: *rtn_name = name; *rtn_line = line; } static int parseit(struct charmap *map,unsigned char *s, long int row, void (*parseone)(struct charmap *map, unsigned char *s, unsigned char **rtn_name, long *rtn_line), unsigned char *current_dir) { unsigned char *name = NULL; long line = -1; ERROR *err; parseone(map,s,&name,&line); if (name) { if (line != -1) { /* We have an error */ err = (ERROR *) alitem(&errnodes, sizeof(ERROR)); err->file = name; if (current_dir) { err->file = vsncpy(NULL, 0, sv(current_dir)); err->file = vsncpy(sv(err->file), sv(name)); err->file = canonical(err->file); vsrm(name); } else { err->file = name; } err->org = err->line = line; err->src = row; err->msg = vsncpy(NULL, 0, sc("\\i")); err->msg = vsncpy(sv(err->msg), sv(s)); enqueb(ERROR, link, &errors, err); return 1; } else vsrm(name); } return 0; } /* Parse the error output contained in a buffer */ void kill_ansi(unsigned char *s); static long parserr(B *b) { if (markv(1)) { P *p = pdup(markb, USTR "parserr1"); P *q = pdup(markb, USTR "parserr2"); long nerrs = 0; errbuf = markb->b; freeall(); p_goto_bol(p); do { unsigned char *s; pset(q, p); p_goto_eol(p); s = brvs(q, (int) (p->byte - q->byte)); if (s) { kill_ansi(s); nerrs += parseit(q->b->o.charmap, s, q->line, (q->b->parseone ? q->b->parseone : parseone),q->b->current_dir); vsrm(s); } pgetc(p); } while (p->byte < markk->byte); prm(p); prm(q); return nerrs; } else { P *p = pdup(b->bof, USTR "parserr3"); P *q = pdup(p, USTR "parserr4"); long nerrs = 0; errbuf = b; freeall(); do { unsigned char *s; pset(q, p); p_goto_eol(p); s = brvs(q, (int) (p->byte - q->byte)); if (s) { kill_ansi(s); nerrs += parseit(q->b->o.charmap, s, q->line, (q->b->parseone ? q->b->parseone : parseone), q->b->current_dir); vsrm(s); } } while (pgetc(p) != NO_MORE_DATA); prm(p); prm(q); return nerrs; } } BW *find_a_good_bw(B *b) { W *w; BW *bw = 0; /* Find lowest window with buffer */ if ((w = maint->topwin) != NULL) { do { if ((w->watom->what&TYPETW) && ((BW *)w->object)->b==b && w->y>=0) bw = (BW *)w->object; w = w->link.next; } while (w != maint->topwin); } if (bw) return bw; /* Otherwise just find lowest window */ if ((w = maint->topwin) != NULL) { do { if ((w->watom->what&TYPETW) && w->y>=0) bw = (BW *)w->object; w = w->link.next; } while (w != maint->topwin); } return bw; } int parserrb(B *b) { BW *bw; int n; freeall(); bw = find_a_good_bw(b); unmark(bw); n = parserr(b); if (n) joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n); else joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found"))); msgnw(bw->parent, msgbuf); return 0; } int urelease(BW *bw) { bw->b->parseone = 0; if (qempty(ERROR, link, &errors) && !errbuf) { joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages"))); } else { int count = freeall(); errbuf = NULL; joe_snprintf_1(msgbuf, sizeof(msgbuf), joe_gettext(_("%d messages cleared")), count); } msgnw(bw->parent, msgbuf); updall(); return 0; } int uparserr(BW *bw) { int n; freeall(); bw->b->parseone = parseone; n = parserr(bw->b); if (n) joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n); else joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found"))); msgnw(bw->parent, msgbuf); return 0; } int ugparse(BW *bw) { int n; freeall(); bw->b->parseone = parseone_grep; n = parserr(bw->b); if (n) joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n); else joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found"))); msgnw(bw->parent, msgbuf); return 0; } int jump_to_file_line(BW *bw,unsigned char *file,int line,unsigned char *msg) { int omid; if (!bw->b->name || zcmp(file, bw->b->name)) { if (doswitch(bw, vsdup(file), NULL, NULL)) return -1; bw = (BW *) maint->curwin->object; } omid = mid; mid = 1; pline(bw->cursor, line); dofollows(); mid = omid; bw->cursor->xcol = piscol(bw->cursor); msgnw(bw->parent, msg); return 0; } /* Show current message */ int ucurrent_msg(BW *bw) { if (errptr != &errors) { msgnw(bw->parent, errptr->msg); return 0; } else { msgnw(bw->parent, joe_gettext(_("No messages"))); return -1; } } /* Find line in error database: return pointer to message */ ERROR *srcherr(BW *bw,unsigned char *file,long line) { ERROR *p; for (p = errors.link.next; p != &errors; p=p->link.next) if (!zcmp(p->file,file) && p->org == line) { errptr = p; setline(errbuf, errptr->src); return errptr; } return 0; } /* Delete ansi formatting */ void kill_ansi(unsigned char *s) { unsigned char *d = s; while (*s) if (*s == 27) { while (*s && (*s == 27 || *s == '[' || (*s >= '0' && *s <= '9') || *s == ';')) ++s; if (*s) ++s; } else *d++ = *s++; *d = 0; } int ujump(BW *bw) { int rtn = -1; P *p = pdup(bw->cursor, USTR "ujump"); P *q = pdup(p, USTR "ujump"); unsigned char *s; p_goto_bol(p); p_goto_eol(q); s = brvs(p, (int) (q->byte - p->byte)); kill_ansi(s); prm(p); prm(q); if (s) { unsigned char *name = NULL; unsigned char *fullname = NULL; unsigned char *curd = get_cd(bw->parent); long line = -1; if (bw->b->parseone) bw->b->parseone(bw->b->o.charmap,s,&name,&line); else parseone_grep(bw->b->o.charmap,s,&name,&line); /* Prepend current directory.. */ fullname = vsncpy(NULL, 0, sv(curd)); fullname = vsncpy(sv(fullname), sv(name)); vsrm(name); name = canonical(fullname); if (name && line != -1) { ERROR *p = srcherr(bw, name, line); uprevw((BASE *)bw); /* Check that we made it to a tw */ if (p) rtn = jump_to_file_line(maint->curwin->object,name,p->line,NULL /* p->msg */); else rtn = jump_to_file_line(maint->curwin->object,name,line,NULL); vsrm(name); } vsrm(s); } return rtn; } int unxterr(BW *bw) { if (errptr->link.next == &errors) { msgnw(bw->parent, joe_gettext(_("No more errors"))); return -1; } errptr = errptr->link.next; setline(errbuf, errptr->src); return jump_to_file_line(bw,errptr->file,errptr->line,NULL /* errptr->msg */); } int uprverr(BW *bw) { if (errptr->link.prev == &errors) { msgnw(bw->parent, joe_gettext(_("No more errors"))); return -1; } errptr = errptr->link.prev; setline(errbuf, errptr->src); return jump_to_file_line(bw,errptr->file,errptr->line,NULL /* errptr->msg */); }
jhallen/joe-editor
joe/uerror.c
C
gpl-2.0
11,705
#ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif /* * 1 Header File Including */ #include <linux/module.h> #include <linux/netdevice.h> #include "hwifi_tps.h" #include "cfg80211_stru.h" #include "hwifi_cfg80211.h" #include "hwifi_wpa_ioctl.h" /* for wl_pwrm_set */ #include "hwifi_wl_config_ioctl.h" #include <net/cfg80211.h> /* wdev_priv */ #include <linux/etherdevice.h> /* eth_type_trans */ #include "hwifi_utils.h" #include "hwifi_hcc.h" #include "hwifi_netdev.h" #include "hwifi_cfgapi.h" /* * 2 Global Variable Definition */ /* * 3 Function Definition */ /***************************************************************************** º¯ Êý Ãû : hwifi_test_freq_set ¹¦ÄÜÃèÊö : ÉèÖÃwifiƵ¶Î ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_test_freq_set(struct cfg_struct *cfg, int32 freq) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *wid_freq; uint16 msg_size; int32 ret; if(IS_CONNECTED(cfg)) { HWIFI_WARNING("Current connected status not support wifreq param setting."); return -EFAIL; } msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill ps mode */ wid_freq = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(wid_freq, WID_PRIMARY_CHANNEL , freq); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("Failed to send wifi freq set msg!"); return -EFAIL; } cfg->ap_info.curr_channel=freq; HWIFI_DEBUG("Succeed to set wifreq: %d", freq); return SUCC; } /***************************************************************************** º¯ Êý Ãû : hwifi_test_userpow_set ¹¦ÄÜÃèÊö : ÉèÖÃWIFI¹¦ÂÊ ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_test_userpow_set(struct cfg_struct *cfg, int32 userpow) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *wid_userpow; uint16 msg_size; int32 ret; msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill ps mode */ wid_userpow = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(wid_userpow, WID_USER_CONTROL_ON_TX_POWER , (uint8)userpow); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("Failed to send wifi userpow set msg!"); return -EFAIL; } cfg->hi110x_dev->tps->userpow=userpow; HWIFI_DEBUG("succeed to set wiuserpow: %d", userpow); return SUCC; } /***************************************************************************** º¯ Êý Ãû : hwifi_test_userpow_get ¹¦ÄÜÃèÊö : »ñÈ¡WIFI¹¦ÂÊ ÊäÈë²ÎÊý : struct cfg_struct *cfg Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWS160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_test_userpow_get(struct cfg_struct *cfg) { return cfg->hi110x_dev->tps->userpow; } /***************************************************************************** º¯ Êý Ãû : hwifi_test_pow_set ¹¦ÄÜÃèÊö : É趨WIFIÖ¸¶¨¹¦ÂÊ·¢ËÍ ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_test_pow_set(struct cfg_struct *cfg, int32 pow) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *wid_pow; uint16 msg_size; int32 ret; int32 n_channels_2G = 1; int32 n_channels_5G = 0; if (HWIFI_CONNECTED == cfg->conn.status) { if (cfg->conn.bss.freq <= HWIFI_AT_TEST_MAX_FREQ_2G) { HWIFI_INFO("scan: 2.4G connected scan, only scan 2.4G"); n_channels_5G = 0; n_channels_2G = 1; } else { HWIFI_INFO("scan: 5G connected scan, only scan 5G"); n_channels_5G = 1; n_channels_2G = 0; } } else if(IS_AP(cfg)) { if(cfg->ap_info.channel_info & HWIFI_AT_TEST_5G_BAND) { HWIFI_INFO("ap operation on 5G, only scan 5G"); n_channels_5G = 1; n_channels_2G = 0; } else { HWIFI_INFO("ap operation on 2.4G, only scan 2.4G"); n_channels_5G = 0; n_channels_2G = 1; } } if(n_channels_5G > 0) { if(pow > 180 || pow <0) { HWIFI_WARNING("can not set the pow value %d",pow); return -EFAIL; } } else if(n_channels_2G > 0) { if(pow > 200 || pow <0) { HWIFI_WARNING("can not set the pow value %d",pow); return -EFAIL; } } msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill ps mode */ wid_pow = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(wid_pow, WID_CURRENT_TX_POW , (uint16)pow); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("fail to send wifi pow set msg"); return -EFAIL; } cfg->hi110x_dev->tps->pow=pow; HWIFI_INFO("succeed to send wifi pow set msg %d",pow); return SUCC; } /***************************************************************************** º¯ Êý Ãû : hwifi_test_pow_get ¹¦ÄÜÃèÊö : »ñÈ¡WIFIÖ¸¶¨¹¦ÂÊ ÊäÈë²ÎÊý :struct cfg_struct *cfg Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_test_pow_get(struct cfg_struct *cfg) { return cfg->hi110x_dev->tps->pow; } /***************************************************************************** º¯ Êý Ãû : hwifi_oltpc_active_set ¹¦ÄÜÃèÊö : ÉèÖÃWiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁÈ¡Ö¸Áî ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_oltpc_active_set(struct cfg_struct *cfg, int32 enabled) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *wid_oltpc; uint16 msg_size; int32 ret; msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill ps mode */ wid_oltpc = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(wid_oltpc, WID_OLTPC_ACTIVE , (uint8)enabled); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("fail to send wifi oltpc active set msg"); return -EFAIL; } cfg->hi110x_dev->tps->oltpc_active=enabled; HWIFI_DEBUG("succeed to send wifi oltpc active set msg"); return SUCC; } /***************************************************************************** º¯ Êý Ãû : hwifi_oltpc_active_get ¹¦ÄÜÃèÊö : »ñÈ¡WiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁÈ¡Ö¸Áî ÊäÈë²ÎÊý :struct cfg_struct *cfg Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_oltpc_active_get(struct cfg_struct *cfg) { return cfg->hi110x_dev->tps->oltpc_active; } /***************************************************************************** º¯ Êý Ãû : hwifi_oltpc_switch_set ¹¦ÄÜÃèÊö : ÉèÖÃWiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁÈ¡Ö¸Áî ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_oltpc_switch_set(struct cfg_struct *cfg, int32 enabled) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *wid_oltpc; uint16 msg_size; int32 ret; msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill ps mode */ wid_oltpc = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(wid_oltpc, WID_OLTPC_SWITCH , (uint8)enabled); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("Failed to send wifi olptc active set msg!"); return -EFAIL; } cfg->hi110x_dev->tps->oltpc_switch=enabled; HWIFI_DEBUG("succeed to send wifi oltpc switch set msg"); return SUCC; } /***************************************************************************** º¯ Êý Ãû : hwifi_oltpc_switch_get ¹¦ÄÜÃèÊö : »ñÈ¡WiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁÈ¡Ö¸Áî ÊäÈë²ÎÊý :struct cfg_struct *cfg Êä³ö²ÎÊý : ÎÞ ·µ »Ø Öµ : µ÷Óú¯Êý : ±»µ÷º¯Êý : ÐÞ¸ÄÀúÊ· : 1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ ×÷ Õß : hWX160629 ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý *****************************************************************************/ int32 hwifi_oltpc_switch_get(struct cfg_struct *cfg) { return cfg->hi110x_dev->tps->oltpc_switch; } /* * Prototype : hwifi_test_mode_set * Description : set burst rx/tx mode * Input : struct cfg_struct *cfg, uint8 enabled * Output : None * Return Value : * Calls : * Called By : * * History : * 1.Date : 2013/5/3 * Author : hWX160629 * Modification : Created function * */ int32 hwifi_test_mode_set(struct cfg_struct *cfg, uint8 mode) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *test_mode; uint16 msg_size; int32 ret; msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } if(!IS_STA(cfg) && !IS_AP(cfg)) { HWIFI_WARNING("Current status can not support burst tx/rx mode set."); dev_kfree_skb_any(skb); return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_MODE, msg_size); /* fill ps mode */ test_mode = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(test_mode, WID_MODE_CHANGE, mode); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("Failed to send mode set msg!"); return -EFAIL; } cfg->hi110x_dev->tps->mode=mode; HWIFI_DEBUG("Succeed to set mode param :%d", mode); return SUCC; } /* * Prototype : hwifi_test_mode_get * Description : get the setting of mode param * Input : struct cfg_struct *cfg * Output : None * Return Value : * Calls : * Called By : * * History : * 1.Date : 2013/5/3 * Author : hWX160629 * Modification : Created function * */ int32 hwifi_test_mode_get(struct cfg_struct *cfg) { return cfg->hi110x_dev->tps->mode; } /* * Prototype : hwifi_test_datarate_set * Description : set rate * Input : struct cfg_struct *cfg, * uint8 enabled * Output : None * Return Value : int32 * Calls : * Called By : * * History : * 1.Date : 2012/2/19 * Author : hWX160629 * Modification : Created function * */ int32 hwifi_test_datarate_set(struct cfg_struct *cfg, uint8 rate) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *rate_set; uint16 msg_size; int32 ret; msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill ps mode */ rate_set = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(rate_set, WID_CURRENT_TX_RATE, rate); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("fail to send rate set msg"); return -EFAIL; } HWIFI_INFO("succeed to send rate set msg %d",rate); return SUCC; } /* * Prototype : hwifi_band_set * Description : enable/disable support for 40MHz operation * Input : struct cfg_struct *cfg,uint8 enabled * Output : None * Return Value : int32 * Calls : * Called By : * * History : * 1.Date : 2013/4/26 * Author : hWX160629 * Modification : Created function * */ int32 hwifi_band_set(struct cfg_struct *cfg,uint8 band) { int32 ret; ret = hwifi_sta_2040_enable_ctrl_set(cfg,band); if (SUCC != ret) { HWIFI_WARNING("Failed to send band param set msg!"); return -EFAIL; } HWIFI_INFO("Succeed to set band param:%d", band); return SUCC; } /* * Prototype : wifitest_protocol_gmode_set * Description : set 11g operating mode * Input : struct cfg_struct *cfg,uint8 enabled * Output : None * Return Value : int32 * Calls : * Called By : * * History : * 1.Date : 2013/4/26 * Author : hWX160629 * Modification : Created function * */ int32 wifitest_protocol_gmode_set(struct cfg_struct *cfg,uint8 mode) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *gmode; uint16 msg_size; int32 ret; if(IS_CONNECTED(cfg)||(IS_P2P_ON(cfg))) { HWIFI_WARNING("current status can not support protocol gmode set."); return -EFAIL; } msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill gmode */ gmode = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(gmode, WID_11G_OPERATING_MODE, mode); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("fail to send protocol gmode set msg"); return -EFAIL; } cfg->sta_info.gmode= mode; HWIFI_INFO("succeed to set protocol gmode:%d", mode); return SUCC; } /* * Prototype : wifitest_protocol_nmode_set * Description : set ht capability enabled * Input : struct cfg_struct *cfg,uint8 enabled * uint8 enabled * Output : None * Return Value : int32 * Calls : * Called By : * * History : * 1.Date : 2012/2/19 * Author : hWX160629 * Modification : Created function * */ int32 wifitest_protocol_nmode_set(struct cfg_struct *cfg,uint8 mode) { struct sk_buff *skb; struct hwifi_msg_header *msghdr; struct char_wid *ht; uint16 msg_size; int32 ret; if (IS_CONNECTED(cfg) || IS_AP(cfg)) { HWIFI_WARNING("current status can not support 11n mode set."); return -EFAIL; } msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } /* fill the msg header */ msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header)); hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size); /* fill ps mode */ ht = (struct char_wid *)skb_put(skb, sizeof(struct char_wid)); hwifi_fill_char_wid(ht, WID_11N_ENABLE, mode); ret = hwifi_send_cmd(cfg, skb); if (SUCC != ret) { HWIFI_WARNING("fail to send 11n mode set msg"); return -EFAIL; } HWIFI_INFO("succeed to send 11n mode set msg %d",mode); return SUCC; } /* * Prototype : hwifi_dbb_get * Description : get dbb of wifi * Input : struct cfg_struct *cfg * Output : None * Return Value : int * Calls : * Called By : * * History : * 1.Date : 2013/11/9 * Author : hWX160629 * Modification : Created function * */ int32 hwifi_dbb_get(struct cfg_struct *cfg,int8 *dbb) { int32 ret; if (NULL == cfg) { HWIFI_WARNING("Invalid NULL cfg!"); return -EFAIL; } cfg->hi110x_dev->tps->dbb_ver_got = 0xFF; ret = wl_get_dbb_info(cfg); if(SUCC != ret) { HWIFI_WARNING("Failed to get DBB number!"); return -EFAIL; } ret = wait_event_interruptible_timeout(cfg->wait_queue, (0xFF != cfg->hi110x_dev->tps->dbb_ver_got), 5 * HZ); if (0 == ret) { HWIFI_WARNING("wait for dbb version message time out(5s)!"); return -EFAIL; } else if (ret < 0) { HWIFI_WARNING("wait for dbb version message error!"); return -EFAIL; } strncpy(dbb,cfg->hi110x_dev->tps->dbb,HISI_WIFI_DBB_LEN); HWIFI_DEBUG("DBB number is %s",cfg->hi110x_dev->tps->dbb); return SUCC; } int32 hwifi_upc_get(struct cfg_struct *cfg) { int32 ret; if (NULL == cfg) { HWIFI_WARNING("Invalid NULL cfg!"); return -EFAIL; } cfg->hi110x_dev->tps->check_upc_ctrl = -EFAIL; ret = wl_get_upc_info(cfg); if(SUCC != ret) { HWIFI_WARNING("Failed to get upc!"); return -EFAIL; } ret = wait_event_interruptible_timeout(cfg->wait_queue, (-EFAIL != cfg->hi110x_dev->tps->check_upc_ctrl), 5 * HZ); if (0 == ret) { HWIFI_WARNING("wait for upc info message time out(5s)!"); return -EFAIL; } else if (ret < 0) { HWIFI_WARNING("wait for upc info message error!"); return -EFAIL; } HWIFI_DEBUG("report upc info is %d",cfg->hi110x_dev->tps->check_upc_flag); return cfg->hi110x_dev->tps->check_upc_flag; } int32 hwifi_gen_cw_single_tone_set(struct cfg_struct *cfg) { int32 ret; uint16 msg_size; struct sk_buff *skb; struct hwifi_gen_cw_single_tone_msg *msg; HWIFI_ASSERT((NULL != cfg)); msg_size = sizeof(struct hwifi_gen_cw_single_tone_msg); skb = hwifi_alloc_skb_for_cmd(msg_size); if (NULL == skb) { return -EFAIL; } msg = (struct hwifi_gen_cw_single_tone_msg *)skb_put(skb, msg_size); /* set the msg header */ hwifi_fill_msg_hdr(&msg->msg_hdr, HOST_CMD_CONFIG, msg_size); hwifi_fill_char_wid(&msg->phy_active_reg_1, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_1); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_1, WID_11N_PHY_ACTIVE_REG_VAL, WID_SIGNAL_TONE_ACTIVE_REG_VAL_1); hwifi_fill_char_wid(&msg->phy_active_reg_2, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_2); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_2,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_2); hwifi_fill_char_wid(&msg->phy_active_reg_3, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_3); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_3,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_3); hwifi_fill_char_wid(&msg->phy_active_reg_4, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_4); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_4,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_4); hwifi_fill_char_wid(&msg->phy_active_reg_5, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_5); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_5,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_5); hwifi_fill_char_wid(&msg->phy_active_reg_6, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_6); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_6,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_6); hwifi_fill_char_wid(&msg->phy_active_reg_7, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_7); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_7,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_7); hwifi_fill_char_wid(&msg->phy_active_reg_8, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_8); hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_8,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_8); hwifi_fill_int_wid(&msg->rf_reg_info, WID_RF_REG_VAL, WID_SIGNAL_TONE_RF_REG_INFO); ret = hwifi_send_cmd(cfg, skb); PRINT_SEND_CMD_RET("connect status,gen_cw_single_tone param set success", ret); return ret; } int32 hwifi_tps_ioctl_cmd(struct hi110x_device* hi110x_dev, struct ifreq *ifr, int32 cmd) { wifi_ioctl_test_data_struct ioctl_data; int32 ret = SUCC; if ((NULL == hi110x_dev) || (NULL == ifr) || (NULL == ifr->ifr_data)) { HWIFI_WARNING("Invalid NULL params!"); return -EFAIL; } HWIFI_PRINT_ONCE(INFO, "sizeof wifi_ioctl_test_data_struct is %zu", sizeof(wifi_ioctl_test_data_struct)); if(copy_from_user(&ioctl_data,ifr->ifr_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("Failed to copy ifr->ifr_data from user!"); return -EFAIL; } if(ioctl_data.verify != VERIFY_CODE) { HWIFI_WARNING("ioctl verify failed,verify code is:%d(not equal %d)", ioctl_data.verify, VERIFY_CODE); return -EFAIL; } switch(ioctl_data.cmd) { case HWIFI_IOCTL_CMD_WI_FREQ_SET: ret = hwifi_test_freq_set(hi110x_dev->cfg,ioctl_data.pri_data.freq); break; case HWIFI_IOCTL_CMD_WI_USERPOW_SET: ret = hwifi_test_userpow_set(hi110x_dev->cfg,ioctl_data.pri_data.userpow); break; case HWIFI_IOCTL_CMD_WI_USERPOW_GET: ioctl_data.pri_data.userpow = hwifi_test_userpow_get(hi110x_dev->cfg); if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("Failed to copy ioctl_data to user !"); ret = -EFAIL; } break; case HWIFI_IOCTL_CMD_WI_POWER_SET: ret = hwifi_test_pow_set(hi110x_dev->cfg,ioctl_data.pri_data.pow); break; case HWIFI_IOCTL_CMD_WI_POWER_GET: ioctl_data.pri_data.pow = hwifi_test_pow_get(hi110x_dev->cfg); if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("Failed to copy ioctl_data to user !"); ret = -EFAIL; } break; case HWIFI_IOCTL_OLTPC_ACTIVE_SET: ret = hwifi_oltpc_active_set(hi110x_dev->cfg,ioctl_data.pri_data.oltpc_active); break; case HWIFI_IOCTL_OLTPC_SWITCH_SET: ret = hwifi_oltpc_switch_set(hi110x_dev->cfg,ioctl_data.pri_data.oltpc_switch); break; case HWIFI_IOCTL_OLTPC_ACTIVE_GET: ioctl_data.pri_data.oltpc_active=hwifi_oltpc_active_get(hi110x_dev->cfg); if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("Failed to copy ioctl_data to user !"); ret = -EFAIL; } break; case HWIFI_IOCTL_OLTPC_SWITCH_GET: ioctl_data.pri_data.oltpc_switch=hwifi_oltpc_switch_get(hi110x_dev->cfg); if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("copy_to_user failed"); ret = -EFAIL; } break; case HWIFI_IOCTL_CMD_MODE_SET: ret = hwifi_test_mode_set(hi110x_dev->cfg,ioctl_data.pri_data.mode); break; case HWIFI_IOCTL_CMD_MODE_GET: ioctl_data.pri_data.mode=hwifi_test_mode_get(hi110x_dev->cfg); if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("Failed to copy ioctl_data to user !"); ret = -EFAIL; } break; case HWIFI_IOCTL_CMD_DATARATE_SET: ret = hwifi_test_datarate_set(hi110x_dev->cfg,(uint8)ioctl_data.pri_data.datarate); break; case HWIFI_IOCTL_CMD_BAND_SET: ret = hwifi_band_set(hi110x_dev->cfg,ioctl_data.pri_data.band); break; case HWIFI_IOCTL_CMD_PROTOCOL_GMODE_SET: ret = wifitest_protocol_gmode_set(hi110x_dev->cfg,ioctl_data.pri_data.protocol_gmode); break; case HWIFI_IOCTL_CMD_PROTOCOL_NMODE_SET: ret = wifitest_protocol_nmode_set(hi110x_dev->cfg,ioctl_data.pri_data.protocol_nmode); break; case HWIFI_IOCTL_CMD_DBB_GET: ret = hwifi_dbb_get(hi110x_dev->cfg,ioctl_data.pri_data.dbb); if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("Failed to copy ioctl_data to user !"); ret = -EFAIL; } break; case HWIFI_IOCTL_CMD_UPC_GET: ioctl_data.pri_data.check_upc_flag = hwifi_upc_get(hi110x_dev->cfg); if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct))) { HWIFI_WARNING("Failed to copy ioctl_data to user !"); ret = -EFAIL; } break; case HWIFI_IOCTL_CMD_GEN_CW_SINGLE_TONE_SET: ret = hwifi_gen_cw_single_tone_set(hi110x_dev->cfg); break; default: HWIFI_WARNING("Invalid not support ioctl_data.cmd(%d)",ioctl_data.cmd); ret = -EFAIL; break; } return ret; } #ifdef __cplusplus #if __cplusplus } #endif #endif
gabry3795/android_kernel_huawei_mt7_l09
drivers/huawei_platform/connectivity/hisi/hisiwifi/hwifi_tps.c
C
gpl-2.0
28,729
#include <psp2/display.h> #include <psp2/io/fcntl.h> #include <psp2/kernel/processmgr.h> #include <stdio.h> // sprintf() #include <psp2/ctrl.h> // sceCtrl*() #include "graphics.h" #define VER_MAJOR 0 #define VER_MINOR 9 #define VER_BUILD "" #define VAL_LENGTH 0x10 #define VAL_PUBLIC 0x0A #define VAL_PRIVATE 0x06 #define printf psvDebugScreenPrintf int _vshSblAimgrGetConsoleId(char CID[32]); /* Model: Proto, SKU: DEM-3000, MoBo: IRT-001/IRT-002; Model: FatWF, SKU: PCH-1000, MoBo: IRS-002/IRS-1001; Model: Fat3G, SKU: PCH-1100, MoBo: IRS-002/IRS-1001; Model: Slim, SKU: PCH-2000, MoBo: USS-1001/USS-1002; Model: TV, SKU: VTE-1000, MoBo: DOL-1001/DOL-1002. No diff between FatWF and Fat3G. No diff between Vita TV (Asian) and PSTV (Western). */ SceCtrlData pad; void ExitCross(char*text) { printf("%s, press X to exit...\n", text); do { sceCtrlReadBufferPositive(0, &pad, 1); sceKernelDelayThread(0.05*1000*1000); } while(!(pad.buttons & SCE_CTRL_CROSS)); sceKernelExitProcess(0); } void ExitError(char*text, int delay, int error) { printf(text, error); sceKernelDelayThread(delay*1000*1000); sceKernelExitProcess(0); } int WriteFile(char*file, void*buf, int size) { sceIoRemove(file); SceUID fd = sceIoOpen(file, SCE_O_WRONLY | SCE_O_CREAT | SCE_O_TRUNC, 0777); if (fd < 0) return fd; int written = sceIoWrite(fd, buf, size); sceIoClose(fd); return written; } int main(int argc, char *argv[]) { int i = 0; int paranoid = 0; char idps_buffer[16]; unsigned char idps_text_char_tmp[1]; unsigned char idps_text_char_1st[1]; unsigned char idps_text_char_2nd[1]; char idps_text_buffer[32] = ""; for (i = 0; i < 1000; i++) { sceCtrlReadBufferPositive(0, &pad, 1); if (pad.buttons & SCE_CTRL_LTRIGGER) paranoid = 1; sceKernelDelayThread(1000); } psvDebugScreenInit(); psvDebugScreenClear(0); printf("PSV IDPS Dumper v%i.%i%s by Yoti\n\n", VER_MAJOR, VER_MINOR, VER_BUILD); #if (VAL_PUBLIC + VAL_PRIVATE != 0x10) #error IDPS Lenght must be 16 bytes long! #endif _vshSblAimgrGetConsoleId(idps_buffer); printf(" Your IDPS is: "); for (i=0; i<VAL_PUBLIC; i++) { if (i == 0x04) psvDebugScreenSetFgColor(0xFF0000FF); // red #1 else if (i == 0x05) psvDebugScreenSetFgColor(0xFFFF0000); // blue #2 else if (i == 0x06) psvDebugScreenSetFgColor(0xFF0000FF); // red #3 else if (i == 0x07) psvDebugScreenSetFgColor(0xFF00FF00); // green #4 else psvDebugScreenSetFgColor(0xFFFFFFFF); // white printf("%02X", (u8)idps_buffer[i]); } if (paranoid == 1) { for (i=0; i<VAL_PRIVATE; i++) { psvDebugScreenSetFgColor(0xFF777777); // gray printf("XX"); psvDebugScreenSetFgColor(0xFFFFFFFF); // white } } else { for (i=0; i<VAL_PRIVATE; i++) { psvDebugScreenSetFgColor(0xFFFFFFFF); // white printf("%02X", (u8)idps_buffer[VAL_PUBLIC+i]); } } printf("\n\n"); printf(" It seems that you are using "); psvDebugScreenSetFgColor(0xFF0000FF); // red if (idps_buffer[0x04] == 0x00) printf("PlayStation Portable"); else if (idps_buffer[0x04] == 0x01) // psv, vtv/pstv { if (idps_buffer[0x06] == 0x00) printf("PlayStation Vita"); // fatWF/fat3G, slim else if (idps_buffer[0x06] == 0x02) printf("PlayStation/Vita TV"); // vtv, pstv else if (idps_buffer[0x06] == 0x06) printf("PlayStation/Vita TV"); // vtv, pstv (testkit) else printf("Unknown Vita 0x%02X", idps_buffer[0x06]); } else printf("Unknown PS 0x%02X", idps_buffer[0x04]); psvDebugScreenSetFgColor(0xFFFFFFFF); // white printf("\n"); printf(" Your motherboard is "); psvDebugScreenSetFgColor(0xFF00FF00); // green if (idps_buffer[0x06] == 0x00) // portable { switch(idps_buffer[0x07]) { case 0x01: printf("TA-079/081 (PSP-1000)"); break; case 0x02: printf("TA-082/086 (PSP-1000)"); break; case 0x03: printf("TA-085/088 (PSP-2000)"); break; case 0x04: printf("TA-090/092 (PSP-3000)"); break; case 0x05: printf("TA-091 (PSP-N1000)"); break; case 0x06: printf("TA-093 (PSP-3000)"); break; //case 0x07: // printf("TA-094 (PSP-N1000)"); // break; case 0x08: printf("TA-095 (PSP-3000)"); break; case 0x09: printf("TA-096/097 (PSP-E1000)"); break; case 0x10: printf("IRS-002 (PCH-1000/1100)"); break; case 0x11: // 3G? case 0x12: // WF? printf("IRS-1001 (PCH-1000/1100)"); break; case 0x14: printf("USS-1001 (PCH-2000)"); break; case 0x18: printf("USS-1002 (PCH-2000)"); break; default: printf("Unknown MoBo 0x%02X", idps_buffer[0x07]); break; } } else if ((idps_buffer[0x06] == 0x02) || (idps_buffer[0x06] == 0x06)) // home system { switch(idps_buffer[0x07]) { case 0x01: printf("DOL-1001 (VTE-1000)"); break; case 0x02: printf("DOL-1002 (VTE-1000)"); break; default: printf("Unknown MoBo 0x%02X", idps_buffer[0x07]); break; } } else printf("Unknown type 0x%02X", idps_buffer[0x06]); psvDebugScreenSetFgColor(0xFFFFFFFF); // white printf("\n"); printf(" And your region is "); psvDebugScreenSetFgColor(0xFFFF0000); // blue switch(idps_buffer[0x05]) { case 0x00: printf("Proto"); break; case 0x01: printf("DevKit"); break; case 0x02: printf("TestKit"); break; case 0x03: printf("Japan"); break; case 0x04: printf("North America"); break; case 0x05: printf("Europe/East/Africa"); break; case 0x06: printf("Korea"); break; case 0x07: // PCH-xx03 VTE-1016 printf("Great Britain/United Kingdom"); break; case 0x08: printf("Mexica/Latin America"); break; case 0x09: printf("Australia/New Zeland"); break; case 0x0A: printf("Hong Kong/Singapore"); break; case 0x0B: printf("Taiwan"); break; case 0x0C: printf("Russia"); break; case 0x0D: printf("China"); break; default: printf("Unknown region 0x%02X", idps_buffer[0x05]); break; } psvDebugScreenSetFgColor(0xFFFFFFFF); // white printf("\n\n"); // binary printf(" Saving as ux0:data/idps.bin... "); if (WriteFile("ux0:data/idps.bin", idps_buffer, 16) > 0) printf("OK"); else printf("NG"); printf("\n"); // text for (i=0; i<0x10; i++) { idps_text_char_tmp[1]=idps_buffer[i]; idps_text_char_1st[1]=(idps_text_char_tmp[1] & 0xf0) >> 4; idps_text_char_2nd[1]=(idps_text_char_tmp[1] & 0x0f); // 1st half of byte if (idps_text_char_1st[1] < 0xA) // digit sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_1st[1]+0x30); else // char sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_1st[1]+0x37); // 2nd half of byte if (idps_text_char_2nd[1] < 0xA) // digit sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_2nd[1]+0x30); else // char sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_2nd[1]+0x37); } printf(" Saving as ux0:data/idps.txt... "); if (WriteFile("ux0:data/idps.txt", idps_text_buffer, 32) > 0) printf("OK"); else printf("NG"); printf("\n\n"); printf(" https://github.com/yoti/psv_idpsdump/\n"); ExitCross("\nDone"); return 0; }
Yoti/psv_idpsdump
main.c
C
gpl-3.0
7,135
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2015 Leslie Zhai <xiang.zhai@i-soft.com.cn> * * 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <glib.h> #include <glib/gstdio.h> int main(int argc, char *argv[]) { char *path = argv[1]; struct stat buf; if (lstat(path, &buf) == -1) { printf("ERROR: failed to get %s lstat\n", path); return 0; } switch (buf.st_mode & S_IFMT) { case S_IFDIR: printf("DEBUG: line %d %s is directory\n", __LINE__, path); break; case S_IFLNK: printf("DEBUG: line %d %s is symbolic link\n", __LINE__, path); break; case S_IFREG: printf("DEBUG: line %d %s is regular file\n", __LINE__, path); break; default: break; } if (g_file_test(path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_SYMLINK)) printf("DEBUG: line %d %s is symbolic link\n", __LINE__, path); return 0; }
LeetcodeCN/leetcodecn.github.io
src/stat/hello-stat.c
C
gpl-3.0
1,716
#include <includes.h> #include <utils.h> #include <methnum.h> #include "s_param.h" #include "integral.h" double Ivac ( Param * P , double m ) { double m2 = m*m ; double LE = sqrt ( m2 + P->L2 ); return 0.5 * ONE_OVER_8PI_2 * ( P->L * LE * ( m2 + 2*P->L ) + m2*m2 * log ( m/(P->L + LE) ) ) ; } double dm_Ivac ( Param * P , double m ) { double m2 = m*m ; double LE = sqrt ( m2 + P->L2 ); return m * ONE_OVER_4PI_2 * ( P->L * LE + m2 * log ( m/(P->L + LE) ) ); } double dm2_Ivac ( Param * P , double m ) { double m2 = m*m ; double LE = sqrt ( m2 + P->L2 ); return ONE_OVER_4PI_2 * ( P->L*(3*m2 + P->L2)/LE + 3*m2 * log ( m / (P->L + LE) ) ) ; } double dm3_Ivac ( Param * P , double m ) { double m2 = m*m ; double LE2 = m2 + P->L2 ; double LE = sqrt( LE2 ); return 3 * m * ONE_OVER_2PI_2 * ( P->L*( 3*m2 + 4*P->L2 )/(3*LE2*LE) + log ( m / (P->L + LE) ) ); } double Imed ( Param * P , double m , double T , double mu ) { double m2 = m*m ; double b = 1./T ; double integ ( double p ) { double p2 = p*p ; double E2 = p2 + m2 ; double E = sqrt ( E2 ); double x = -(E - mu) * b ; double y = -(E + mu) * b ; double a = log ( 1 + exp ( x ) ) ; double b = log ( 1 + exp ( y ) ) ; return p2 * ( a + b ); } double I = ONE_OVER_2PI_2 * integ_dp ( integ , 0. , P->L , cutoff ); return I ; } double dm_Imed ( Param * P , double m , double T , double mu ) { double m2 = m*m ; double b = 1./T ; double integ ( double p ) { double p2 = p*p ; double E2 = p2 + m2 ; double E = sqrt ( E2 ); double x = (E - mu) * b ; double y = (E + mu) * b ; double ex = exp ( x ) ; double ey = exp ( y ); double f = 1. / ( 1 + ex ); double fb = 1. / ( 1 + ey ); return p2 * ( - f - fb ) / E ; } double I = integ_dp ( integ , 0. , P->L , cutoff ); return m * I ; } double dT_Imed ( Param * P , double m , double T , double mu ) { } double dmu_Imed ( Param * P , double m , double T , double mu ); /* double dm2_Imed ( Param * P , double m , double T , double mu ); */ /* double dmT_Imed ( Param * P , double m , double T , double mu ); */ /* double dmmu_Imed ( Param * P , double m , double T , double mu ); */ /* double dT2_Imed ( Param * P , double m , double T , double mu ); */ /* double dTmu_Imed ( Param * P , double m , double T , double mu ); */ /* double dmu2_Imed ( Param * P , double m , double T , double mu ); */
AlexandreBiguet/NJLlikeModels
legacy/programs/njl-0/njl1-b/integral.c
C
gpl-3.0
2,487
/* * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * Change log: * 06/29/95 - Modified to handle flow control for writing (Tuyen Nguyen) * Modified for MP, 1996 by Tuyen Nguyen * Modified, April 9, 1997 by Tuyen Nguyen for MacOSX. */ #define RESOLVE_DBG #include <sys/errno.h> #include <sys/types.h> #include <sys/param.h> #include <machine/spl.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/proc.h> #include <sys/filedesc.h> #include <sys/fcntl.h> #include <sys/mbuf.h> #include <sys/socket.h> #include <netat/sysglue.h> #include <netat/appletalk.h> #include <netat/at_pcb.h> #include <netat/ddp.h> #include <netat/adsp.h> #include <netat/adsp_internal.h> #ifdef notdefn struct adsp_debug adsp_dtable[1025]; int ad_entry = 0; #endif int adspAllocateCCB(gref) register gref_t *gref; /* READ queue */ { gbuf_t *ccb_mp; register CCBPtr sp; if (!(ccb_mp = gbuf_alloc(sizeof(CCB), PRI_LO))) { return (0); } bzero((caddr_t) gbuf_rptr(ccb_mp), sizeof(CCB)); gbuf_wset(ccb_mp,sizeof(CCB)); gref->info = (caddr_t) ccb_mp; sp = (CCBPtr)gbuf_rptr(((gbuf_t *)gref->info)); sp->pid = gref->pid; /* save the caller process pointer */ sp->gref = gref; /* save a back pointer to the WRITE queue */ sp->sp_mp = ccb_mp; /* and its message block */ return 1; } int adspRelease(gref) register gref_t *gref; /* READ queue */ { register CCBPtr sp; if (gref->info) { sp = (CCBPtr)gbuf_rptr(((gbuf_t *)gref->info)); /* Tells completion routine of close */ /* packet to remove us. */ if (sp->state == sPassive || sp->state == sClosed || sp->state == sOpening || sp->state == sListening) { if (sp->state == sListening) CompleteQueue(&sp->opb, errAborted); sp->removing = 1; /* Prevent allowing another dspClose. */ DoClose(sp, errAborted, 0); /* will remove CCB */ return 0; } else { /* sClosing & sOpen */ sp->state = sClosing; } if (CheckOkToClose(sp)) { /* going to close */ sp->sendCtl = B_CTL_CLOSE; /* Send close advice */ } else { CheckSend(sp); /* try one more time to send out data */ if (sp->state != sClosed) sp->sendCtl = B_CTL_CLOSE; /* Setup to send close advice */ } CheckSend(sp); /* and force out the close */ sp->removing = 1; /* Prevent allowing another dspClose. */ sp->state = sClosed; DoClose(sp, errAborted, 0); /* to closed and remove CCB */ } return 0; } int adspWriteHandler(gref, mp) gref_t *gref; /* WRITE queue */ gbuf_t *mp; { register ioc_t *iocbp; register struct adspcmd *ap; int error, flag; void *sp; switch(gbuf_type(mp)) { case MSG_DATA: if (gref->info == 0) { gbuf_freem(mp); return(STR_IGNORE); } /* * Fill in the global stuff */ ap = (struct adspcmd *)gbuf_rptr(mp); ap->gref = gref; ap->ioc = 0; ap->mp = mp; sp = (void *)gbuf_rptr(((gbuf_t *)gref->info)); switch(ap->csCode) { case dspWrite: if ((error = adspWrite(sp, ap))) gbuf_freem(mp); return(STR_IGNORE); case dspAttention: if ((error = adspAttention(sp, (CCBPtr)ap))) gbuf_freem(mp); return(STR_IGNORE); } case MSG_IOCTL: if (gref->info == 0) { adspioc_ack(EPROTOTYPE, mp, gref); return(STR_IGNORE); } iocbp = (ioc_t *) gbuf_rptr(mp); if (ADSP_IOCTL(iocbp->ioc_cmd)) { iocbp->ioc_count = sizeof(*ap) - 1; if (gbuf_cont(mp) == 0) { adspioc_ack(EINVAL, mp, gref); return(STR_IGNORE); } ap = (struct adspcmd *) gbuf_rptr(gbuf_cont(mp)); ap->gref = gref; ap->ioc = (caddr_t) mp; ap->mp = gbuf_cont(mp); /* request head */ ap->ioResult = 0; if ((gref->info == 0) && ((iocbp->ioc_cmd != ADSPOPEN) && (iocbp->ioc_cmd != ADSPCLLISTEN))) { ap->ioResult = errState; adspioc_ack(EINVAL, mp, gref); return(STR_IGNORE); } } else return(STR_PUTNEXT); /* pass it on down */ sp = (void *)gbuf_rptr(((gbuf_t *)gref->info)); switch(iocbp->ioc_cmd) { case ADSPOPEN: case ADSPCLLISTEN: ap->socket = ((CCBPtr)sp)->localSocket; flag = (adspMode(ap) == ocAccept) ? 1 : 0; if (flag && ap->socket) { if (adspDeassignSocket((CCBPtr)sp) >= 0) ap->socket = 0; } if ((ap->socket == 0) && ((ap->socket = (at_socket)adspAssignSocket(gref, flag)) == 0)) { adspioc_ack(EADDRNOTAVAIL, mp, gref); return(STR_IGNORE); } ap->csCode = iocbp->ioc_cmd == ADSPOPEN ? dspInit : dspCLInit; if ((error = adspInit(sp, ap)) == 0) { switch(ap->csCode) { case dspInit: /* and open the connection */ ap->csCode = dspOpen; error = adspOpen(sp, ap); break; case dspCLInit: /* ADSPCLLISTEN */ ap->csCode = dspCLListen; error = adspCLListen(sp, ap); break; } } if (error) adspioc_ack(error, mp, gref); /* if this failed req complete */ return(STR_IGNORE); case ADSPCLOSE: ap->csCode = dspClose; if ((error = adspClose(sp, ap))) { adspioc_ack(error, mp, gref); break; } break; case ADSPCLREMOVE: ap->csCode = dspCLRemove; error = adspClose(sp, ap); adspioc_ack(error, mp, gref); return(STR_IGNORE); case ADSPCLDENY: ap->csCode = dspCLDeny; if ((error = adspCLDeny(sp, (CCBPtr)ap))) { adspioc_ack(error, mp, gref); } return(STR_IGNORE); case ADSPSTATUS: ap->csCode = dspStatus; if ((error = adspStatus(sp, ap))) { adspioc_ack(error, mp, gref); } return(STR_IGNORE); case ADSPREAD: ap->csCode = dspRead; if ((error = adspRead(sp, ap))) { adspioc_ack(error, mp, gref); } return(STR_IGNORE); case ADSPATTENTION: ap->csCode = dspAttention; if ((error = adspReadAttention((CCBPtr)sp, ap))) { adspioc_ack(error, mp, gref); } return(STR_IGNORE); case ADSPOPTIONS: ap->csCode = dspOptions; if ((error = adspOptions(sp, ap))) { adspioc_ack(error, mp, gref); } return(STR_IGNORE); case ADSPRESET: ap->csCode = dspReset; if ((error = adspReset(sp, ap))) { adspioc_ack(error, mp, gref); } return(STR_IGNORE); case ADSPNEWCID: ap->csCode = dspNewCID; if ((error = adspNewCID(sp, ap))) { adspioc_ack(error, mp, gref); } return(STR_IGNORE); default: return(STR_PUTNEXT); /* pass it on down */ } return(STR_IGNORE); case MSG_PROTO: default: gbuf_freem(mp); } return(STR_IGNORE); } int adspReadHandler(gref, mp) gref_t *gref; gbuf_t *mp; { int error; switch(gbuf_type(mp)) { case MSG_DATA: if ((error = adspPacket(gref, mp))) { gbuf_freem(mp); } break; case MSG_IOCTL: default: return(STR_PUTNEXT); break; } return(STR_IGNORE); } /* * adsp_sendddp() * * Description: * This procedure a formats a DDP datagram header and calls the * DDP module to queue it for routing and transmission according to * the DDP parameters. We always take control of the datagram; * if there is an error we free it, otherwise we pass it to the next * layer. We don't need to set the src address fileds because the * DDP layer fills these in for us. * * Calling Sequence: * ret_status = adsp_sendddp(q, sp, mp, length, dstnetaddr, ddptype); * * Formal Parameters: * sp Caller stream pointer * mp gbuf_t chain containing the datagram to transmit * The first mblk contains the ADSP header and space * for the DDP header. * length size of data portion of datagram * dstnetaddr address of 4-byte destination internet address * ddptype DDP protocol to assign to the datagram * * Completion Status: * 0 Procedure successful completed. * EMSGSIZE Specified datagram length is too big. * * Side Effects: * NONE */ int adsp_sendddp(sp, mp, length, dstnetaddr, ddptype) CCBPtr sp; gbuf_t *mp; int length; AddrUnion *dstnetaddr; int ddptype; { DDPX_FRAME *ddp; gbuf_t *mlist = mp; if (mp == 0) return EINVAL; if (length > DDP_DATA_SIZE) { gbuf_freel(mlist); return EMSGSIZE; } while (mp) { if (length == 0) length = gbuf_msgsize(mp) - DDPL_FRAME_LEN; /* Set up the DDP header */ ddp = (DDPX_FRAME *) gbuf_rptr(mp); UAS_ASSIGN_HTON(ddp->ddpx_length, (length + DDPL_FRAME_LEN)); UAS_ASSIGN(ddp->ddpx_cksm, 0); if (sp) { if (sp->useCheckSum) UAS_ASSIGN_HTON(ddp->ddpx_cksm, 1); } NET_ASSIGN(ddp->ddpx_dnet, dstnetaddr->a.net); ddp->ddpx_dnode = dstnetaddr->a.node; ddp->ddpx_source = sp ? sp->localSocket : ddp->ddpx_dest; ddp->ddpx_dest = dstnetaddr->a.socket; ddp->ddpx_type = ddptype; length = 0; mp = gbuf_next(mp); } DDP_OUTPUT(mlist); return 0; } void NotifyUser( __unused CCBPtr sp) { /* pidsig(sp->pid, SIGIO); */ } void UrgentUser( __unused CCBPtr sp) { /* pidsig(sp->pid, SIGURG); */ }
p01arst0rm/decorum-linux
_resources/kernels/xnu-arm/bsd/netat/adsp.c
C
gpl-3.0
10,262
/* ** ** This file is part of BananaCam. ** ** BananaCam 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. ** ** BananaCam 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 BananaCam. If not, see <http://www.gnu.org/licenses/>. ** */ #include "camera_control.h" void error_func (GPContext *context, const char *format, va_list args, void *data) { context = context; data = data; fprintf(stderr, "*** Contexterror ***\n"); vfprintf(stderr, format, args); fprintf(stderr, "\n"); } void message_func (GPContext *context, const char *format, va_list args, void *data) { context = context; data = data; vprintf(format, args); printf("\n"); } void signal_handler(int sig) { printf("Signal ==> %i\n", sig); } void signal_inib() { struct sigaction act; int i; act.sa_handler = signal_handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; i = 1; while (i < 32) { if (i != 11) sigaction(i, &act, NULL); i++; } } int init(t_cam *c) { c->liveview = 0; c->liveview_fps = 30; c->liveview_fps_time = 1000000 / 30; pthread_mutex_init(&c->liveview_mutex, NULL); pthread_cond_init(&c->liveview_condvar, NULL); c->folder_path = strdup("/tmp/"); c->camera_value_list = NULL; gp_context_set_error_func(c->context, (GPContextErrorFunc)error_func, NULL); gp_context_set_message_func(c->context, (GPContextMessageFunc)message_func, NULL); gp_camera_new(&c->camera); c->context = gp_context_new(); printf("Camera Init\n"); c->ret = gp_camera_init(c->camera, c->context); if (c->ret != GP_OK) { printf("gp_camera_init: %d\n", c->ret); return (GP_ERROR); } /* get_initial_camera_values(t_cam *c); */ return (GP_OK); } void generic_exec(t_cam *c, char *command, char **param) { char *msg = NULL; if (command && strncmp(command, "get_", 4) == 0) { command = &command[4]; get_config(command, c); return; } if (param) { if (param[0]) set_config(command, param[0], c); } else { asprintf(&msg, "bad parameters for %s", command); creat_and_send_message(BAD_PARAMETERS, NULL, NULL, msg, c); } } int exec_command(t_cam *c, char *command, char **param) { t_func *tmp = NULL; int flag = 0; if (strcmp(command, "liveview") != 0 && c->liveview == 1) { printf("enter inside here\n"); c->liveview = 0; flag = 1; sleep(1); } tmp = c->first_func_ptr; while (tmp != NULL) { if (strcmp(command, tmp->name) == 0) { tmp->func_ptr(c, param); break; } tmp = tmp->next; } if (tmp == NULL) generic_exec(c, command, param); if (flag == 1) liveview(c, NULL); return (0); } void add_func_ptr_list(t_cam *c, char *name, int (*func_ptr)(t_cam *c, char **param)) { t_func *tmp; if (c->first_func_ptr == NULL) { c->first_func_ptr = malloc(sizeof(*c->first_func_ptr)); tmp = c->first_func_ptr; tmp->next = NULL; tmp->func_ptr = func_ptr; tmp->name = strdup(name); c->first_func_ptr = tmp; } else { tmp = c->first_func_ptr; while (tmp->next != NULL) tmp = tmp->next; tmp->next = malloc(sizeof(*tmp->next)); tmp = tmp->next; tmp->next = NULL; tmp->func_ptr = func_ptr; tmp->name = strdup(name); } } int main(int ac, char **av) { t_cam *c; ac = ac; av = av; #ifdef __APPLE__ //pthread_t thread; printf("Killing PTPCamera process\n"); system("killall PTPCamera"); //pthread_create(&thread, NULL, initUSBDetect, (void *)c); #endif signal_inib(); c = malloc(sizeof(*c)); c->first_func_ptr = NULL; init(c); get_all_widget_and_choices(c); add_func_ptr_list(c, "capture", trigger_capture); add_func_ptr_list(c, "liveview", liveview); add_func_ptr_list(c, "auto_focus", auto_focus); add_func_ptr_list(c, "liveviewfps", liveviewfps); add_func_ptr_list(c, "get_liveviewfps", get_liveviewfps); add_func_ptr_list(c, "defaultpath", set_default_folder_path); add_func_ptr_list(c, "get_defaultpath", get_default_folder_path); pthread_create(&c->liveview_thread, NULL, liveview_launcher, (void*)c); init_comm(c, UNIX_SOCKET_PATH); gp_camera_exit(c->camera, c->context); return (0); }
OliverNicolini/BananaCam
src/main.c
C
gpl-3.0
4,707
/* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc. This file is part of GNU Inetutils. GNU Inetutils 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. GNU Inetutils 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/'. */ /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <config.h> #if defined AUTHENTICATION || defined ENCRYPTION # include <unistd.h> # include <sys/types.h> # include <arpa/telnet.h> # include <libtelnet/encrypt.h> # include <libtelnet/misc.h> # include "general.h" # include "ring.h" # include "externs.h" # include "defines.h" # include "types.h" int net_write (unsigned char *str, int len) { if (NETROOM () > len) { ring_supply_data (&netoring, str, len); if (str[0] == IAC && str[1] == SE) printsub ('>', &str[2], len - 2); return (len); } return (0); } void net_encrypt () { # ifdef ENCRYPTION if (encrypt_output) ring_encrypt (&netoring, encrypt_output); else ring_clearto (&netoring); # endif /* ENCRYPTION */ } int telnet_spin () { return (-1); } char * telnet_getenv (char *val) { return ((char *) env_getvalue (val)); } char * telnet_gets (char *prompt, char *result, int length, int echo) { # if !HAVE_DECL_GETPASS extern char *getpass (); # endif extern int globalmode; int om = globalmode; char *res; TerminalNewMode (-1); if (echo) { printf ("%s", prompt); res = fgets (result, length, stdin); } else { res = getpass (prompt); if (res) { strncpy (result, res, length); memset (res, 0, strlen (res)); res = result; } } TerminalNewMode (om); return (res); } #endif /* defined(AUTHENTICATION) || defined(ENCRYPTION) */
infoburp/inetutils
telnet/authenc.c
C
gpl-3.0
3,857
/* * Multi2Sim * Copyright (C) 2012 Rafael Ubal (ubal@ece.neu.edu) * * 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 <assert.h> #include <lib/mhandle/mhandle.h> #include <lib/util/debug.h> #include <lib/util/linked-list.h> #include "opencl-repo.h" #include "opencl-command-queue.h" #include "opencl-context.h" #include "opencl-device.h" #include "opencl-event.h" #include "opencl-kernel.h" #include "opencl-mem.h" #include "opencl-platform.h" #include "opencl-program.h" #include "opencl-sampler.h" struct si_opencl_repo_t { struct linked_list_t *object_list; }; struct si_opencl_repo_t *si_opencl_repo_create(void) { struct si_opencl_repo_t *repo; /* Initialize */ repo = xcalloc(1, sizeof(struct si_opencl_repo_t)); repo->object_list = linked_list_create(); /* Return */ return repo; } void si_opencl_repo_free(struct si_opencl_repo_t *repo) { linked_list_free(repo->object_list); free(repo); } void si_opencl_repo_add_object(struct si_opencl_repo_t *repo, void *object) { struct linked_list_t *object_list = repo->object_list; /* Check that object does not exist */ linked_list_find(object_list, object); if (!object_list->error_code) fatal("%s: object already exists", __FUNCTION__); /* Insert */ linked_list_add(object_list, object); } void si_opencl_repo_remove_object(struct si_opencl_repo_t *repo, void *object) { struct linked_list_t *object_list = repo->object_list; /* Check that object exists */ linked_list_find(object_list, object); if (object_list->error_code) fatal("%s: object does not exist", __FUNCTION__); /* Remove */ linked_list_remove(object_list); } /* Look for an object in the repository. The first field of every OpenCL object * is its identifier. */ void *si_opencl_repo_get_object(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type, unsigned int object_id) { struct linked_list_t *object_list = repo->object_list; void *object; unsigned int current_object_id; /* Upper 16-bits represent the type of the object */ if (object_id >> 16 != type) fatal("%s: requested OpenCL object of incorrect type", __FUNCTION__); /* Search object */ LINKED_LIST_FOR_EACH(object_list) { object = linked_list_get(object_list); assert(object); current_object_id = * (unsigned int *) object; if (current_object_id == object_id) return object; } /* Not found */ fatal("%s: requested OpenCL does not exist (id=0x%x)", __FUNCTION__, object_id); return NULL; } /* Get the oldest created OpenCL object of the specified type */ void *si_opencl_repo_get_object_of_type(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type) { struct linked_list_t *object_list = repo->object_list; void *object; unsigned int object_id; /* Find object. Upper 16-bits of identifier contain its type. */ LINKED_LIST_FOR_EACH(object_list) { object = linked_list_get(object_list); assert(object); object_id = * (unsigned int *) object; if (object_id >> 16 == type) return object; } /* No object found */ return NULL; } /* Assignment of OpenCL object identifiers * An identifier is a 32-bit value, whose 16 most significant bits represent the * object type, while the 16 least significant bits represent a unique object ID. */ unsigned int si_opencl_repo_new_object_id(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type) { static unsigned int si_opencl_object_id_counter; unsigned int object_id; object_id = (type << 16) | si_opencl_object_id_counter; si_opencl_object_id_counter++; if (si_opencl_object_id_counter > 0xffff) fatal("%s: limit of OpenCL objects exceeded\n", __FUNCTION__); return object_id; } void si_opencl_repo_free_all_objects(struct si_opencl_repo_t *repo) { void *object; /* Platforms */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_platform))) si_opencl_platform_free((struct si_opencl_platform_t *) object); /* Devices */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_device))) si_opencl_device_free((struct si_opencl_device_t *) object); /* Contexts */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_context))) si_opencl_context_free((struct si_opencl_context_t *) object); /* Command queues */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_command_queue))) si_opencl_command_queue_free((struct si_opencl_command_queue_t *) object); /* Programs */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_program))) si_opencl_program_free((struct si_opencl_program_t *) object); /* Kernels */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_kernel))) si_opencl_kernel_free((struct si_opencl_kernel_t *) object); /* Mems */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_mem))) si_opencl_mem_free((struct si_opencl_mem_t *) object); /* Events */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_event))) si_opencl_event_free((struct si_opencl_event_t *) object); /* Samplers */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_sampler))) si_opencl_sampler_free((struct si_opencl_sampler_t *) object); /* Any object left */ if (linked_list_count(repo->object_list)) panic("%s: not all objects were freed", __FUNCTION__); }
filippo-ceid/multi2sim
src/arch/southern-islands/emu/opencl-repo.c
C
gpl-3.0
6,076
/* Multiple Lua Programming Language : Intermediate Code Generator * Copyright(C) 2014 Cheryl Natsu * This file is part of multiple - Multiple Paradigm Language Interpreter * multiple 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. * multiple is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "selfcheck.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "multiple_ir.h" #include "multiply.h" #include "multiply_assembler.h" #include "multiply_str_aux.h" #include "multiple_misc.h" #include "multiple_err.h" #include "vm_predef.h" #include "vm_opcode.h" #include "vm_types.h" #include "mlua_lexer.h" #include "mlua_ast.h" #include "mlua_icg.h" #include "mlua_icg_aux.h" #include "mlua_icg_fcb.h" #include "mlua_icg_context.h" #include "mlua_icg_expr.h" #include "mlua_icg_stmt.h" #include "mlua_icg_built_in_proc.h" #include "mlua_icg_built_in_table.h" /* Declaration */ int mlua_icodegen_statement_list(struct multiple_error *err, \ struct mlua_icg_context *context, \ struct mlua_icg_fcb_block *icg_fcb_block, \ struct mlua_map_offset_label_list *map_offset_label_list, \ struct mlua_ast_statement_list *list, \ struct multiply_offset_item_pack *offset_pack_break); static int mlua_icodegen_merge_blocks(struct multiple_error *err, \ struct mlua_icg_context *context) { int ret = 0; struct mlua_icg_fcb_block *icg_fcb_block_cur; struct mlua_icg_fcb_line *icg_fcb_line_cur; uint32_t instrument_number; struct multiple_ir_export_section_item *export_section_item_cur; struct multiple_ir_text_section_item *text_section_item_cur; uint32_t offset_start; uint32_t fcb_size = 0; uint32_t count; /* Do not disturb the instrument produced by other way */ offset_start = (uint32_t)(context->icode->text_section->size); export_section_item_cur = context->icode->export_section->begin; icg_fcb_block_cur = context->icg_fcb_block_list->begin; while (icg_fcb_block_cur != NULL) { icg_fcb_line_cur = icg_fcb_block_cur->begin; /* Record the absolute instrument number */ instrument_number = (uint32_t)context->icode->text_section->size; if (export_section_item_cur == NULL) { MULTIPLE_ERROR_INTERNAL(); ret = -MULTIPLE_ERR_INTERNAL; goto fail; } export_section_item_cur->instrument_number = instrument_number; while (icg_fcb_line_cur != NULL) { switch (icg_fcb_line_cur->type) { case MLUA_ICG_FCB_LINE_TYPE_NORMAL: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_PC: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, instrument_number + icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK: /* Operand of this instrument here is the index number of lambda */ if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_BLTIN_PROC_MK: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; } fcb_size += 1; icg_fcb_line_cur = icg_fcb_line_cur->next; } icg_fcb_block_cur = icg_fcb_block_cur->next; export_section_item_cur = export_section_item_cur->next; } /* 2nd pass, dealing with lambdas */ icg_fcb_block_cur = context->icg_fcb_block_list->begin; /* Skip text body of built-in procedures at the beginning part */ text_section_item_cur = context->icode->text_section->begin; while (offset_start-- > 0) { text_section_item_cur = text_section_item_cur->next; } /* Process lambda mks */ while (icg_fcb_block_cur != NULL) { icg_fcb_line_cur = icg_fcb_block_cur->begin; while (icg_fcb_line_cur != NULL) { if (icg_fcb_line_cur->type == MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK) { /* Locate to the export section item */ count = icg_fcb_line_cur->operand; export_section_item_cur = context->icode->export_section->begin; while ((export_section_item_cur != NULL) && (count != 0)) { count--; export_section_item_cur = export_section_item_cur->next; } if (export_section_item_cur == NULL) { MULTIPLE_ERROR_INTERNAL(); ret = -MULTIPLE_ERR_INTERNAL; goto fail; } text_section_item_cur->operand = export_section_item_cur->instrument_number; } text_section_item_cur = text_section_item_cur->next; icg_fcb_line_cur = icg_fcb_line_cur->next; } icg_fcb_block_cur = icg_fcb_block_cur->next; } goto done; fail: done: return ret; } static int mlua_icodegen_special(struct multiple_error *err, \ struct multiple_ir *icode, \ struct multiply_resource_id_pool *res_id, \ struct mlua_icg_fcb_block_list *icg_fcb_block_list, \ struct mlua_icg_fcb_block *icg_fcb_block, \ const char *name, const size_t name_len) { int ret = 0; uint32_t id; struct multiple_ir_export_section_item *new_export_section_item = NULL; new_export_section_item = multiple_ir_export_section_item_new(); if (new_export_section_item == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_export_section_item->args_count = 0; new_export_section_item->args = NULL; new_export_section_item->args_types = NULL; /* Return */ if ((ret = mlua_icg_fcb_block_append_with_configure(icg_fcb_block, OP_RETNONE, 0)) != 0) { goto fail; } /* Append block */ if ((ret = mlua_icg_fcb_block_list_append(icg_fcb_block_list, icg_fcb_block)) != 0) { MULTIPLE_ERROR_INTERNAL(); goto fail; } /* Append export section item */ if ((ret = multiply_resource_get_id( \ err, \ icode, \ res_id, \ &id, \ name, name_len)) != 0) { goto fail; } new_export_section_item->name = id; new_export_section_item->instrument_number = (uint32_t)icode->export_section->size; multiple_ir_export_section_append(icode->export_section, new_export_section_item); goto done; fail: if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item); done: return ret; } static int mlua_icodegen_program(struct multiple_error *err, \ struct mlua_icg_context *context, \ struct mlua_ast_program *program) { int ret = 0; struct mlua_icg_fcb_block *new_icg_fcb_block_autorun = NULL; struct mlua_map_offset_label_list *new_map_offset_label_list = NULL; uint32_t id; struct multiple_ir_export_section_item *new_export_section_item = NULL; uint32_t instrument_number_insert_point_built_in_proc; uint32_t instrument_count_built_in_proc; new_icg_fcb_block_autorun = mlua_icg_fcb_block_new(); if (new_icg_fcb_block_autorun == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_map_offset_label_list = mlua_map_offset_label_list_new(); if (new_map_offset_label_list == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_export_section_item = multiple_ir_export_section_item_new(); if (new_export_section_item == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } /* def in .text section */ if ((ret = multiply_resource_get_id( \ err, \ context->icode, \ context->res_id, \ &id, \ VM_PREDEF_MODULE_AUTORUN, \ VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } if ((ret = mlua_icg_fcb_block_append_with_configure(new_icg_fcb_block_autorun, OP_DEF, id)) != 0) { goto fail; } new_export_section_item->name = id; new_export_section_item->args_count = 0; new_export_section_item->args = NULL; new_export_section_item->args_types = NULL; instrument_number_insert_point_built_in_proc = mlua_icg_fcb_block_get_instrument_number(new_icg_fcb_block_autorun); /* Statements of top level */ if ((ret = mlua_icodegen_statement_list(err, context, \ new_icg_fcb_block_autorun, \ new_map_offset_label_list, \ program->stmts, NULL)) != 0) { goto fail; } /* Apply goto to label */ if ((ret = mlua_icodegen_statement_list_apply_goto(err, \ context, \ new_icg_fcb_block_autorun, \ new_map_offset_label_list)) != 0) { goto fail; } /* Pop a label offset pack */ multiply_offset_item_pack_stack_pop(context->offset_item_pack_stack); /* Put built-in procedures directly into icode, * and put initialize code into '__autorun__' */ if ((ret = mlua_icg_add_built_in_procs(err, \ context->icode, \ context->res_id, \ new_icg_fcb_block_autorun, \ context->customizable_built_in_procedure_list, \ instrument_number_insert_point_built_in_proc, &instrument_count_built_in_proc)) != 0) { goto fail; } /* Put built-in 'tables' directly into icode, * and put initialize code into '__autorun__' */ if ((ret = mlua_icg_add_built_in_tables(err, \ context->icode, \ context->res_id, \ new_icg_fcb_block_autorun, \ context->stdlibs, \ instrument_number_insert_point_built_in_proc, &instrument_count_built_in_proc)) != 0) { goto fail; } /* '__autorun__' subroutine */ if ((ret = mlua_icodegen_special( \ err, \ context->icode, \ context->res_id, \ context->icg_fcb_block_list, new_icg_fcb_block_autorun, \ VM_PREDEF_MODULE_AUTORUN, VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } new_icg_fcb_block_autorun = NULL; /* Append export section item */ if ((ret = multiply_resource_get_id( \ err, \ context->icode, \ context->res_id, \ &id, \ VM_PREDEF_MODULE_AUTORUN, \ VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } new_export_section_item->name = id; goto done; fail: if (new_icg_fcb_block_autorun != NULL) mlua_icg_fcb_block_destroy(new_icg_fcb_block_autorun); done: if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item); if (new_map_offset_label_list != NULL) mlua_map_offset_label_list_destroy(new_map_offset_label_list); return ret; } int mlua_irgen(struct multiple_error *err, \ struct multiple_ir **icode_out, \ struct mlua_ast_program *program, \ int verbose) { int ret = 0; struct mlua_icg_context context; struct mlua_icg_fcb_block_list *new_icg_fcb_block_list = NULL; struct multiple_ir *new_icode = NULL; struct multiply_resource_id_pool *new_res_id = NULL; struct mlua_icg_customizable_built_in_procedure_list *new_customizable_built_in_procedure_list = NULL; struct multiply_offset_item_pack_stack *new_offset_item_pack_stack = NULL; struct mlua_icg_stdlib_table_list *new_table_list = NULL; (void)verbose; if ((new_customizable_built_in_procedure_list = mlua_icg_customizable_built_in_procedure_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_icg_fcb_block_list = mlua_icg_fcb_block_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_offset_item_pack_stack = multiply_offset_item_pack_stack_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_table_list = mlua_icg_stdlib_table_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_icode = multiple_ir_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_res_id = multiply_resource_id_pool_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } mlua_icg_context_init(&context); context.icg_fcb_block_list = new_icg_fcb_block_list; context.icode = new_icode; context.res_id = new_res_id; context.customizable_built_in_procedure_list = new_customizable_built_in_procedure_list; context.offset_item_pack_stack = new_offset_item_pack_stack; context.stdlibs = new_table_list; /* Generating icode for '__init__' */ if ((ret = mlua_icodegen_program(err, \ &context, \ program)) != 0) { goto fail; } /* Merge blocks */ if ((ret = mlua_icodegen_merge_blocks(err, \ &context)) != 0) { goto fail; } *icode_out = new_icode; ret = 0; goto done; fail: if (new_icode != NULL) multiple_ir_destroy(new_icode); done: if (new_res_id != NULL) multiply_resource_id_pool_destroy(new_res_id); if (new_icg_fcb_block_list != NULL) mlua_icg_fcb_block_list_destroy(new_icg_fcb_block_list); if (new_customizable_built_in_procedure_list != NULL) \ { mlua_icg_customizable_built_in_procedure_list_destroy(new_customizable_built_in_procedure_list); } if (new_offset_item_pack_stack != NULL) { multiply_offset_item_pack_stack_destroy(new_offset_item_pack_stack); } if (new_table_list != NULL) { mlua_icg_stdlib_table_list_destroy(new_table_list); } return ret; }
zooxyt/lua
mlua_icg.c
C
gpl-3.0
15,534
/** ****************************************************************************** * @file Examples_LL/USART/USART_Communication_TxRx_DMA/Src/main.c * @author MCD Application Team * @brief This example describes how to send/receive bytes over USART IP using * the STM32F0xx USART LL API in DMA mode. * Peripheral initialization done using LL unitary services functions. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * 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 STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F0xx_LL_Examples * @{ */ /** @addtogroup USART_Communication_TxRx_DMA * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint8_t ubButtonPress = 0; __IO uint8_t ubSend = 0; /* Buffer used for transmission */ const uint8_t aTxBuffer[] = "STM32F0xx USART LL API Example : TX/RX in DMA mode\r\nConfiguration UART 115200 bps, 8 data bit/1 stop bit/No parity/No HW flow control\r\nPlease enter 'END' string ...\r\n"; uint8_t ubNbDataToTransmit = sizeof(aTxBuffer); __IO uint8_t ubTransmissionComplete = 0; /* Buffer used for reception */ const uint8_t aStringToReceive[] = "END"; uint8_t ubNbDataToReceive = sizeof(aStringToReceive) - 1; uint8_t aRxBuffer[sizeof(aStringToReceive) - 1]; __IO uint8_t ubReceptionComplete = 0; /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); void Configure_DMA(void); void Configure_USART(void); void StartTransfers(void); void LED_Init(void); void LED_On(void); void LED_Blinking(uint32_t Period); void LED_Off(void); void UserButton_Init(void); void WaitForUserButtonPress(void); void WaitAndCheckEndOfTransfer(void); uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength); /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* Configure the system clock to 48 MHz */ SystemClock_Config(); /* Initialize LED2 */ LED_Init(); /* Initialize button in EXTI mode */ UserButton_Init(); /* Configure USARTx (USART IP configuration and related GPIO initialization) */ Configure_USART(); /* Configure DMA channels for USART instance */ Configure_DMA(); /* Wait for User push-button press to start transfer */ WaitForUserButtonPress(); /* Initiate DMA transfers */ StartTransfers(); /* Wait for the end of the transfer and check received data */ WaitAndCheckEndOfTransfer(); /* Infinite loop */ while (1) { } } /** * @brief This function configures the DMA Channels for TX and RX transfers * @note This function is used to : * -1- Enable DMA1 clock * -2- Configure NVIC for DMA transfer complete/error interrupts * -3- Configure DMA TX channel functional parameters * -4- Configure DMA RX channel functional parameters * -5- Enable transfer complete/error interrupts * @param None * @retval None */ void Configure_DMA(void) { /* DMA1 used for USART2 Transmission and Reception */ /* (1) Enable the clock of DMA1 */ LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1); /* (2) Configure NVIC for DMA transfer complete/error interrupts */ NVIC_SetPriority(DMA1_Channel4_5_6_7_IRQn, 0); NVIC_EnableIRQ(DMA1_Channel4_5_6_7_IRQn); /* (3) Configure the DMA functional parameters for transmission */ LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_4, LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE); LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_4, (uint32_t)aTxBuffer, LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_TRANSMIT), LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_4)); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_4, ubNbDataToTransmit); /* (4) Configure the DMA functional parameters for reception */ LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_5, LL_DMA_DIRECTION_PERIPH_TO_MEMORY | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE); LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_5, LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_RECEIVE), (uint32_t)aRxBuffer, LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_5)); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_5, ubNbDataToReceive); /* (5) Enable DMA transfer complete/error interrupts */ LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_4); LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_4); LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_5); LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_5); } /** * @brief This function configures USARTx Instance. * @note This function is used to : * -1- Enable GPIO clock and configures the USART2 pins. * -2- Enable the USART2 peripheral clock and clock source. * -3- Configure USART2 functional parameters. * -4- Enable USART2. * @note Peripheral configuration is minimal configuration from reset values. * Thus, some useless LL unitary functions calls below are provided as * commented examples - setting is default configuration from reset. * @param None * @retval None */ void Configure_USART(void) { /* (1) Enable GPIO clock and configures the USART pins **********************/ /* Enable the peripheral clock of GPIO Port */ LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA); /* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_2, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_2, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_2, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_2, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_2, LL_GPIO_PULL_UP); /* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_3, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_3, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_3, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_3, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_3, LL_GPIO_PULL_UP); /* (2) Enable USART2 peripheral clock and clock source ****************/ LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART2); /* Set clock source */ LL_RCC_SetUSARTClockSource(LL_RCC_USART2_CLKSOURCE_PCLK1); /* (3) Configure USART2 functional parameters ********************************/ /* Disable USART prior modifying configuration registers */ /* Note: Commented as corresponding to Reset value */ // LL_USART_Disable(USART2); /* TX/RX direction */ LL_USART_SetTransferDirection(USART2, LL_USART_DIRECTION_TX_RX); /* 8 data bit, 1 start bit, 1 stop bit, no parity */ LL_USART_ConfigCharacter(USART2, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1); /* No Hardware Flow control */ /* Reset value is LL_USART_HWCONTROL_NONE */ // LL_USART_SetHWFlowCtrl(USART2, LL_USART_HWCONTROL_NONE); /* Oversampling by 16 */ /* Reset value is LL_USART_OVERSAMPLING_16 */ // LL_USART_SetOverSampling(USART2, LL_USART_OVERSAMPLING_16); /* Set Baudrate to 115200 using APB frequency set to 48000000 Hz */ /* Frequency available for USART peripheral can also be calculated through LL RCC macro */ /* Ex : Periphclk = LL_RCC_GetUSARTClockFreq(Instance); or LL_RCC_GetUARTClockFreq(Instance); depending on USART/UART instance In this example, Peripheral Clock is expected to be equal to 48000000 Hz => equal to SystemCoreClock */ LL_USART_SetBaudRate(USART2, SystemCoreClock, LL_USART_OVERSAMPLING_16, 115200); /* (4) Enable USART2 **********************************************************/ LL_USART_Enable(USART2); /* Polling USART initialisation */ while((!(LL_USART_IsActiveFlag_TEACK(USART2))) || (!(LL_USART_IsActiveFlag_REACK(USART2)))) { } } /** * @brief This function initiates TX and RX DMA transfers by enabling DMA channels * @param None * @retval None */ void StartTransfers(void) { /* Enable DMA RX Interrupt */ LL_USART_EnableDMAReq_RX(USART2); /* Enable DMA TX Interrupt */ LL_USART_EnableDMAReq_TX(USART2); /* Enable DMA Channel Rx */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_5); /* Enable DMA Channel Tx */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_4); } /** * @brief Initialize LED2. * @param None * @retval None */ void LED_Init(void) { /* Enable the LED2 Clock */ LED2_GPIO_CLK_ENABLE(); /* Configure IO in output push-pull mode to drive external LED2 */ LL_GPIO_SetPinMode(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_MODE_OUTPUT); /* Reset value is LL_GPIO_OUTPUT_PUSHPULL */ //LL_GPIO_SetPinOutputType(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_OUTPUT_PUSHPULL); /* Reset value is LL_GPIO_SPEED_FREQ_LOW */ //LL_GPIO_SetPinSpeed(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_SPEED_FREQ_LOW); /* Reset value is LL_GPIO_PULL_NO */ //LL_GPIO_SetPinPull(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_PULL_NO); } /** * @brief Turn-on LED2. * @param None * @retval None */ void LED_On(void) { /* Turn LED2 on */ LL_GPIO_SetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Turn-off LED2. * @param None * @retval None */ void LED_Off(void) { /* Turn LED2 off */ LL_GPIO_ResetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Set LED2 to Blinking mode for an infinite loop (toggle period based on value provided as input parameter). * @param Period : Period of time (in ms) between each toggling of LED * This parameter can be user defined values. Pre-defined values used in that example are : * @arg LED_BLINK_FAST : Fast Blinking * @arg LED_BLINK_SLOW : Slow Blinking * @arg LED_BLINK_ERROR : Error specific Blinking * @retval None */ void LED_Blinking(uint32_t Period) { /* Toggle LED2 in an infinite loop */ while (1) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(Period); } } /** * @brief Configures User push-button in GPIO or EXTI Line Mode. * @param None * @retval None */ void UserButton_Init(void) { /* Enable the BUTTON Clock */ USER_BUTTON_GPIO_CLK_ENABLE(); /* Configure GPIO for BUTTON */ LL_GPIO_SetPinMode(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_MODE_INPUT); LL_GPIO_SetPinPull(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_PULL_NO); /* Connect External Line to the GPIO*/ USER_BUTTON_SYSCFG_SET_EXTI(); /* Enable a rising trigger EXTI_Line4_15 Interrupt */ USER_BUTTON_EXTI_LINE_ENABLE(); USER_BUTTON_EXTI_FALLING_TRIG_ENABLE(); /* Configure NVIC for USER_BUTTON_EXTI_IRQn */ NVIC_SetPriority(USER_BUTTON_EXTI_IRQn, 3); NVIC_EnableIRQ(USER_BUTTON_EXTI_IRQn); } /** * @brief Wait for User push-button press to start transfer. * @param None * @retval None */ /* */ void WaitForUserButtonPress(void) { while (ubButtonPress == 0) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(LED_BLINK_FAST); } /* Ensure that LED2 is turned Off */ LED_Off(); } /** * @brief Wait end of transfer and check if received Data are well. * @param None * @retval None */ void WaitAndCheckEndOfTransfer(void) { /* 1 - Wait end of transmission */ while (ubTransmissionComplete != 1) { } /* Disable DMA1 Tx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4); /* 2 - Wait end of reception */ while (ubReceptionComplete != 1) { } /* Disable DMA1 Rx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5); /* 3 - Compare received string to expected one */ if(Buffercmp8((uint8_t*)aStringToReceive, (uint8_t*)aRxBuffer, ubNbDataToReceive)) { /* Processing Error */ LED_Blinking(LED_BLINK_ERROR); } else { /* Turn On Led if data are well received */ LED_On(); } } /** * @brief Compares two 8-bit buffers and returns the comparison result. * @param pBuffer1: pointer to the source buffer to be compared to. * @param pBuffer2: pointer to the second source buffer to be compared to the first. * @param BufferLength: buffer's length. * @retval 0: Comparison is OK (the two Buffers are identical) * Value different from 0: Comparison is NOK (Buffers are different) */ uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength) { while (BufferLength--) { if (*pBuffer1 != *pBuffer2) { return 1; } pBuffer1++; pBuffer2++; } return 0; } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSI48) * SYSCLK(Hz) = 48000000 * HCLK(Hz) = 48000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * HSI Frequency(Hz) = 48000000 * PREDIV = 2 * PLLMUL = 2 * Flash Latency(WS) = 1 * @param None * @retval None */ void SystemClock_Config(void) { /* Set FLASH latency */ LL_FLASH_SetLatency(LL_FLASH_LATENCY_1); /* Enable HSI48 and wait for activation*/ LL_RCC_HSI48_Enable(); while(LL_RCC_HSI48_IsReady() != 1) { }; /* Main PLL configuration and activation */ LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSI48, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2); LL_RCC_PLL_Enable(); while(LL_RCC_PLL_IsReady() != 1) { }; /* Sysclk activation on the main PLL */ LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1); LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL); while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL) { }; /* Set APB1 prescaler */ LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1); /* Set systick to 1ms in using frequency set to 48MHz */ /* This frequency can be calculated through LL RCC macro */ /* ex: __LL_RCC_CALC_PLLCLK_FREQ (HSI48_VALUE, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2) */ LL_Init1msTick(48000000); /* Update CMSIS variable (which can be updated also through SystemCoreClockUpdate function) */ LL_SetSystemCoreClock(48000000); } /******************************************************************************/ /* USER IRQ HANDLER TREATMENT Functions */ /******************************************************************************/ /** * @brief Function to manage User push-button * @param None * @retval None */ void UserButton_Callback(void) { /* Update User push-button variable : to be checked in waiting loop in main program */ ubButtonPress = 1; } /** * @brief Function called from DMA1 IRQ Handler when Tx transfer is completed * @param None * @retval None */ void DMA1_TransmitComplete_Callback(void) { /* DMA Tx transfer completed */ ubTransmissionComplete = 1; } /** * @brief Function called from DMA1 IRQ Handler when Rx transfer is completed * @param None * @retval None */ void DMA1_ReceiveComplete_Callback(void) { /* DMA Rx transfer completed */ ubReceptionComplete = 1; } /** * @brief Function called in case of error detected in USART IT Handler * @param None * @retval None */ void USART_TransferError_Callback(void) { /* Disable DMA1 Tx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4); /* Disable DMA1 Rx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5); /* Set LED2 to Blinking mode to indicate error occurs */ LED_Blinking(LED_BLINK_ERROR); } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Fdepraetre/Handmouse
Software/Handmouse_STM/Lib_DL/STM32Cube_FW_F0_V1.8.0/Projects/STM32F072RB-Nucleo/Examples_LL/USART/USART_Communication_TxRx_DMA/Src/main.c
C
gpl-3.0
19,128
/* * FuchsTracker.c Copyright (C) 1999 Sylvain "Asle" Chipaux * * Depacks Fuchs Tracker modules * * Modified in 2006,2007,2014 by Claudio Matsuoka */ #include <string.h> #include <stdlib.h> #include "prowiz.h" static int depack_fuchs(HIO_HANDLE *in, FILE *out) { uint8 *tmp; uint8 max_pat; /*int ssize;*/ uint8 data[1080]; unsigned smp_len[16]; unsigned loop_start[16]; unsigned pat_size; unsigned i; memset(smp_len, 0, 16 * 4); memset(loop_start, 0, 16 * 4); memset(data, 0, 1080); hio_read(data, 1, 10, in); /* read/write title */ /*ssize =*/ hio_read32b(in); /* read all sample data size */ /* read/write sample sizes */ for (i = 0; i < 16; i++) { smp_len[i] = hio_read16b(in); data[42 + i * 30] = smp_len[i] >> 9; data[43 + i * 30] = smp_len[i] >> 1; } /* read/write volumes */ for (i = 0; i < 16; i++) { data[45 + i * 30] = hio_read16b(in); } /* read/write loop start */ for (i = 0; i < 16; i++) { loop_start[i] = hio_read16b(in); data[46 + i * 30] = loop_start[i] >> 1; } /* write replen */ for (i = 0; i < 16; i++) { int loop_size; loop_size = smp_len[i] - loop_start[i]; if (loop_size == 0 || loop_start[i] == 0) { data[49 + i * 30] = 1; } else { data[48 + i * 30] = loop_size >> 9; data[49 + i * 30] = loop_size >> 1; } } /* fill replens up to 31st sample wiz $0001 */ for (i = 16; i < 31; i++) { data[49 + i * 30] = 1; } /* that's it for the samples ! */ /* now, the pattern list */ /* read number of pattern to play */ data[950] = hio_read16b(in); data[951] = 0x7f; /* read/write pattern list */ for (max_pat = i = 0; i < 40; i++) { uint8 pat = hio_read16b(in); data[952 + i] = pat; if (pat > max_pat) { max_pat = pat; } } /* write ptk's ID */ if (fwrite(data, 1, 1080, out) != 1080) { return -1; } write32b(out, PW_MOD_MAGIC); /* now, the pattern data */ /* bypass the "SONG" ID */ hio_read32b(in); /* read pattern data size */ pat_size = hio_read32b(in); /* Sanity check */ if (pat_size <= 0 || pat_size > 0x20000) return -1; /* read pattern data */ tmp = (uint8 *)malloc(pat_size); if (hio_read(tmp, 1, pat_size, in) != pat_size) { free(tmp); return -1; } /* convert shits */ for (i = 0; i < pat_size; i += 4) { /* convert fx C arg back to hex value */ if ((tmp[i + 2] & 0x0f) == 0x0c) { int x = tmp[i + 3]; tmp[i + 3] = 10 * (x >> 4) + (x & 0xf); } } /* write pattern data */ fwrite(tmp, pat_size, 1, out); free(tmp); /* read/write sample data */ hio_read32b(in); /* bypass "INST" Id */ for (i = 0; i < 16; i++) { if (smp_len[i] != 0) pw_move_data(out, in, smp_len[i]); } return 0; } static int test_fuchs (uint8 *data, char *t, int s) { int i; int ssize, hdr_ssize; #if 0 /* test #1 */ if (i < 192) { Test = BAD; return; } start = i - 192; #endif if (readmem32b(data + 192) != 0x534f4e47) /* SONG */ return -1; /* all sample size */ hdr_ssize = readmem32b(data + 10); if (hdr_ssize <= 2 || hdr_ssize >= 65535 * 16) return -1; /* samples descriptions */ ssize = 0; for (i = 0; i < 16; i++) { uint8 *d = data + i * 2; int len = readmem16b(d + 14); int start = readmem16b(d + 78); /* volumes */ if (d[46] > 0x40) return -1; if (len < start) return -1; ssize += len; } if (ssize <= 2 || ssize > hdr_ssize) return -1; /* get highest pattern number in pattern list */ /*max_pat = 0;*/ for (i = 0; i < 40; i++) { int pat = data[i * 2 + 113]; if (pat > 40) return -1; /*if (pat > max_pat) max_pat = pat;*/ } #if 0 /* input file not long enough ? */ max_pat++; max_pat *= 1024; PW_REQUEST_DATA (s, k + 200); #endif pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_fchs = { "Fuchs Tracker", test_fuchs, depack_fuchs };
DodgeeSoftware/OpenALWrapper
_dependencies/libxmp-4.4.0/src/loaders/prowizard/fuchs.c
C
gpl-3.0
3,794
/** ****************************************************************************** * @file I2C/I2C_TwoBoards_ComPolling/Src/stm32f4xx_it.c * @author MCD Application Team * @version V1.2.7 * @date 17-February-2017 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * 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 STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f4xx_it.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup I2C_TwoBoards_ComPolling * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* I2C handler declared in "main.c" file */ extern I2C_HandleTypeDef hi2c; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { HAL_IncTick(); } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f4xx.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
TRothfelder/Multicopter
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32F4-Discovery/Examples/I2C/I2C_TwoBoards_ComPolling/Src/stm32f4xx_it.c
C
gpl-3.0
5,686
/* * sound/oss/ad1848.c * * The low level driver for the AD1848/CS4248 codec chip which * is used for example in the MS Sound System. * * The CS4231 which is used in the GUS MAX and some other cards is * upwards compatible with AD1848 and this driver is able to drive it. * * CS4231A and AD1845 are upward compatible with CS4231. However * the new features of these chips are different. * * CS4232 is a PnP audio chip which contains a CS4231A (and SB, MPU). * CS4232A is an improved version of CS4232. * * * * Copyright (C) by Hannu Savolainen 1993-1997 * * OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL) * Version 2 (June 1991). See the "COPYING" file distributed with this software * for more info. * * * Thomas Sailer : ioctl code reworked (vmalloc/vfree removed) * general sleep/wakeup clean up. * Alan Cox : reformatted. Fixed SMP bugs. Moved to kernel alloc/free * of irqs. Use dev_id. * Christoph Hellwig : adapted to module_init/module_exit * Aki Laukkanen : added power management support * Arnaldo C. de Melo : added missing restore_flags in ad1848_resume * Miguel Freitas : added ISA PnP support * Alan Cox : Added CS4236->4239 identification * Daniel T. Cobra : Alernate config/mixer for later chips * Alan Cox : Merged chip idents and config code * * TODO * APM save restore assist code on IBM thinkpad * * Status: * Tested. Believed fully functional. */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/stddef.h> #include <linux/slab.h> #include <linux/isapnp.h> #include <linux/pnp.h> #include <linux/spinlock.h> #include "sound_config.h" #include "ad1848.h" #include "ad1848_mixer.h" typedef struct { spinlock_t lock; int base; int irq; int dma1, dma2; int dual_dma; /* 1, when two DMA channels allocated */ int subtype; unsigned char MCE_bit; unsigned char saved_regs[64]; /* Includes extended register space */ int debug_flag; int audio_flags; int record_dev, playback_dev; int xfer_count; int audio_mode; int open_mode; int intr_active; char *chip_name, *name; int model; #define MD_1848 1 #define MD_4231 2 #define MD_4231A 3 #define MD_1845 4 #define MD_4232 5 #define MD_C930 6 #define MD_IWAVE 7 #define MD_4235 8 /* Crystal Audio CS4235 */ #define MD_1845_SSCAPE 9 /* Ensoniq Soundscape PNP*/ #define MD_4236 10 /* 4236 and higher */ #define MD_42xB 11 /* CS 42xB */ #define MD_4239 12 /* CS4239 */ /* Mixer parameters */ int recmask; int supported_devices, orig_devices; int supported_rec_devices, orig_rec_devices; int *levels; short mixer_reroute[32]; int dev_no; volatile unsigned long timer_ticks; int timer_running; int irq_ok; mixer_ents *mix_devices; int mixer_output_port; } ad1848_info; typedef struct ad1848_port_info { int open_mode; int speed; unsigned char speed_bits; int channels; int audio_format; unsigned char format_bits; } ad1848_port_info; static struct address_info cfg; static int nr_ad1848_devs; static bool deskpro_xl; static bool deskpro_m; static bool soundpro; static volatile signed char irq2dev[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; #ifndef EXCLUDE_TIMERS static int timer_installed = -1; #endif static int loaded; static int ad_format_mask[13 /*devc->model */ ] = { 0, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW, /* AD1845 */ AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE /* CS4235 */, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW /* Ensoniq Soundscape*/, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM }; static ad1848_info adev_info[MAX_AUDIO_DEV]; #define io_Index_Addr(d) ((d)->base) #define io_Indexed_Data(d) ((d)->base+1) #define io_Status(d) ((d)->base+2) #define io_Polled_IO(d) ((d)->base+3) static struct { unsigned char flags; #define CAP_F_TIMER 0x01 } capabilities [10 /*devc->model */ ] = { {0} , {0} /* MD_1848 */ , {CAP_F_TIMER} /* MD_4231 */ , {CAP_F_TIMER} /* MD_4231A */ , {CAP_F_TIMER} /* MD_1845 */ , {CAP_F_TIMER} /* MD_4232 */ , {0} /* MD_C930 */ , {CAP_F_TIMER} /* MD_IWAVE */ , {0} /* MD_4235 */ , {CAP_F_TIMER} /* MD_1845_SSCAPE */ }; #ifdef CONFIG_PNP static int isapnp = 1; static int isapnpjump; static bool reverse; static int audio_activated; #else static int isapnp; #endif static int ad1848_open(int dev, int mode); static void ad1848_close(int dev); static void ad1848_output_block(int dev, unsigned long buf, int count, int intrflag); static void ad1848_start_input(int dev, unsigned long buf, int count, int intrflag); static int ad1848_prepare_for_output(int dev, int bsize, int bcount); static int ad1848_prepare_for_input(int dev, int bsize, int bcount); static void ad1848_halt(int dev); static void ad1848_halt_input(int dev); static void ad1848_halt_output(int dev); static void ad1848_trigger(int dev, int bits); static irqreturn_t adintr(int irq, void *dev_id); #ifndef EXCLUDE_TIMERS static int ad1848_tmr_install(int dev); static void ad1848_tmr_reprogram(int dev); #endif static int ad_read(ad1848_info *devc, int reg) { int x; int timeout = 900000; while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */ { timeout--; } if (reg < 32) { outb(((unsigned char) (reg & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); x = inb(io_Indexed_Data(devc)); } else { int xreg, xra; xreg = (reg & 0xff) - 32; xra = (((xreg & 0x0f) << 4) & 0xf0) | 0x08 | ((xreg & 0x10) >> 2); outb(((unsigned char) (23 & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); outb(((unsigned char) (xra & 0xff)), io_Indexed_Data(devc)); x = inb(io_Indexed_Data(devc)); } return x; } static void ad_write(ad1848_info *devc, int reg, int data) { int timeout = 900000; while (timeout > 0 && inb(devc->base) == 0x80) /* Are we initializing */ { timeout--; } if (reg < 32) { outb(((unsigned char) (reg & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); outb(((unsigned char) (data & 0xff)), io_Indexed_Data(devc)); } else { int xreg, xra; xreg = (reg & 0xff) - 32; xra = (((xreg & 0x0f) << 4) & 0xf0) | 0x08 | ((xreg & 0x10) >> 2); outb(((unsigned char) (23 & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); outb(((unsigned char) (xra & 0xff)), io_Indexed_Data(devc)); outb((unsigned char) (data & 0xff), io_Indexed_Data(devc)); } } static void wait_for_calibration(ad1848_info *devc) { int timeout; /* * Wait until the auto calibration process has finished. * * 1) Wait until the chip becomes ready (reads don't return 0x80). * 2) Wait until the ACI bit of I11 gets on and then off. */ timeout = 100000; while (timeout > 0 && inb(devc->base) == 0x80) { timeout--; } if (inb(devc->base) & 0x80) { printk(KERN_WARNING "ad1848: Auto calibration timed out(1).\n"); } timeout = 100; while (timeout > 0 && !(ad_read(devc, 11) & 0x20)) { timeout--; } if (!(ad_read(devc, 11) & 0x20)) { return; } timeout = 80000; while (timeout > 0 && (ad_read(devc, 11) & 0x20)) { timeout--; } if (ad_read(devc, 11) & 0x20) if ((devc->model != MD_1845) && (devc->model != MD_1845_SSCAPE)) { printk(KERN_WARNING "ad1848: Auto calibration timed out(3).\n"); } } static void ad_mute(ad1848_info *devc) { int i; unsigned char prev; /* * Save old register settings and mute output channels */ for (i = 6; i < 8; i++) { prev = devc->saved_regs[i] = ad_read(devc, i); } } static void ad_unmute(ad1848_info *devc) { } static void ad_enter_MCE(ad1848_info *devc) { int timeout = 1000; unsigned short prev; while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */ { timeout--; } devc->MCE_bit = 0x40; prev = inb(io_Index_Addr(devc)); if (prev & 0x40) { return; } outb((devc->MCE_bit), io_Index_Addr(devc)); } static void ad_leave_MCE(ad1848_info *devc) { unsigned char prev, acal; int timeout = 1000; while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */ { timeout--; } acal = ad_read(devc, 9); devc->MCE_bit = 0x00; prev = inb(io_Index_Addr(devc)); outb((0x00), io_Index_Addr(devc)); /* Clear the MCE bit */ if ((prev & 0x40) == 0) /* Not in MCE mode */ { return; } outb((0x00), io_Index_Addr(devc)); /* Clear the MCE bit */ if (acal & 0x08) /* Auto calibration is enabled */ { wait_for_calibration(devc); } } static int ad1848_set_recmask(ad1848_info *devc, int mask) { unsigned char recdev; int i, n; unsigned long flags; mask &= devc->supported_rec_devices; /* Rename the mixer bits if necessary */ for (i = 0; i < 32; i++) { if (devc->mixer_reroute[i] != i) { if (mask & (1 << i)) { mask &= ~(1 << i); mask |= (1 << devc->mixer_reroute[i]); } } } n = 0; for (i = 0; i < 32; i++) /* Count selected device bits */ if (mask & (1 << i)) { n++; } spin_lock_irqsave(&devc->lock, flags); if (!soundpro) { if (n == 0) { mask = SOUND_MASK_MIC; } else if (n != 1) /* Too many devices selected */ { mask &= ~devc->recmask; /* Filter out active settings */ n = 0; for (i = 0; i < 32; i++) /* Count selected device bits */ if (mask & (1 << i)) { n++; } if (n != 1) { mask = SOUND_MASK_MIC; } } switch (mask) { case SOUND_MASK_MIC: recdev = 2; break; case SOUND_MASK_LINE: case SOUND_MASK_LINE3: recdev = 0; break; case SOUND_MASK_CD: case SOUND_MASK_LINE1: recdev = 1; break; case SOUND_MASK_IMIX: recdev = 3; break; default: mask = SOUND_MASK_MIC; recdev = 2; } recdev <<= 6; ad_write(devc, 0, (ad_read(devc, 0) & 0x3f) | recdev); ad_write(devc, 1, (ad_read(devc, 1) & 0x3f) | recdev); } else /* soundpro */ { unsigned char val; int set_rec_bit; int j; for (i = 0; i < 32; i++) /* For each bit */ { if ((devc->supported_rec_devices & (1 << i)) == 0) { continue; /* Device not supported */ } for (j = LEFT_CHN; j <= RIGHT_CHN; j++) { if (devc->mix_devices[i][j].nbits == 0) /* Inexistent channel */ { continue; } /* * This is tricky: * set_rec_bit becomes 1 if the corresponding bit in mask is set * then it gets flipped if the polarity is inverse */ set_rec_bit = ((mask & (1 << i)) != 0) ^ devc->mix_devices[i][j].recpol; val = ad_read(devc, devc->mix_devices[i][j].recreg); val &= ~(1 << devc->mix_devices[i][j].recpos); val |= (set_rec_bit << devc->mix_devices[i][j].recpos); ad_write(devc, devc->mix_devices[i][j].recreg, val); } } } spin_unlock_irqrestore(&devc->lock, flags); /* Rename the mixer bits back if necessary */ for (i = 0; i < 32; i++) { if (devc->mixer_reroute[i] != i) { if (mask & (1 << devc->mixer_reroute[i])) { mask &= ~(1 << devc->mixer_reroute[i]); mask |= (1 << i); } } } devc->recmask = mask; return mask; } static void oss_change_bits(ad1848_info *devc, unsigned char *regval, unsigned char *muteval, int dev, int chn, int newval) { unsigned char mask; int shift; int mute; int mutemask; int set_mute_bit; set_mute_bit = (newval == 0) ^ devc->mix_devices[dev][chn].mutepol; if (devc->mix_devices[dev][chn].polarity == 1) /* Reverse */ { newval = 100 - newval; } mask = (1 << devc->mix_devices[dev][chn].nbits) - 1; shift = devc->mix_devices[dev][chn].bitpos; if (devc->mix_devices[dev][chn].mutepos == 8) { /* if there is no mute bit */ mute = 0; /* No mute bit; do nothing special */ mutemask = ~0; /* No mute bit; do nothing special */ } else { mute = (set_mute_bit << devc->mix_devices[dev][chn].mutepos); mutemask = ~(1 << devc->mix_devices[dev][chn].mutepos); } newval = (int) ((newval * mask) + 50) / 100; /* Scale it */ *regval &= ~(mask << shift); /* Clear bits */ *regval |= (newval & mask) << shift; /* Set new value */ *muteval &= mutemask; *muteval |= mute; } static int ad1848_mixer_get(ad1848_info *devc, int dev) { if (!((1 << dev) & devc->supported_devices)) { return -EINVAL; } dev = devc->mixer_reroute[dev]; return devc->levels[dev]; } static void ad1848_mixer_set_channel(ad1848_info *devc, int dev, int value, int channel) { int regoffs, muteregoffs; unsigned char val, muteval; unsigned long flags; regoffs = devc->mix_devices[dev][channel].regno; muteregoffs = devc->mix_devices[dev][channel].mutereg; val = ad_read(devc, regoffs); if (muteregoffs != regoffs) { muteval = ad_read(devc, muteregoffs); oss_change_bits(devc, &val, &muteval, dev, channel, value); } else { oss_change_bits(devc, &val, &val, dev, channel, value); } spin_lock_irqsave(&devc->lock, flags); ad_write(devc, regoffs, val); devc->saved_regs[regoffs] = val; if (muteregoffs != regoffs) { ad_write(devc, muteregoffs, muteval); devc->saved_regs[muteregoffs] = muteval; } spin_unlock_irqrestore(&devc->lock, flags); } static int ad1848_mixer_set(ad1848_info *devc, int dev, int value) { int left = value & 0x000000ff; int right = (value & 0x0000ff00) >> 8; int retvol; if (dev > 31) { return -EINVAL; } if (!(devc->supported_devices & (1 << dev))) { return -EINVAL; } dev = devc->mixer_reroute[dev]; if (devc->mix_devices[dev][LEFT_CHN].nbits == 0) { return -EINVAL; } if (left > 100) { left = 100; } if (right > 100) { right = 100; } if (devc->mix_devices[dev][RIGHT_CHN].nbits == 0) /* Mono control */ { right = left; } retvol = left | (right << 8); /* Scale volumes */ left = mix_cvt[left]; right = mix_cvt[right]; devc->levels[dev] = retvol; /* * Set the left channel */ ad1848_mixer_set_channel(devc, dev, left, LEFT_CHN); /* * Set the right channel */ if (devc->mix_devices[dev][RIGHT_CHN].nbits == 0) { goto out; } ad1848_mixer_set_channel(devc, dev, right, RIGHT_CHN); out: return retvol; } static void ad1848_mixer_reset(ad1848_info *devc) { int i; char name[32]; unsigned long flags; devc->mix_devices = &(ad1848_mix_devices[0]); sprintf(name, "%s_%d", devc->chip_name, nr_ad1848_devs); for (i = 0; i < 32; i++) { devc->mixer_reroute[i] = i; } devc->supported_rec_devices = MODE1_REC_DEVICES; switch (devc->model) { case MD_4231: case MD_4231A: case MD_1845: case MD_1845_SSCAPE: devc->supported_devices = MODE2_MIXER_DEVICES; break; case MD_C930: devc->supported_devices = C930_MIXER_DEVICES; devc->mix_devices = &(c930_mix_devices[0]); break; case MD_IWAVE: devc->supported_devices = MODE3_MIXER_DEVICES; devc->mix_devices = &(iwave_mix_devices[0]); break; case MD_42xB: case MD_4239: devc->mix_devices = &(cs42xb_mix_devices[0]); devc->supported_devices = MODE3_MIXER_DEVICES; break; case MD_4232: case MD_4235: case MD_4236: devc->supported_devices = MODE3_MIXER_DEVICES; break; case MD_1848: if (soundpro) { devc->supported_devices = SPRO_MIXER_DEVICES; devc->supported_rec_devices = SPRO_REC_DEVICES; devc->mix_devices = &(spro_mix_devices[0]); break; } default: devc->supported_devices = MODE1_MIXER_DEVICES; } devc->orig_devices = devc->supported_devices; devc->orig_rec_devices = devc->supported_rec_devices; devc->levels = load_mixer_volumes(name, default_mixer_levels, 1); for (i = 0; i < SOUND_MIXER_NRDEVICES; i++) { if (devc->supported_devices & (1 << i)) { ad1848_mixer_set(devc, i, devc->levels[i]); } } ad1848_set_recmask(devc, SOUND_MASK_MIC); devc->mixer_output_port = devc->levels[31] | AUDIO_HEADPHONE | AUDIO_LINE_OUT; spin_lock_irqsave(&devc->lock, flags); if (!soundpro) { if (devc->mixer_output_port & AUDIO_SPEAKER) { ad_write(devc, 26, ad_read(devc, 26) & ~0x40); /* Unmute mono out */ } else { ad_write(devc, 26, ad_read(devc, 26) | 0x40); /* Mute mono out */ } } else { /* * From the "wouldn't it be nice if the mixer API had (better) * support for custom stuff" category */ /* Enable surround mode and SB16 mixer */ ad_write(devc, 16, 0x60); } spin_unlock_irqrestore(&devc->lock, flags); } static int ad1848_mixer_ioctl(int dev, unsigned int cmd, void __user *arg) { ad1848_info *devc = mixer_devs[dev]->devc; int val; if (cmd == SOUND_MIXER_PRIVATE1) { if (get_user(val, (int __user *)arg)) { return -EFAULT; } if (val != 0xffff) { unsigned long flags; val &= (AUDIO_SPEAKER | AUDIO_HEADPHONE | AUDIO_LINE_OUT); devc->mixer_output_port = val; val |= AUDIO_HEADPHONE | AUDIO_LINE_OUT; /* Always on */ devc->mixer_output_port = val; spin_lock_irqsave(&devc->lock, flags); if (val & AUDIO_SPEAKER) { ad_write(devc, 26, ad_read(devc, 26) & ~0x40); /* Unmute mono out */ } else { ad_write(devc, 26, ad_read(devc, 26) | 0x40); /* Mute mono out */ } spin_unlock_irqrestore(&devc->lock, flags); } val = devc->mixer_output_port; return put_user(val, (int __user *)arg); } if (cmd == SOUND_MIXER_PRIVATE2) { if (get_user(val, (int __user *)arg)) { return -EFAULT; } return (ad1848_control(AD1848_MIXER_REROUTE, val)); } if (((cmd >> 8) & 0xff) == 'M') { if (_SIOC_DIR(cmd) & _SIOC_WRITE) { switch (cmd & 0xff) { case SOUND_MIXER_RECSRC: if (get_user(val, (int __user *)arg)) { return -EFAULT; } val = ad1848_set_recmask(devc, val); break; default: if (get_user(val, (int __user *)arg)) { return -EFAULT; } val = ad1848_mixer_set(devc, cmd & 0xff, val); break; } return put_user(val, (int __user *)arg); } else { switch (cmd & 0xff) { /* * Return parameters */ case SOUND_MIXER_RECSRC: val = devc->recmask; break; case SOUND_MIXER_DEVMASK: val = devc->supported_devices; break; case SOUND_MIXER_STEREODEVS: val = devc->supported_devices; if (devc->model != MD_C930) { val &= ~(SOUND_MASK_SPEAKER | SOUND_MASK_IMIX); } break; case SOUND_MIXER_RECMASK: val = devc->supported_rec_devices; break; case SOUND_MIXER_CAPS: val = SOUND_CAP_EXCL_INPUT; break; default: val = ad1848_mixer_get(devc, cmd & 0xff); break; } return put_user(val, (int __user *)arg); } } else { return -EINVAL; } } static int ad1848_set_speed(int dev, int arg) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; /* * The sampling speed is encoded in the least significant nibble of I8. The * LSB selects the clock source (0=24.576 MHz, 1=16.9344 MHz) and other * three bits select the divisor (indirectly): * * The available speeds are in the following table. Keep the speeds in * the increasing order. */ typedef struct { int speed; unsigned char bits; } speed_struct; static speed_struct speed_table[] = { {5510, (0 << 1) | 1}, {5510, (0 << 1) | 1}, {6620, (7 << 1) | 1}, {8000, (0 << 1) | 0}, {9600, (7 << 1) | 0}, {11025, (1 << 1) | 1}, {16000, (1 << 1) | 0}, {18900, (2 << 1) | 1}, {22050, (3 << 1) | 1}, {27420, (2 << 1) | 0}, {32000, (3 << 1) | 0}, {33075, (6 << 1) | 1}, {37800, (4 << 1) | 1}, {44100, (5 << 1) | 1}, {48000, (6 << 1) | 0} }; int i, n, selected = -1; n = sizeof(speed_table) / sizeof(speed_struct); if (arg <= 0) { return portc->speed; } if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) /* AD1845 has different timer than others */ { if (arg < 4000) { arg = 4000; } if (arg > 50000) { arg = 50000; } portc->speed = arg; portc->speed_bits = speed_table[3].bits; return portc->speed; } if (arg < speed_table[0].speed) { selected = 0; } if (arg > speed_table[n - 1].speed) { selected = n - 1; } for (i = 1 /*really */ ; selected == -1 && i < n; i++) { if (speed_table[i].speed == arg) { selected = i; } else if (speed_table[i].speed > arg) { int diff1, diff2; diff1 = arg - speed_table[i - 1].speed; diff2 = speed_table[i].speed - arg; if (diff1 < diff2) { selected = i - 1; } else { selected = i; } } } if (selected == -1) { printk(KERN_WARNING "ad1848: Can't find speed???\n"); selected = 3; } portc->speed = speed_table[selected].speed; portc->speed_bits = speed_table[selected].bits; return portc->speed; } static short ad1848_set_channels(int dev, short arg) { ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; if (arg != 1 && arg != 2) { return portc->channels; } portc->channels = arg; return arg; } static unsigned int ad1848_set_bits(int dev, unsigned int arg) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; static struct format_tbl { int format; unsigned char bits; } format2bits[] = { { 0, 0 } , { AFMT_MU_LAW, 1 } , { AFMT_A_LAW, 3 } , { AFMT_IMA_ADPCM, 5 } , { AFMT_U8, 0 } , { AFMT_S16_LE, 2 } , { AFMT_S16_BE, 6 } , { AFMT_S8, 0 } , { AFMT_U16_LE, 0 } , { AFMT_U16_BE, 0 } }; int i, n = sizeof(format2bits) / sizeof(struct format_tbl); if (arg == 0) { return portc->audio_format; } if (!(arg & ad_format_mask[devc->model])) { arg = AFMT_U8; } portc->audio_format = arg; for (i = 0; i < n; i++) if (format2bits[i].format == arg) { if ((portc->format_bits = format2bits[i].bits) == 0) { return portc->audio_format = AFMT_U8; /* Was not supported */ } return arg; } /* Still hanging here. Something must be terribly wrong */ portc->format_bits = 0; return portc->audio_format = AFMT_U8; } static struct audio_driver ad1848_audio_driver = { .owner = THIS_MODULE, .open = ad1848_open, .close = ad1848_close, .output_block = ad1848_output_block, .start_input = ad1848_start_input, .prepare_for_input = ad1848_prepare_for_input, .prepare_for_output = ad1848_prepare_for_output, .halt_io = ad1848_halt, .halt_input = ad1848_halt_input, .halt_output = ad1848_halt_output, .trigger = ad1848_trigger, .set_speed = ad1848_set_speed, .set_bits = ad1848_set_bits, .set_channels = ad1848_set_channels }; static struct mixer_operations ad1848_mixer_operations = { .owner = THIS_MODULE, .id = "SOUNDPORT", .name = "AD1848/CS4248/CS4231", .ioctl = ad1848_mixer_ioctl }; static int ad1848_open(int dev, int mode) { ad1848_info *devc; ad1848_port_info *portc; unsigned long flags; if (dev < 0 || dev >= num_audiodevs) { return -ENXIO; } devc = (ad1848_info *) audio_devs[dev]->devc; portc = (ad1848_port_info *) audio_devs[dev]->portc; /* here we don't have to protect against intr */ spin_lock(&devc->lock); if (portc->open_mode || (devc->open_mode & mode)) { spin_unlock(&devc->lock); return -EBUSY; } devc->dual_dma = 0; if (audio_devs[dev]->flags & DMA_DUPLEX) { devc->dual_dma = 1; } devc->intr_active = 0; devc->audio_mode = 0; devc->open_mode |= mode; portc->open_mode = mode; spin_unlock(&devc->lock); ad1848_trigger(dev, 0); if (mode & OPEN_READ) { devc->record_dev = dev; } if (mode & OPEN_WRITE) { devc->playback_dev = dev; } /* * Mute output until the playback really starts. This decreases clicking (hope so). */ spin_lock_irqsave(&devc->lock, flags); ad_mute(devc); spin_unlock_irqrestore(&devc->lock, flags); return 0; } static void ad1848_close(int dev) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; devc->intr_active = 0; ad1848_halt(dev); spin_lock_irqsave(&devc->lock, flags); devc->audio_mode = 0; devc->open_mode &= ~portc->open_mode; portc->open_mode = 0; ad_unmute(devc); spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_output_block(int dev, unsigned long buf, int count, int intrflag) { unsigned long flags, cnt; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; cnt = count; if (portc->audio_format == AFMT_IMA_ADPCM) { cnt /= 4; } else { if (portc->audio_format & (AFMT_S16_LE | AFMT_S16_BE)) /* 16 bit data */ { cnt >>= 1; } } if (portc->channels > 1) { cnt >>= 1; } cnt--; if ((devc->audio_mode & PCM_ENABLE_OUTPUT) && (audio_devs[dev]->flags & DMA_AUTOMODE) && intrflag && cnt == devc->xfer_count) { devc->audio_mode |= PCM_ENABLE_OUTPUT; devc->intr_active = 1; return; /* * Auto DMA mode on. No need to react */ } spin_lock_irqsave(&devc->lock, flags); ad_write(devc, 15, (unsigned char) (cnt & 0xff)); ad_write(devc, 14, (unsigned char) ((cnt >> 8) & 0xff)); devc->xfer_count = cnt; devc->audio_mode |= PCM_ENABLE_OUTPUT; devc->intr_active = 1; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_start_input(int dev, unsigned long buf, int count, int intrflag) { unsigned long flags, cnt; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; cnt = count; if (portc->audio_format == AFMT_IMA_ADPCM) { cnt /= 4; } else { if (portc->audio_format & (AFMT_S16_LE | AFMT_S16_BE)) /* 16 bit data */ { cnt >>= 1; } } if (portc->channels > 1) { cnt >>= 1; } cnt--; if ((devc->audio_mode & PCM_ENABLE_INPUT) && (audio_devs[dev]->flags & DMA_AUTOMODE) && intrflag && cnt == devc->xfer_count) { devc->audio_mode |= PCM_ENABLE_INPUT; devc->intr_active = 1; return; /* * Auto DMA mode on. No need to react */ } spin_lock_irqsave(&devc->lock, flags); if (devc->model == MD_1848) { ad_write(devc, 15, (unsigned char) (cnt & 0xff)); ad_write(devc, 14, (unsigned char) ((cnt >> 8) & 0xff)); } else { ad_write(devc, 31, (unsigned char) (cnt & 0xff)); ad_write(devc, 30, (unsigned char) ((cnt >> 8) & 0xff)); } ad_unmute(devc); devc->xfer_count = cnt; devc->audio_mode |= PCM_ENABLE_INPUT; devc->intr_active = 1; spin_unlock_irqrestore(&devc->lock, flags); } static int ad1848_prepare_for_output(int dev, int bsize, int bcount) { int timeout; unsigned char fs, old_fs, tmp = 0; unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; ad_mute(devc); spin_lock_irqsave(&devc->lock, flags); fs = portc->speed_bits | (portc->format_bits << 5); if (portc->channels > 1) { fs |= 0x10; } ad_enter_MCE(devc); /* Enables changes to the format select reg */ if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) /* Use alternate speed select registers */ { fs &= 0xf0; /* Mask off the rate select bits */ ad_write(devc, 22, (portc->speed >> 8) & 0xff); /* Speed MSB */ ad_write(devc, 23, portc->speed & 0xff); /* Speed LSB */ } old_fs = ad_read(devc, 8); if (devc->model == MD_4232 || devc->model >= MD_4236) { tmp = ad_read(devc, 16); ad_write(devc, 16, tmp | 0x30); } if (devc->model == MD_IWAVE) { ad_write(devc, 17, 0xc2); /* Disable variable frequency select */ } ad_write(devc, 8, fs); /* * Write to I8 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } if (devc->model >= MD_4232) { ad_write(devc, 16, tmp & ~0x30); } ad_leave_MCE(devc); /* * Starts the calibration process. */ spin_unlock_irqrestore(&devc->lock, flags); devc->xfer_count = 0; #ifndef EXCLUDE_TIMERS if (dev == timer_installed && devc->timer_running) if ((fs & 0x01) != (old_fs & 0x01)) { ad1848_tmr_reprogram(dev); } #endif ad1848_halt_output(dev); return 0; } static int ad1848_prepare_for_input(int dev, int bsize, int bcount) { int timeout; unsigned char fs, old_fs, tmp = 0; unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; if (devc->audio_mode) { return 0; } spin_lock_irqsave(&devc->lock, flags); fs = portc->speed_bits | (portc->format_bits << 5); if (portc->channels > 1) { fs |= 0x10; } ad_enter_MCE(devc); /* Enables changes to the format select reg */ if ((devc->model == MD_1845) || (devc->model == MD_1845_SSCAPE)) /* Use alternate speed select registers */ { fs &= 0xf0; /* Mask off the rate select bits */ ad_write(devc, 22, (portc->speed >> 8) & 0xff); /* Speed MSB */ ad_write(devc, 23, portc->speed & 0xff); /* Speed LSB */ } if (devc->model == MD_4232) { tmp = ad_read(devc, 16); ad_write(devc, 16, tmp | 0x30); } if (devc->model == MD_IWAVE) { ad_write(devc, 17, 0xc2); /* Disable variable frequency select */ } /* * If mode >= 2 (CS4231), set I28. It's the capture format register. */ if (devc->model != MD_1848) { old_fs = ad_read(devc, 28); ad_write(devc, 28, fs); /* * Write to I28 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } if (devc->model != MD_1848 && devc->model != MD_1845 && devc->model != MD_1845_SSCAPE) { /* * CS4231 compatible devices don't have separate sampling rate selection * register for recording an playback. The I8 register is shared so we have to * set the speed encoding bits of it too. */ unsigned char tmp = portc->speed_bits | (ad_read(devc, 8) & 0xf0); ad_write(devc, 8, tmp); /* * Write to I8 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } } } else { /* For AD1848 set I8. */ old_fs = ad_read(devc, 8); ad_write(devc, 8, fs); /* * Write to I8 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } } if (devc->model == MD_4232) { ad_write(devc, 16, tmp & ~0x30); } ad_leave_MCE(devc); /* * Starts the calibration process. */ spin_unlock_irqrestore(&devc->lock, flags); devc->xfer_count = 0; #ifndef EXCLUDE_TIMERS if (dev == timer_installed && devc->timer_running) { if ((fs & 0x01) != (old_fs & 0x01)) { ad1848_tmr_reprogram(dev); } } #endif ad1848_halt_input(dev); return 0; } static void ad1848_halt(int dev) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; unsigned char bits = ad_read(devc, 9); if (bits & 0x01 && (portc->open_mode & OPEN_WRITE)) { ad1848_halt_output(dev); } if (bits & 0x02 && (portc->open_mode & OPEN_READ)) { ad1848_halt_input(dev); } devc->audio_mode = 0; } static void ad1848_halt_input(int dev) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; unsigned long flags; if (!(ad_read(devc, 9) & 0x02)) { return; /* Capture not enabled */ } spin_lock_irqsave(&devc->lock, flags); ad_mute(devc); { int tmout; if (!isa_dma_bridge_buggy) { disable_dma(audio_devs[dev]->dmap_in->dma); } for (tmout = 0; tmout < 100000; tmout++) if (ad_read(devc, 11) & 0x10) { break; } ad_write(devc, 9, ad_read(devc, 9) & ~0x02); /* Stop capture */ if (!isa_dma_bridge_buggy) { enable_dma(audio_devs[dev]->dmap_in->dma); } devc->audio_mode &= ~PCM_ENABLE_INPUT; } outb(0, io_Status(devc)); /* Clear interrupt status */ outb(0, io_Status(devc)); /* Clear interrupt status */ devc->audio_mode &= ~PCM_ENABLE_INPUT; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_halt_output(int dev) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; unsigned long flags; if (!(ad_read(devc, 9) & 0x01)) { return; /* Playback not enabled */ } spin_lock_irqsave(&devc->lock, flags); ad_mute(devc); { int tmout; if (!isa_dma_bridge_buggy) { disable_dma(audio_devs[dev]->dmap_out->dma); } for (tmout = 0; tmout < 100000; tmout++) if (ad_read(devc, 11) & 0x10) { break; } ad_write(devc, 9, ad_read(devc, 9) & ~0x01); /* Stop playback */ if (!isa_dma_bridge_buggy) { enable_dma(audio_devs[dev]->dmap_out->dma); } devc->audio_mode &= ~PCM_ENABLE_OUTPUT; } outb((0), io_Status(devc)); /* Clear interrupt status */ outb((0), io_Status(devc)); /* Clear interrupt status */ devc->audio_mode &= ~PCM_ENABLE_OUTPUT; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_trigger(int dev, int state) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; unsigned long flags; unsigned char tmp, old; spin_lock_irqsave(&devc->lock, flags); state &= devc->audio_mode; tmp = old = ad_read(devc, 9); if (portc->open_mode & OPEN_READ) { if (state & PCM_ENABLE_INPUT) { tmp |= 0x02; } else { tmp &= ~0x02; } } if (portc->open_mode & OPEN_WRITE) { if (state & PCM_ENABLE_OUTPUT) { tmp |= 0x01; } else { tmp &= ~0x01; } } /* ad_mute(devc); */ if (tmp != old) { ad_write(devc, 9, tmp); ad_unmute(devc); } spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_init_hw(ad1848_info *devc) { int i; int *init_values; /* * Initial values for the indirect registers of CS4248/AD1848. */ static int init_values_a[] = { 0xa8, 0xa8, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x0c, 0x02, 0x00, 0x8a, 0x01, 0x00, 0x00, /* Positions 16 to 31 just for CS4231/2 and ad1845 */ 0x80, 0x00, 0x10, 0x10, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static int init_values_b[] = { /* Values for the newer chips Some of the register initialization values were changed. In order to get rid of the click that preceded PCM playback, calibration was disabled on the 10th byte. On that same byte, dual DMA was enabled; on the 11th byte, ADC dithering was enabled, since that is theoretically desirable; on the 13th byte, Mode 3 was selected, to enable access to extended registers. */ 0xa8, 0xa8, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x10, 0x10, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /* * Select initialisation data */ init_values = init_values_a; if (devc->model >= MD_4236) { init_values = init_values_b; } for (i = 0; i < 16; i++) { ad_write(devc, i, init_values[i]); } ad_mute(devc); /* Initialize some variables */ ad_unmute(devc); /* Leave it unmuted now */ if (devc->model > MD_1848) { if (devc->model == MD_1845_SSCAPE) { ad_write(devc, 12, ad_read(devc, 12) | 0x50); } else { ad_write(devc, 12, ad_read(devc, 12) | 0x40); /* Mode2 = enabled */ } if (devc->model == MD_IWAVE) { ad_write(devc, 12, 0x6c); /* Select codec mode 3 */ } if (devc->model != MD_1845_SSCAPE) for (i = 16; i < 32; i++) { ad_write(devc, i, init_values[i]); } if (devc->model == MD_IWAVE) { ad_write(devc, 16, 0x30); /* Playback and capture counters enabled */ } } if (devc->model > MD_1848) { if (devc->audio_flags & DMA_DUPLEX) { ad_write(devc, 9, ad_read(devc, 9) & ~0x04); /* Dual DMA mode */ } else { ad_write(devc, 9, ad_read(devc, 9) | 0x04); /* Single DMA mode */ } if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) { ad_write(devc, 27, ad_read(devc, 27) | 0x08); /* Alternate freq select enabled */ } if (devc->model == MD_IWAVE) { /* Some magic Interwave specific initialization */ ad_write(devc, 12, 0x6c); /* Select codec mode 3 */ ad_write(devc, 16, 0x30); /* Playback and capture counters enabled */ ad_write(devc, 17, 0xc2); /* Alternate feature enable */ } } else { devc->audio_flags &= ~DMA_DUPLEX; ad_write(devc, 9, ad_read(devc, 9) | 0x04); /* Single DMA mode */ if (soundpro) { ad_write(devc, 12, ad_read(devc, 12) | 0x40); /* Mode2 = enabled */ } } outb((0), io_Status(devc)); /* Clear pending interrupts */ /* * Toggle the MCE bit. It completes the initialization phase. */ ad_enter_MCE(devc); /* In case the bit was off */ ad_leave_MCE(devc); ad1848_mixer_reset(devc); } int ad1848_detect(struct resource *ports, int *ad_flags, int *osp) { unsigned char tmp; ad1848_info *devc = &adev_info[nr_ad1848_devs]; unsigned char tmp1 = 0xff, tmp2 = 0xff; int optiC930 = 0; /* OPTi 82C930 flag */ int interwave = 0; int ad1847_flag = 0; int cs4248_flag = 0; int sscape_flag = 0; int io_base = ports->start; int i; DDB(printk("ad1848_detect(%x)\n", io_base)); if (ad_flags) { if (*ad_flags == 0x12345678) { interwave = 1; *ad_flags = 0; } if (*ad_flags == 0x87654321) { sscape_flag = 1; *ad_flags = 0; } if (*ad_flags == 0x12345677) { cs4248_flag = 1; *ad_flags = 0; } } if (nr_ad1848_devs >= MAX_AUDIO_DEV) { printk(KERN_ERR "ad1848 - Too many audio devices\n"); return 0; } spin_lock_init(&devc->lock); devc->base = io_base; devc->irq_ok = 0; devc->timer_running = 0; devc->MCE_bit = 0x40; devc->irq = 0; devc->open_mode = 0; devc->chip_name = devc->name = "AD1848"; devc->model = MD_1848; /* AD1848 or CS4248 */ devc->levels = NULL; devc->debug_flag = 0; /* * Check that the I/O address is in use. * * The bit 0x80 of the base I/O port is known to be 0 after the * chip has performed its power on initialization. Just assume * this has happened before the OS is starting. * * If the I/O address is unused, it typically returns 0xff. */ if (inb(devc->base) == 0xff) { DDB(printk("ad1848_detect: The base I/O address appears to be dead\n")); } /* * Wait for the device to stop initialization */ DDB(printk("ad1848_detect() - step 0\n")); for (i = 0; i < 10000000; i++) { unsigned char x = inb(devc->base); if (x == 0xff || !(x & 0x80)) { break; } } DDB(printk("ad1848_detect() - step A\n")); if (inb(devc->base) == 0x80) /* Not ready. Let's wait */ { ad_leave_MCE(devc); } if ((inb(devc->base) & 0x80) != 0x00) /* Not a AD1848 */ { DDB(printk("ad1848 detect error - step A (%02x)\n", (int) inb(devc->base))); return 0; } /* * Test if it's possible to change contents of the indirect registers. * Registers 0 and 1 are ADC volume registers. The bit 0x10 is read only * so try to avoid using it. */ DDB(printk("ad1848_detect() - step B\n")); ad_write(devc, 0, 0xaa); ad_write(devc, 1, 0x45); /* 0x55 with bit 0x10 clear */ if ((tmp1 = ad_read(devc, 0)) != 0xaa || (tmp2 = ad_read(devc, 1)) != 0x45) { if (tmp2 == 0x65) /* AD1847 has couple of bits hardcoded to 1 */ { ad1847_flag = 1; } else { DDB(printk("ad1848 detect error - step B (%x/%x)\n", tmp1, tmp2)); return 0; } } DDB(printk("ad1848_detect() - step C\n")); ad_write(devc, 0, 0x45); ad_write(devc, 1, 0xaa); if ((tmp1 = ad_read(devc, 0)) != 0x45 || (tmp2 = ad_read(devc, 1)) != 0xaa) { if (tmp2 == 0x8a) /* AD1847 has few bits hardcoded to 1 */ { ad1847_flag = 1; } else { DDB(printk("ad1848 detect error - step C (%x/%x)\n", tmp1, tmp2)); return 0; } } /* * The indirect register I12 has some read only bits. Let's * try to change them. */ DDB(printk("ad1848_detect() - step D\n")); tmp = ad_read(devc, 12); ad_write(devc, 12, (~tmp) & 0x0f); if ((tmp & 0x0f) != ((tmp1 = ad_read(devc, 12)) & 0x0f)) { DDB(printk("ad1848 detect error - step D (%x)\n", tmp1)); return 0; } /* * NOTE! Last 4 bits of the reg I12 tell the chip revision. * 0x01=RevB and 0x0A=RevC. */ /* * The original AD1848/CS4248 has just 15 indirect registers. This means * that I0 and I16 should return the same value (etc.). * However this doesn't work with CS4248. Actually it seems to be impossible * to detect if the chip is a CS4231 or CS4248. * Ensure that the Mode2 enable bit of I12 is 0. Otherwise this test fails * with CS4231. */ /* * OPTi 82C930 has mode2 control bit in another place. This test will fail * with it. Accept this situation as a possible indication of this chip. */ DDB(printk("ad1848_detect() - step F\n")); ad_write(devc, 12, 0); /* Mode2=disabled */ for (i = 0; i < 16; i++) { if ((tmp1 = ad_read(devc, i)) != (tmp2 = ad_read(devc, i + 16))) { DDB(printk("ad1848 detect step F(%d/%x/%x) - OPTi chip???\n", i, tmp1, tmp2)); if (!ad1847_flag) { optiC930 = 1; } break; } } /* * Try to switch the chip to mode2 (CS4231) by setting the MODE2 bit (0x40). * The bit 0x80 is always 1 in CS4248 and CS4231. */ DDB(printk("ad1848_detect() - step G\n")); if (ad_flags && *ad_flags == 400) { *ad_flags = 0; } else { ad_write(devc, 12, 0x40); /* Set mode2, clear 0x80 */ } if (ad_flags) { *ad_flags = 0; } tmp1 = ad_read(devc, 12); if (tmp1 & 0x80) { if (ad_flags) { *ad_flags |= AD_F_CS4248; } devc->chip_name = "CS4248"; /* Our best knowledge just now */ } if (optiC930 || (tmp1 & 0xc0) == (0x80 | 0x40)) { /* * CS4231 detected - is it? * * Verify that setting I0 doesn't change I16. */ DDB(printk("ad1848_detect() - step H\n")); ad_write(devc, 16, 0); /* Set I16 to known value */ ad_write(devc, 0, 0x45); if ((tmp1 = ad_read(devc, 16)) != 0x45) /* No change -> CS4231? */ { ad_write(devc, 0, 0xaa); if ((tmp1 = ad_read(devc, 16)) == 0xaa) /* Rotten bits? */ { DDB(printk("ad1848 detect error - step H(%x)\n", tmp1)); return 0; } /* * Verify that some bits of I25 are read only. */ DDB(printk("ad1848_detect() - step I\n")); tmp1 = ad_read(devc, 25); /* Original bits */ ad_write(devc, 25, ~tmp1); /* Invert all bits */ if ((ad_read(devc, 25) & 0xe7) == (tmp1 & 0xe7)) { int id; /* * It's at least CS4231 */ devc->chip_name = "CS4231"; devc->model = MD_4231; /* * It could be an AD1845 or CS4231A as well. * CS4231 and AD1845 report the same revision info in I25 * while the CS4231A reports different. */ id = ad_read(devc, 25); if ((id & 0xe7) == 0x80) /* Device busy??? */ { id = ad_read(devc, 25); } if ((id & 0xe7) == 0x80) /* Device still busy??? */ { id = ad_read(devc, 25); } DDB(printk("ad1848_detect() - step J (%02x/%02x)\n", id, ad_read(devc, 25))); if ((id & 0xe7) == 0x80) { /* * It must be a CS4231 or AD1845. The register I23 of * CS4231 is undefined and it appears to be read only. * AD1845 uses I23 for setting sample rate. Assume * the chip is AD1845 if I23 is changeable. */ unsigned char tmp = ad_read(devc, 23); ad_write(devc, 23, ~tmp); if (interwave) { devc->model = MD_IWAVE; devc->chip_name = "IWave"; } else if (ad_read(devc, 23) != tmp) /* AD1845 ? */ { devc->chip_name = "AD1845"; devc->model = MD_1845; } else if (cs4248_flag) { if (ad_flags) { *ad_flags |= AD_F_CS4248; } devc->chip_name = "CS4248"; devc->model = MD_1848; ad_write(devc, 12, ad_read(devc, 12) & ~0x40); /* Mode2 off */ } ad_write(devc, 23, tmp); /* Restore */ } else { switch (id & 0x1f) { case 3: /* CS4236/CS4235/CS42xB/CS4239 */ { int xid; ad_write(devc, 12, ad_read(devc, 12) | 0x60); /* switch to mode 3 */ ad_write(devc, 23, 0x9c); /* select extended register 25 */ xid = inb(io_Indexed_Data(devc)); ad_write(devc, 12, ad_read(devc, 12) & ~0x60); /* back to mode 0 */ switch (xid & 0x1f) { case 0x00: devc->chip_name = "CS4237B(B)"; devc->model = MD_42xB; break; case 0x08: /* Seems to be a 4238 ?? */ devc->chip_name = "CS4238"; devc->model = MD_42xB; break; case 0x09: devc->chip_name = "CS4238B"; devc->model = MD_42xB; break; case 0x0b: devc->chip_name = "CS4236B"; devc->model = MD_4236; break; case 0x10: devc->chip_name = "CS4237B"; devc->model = MD_42xB; break; case 0x1d: devc->chip_name = "CS4235"; devc->model = MD_4235; break; case 0x1e: devc->chip_name = "CS4239"; devc->model = MD_4239; break; default: printk("Chip ident is %X.\n", xid & 0x1F); devc->chip_name = "CS42xx"; devc->model = MD_4232; break; } } break; case 2: /* CS4232/CS4232A */ devc->chip_name = "CS4232"; devc->model = MD_4232; break; case 0: if ((id & 0xe0) == 0xa0) { devc->chip_name = "CS4231A"; devc->model = MD_4231A; } else { devc->chip_name = "CS4321"; devc->model = MD_4231; } break; default: /* maybe */ DDB(printk("ad1848: I25 = %02x/%02x\n", ad_read(devc, 25), ad_read(devc, 25) & 0xe7)); if (optiC930) { devc->chip_name = "82C930"; devc->model = MD_C930; } else { devc->chip_name = "CS4231"; devc->model = MD_4231; } } } } ad_write(devc, 25, tmp1); /* Restore bits */ DDB(printk("ad1848_detect() - step K\n")); } } else if (tmp1 == 0x0a) { /* * Is it perhaps a SoundPro CMI8330? * If so, then we should be able to change indirect registers * greater than I15 after activating MODE2, even though reading * back I12 does not show it. */ /* * Let's try comparing register values */ for (i = 0; i < 16; i++) { if ((tmp1 = ad_read(devc, i)) != (tmp2 = ad_read(devc, i + 16))) { DDB(printk("ad1848 detect step H(%d/%x/%x) - SoundPro chip?\n", i, tmp1, tmp2)); soundpro = 1; devc->chip_name = "SoundPro CMI 8330"; break; } } } DDB(printk("ad1848_detect() - step L\n")); if (ad_flags) { if (devc->model != MD_1848) { *ad_flags |= AD_F_CS4231; } } DDB(printk("ad1848_detect() - Detected OK\n")); if (devc->model == MD_1848 && ad1847_flag) { devc->chip_name = "AD1847"; } if (sscape_flag == 1) { devc->model = MD_1845_SSCAPE; } return 1; } int ad1848_init (char *name, struct resource *ports, int irq, int dma_playback, int dma_capture, int share_dma, int *osp, struct module *owner) { /* * NOTE! If irq < 0, there is another driver which has allocated the IRQ * so that this driver doesn't need to allocate/deallocate it. * The actually used IRQ is ABS(irq). */ int my_dev; char dev_name[100]; int e; ad1848_info *devc = &adev_info[nr_ad1848_devs]; ad1848_port_info *portc = NULL; devc->irq = (irq > 0) ? irq : 0; devc->open_mode = 0; devc->timer_ticks = 0; devc->dma1 = dma_playback; devc->dma2 = dma_capture; devc->subtype = cfg.card_subtype; devc->audio_flags = DMA_AUTOMODE; devc->playback_dev = devc->record_dev = 0; if (name != NULL) { devc->name = name; } if (name != NULL && name[0] != 0) sprintf(dev_name, "%s (%s)", name, devc->chip_name); else sprintf(dev_name, "Generic audio codec (%s)", devc->chip_name); rename_region(ports, devc->name); conf_printf2(dev_name, devc->base, devc->irq, dma_playback, dma_capture); if (devc->model == MD_1848 || devc->model == MD_C930) { devc->audio_flags |= DMA_HARDSTOP; } if (devc->model > MD_1848) { if (devc->dma1 == devc->dma2 || devc->dma2 == -1 || devc->dma1 == -1) { devc->audio_flags &= ~DMA_DUPLEX; } else { devc->audio_flags |= DMA_DUPLEX; } } portc = kmalloc(sizeof(ad1848_port_info), GFP_KERNEL); if (portc == NULL) { release_region(devc->base, 4); return -1; } if ((my_dev = sound_install_audiodrv(AUDIO_DRIVER_VERSION, dev_name, &ad1848_audio_driver, sizeof(struct audio_driver), devc->audio_flags, ad_format_mask[devc->model], devc, dma_playback, dma_capture)) < 0) { release_region(devc->base, 4); kfree(portc); return -1; } audio_devs[my_dev]->portc = portc; audio_devs[my_dev]->mixer_dev = -1; if (owner) { audio_devs[my_dev]->d->owner = owner; } memset((char *) portc, 0, sizeof(*portc)); nr_ad1848_devs++; ad1848_init_hw(devc); if (irq > 0) { devc->dev_no = my_dev; if (request_irq(devc->irq, adintr, 0, devc->name, (void *)(long)my_dev) < 0) { printk(KERN_WARNING "ad1848: Unable to allocate IRQ\n"); /* Don't free it either then.. */ devc->irq = 0; } if (capabilities[devc->model].flags & CAP_F_TIMER) { #ifndef CONFIG_SMP int x; unsigned char tmp = ad_read(devc, 16); #endif devc->timer_ticks = 0; ad_write(devc, 21, 0x00); /* Timer MSB */ ad_write(devc, 20, 0x10); /* Timer LSB */ #ifndef CONFIG_SMP ad_write(devc, 16, tmp | 0x40); /* Enable timer */ for (x = 0; x < 100000 && devc->timer_ticks == 0; x++); ad_write(devc, 16, tmp & ~0x40); /* Disable timer */ if (devc->timer_ticks == 0) { printk(KERN_WARNING "ad1848: Interrupt test failed (IRQ%d)\n", irq); } else { DDB(printk("Interrupt test OK\n")); devc->irq_ok = 1; } #else devc->irq_ok = 1; #endif } else { devc->irq_ok = 1; /* Couldn't test. assume it's OK */ } } else if (irq < 0) { irq2dev[-irq] = devc->dev_no = my_dev; } #ifndef EXCLUDE_TIMERS if ((capabilities[devc->model].flags & CAP_F_TIMER) && devc->irq_ok) { ad1848_tmr_install(my_dev); } #endif if (!share_dma) { if (sound_alloc_dma(dma_playback, devc->name)) { printk(KERN_WARNING "ad1848.c: Can't allocate DMA%d\n", dma_playback); } if (dma_capture != dma_playback) if (sound_alloc_dma(dma_capture, devc->name)) { printk(KERN_WARNING "ad1848.c: Can't allocate DMA%d\n", dma_capture); } } if ((e = sound_install_mixer(MIXER_DRIVER_VERSION, dev_name, &ad1848_mixer_operations, sizeof(struct mixer_operations), devc)) >= 0) { audio_devs[my_dev]->mixer_dev = e; if (owner) { mixer_devs[e]->owner = owner; } } return my_dev; } int ad1848_control(int cmd, int arg) { ad1848_info *devc; unsigned long flags; if (nr_ad1848_devs < 1) { return -ENODEV; } devc = &adev_info[nr_ad1848_devs - 1]; switch (cmd) { case AD1848_SET_XTAL: /* Change clock frequency of AD1845 (only ) */ if (devc->model != MD_1845 && devc->model != MD_1845_SSCAPE) { return -EINVAL; } spin_lock_irqsave(&devc->lock, flags); ad_enter_MCE(devc); ad_write(devc, 29, (ad_read(devc, 29) & 0x1f) | (arg << 5)); ad_leave_MCE(devc); spin_unlock_irqrestore(&devc->lock, flags); break; case AD1848_MIXER_REROUTE: { int o = (arg >> 8) & 0xff; int n = arg & 0xff; if (o < 0 || o >= SOUND_MIXER_NRDEVICES) { return -EINVAL; } if (!(devc->supported_devices & (1 << o)) && !(devc->supported_rec_devices & (1 << o))) { return -EINVAL; } if (n == SOUND_MIXER_NONE) { /* Just hide this control */ ad1848_mixer_set(devc, o, 0); /* Shut up it */ devc->supported_devices &= ~(1 << o); devc->supported_rec_devices &= ~(1 << o); break; } /* Make the mixer control identified by o to appear as n */ if (n < 0 || n >= SOUND_MIXER_NRDEVICES) { return -EINVAL; } devc->mixer_reroute[n] = o; /* Rename the control */ if (devc->supported_devices & (1 << o)) { devc->supported_devices |= (1 << n); } if (devc->supported_rec_devices & (1 << o)) { devc->supported_rec_devices |= (1 << n); } devc->supported_devices &= ~(1 << o); devc->supported_rec_devices &= ~(1 << o); } break; } return 0; } void ad1848_unload(int io_base, int irq, int dma_playback, int dma_capture, int share_dma) { int i, mixer, dev = 0; ad1848_info *devc = NULL; for (i = 0; devc == NULL && i < nr_ad1848_devs; i++) { if (adev_info[i].base == io_base) { devc = &adev_info[i]; dev = devc->dev_no; } } if (devc != NULL) { kfree(audio_devs[dev]->portc); release_region(devc->base, 4); if (!share_dma) { if (devc->irq > 0) /* There is no point in freeing irq, if it wasn't allocated */ { free_irq(devc->irq, (void *)(long)devc->dev_no); } sound_free_dma(dma_playback); if (dma_playback != dma_capture) { sound_free_dma(dma_capture); } } mixer = audio_devs[devc->dev_no]->mixer_dev; if (mixer >= 0) { sound_unload_mixerdev(mixer); } nr_ad1848_devs--; for ( ; i < nr_ad1848_devs ; i++) { adev_info[i] = adev_info[i + 1]; } } else { printk(KERN_ERR "ad1848: Can't find device to be unloaded. Base=%x\n", io_base); } } static irqreturn_t adintr(int irq, void *dev_id) { unsigned char status; ad1848_info *devc; int dev; int alt_stat = 0xff; unsigned char c930_stat = 0; int cnt = 0; dev = (long)dev_id; devc = (ad1848_info *) audio_devs[dev]->devc; interrupt_again: /* Jump back here if int status doesn't reset */ status = inb(io_Status(devc)); if (status == 0x80) { printk(KERN_DEBUG "adintr: Why?\n"); } if (devc->model == MD_1848) { outb((0), io_Status(devc)); /* Clear interrupt status */ } if (status & 0x01) { if (devc->model == MD_C930) { /* 82C930 has interrupt status register in MAD16 register MC11 */ spin_lock(&devc->lock); /* 0xe0e is C930 address port * 0xe0f is C930 data port */ outb(11, 0xe0e); c930_stat = inb(0xe0f); outb((~c930_stat), 0xe0f); spin_unlock(&devc->lock); alt_stat = (c930_stat << 2) & 0x30; } else if (devc->model != MD_1848) { spin_lock(&devc->lock); alt_stat = ad_read(devc, 24); ad_write(devc, 24, ad_read(devc, 24) & ~alt_stat); /* Selective ack */ spin_unlock(&devc->lock); } if ((devc->open_mode & OPEN_READ) && (devc->audio_mode & PCM_ENABLE_INPUT) && (alt_stat & 0x20)) { DMAbuf_inputintr(devc->record_dev); } if ((devc->open_mode & OPEN_WRITE) && (devc->audio_mode & PCM_ENABLE_OUTPUT) && (alt_stat & 0x10)) { DMAbuf_outputintr(devc->playback_dev, 1); } if (devc->model != MD_1848 && (alt_stat & 0x40)) /* Timer interrupt */ { devc->timer_ticks++; #ifndef EXCLUDE_TIMERS if (timer_installed == dev && devc->timer_running) { sound_timer_interrupt(); } #endif } } /* * Sometimes playback or capture interrupts occur while a timer interrupt * is being handled. The interrupt will not be retriggered if we don't * handle it now. Check if an interrupt is still pending and restart * the handler in this case. */ if (inb(io_Status(devc)) & 0x01 && cnt++ < 4) { goto interrupt_again; } return IRQ_HANDLED; } /* * Experimental initialization sequence for the integrated sound system * of the Compaq Deskpro M. */ static int init_deskpro_m(struct address_info *hw_config) { unsigned char tmp; if ((tmp = inb(0xc44)) == 0xff) { DDB(printk("init_deskpro_m: Dead port 0xc44\n")); return 0; } outb(0x10, 0xc44); outb(0x40, 0xc45); outb(0x00, 0xc46); outb(0xe8, 0xc47); outb(0x14, 0xc44); outb(0x40, 0xc45); outb(0x00, 0xc46); outb(0xe8, 0xc47); outb(0x10, 0xc44); return 1; } /* * Experimental initialization sequence for the integrated sound system * of Compaq Deskpro XL. */ static int init_deskpro(struct address_info *hw_config) { unsigned char tmp; if ((tmp = inb(0xc44)) == 0xff) { DDB(printk("init_deskpro: Dead port 0xc44\n")); return 0; } outb((tmp | 0x04), 0xc44); /* Select bank 1 */ if (inb(0xc44) != 0x04) { DDB(printk("init_deskpro: Invalid bank1 signature in port 0xc44\n")); return 0; } /* * OK. It looks like a Deskpro so let's proceed. */ /* * I/O port 0xc44 Audio configuration register. * * bits 0xc0: Audio revision bits * 0x00 = Compaq Business Audio * 0x40 = MS Sound System Compatible (reset default) * 0x80 = Reserved * 0xc0 = Reserved * bit 0x20: No Wait State Enable * 0x00 = Disabled (reset default, DMA mode) * 0x20 = Enabled (programmed I/O mode) * bit 0x10: MS Sound System Decode Enable * 0x00 = Decoding disabled (reset default) * 0x10 = Decoding enabled * bit 0x08: FM Synthesis Decode Enable * 0x00 = Decoding Disabled (reset default) * 0x08 = Decoding enabled * bit 0x04 Bank select * 0x00 = Bank 0 * 0x04 = Bank 1 * bits 0x03 MSS Base address * 0x00 = 0x530 (reset default) * 0x01 = 0x604 * 0x02 = 0xf40 * 0x03 = 0xe80 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc44 (before): "); outb((tmp & ~0x04), 0xc44); printk("%02x ", inb(0xc44)); outb((tmp | 0x04), 0xc44); printk("%02x\n", inb(0xc44)); #endif /* Set bank 1 of the register */ tmp = 0x58; /* MSS Mode, MSS&FM decode enabled */ switch (hw_config->io_base) { case 0x530: tmp |= 0x00; break; case 0x604: tmp |= 0x01; break; case 0xf40: tmp |= 0x02; break; case 0xe80: tmp |= 0x03; break; default: DDB(printk("init_deskpro: Invalid MSS port %x\n", hw_config->io_base)); return 0; } outb((tmp & ~0x04), 0xc44); /* Write to bank=0 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc44 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc44)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc44)); #endif /* * I/O port 0xc45 FM Address Decode/MSS ID Register. * * bank=0, bits 0xfe: FM synthesis Decode Compare bits 7:1 (default=0x88) * bank=0, bit 0x01: SBIC Power Control Bit * 0x00 = Powered up * 0x01 = Powered down * bank=1, bits 0xfc: MSS ID (default=0x40) */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc45 (before): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc45)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc45)); #endif outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ outb((0x88), 0xc45); /* FM base 7:0 = 0x88 */ outb((tmp | 0x04), 0xc44); /* Select bank=1 */ outb((0x10), 0xc45); /* MSS ID = 0x10 (MSS port returns 0x04) */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc45 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc45)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc45)); #endif /* * I/O port 0xc46 FM Address Decode/Address ASIC Revision Register. * * bank=0, bits 0xff: FM synthesis Decode Compare bits 15:8 (default=0x03) * bank=1, bits 0xff: Audio addressing ASIC id */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc46 (before): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc46)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc46)); #endif outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ outb((0x03), 0xc46); /* FM base 15:8 = 0x03 */ outb((tmp | 0x04), 0xc44); /* Select bank=1 */ outb((0x11), 0xc46); /* ASIC ID = 0x11 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc46 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc46)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc46)); #endif /* * I/O port 0xc47 FM Address Decode Register. * * bank=0, bits 0xff: Decode enable selection for various FM address bits * bank=1, bits 0xff: Reserved */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc47 (before): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc47)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc47)); #endif outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ outb((0x7c), 0xc47); /* FM decode enable bits = 0x7c */ outb((tmp | 0x04), 0xc44); /* Select bank=1 */ outb((0x00), 0xc47); /* Reserved bank1 = 0x00 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc47 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc47)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc47)); #endif /* * I/O port 0xc6f = Audio Disable Function Register */ #ifdef DEBUGXL printk("Port 0xc6f (before) = %02x\n", inb(0xc6f)); #endif outb((0x80), 0xc6f); #ifdef DEBUGXL printk("Port 0xc6f (after) = %02x\n", inb(0xc6f)); #endif return 1; } int probe_ms_sound(struct address_info *hw_config, struct resource *ports) { unsigned char tmp; DDB(printk("Entered probe_ms_sound(%x, %d)\n", hw_config->io_base, hw_config->card_subtype)); if (hw_config->card_subtype == 1) /* Has no IRQ/DMA registers */ { /* check_opl3(0x388, hw_config); */ return ad1848_detect(ports, NULL, hw_config->osp); } if (deskpro_xl && hw_config->card_subtype == 2) /* Compaq Deskpro XL */ { if (!init_deskpro(hw_config)) { return 0; } } if (deskpro_m) /* Compaq Deskpro M */ { if (!init_deskpro_m(hw_config)) { return 0; } } /* * Check if the IO port returns valid signature. The original MS Sound * system returns 0x04 while some cards (AudioTrix Pro for example) * return 0x00 or 0x0f. */ if ((tmp = inb(hw_config->io_base + 3)) == 0xff) /* Bus float */ { int ret; DDB(printk("I/O address is inactive (%x)\n", tmp)); if (!(ret = ad1848_detect(ports, NULL, hw_config->osp))) { return 0; } return 1; } DDB(printk("MSS signature = %x\n", tmp & 0x3f)); if ((tmp & 0x3f) != 0x04 && (tmp & 0x3f) != 0x0f && (tmp & 0x3f) != 0x00) { int ret; MDB(printk(KERN_ERR "No MSS signature detected on port 0x%x (0x%x)\n", hw_config->io_base, (int) inb(hw_config->io_base + 3))); DDB(printk("Trying to detect codec anyway but IRQ/DMA may not work\n")); if (!(ret = ad1848_detect(ports, NULL, hw_config->osp))) { return 0; } hw_config->card_subtype = 1; return 1; } if ((hw_config->irq != 5) && (hw_config->irq != 7) && (hw_config->irq != 9) && (hw_config->irq != 10) && (hw_config->irq != 11) && (hw_config->irq != 12)) { printk(KERN_ERR "MSS: Bad IRQ %d\n", hw_config->irq); return 0; } if (hw_config->dma != 0 && hw_config->dma != 1 && hw_config->dma != 3) { printk(KERN_ERR "MSS: Bad DMA %d\n", hw_config->dma); return 0; } /* * Check that DMA0 is not in use with a 8 bit board. */ if (hw_config->dma == 0 && inb(hw_config->io_base + 3) & 0x80) { printk(KERN_ERR "MSS: Can't use DMA0 with a 8 bit card/slot\n"); return 0; } if (hw_config->irq > 7 && hw_config->irq != 9 && inb(hw_config->io_base + 3) & 0x80) { printk(KERN_ERR "MSS: Can't use IRQ%d with a 8 bit card/slot\n", hw_config->irq); return 0; } return ad1848_detect(ports, NULL, hw_config->osp); } void attach_ms_sound(struct address_info *hw_config, struct resource *ports, struct module *owner) { static signed char interrupt_bits[12] = { -1, -1, -1, -1, -1, 0x00, -1, 0x08, -1, 0x10, 0x18, 0x20 }; signed char bits; char dma2_bit = 0; static char dma_bits[4] = { 1, 2, 0, 3 }; int config_port = hw_config->io_base + 0; int version_port = hw_config->io_base + 3; int dma = hw_config->dma; int dma2 = hw_config->dma2; if (hw_config->card_subtype == 1) /* Has no IRQ/DMA registers */ { hw_config->slots[0] = ad1848_init("MS Sound System", ports, hw_config->irq, hw_config->dma, hw_config->dma2, 0, hw_config->osp, owner); return; } /* * Set the IRQ and DMA addresses. */ bits = interrupt_bits[hw_config->irq]; if (bits == -1) { printk(KERN_ERR "MSS: Bad IRQ %d\n", hw_config->irq); release_region(ports->start, 4); release_region(ports->start - 4, 4); return; } outb((bits | 0x40), config_port); if ((inb(version_port) & 0x40) == 0) { printk(KERN_ERR "[MSS: IRQ Conflict?]\n"); } /* * Handle the capture DMA channel */ if (dma2 != -1 && dma2 != dma) { if (!((dma == 0 && dma2 == 1) || (dma == 1 && dma2 == 0) || (dma == 3 && dma2 == 0))) { /* Unsupported combination. Try to swap channels */ int tmp = dma; dma = dma2; dma2 = tmp; } if ((dma == 0 && dma2 == 1) || (dma == 1 && dma2 == 0) || (dma == 3 && dma2 == 0)) { dma2_bit = 0x04; /* Enable capture DMA */ } else { printk(KERN_WARNING "MSS: Invalid capture DMA\n"); dma2 = dma; } } else { dma2 = dma; } hw_config->dma = dma; hw_config->dma2 = dma2; outb((bits | dma_bits[dma] | dma2_bit), config_port); /* Write IRQ+DMA setup */ hw_config->slots[0] = ad1848_init("MS Sound System", ports, hw_config->irq, dma, dma2, 0, hw_config->osp, THIS_MODULE); } void unload_ms_sound(struct address_info *hw_config) { ad1848_unload(hw_config->io_base + 4, hw_config->irq, hw_config->dma, hw_config->dma2, 0); sound_unload_audiodev(hw_config->slots[0]); release_region(hw_config->io_base, 4); } #ifndef EXCLUDE_TIMERS /* * Timer stuff (for /dev/music). */ static unsigned int current_interval; static unsigned int ad1848_tmr_start(int dev, unsigned int usecs) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; unsigned long xtal_nsecs; /* nanoseconds per xtal oscillator tick */ unsigned long divider; spin_lock_irqsave(&devc->lock, flags); /* * Length of the timer interval (in nanoseconds) depends on the * selected crystal oscillator. Check this from bit 0x01 of I8. * * AD1845 has just one oscillator which has cycle time of 10.050 us * (when a 24.576 MHz xtal oscillator is used). * * Convert requested interval to nanoseconds before computing * the timer divider. */ if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) { xtal_nsecs = 10050; } else if (ad_read(devc, 8) & 0x01) { xtal_nsecs = 9920; } else { xtal_nsecs = 9969; } divider = (usecs * 1000 + xtal_nsecs / 2) / xtal_nsecs; if (divider < 100) /* Don't allow shorter intervals than about 1ms */ { divider = 100; } if (divider > 65535) /* Overflow check */ { divider = 65535; } ad_write(devc, 21, (divider >> 8) & 0xff); /* Set upper bits */ ad_write(devc, 20, divider & 0xff); /* Set lower bits */ ad_write(devc, 16, ad_read(devc, 16) | 0x40); /* Start the timer */ devc->timer_running = 1; spin_unlock_irqrestore(&devc->lock, flags); return current_interval = (divider * xtal_nsecs + 500) / 1000; } static void ad1848_tmr_reprogram(int dev) { /* * Audio driver has changed sampling rate so that a different xtal * oscillator was selected. We have to reprogram the timer rate. */ ad1848_tmr_start(dev, current_interval); sound_timer_syncinterval(current_interval); } static void ad1848_tmr_disable(int dev) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; spin_lock_irqsave(&devc->lock, flags); ad_write(devc, 16, ad_read(devc, 16) & ~0x40); devc->timer_running = 0; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_tmr_restart(int dev) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; if (current_interval == 0) { return; } spin_lock_irqsave(&devc->lock, flags); ad_write(devc, 16, ad_read(devc, 16) | 0x40); devc->timer_running = 1; spin_unlock_irqrestore(&devc->lock, flags); } static struct sound_lowlev_timer ad1848_tmr = { 0, 2, ad1848_tmr_start, ad1848_tmr_disable, ad1848_tmr_restart }; static int ad1848_tmr_install(int dev) { if (timer_installed != -1) { return 0; /* Don't install another timer */ } timer_installed = ad1848_tmr.dev = dev; sound_timer_init(&ad1848_tmr, audio_devs[dev]->name); return 1; } #endif /* EXCLUDE_TIMERS */ EXPORT_SYMBOL(ad1848_detect); EXPORT_SYMBOL(ad1848_init); EXPORT_SYMBOL(ad1848_unload); EXPORT_SYMBOL(ad1848_control); EXPORT_SYMBOL(probe_ms_sound); EXPORT_SYMBOL(attach_ms_sound); EXPORT_SYMBOL(unload_ms_sound); static int __initdata io = -1; static int __initdata irq = -1; static int __initdata dma = -1; static int __initdata dma2 = -1; static int __initdata type = 0; module_param(io, int, 0); /* I/O for a raw AD1848 card */ module_param(irq, int, 0); /* IRQ to use */ module_param(dma, int, 0); /* First DMA channel */ module_param(dma2, int, 0); /* Second DMA channel */ module_param(type, int, 0); /* Card type */ module_param(deskpro_xl, bool, 0); /* Special magic for Deskpro XL boxen */ module_param(deskpro_m, bool, 0); /* Special magic for Deskpro M box */ module_param(soundpro, bool, 0); /* More special magic for SoundPro chips */ #ifdef CONFIG_PNP module_param(isapnp, int, 0); module_param(isapnpjump, int, 0); module_param(reverse, bool, 0); MODULE_PARM_DESC(isapnp, "When set to 0, Plug & Play support will be disabled"); MODULE_PARM_DESC(isapnpjump, "Jumps to a specific slot in the driver's PnP table. Use the source, Luke."); MODULE_PARM_DESC(reverse, "When set to 1, will reverse ISAPnP search order"); static struct pnp_dev *ad1848_dev = NULL; /* Please add new entries at the end of the table */ static struct { char *name; unsigned short card_vendor, card_device, vendor, function; short mss_io, irq, dma, dma2; /* index into isapnp table */ int type; } ad1848_isapnp_list[] __initdata = { { "CMI 8330 SoundPRO", ISAPNP_VENDOR('C', 'M', 'I'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('@', '@', '@'), ISAPNP_FUNCTION(0x0001), 0, 0, 0, -1, 0 }, { "CS4232 based card", ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0000), 0, 0, 0, 1, 0 }, { "CS4232 based card", ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0100), 0, 0, 0, 1, 0 }, { "OPL3-SA2 WSS mode", ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('Y', 'M', 'H'), ISAPNP_FUNCTION(0x0021), 1, 0, 0, 1, 1 }, { "Advanced Gravis InterWave Audio", ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_FUNCTION(0x0000), 0, 0, 0, 1, 0 }, {NULL} }; #ifdef MODULE static struct isapnp_device_id id_table[] = { { ISAPNP_VENDOR('C', 'M', 'I'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('@', '@', '@'), ISAPNP_FUNCTION(0x0001), 0 }, { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0000), 0 }, { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0100), 0 }, /* The main driver for this card is opl3sa2 { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('Y','M','H'), ISAPNP_FUNCTION(0x0021), 0 }, */ { ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_FUNCTION(0x0000), 0 }, {0} }; MODULE_DEVICE_TABLE(isapnp, id_table); #endif static struct pnp_dev *activate_dev(char *devname, char *resname, struct pnp_dev *dev) { int err; err = pnp_device_attach(dev); if (err < 0) { return (NULL); } if ((err = pnp_activate_dev(dev)) < 0) { printk(KERN_ERR "ad1848: %s %s config failed (out of resources?)[%d]\n", devname, resname, err); pnp_device_detach(dev); return (NULL); } audio_activated = 1; return (dev); } static struct pnp_dev __init *ad1848_init_generic(struct pnp_card *bus, struct address_info *hw_config, int slot) { /* Configure Audio device */ if ((ad1848_dev = pnp_find_dev(bus, ad1848_isapnp_list[slot].vendor, ad1848_isapnp_list[slot].function, NULL))) { if ((ad1848_dev = activate_dev(ad1848_isapnp_list[slot].name, "ad1848", ad1848_dev))) { hw_config->io_base = pnp_port_start(ad1848_dev, ad1848_isapnp_list[slot].mss_io); hw_config->irq = pnp_irq(ad1848_dev, ad1848_isapnp_list[slot].irq); hw_config->dma = pnp_dma(ad1848_dev, ad1848_isapnp_list[slot].dma); if (ad1848_isapnp_list[slot].dma2 != -1) { hw_config->dma2 = pnp_dma(ad1848_dev, ad1848_isapnp_list[slot].dma2); } else { hw_config->dma2 = -1; } hw_config->card_subtype = ad1848_isapnp_list[slot].type; } else { return (NULL); } } else { return (NULL); } return (ad1848_dev); } static int __init ad1848_isapnp_init(struct address_info *hw_config, struct pnp_card *bus, int slot) { char *busname = bus->name[0] ? bus->name : ad1848_isapnp_list[slot].name; /* Initialize this baby. */ if (ad1848_init_generic(bus, hw_config, slot)) { /* We got it. */ printk(KERN_NOTICE "ad1848: PnP reports '%s' at i/o %#x, irq %d, dma %d, %d\n", busname, hw_config->io_base, hw_config->irq, hw_config->dma, hw_config->dma2); return 1; } return 0; } static int __init ad1848_isapnp_probe(struct address_info *hw_config) { static int first = 1; int i; /* Count entries in sb_isapnp_list */ for (i = 0; ad1848_isapnp_list[i].card_vendor != 0; i++); i--; /* Check and adjust isapnpjump */ if ( isapnpjump < 0 || isapnpjump > i) { isapnpjump = reverse ? i : 0; printk(KERN_ERR "ad1848: Valid range for isapnpjump is 0-%d. Adjusted to %d.\n", i, isapnpjump); } if (!first || !reverse) { i = isapnpjump; } first = 0; while (ad1848_isapnp_list[i].card_vendor != 0) { static struct pnp_card *bus = NULL; while ((bus = pnp_find_card( ad1848_isapnp_list[i].card_vendor, ad1848_isapnp_list[i].card_device, bus))) { if (ad1848_isapnp_init(hw_config, bus, i)) { isapnpjump = i; /* start next search from here */ return 0; } } i += reverse ? -1 : 1; } return -ENODEV; } #endif static int __init init_ad1848(void) { printk(KERN_INFO "ad1848/cs4248 codec driver Copyright (C) by Hannu Savolainen 1993-1996\n"); #ifdef CONFIG_PNP if (isapnp && (ad1848_isapnp_probe(&cfg) < 0) ) { printk(KERN_NOTICE "ad1848: No ISAPnP cards found, trying standard ones...\n"); isapnp = 0; } #endif if (io != -1) { struct resource *ports; if ( isapnp == 0 ) { if (irq == -1 || dma == -1) { printk(KERN_WARNING "ad1848: must give I/O , IRQ and DMA.\n"); return -EINVAL; } cfg.irq = irq; cfg.io_base = io; cfg.dma = dma; cfg.dma2 = dma2; cfg.card_subtype = type; } ports = request_region(io + 4, 4, "ad1848"); if (!ports) { return -EBUSY; } if (!request_region(io, 4, "WSS config")) { release_region(io + 4, 4); return -EBUSY; } if (!probe_ms_sound(&cfg, ports)) { release_region(io + 4, 4); release_region(io, 4); return -ENODEV; } attach_ms_sound(&cfg, ports, THIS_MODULE); loaded = 1; } return 0; } static void __exit cleanup_ad1848(void) { if (loaded) { unload_ms_sound(&cfg); } #ifdef CONFIG_PNP if (ad1848_dev) { if (audio_activated) { pnp_device_detach(ad1848_dev); } } #endif } module_init(init_ad1848); module_exit(cleanup_ad1848); #ifndef MODULE static int __init setup_ad1848(char *str) { /* io, irq, dma, dma2, type */ int ints[6]; str = get_options(str, ARRAY_SIZE(ints), ints); io = ints[1]; irq = ints[2]; dma = ints[3]; dma2 = ints[4]; type = ints[5]; return 1; } __setup("ad1848=", setup_ad1848); #endif MODULE_LICENSE("GPL");
williamfdevine/PrettyLinux
sound/oss/ad1848.c
C
gpl-3.0
77,160
/** * @file gensvm_debug.c * @author G.J.J. van den Burg * @date 2016-05-01 * @brief Functions facilitating debugging * * @details * Defines functions useful for debugging matrices. * * @copyright Copyright 2016, G.J.J. van den Burg. This file is part of GenSVM. GenSVM 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. GenSVM 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 GenSVM. If not, see <http://www.gnu.org/licenses/>. */ #include "gensvm_debug.h" /** * @brief Print a dense matrix * * @details * Debug function to print a matrix * * @param[in] M matrix * @param[in] rows number of rows of M * @param[in] cols number of columns of M */ void gensvm_print_matrix(double *M, long rows, long cols) { long i, j; for (i=0; i<rows; i++) { for (j=0; j<cols; j++) { if (j > 0) note(" "); note("%+6.6f", matrix_get(M, cols, i, j)); } note("\n"); } note("\n"); } /** * @brief Print a sparse matrix * * @details * Debug function to print a GenSparse sparse matrix * * @param[in] A a GenSparse matrix to print * */ void gensvm_print_sparse(struct GenSparse *A) { long i; // print matrix dimensions note("Sparse Matrix:\n"); note("\tnnz = %li, rows = %li, cols = %li\n", A->nnz, A->n_row, A->n_col); // print nonzero values note("\tvalues = [ "); for (i=0; i<A->nnz; i++) { if (i != 0) note(", "); note("%f", A->values[i]); } note(" ]\n"); // print row indices note("\tIA = [ "); for (i=0; i<A->n_row+1; i++) { if (i != 0) note(", "); note("%i", A->ia[i]); } note(" ]\n"); // print column indices note("\tJA = [ "); for (i=0; i<A->nnz; i++) { if (i != 0) note(", "); note("%i", A->ja[i]); } note(" ]\n"); }
GjjvdBurg/GenSVM
src/gensvm_debug.c
C
gpl-3.0
2,141
/* * Copyright (C) 2007-2009 Daniel Prevost <dprevost@photonsoftware.org> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ #include "Nucleus/Hash.h" #include "Nucleus/Tests/Hash/HashTest.h" const bool expectedToPass = true; /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ int main() { psonSessionContext context; psonHash* pHash; enum psoErrors errcode; char* key1 = "My Key 1"; char* key2 = "My Key 2"; char* data1 = "My Data 1"; char* data2 = "My Data 2"; psonHashItem * pHashItem; pHash = initHashTest( expectedToPass, &context ); errcode = psonHashInit( pHash, g_memObjOffset, 100, &context ); if ( errcode != PSO_OK ) { ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); } errcode = psonHashInsert( pHash, (unsigned char*)key1, strlen(key1), data1, strlen(data1), &pHashItem, &context ); if ( errcode != PSO_OK ) { ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); } /* A duplicate - not allowed */ errcode = psonHashInsert( pHash, (unsigned char*)key1, strlen(key1), data2, strlen(data2), &pHashItem, &context ); if ( errcode != PSO_ITEM_ALREADY_PRESENT ) { ERROR_EXIT( expectedToPass, NULL, ; ); } errcode = psonHashInsert( pHash, (unsigned char*)key2, strlen(key2), data1, strlen(data1), &pHashItem, &context ); if ( errcode != PSO_OK ) { ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); } return 0; } /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
dprevost/photon
src/Nucleus/Tests/Hash/InsertPass.c
C
gpl-3.0
2,772
/* * This file is part of Cleanflight. * * Cleanflight 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. * * Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>. */ /* * telemetry_hott.c * * Authors: * Konstantin Sharlaimov - HoTT code cleanup, proper state machine implementation, bi-directional serial port operation cleanup * Dominic Clifton - Hydra - Software Serial, Electronics, Hardware Integration and debugging, HoTT Code cleanup and fixes, general telemetry improvements. * Carsten Giesen - cGiesen - Baseflight port * Oliver Bayer - oBayer - MultiWii-HoTT, HoTT reverse engineering * Adam Majerczyk - HoTT-for-ardupilot from which some information and ideas are borrowed. * * https://github.com/obayer/MultiWii-HoTT * https://github.com/oBayer/MultiHoTT-Module * https://code.google.com/p/hott-for-ardupilot * * HoTT is implemented in Graupner equipment using a bi-directional protocol over a single wire. * * Generally the receiver sends a single request byte out using normal uart signals, then waits a short period for a * multiple byte response and checksum byte before it sends out the next request byte. * Each response byte must be send with a protocol specific delay between them. * * Serial ports use two wires but HoTT uses a single wire so some electronics are required so that * the signals don't get mixed up. When cleanflight transmits it should not receive it's own transmission. * * Connect as follows: * HoTT TX/RX -> Serial RX (connect directly) * Serial TX -> 1N4148 Diode -(| )-> HoTT TX/RX (connect via diode) * * The diode should be arranged to allow the data signals to flow the right way * -(| )- == Diode, | indicates cathode marker. * * As noticed by Skrebber the GR-12 (and probably GR-16/24, too) are based on a PIC 24FJ64GA-002, which has 5V tolerant digital pins. * * Note: The softserial ports are not listed as 5V tolerant in the STM32F103xx data sheet pinouts and pin description * section. Verify if you require a 5v/3.3v level shifters. The softserial port should not be inverted. * * There is a technical discussion (in German) about HoTT here * http://www.rc-network.de/forum/showthread.php/281496-Graupner-HoTT-Telemetrie-Sensoren-Eigenbau-DIY-Telemetrie-Protokoll-entschl%C3%BCsselt/page21 */ #include <stdbool.h> #include <stdint.h> #include <string.h> #include "platform.h" #if defined(TELEMETRY) && defined(TELEMETRY_HOTT) #include "build/build_config.h" #include "build/debug.h" #include "common/axis.h" #include "common/time.h" #include "drivers/time.h" #include "drivers/serial.h" #include "fc/runtime_config.h" #include "flight/pid.h" #include "io/serial.h" #include "io/gps.h" #include "navigation/navigation.h" #include "sensors/sensors.h" #include "sensors/battery.h" #include "telemetry/telemetry.h" #include "telemetry/hott.h" //#define HOTT_DEBUG typedef enum { HOTT_WAITING_FOR_REQUEST, HOTT_RECEIVING_REQUEST, HOTT_WAITING_FOR_TX_WINDOW, HOTT_TRANSMITTING, HOTT_ENDING_TRANSMISSION } hottState_e; #define HOTT_MESSAGE_PREPARATION_FREQUENCY_5_HZ ((1000 * 1000) / 5) #define HOTT_RX_SCHEDULE 4000 #define HOTT_TX_SCHEDULE 5000 #define HOTT_TX_DELAY_US 2000 #define MILLISECONDS_IN_A_SECOND 1000 static hottState_e hottState = HOTT_WAITING_FOR_REQUEST; static timeUs_t hottStateChangeUs = 0; static uint8_t *hottTxMsg = NULL; static uint8_t hottTxMsgSize; static uint8_t hottTxMsgCrc; #define HOTT_BAUDRATE 19200 #define HOTT_INITIAL_PORT_MODE MODE_RXTX static serialPort_t *hottPort = NULL; static serialPortConfig_t *portConfig; static bool hottTelemetryEnabled = false; static portSharing_e hottPortSharing; static HOTT_GPS_MSG_t hottGPSMessage; static HOTT_EAM_MSG_t hottEAMMessage; static void hottSwitchState(hottState_e newState, timeUs_t currentTimeUs) { if (hottState != newState) { hottState = newState; hottStateChangeUs = currentTimeUs; } } static void initialiseEAMMessage(HOTT_EAM_MSG_t *msg, size_t size) { memset(msg, 0, size); msg->start_byte = 0x7C; msg->eam_sensor_id = HOTT_TELEMETRY_EAM_SENSOR_ID; msg->sensor_id = HOTT_EAM_SENSOR_TEXT_ID; msg->stop_byte = 0x7D; } #ifdef GPS typedef enum { GPS_FIX_CHAR_NONE = '-', GPS_FIX_CHAR_2D = '2', GPS_FIX_CHAR_3D = '3', GPS_FIX_CHAR_DGPS = 'D', } gpsFixChar_e; static void initialiseGPSMessage(HOTT_GPS_MSG_t *msg, size_t size) { memset(msg, 0, size); msg->start_byte = 0x7C; msg->gps_sensor_id = HOTT_TELEMETRY_GPS_SENSOR_ID; msg->sensor_id = HOTT_GPS_SENSOR_TEXT_ID; msg->stop_byte = 0x7D; } #endif static void initialiseMessages(void) { initialiseEAMMessage(&hottEAMMessage, sizeof(hottEAMMessage)); #ifdef GPS initialiseGPSMessage(&hottGPSMessage, sizeof(hottGPSMessage)); #endif } #ifdef GPS void addGPSCoordinates(HOTT_GPS_MSG_t *hottGPSMessage, int32_t latitude, int32_t longitude) { int16_t deg = latitude / GPS_DEGREES_DIVIDER; int32_t sec = (latitude - (deg * GPS_DEGREES_DIVIDER)) * 6; int8_t min = sec / 1000000L; sec = (sec % 1000000L) / 100L; uint16_t degMin = (deg * 100L) + min; hottGPSMessage->pos_NS = (latitude < 0); hottGPSMessage->pos_NS_dm_L = degMin; hottGPSMessage->pos_NS_dm_H = degMin >> 8; hottGPSMessage->pos_NS_sec_L = sec; hottGPSMessage->pos_NS_sec_H = sec >> 8; deg = longitude / GPS_DEGREES_DIVIDER; sec = (longitude - (deg * GPS_DEGREES_DIVIDER)) * 6; min = sec / 1000000L; sec = (sec % 1000000L) / 100L; degMin = (deg * 100L) + min; hottGPSMessage->pos_EW = (longitude < 0); hottGPSMessage->pos_EW_dm_L = degMin; hottGPSMessage->pos_EW_dm_H = degMin >> 8; hottGPSMessage->pos_EW_sec_L = sec; hottGPSMessage->pos_EW_sec_H = sec >> 8; } void hottPrepareGPSResponse(HOTT_GPS_MSG_t *hottGPSMessage) { hottGPSMessage->gps_satelites = gpsSol.numSat; // Report climb rate regardless of GPS fix const int32_t climbrate = MAX(0, getEstimatedActualVelocity(Z) + 30000); hottGPSMessage->climbrate_L = climbrate & 0xFF; hottGPSMessage->climbrate_H = climbrate >> 8; const int32_t climbrate3s = MAX(0, 3.0f * getEstimatedActualVelocity(Z) / 100 + 120); hottGPSMessage->climbrate3s = climbrate3s & 0xFF; if (!STATE(GPS_FIX)) { hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_NONE; return; } if (gpsSol.fixType == GPS_FIX_3D) { hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_3D; } else { hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_2D; } addGPSCoordinates(hottGPSMessage, gpsSol.llh.lat, gpsSol.llh.lon); // GPS Speed is returned in cm/s (from io/gps.c) and must be sent in km/h (Hott requirement) const uint16_t speed = (gpsSol.groundSpeed * 36) / 1000; hottGPSMessage->gps_speed_L = speed & 0x00FF; hottGPSMessage->gps_speed_H = speed >> 8; hottGPSMessage->home_distance_L = GPS_distanceToHome & 0x00FF; hottGPSMessage->home_distance_H = GPS_distanceToHome >> 8; const uint16_t hottGpsAltitude = (gpsSol.llh.alt / 100) + HOTT_GPS_ALTITUDE_OFFSET; // meters hottGPSMessage->altitude_L = hottGpsAltitude & 0x00FF; hottGPSMessage->altitude_H = hottGpsAltitude >> 8; hottGPSMessage->home_direction = GPS_directionToHome; } #endif static inline void updateAlarmBatteryStatus(HOTT_EAM_MSG_t *hottEAMMessage) { static uint32_t lastHottAlarmSoundTime = 0; if (((millis() - lastHottAlarmSoundTime) >= (telemetryConfig()->hottAlarmSoundInterval * MILLISECONDS_IN_A_SECOND))){ lastHottAlarmSoundTime = millis(); batteryState_e batteryState = getBatteryState(); if (batteryState == BATTERY_WARNING || batteryState == BATTERY_CRITICAL){ hottEAMMessage->warning_beeps = 0x10; hottEAMMessage->alarm_invers1 = HOTT_EAM_ALARM1_FLAG_BATTERY_1; } else { hottEAMMessage->warning_beeps = HOTT_EAM_ALARM1_FLAG_NONE; hottEAMMessage->alarm_invers1 = HOTT_EAM_ALARM1_FLAG_NONE; } } } static inline void hottEAMUpdateBattery(HOTT_EAM_MSG_t *hottEAMMessage) { hottEAMMessage->main_voltage_L = vbat & 0xFF; hottEAMMessage->main_voltage_H = vbat >> 8; hottEAMMessage->batt1_voltage_L = vbat & 0xFF; hottEAMMessage->batt1_voltage_H = vbat >> 8; updateAlarmBatteryStatus(hottEAMMessage); } static inline void hottEAMUpdateCurrentMeter(HOTT_EAM_MSG_t *hottEAMMessage) { const int32_t amp = amperage / 10; hottEAMMessage->current_L = amp & 0xFF; hottEAMMessage->current_H = amp >> 8; } static inline void hottEAMUpdateBatteryDrawnCapacity(HOTT_EAM_MSG_t *hottEAMMessage) { const int32_t mAh = mAhDrawn / 10; hottEAMMessage->batt_cap_L = mAh & 0xFF; hottEAMMessage->batt_cap_H = mAh >> 8; } static inline void hottEAMUpdateAltitudeAndClimbrate(HOTT_EAM_MSG_t *hottEAMMessage) { const int32_t alt = MAX(0, getEstimatedActualPosition(Z) / 100.0f + HOTT_GPS_ALTITUDE_OFFSET); // Value of 500 = 0m hottEAMMessage->altitude_L = alt & 0xFF; hottEAMMessage->altitude_H = alt >> 8; const int32_t climbrate = MAX(0, getEstimatedActualVelocity(Z) + 30000); hottEAMMessage->climbrate_L = climbrate & 0xFF; hottEAMMessage->climbrate_H = climbrate >> 8; const int32_t climbrate3s = MAX(0, 3.0f * getEstimatedActualVelocity(Z) / 100 + 120); hottEAMMessage->climbrate3s = climbrate3s & 0xFF; } void hottPrepareEAMResponse(HOTT_EAM_MSG_t *hottEAMMessage) { // Reset alarms hottEAMMessage->warning_beeps = 0x0; hottEAMMessage->alarm_invers1 = 0x0; hottEAMUpdateBattery(hottEAMMessage); hottEAMUpdateCurrentMeter(hottEAMMessage); hottEAMUpdateBatteryDrawnCapacity(hottEAMMessage); hottEAMUpdateAltitudeAndClimbrate(hottEAMMessage); } static void hottSerialWrite(uint8_t c) { static uint8_t serialWrites = 0; serialWrites++; serialWrite(hottPort, c); } void freeHoTTTelemetryPort(void) { closeSerialPort(hottPort); hottPort = NULL; hottTelemetryEnabled = false; } void initHoTTTelemetry(void) { portConfig = findSerialPortConfig(FUNCTION_TELEMETRY_HOTT); hottPortSharing = determinePortSharing(portConfig, FUNCTION_TELEMETRY_HOTT); initialiseMessages(); } void configureHoTTTelemetryPort(void) { if (!portConfig) { return; } hottPort = openSerialPort(portConfig->identifier, FUNCTION_TELEMETRY_HOTT, NULL, HOTT_BAUDRATE, HOTT_INITIAL_PORT_MODE, SERIAL_NOT_INVERTED); if (!hottPort) { return; } hottTelemetryEnabled = true; } static void hottQueueSendResponse(uint8_t *buffer, int length) { hottTxMsg = buffer; hottTxMsgSize = length; } static bool processBinaryModeRequest(uint8_t address) { switch (address) { #ifdef GPS case 0x8A: if (sensors(SENSOR_GPS)) { hottPrepareGPSResponse(&hottGPSMessage); hottQueueSendResponse((uint8_t *)&hottGPSMessage, sizeof(hottGPSMessage)); return true; } break; #endif case 0x8E: hottPrepareEAMResponse(&hottEAMMessage); hottQueueSendResponse((uint8_t *)&hottEAMMessage, sizeof(hottEAMMessage)); return true; } return false; } static void flushHottRxBuffer(void) { while (serialRxBytesWaiting(hottPort) > 0) { serialRead(hottPort); } } static bool hottSendTelemetryDataByte(timeUs_t currentTimeUs) { static timeUs_t byteSentTimeUs = 0; // Guard intra-byte interval if (currentTimeUs - byteSentTimeUs < HOTT_TX_DELAY_US) { return false; } if (hottTxMsgSize == 0) { // Send CRC byte hottSerialWrite(hottTxMsgCrc); return true; } else { // Send data byte hottTxMsgCrc += *hottTxMsg; hottSerialWrite(*hottTxMsg); hottTxMsg++; hottTxMsgSize--; return false; } } void checkHoTTTelemetryState(void) { bool newTelemetryEnabledValue = telemetryDetermineEnabledState(hottPortSharing); if (newTelemetryEnabledValue == hottTelemetryEnabled) { return; } if (newTelemetryEnabledValue) configureHoTTTelemetryPort(); else freeHoTTTelemetryPort(); } void handleHoTTTelemetry(timeUs_t currentTimeUs) { static uint8_t hottRequestBuffer[2]; static int hottRequestBufferPtr = 0; if (!hottTelemetryEnabled) return; bool reprocessState; do { reprocessState = false; switch (hottState) { case HOTT_WAITING_FOR_REQUEST: if (serialRxBytesWaiting(hottPort)) { hottRequestBufferPtr = 0; hottSwitchState(HOTT_RECEIVING_REQUEST, currentTimeUs); reprocessState = true; } break; case HOTT_RECEIVING_REQUEST: if ((currentTimeUs - hottStateChangeUs) >= HOTT_RX_SCHEDULE) { // Waiting for too long - resync flushHottRxBuffer(); hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } else { while (serialRxBytesWaiting(hottPort) && hottRequestBufferPtr < 2) { hottRequestBuffer[hottRequestBufferPtr++] = serialRead(hottPort); } if (hottRequestBufferPtr >= 2) { if ((hottRequestBuffer[0] == 0) || (hottRequestBuffer[0] == HOTT_BINARY_MODE_REQUEST_ID)) { /* * FIXME the first byte of the HoTT request frame is ONLY either 0x80 (binary mode) or 0x7F (text mode). * The binary mode is read as 0x00 (error reading the upper bit) while the text mode is correctly decoded. * The (requestId == 0) test is a workaround for detecting the binary mode with no ambiguity as there is only * one other valid value (0x7F) for text mode. * The error reading for the upper bit should nevertheless be fixed */ if (processBinaryModeRequest(hottRequestBuffer[1])) { hottSwitchState(HOTT_WAITING_FOR_TX_WINDOW, currentTimeUs); } else { hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } } else if (hottRequestBuffer[0] == HOTT_TEXT_MODE_REQUEST_ID) { // FIXME Text mode hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } else { // Received garbage - resync flushHottRxBuffer(); hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } reprocessState = true; } } break; case HOTT_WAITING_FOR_TX_WINDOW: if ((currentTimeUs - hottStateChangeUs) >= HOTT_TX_SCHEDULE) { hottTxMsgCrc = 0; hottSwitchState(HOTT_TRANSMITTING, currentTimeUs); } break; case HOTT_TRANSMITTING: if (hottSendTelemetryDataByte(currentTimeUs)) { hottSwitchState(HOTT_ENDING_TRANSMISSION, currentTimeUs); } break; case HOTT_ENDING_TRANSMISSION: if ((currentTimeUs - hottStateChangeUs) >= HOTT_TX_DELAY_US) { flushHottRxBuffer(); hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); reprocessState = true; } break; }; } while (reprocessState); } #endif
rb1205/inav
src/main/telemetry/hott.c
C
gpl-3.0
16,523
/* vim: set ts=8 sw=4 sts=4 et: */ /*====================================================================== Copyright (C) 2008,2009,2014 OSSO B.V. <walter+rtpsniff@osso.nl> This file is part of RTPSniff. RTPSniff 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. RTPSniff 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 RTPSniff. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "rtpsniff.h" #include <assert.h> #include <sys/time.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <time.h> #include <unistd.h> /* Settings */ #ifndef INTERVAL_SECONDS # define INTERVAL_SECONDS 10 /* wake the storage engine every N seconds */ #endif /* INTERVAL_SECONDS */ #if INTERVAL_SECONDS < 2 # error INTERVAL_SECONDS be too low #endif #define TIMER__METHOD_NSLEEP 1 #define TIMER__METHOD_SEMAPHORE 2 #if !defined(USE_NSLEEP_TIMER) && (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) # define TIMER__METHOD TIMER__METHOD_SEMAPHORE # include <errno.h> # include <semaphore.h> #else # define TIMER__METHOD TIMER__METHOD_NSLEEP #endif static pthread_t timer__thread; static struct memory_t *timer__memory; #if TIMER__METHOD == TIMER__METHOD_NSLEEP static volatile int timer__done; /* whether we're done */ #elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE static sem_t timer__semaphore; /* semaphore to synchronize the threads */ #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ static void *timer__run(void *thread_arg); void timer_help() { printf( "/*********************" " module: timer (interval) *******************************/\n" "#%s USE_NSLEEP_TIMER\n" "#define INTERVAL_SECONDS %" SCNu32 "\n" "\n" "Sleeps until the specified interval of %.2f minutes have passed and wakes up\n" "to tell the storage engine to write averages.\n" "\n" "The USE_NSLEEP_TIMER define forces the module to use a polling sleep loop even\n" "when the (probably) less cpu intensive and more accurate sem_timedwait()\n" "function is available. The currently compiled in timer method is: %s\n" "\n", #ifdef USE_NSLEEP_TIMER "define", #else /* !USE_NSLEEP_TIMER */ "undef", #endif (uint32_t)INTERVAL_SECONDS, (float)INTERVAL_SECONDS / 60, #if TIMER__METHOD == TIMER__METHOD_NSLEEP "n_sleep" #elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE "semaphore" #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ ); } int timer_loop_bg(struct memory_t *memory) { pthread_attr_t attr; /* Set internal config */ timer__memory = memory; #if TIMER__METHOD == TIMER__METHOD_NSLEEP /* Initialize polling variable */ timer__done = 0; #elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE /* Initialize semaphore */ if (sem_init(&timer__semaphore, 0, 0) != 0) { perror("sem_init"); return -1; } #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ /* We want default pthread attributes */ if (pthread_attr_init(&attr) != 0) { perror("pthread_attr_init"); return -1; } /* Run thread */ if (pthread_create(&timer__thread, &attr, &timer__run, NULL) != 0) { perror("pthread_create"); return -1; } #ifndef NDEBUG fprintf(stderr, "timer_loop_bg: Thread %p started.\n", (void*)timer__thread); #endif return 0; } void timer_loop_stop() { void *ret; /* Tell our thread that it is time */ #if TIMER__METHOD == TIMER__METHOD_NSLEEP timer__done = 1; #elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE sem_post(&timer__semaphore); #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ /* Get its exit status */ if (pthread_join(timer__thread, &ret) != 0) perror("pthread_join"); #ifndef NDEBUG fprintf(stderr, "timer_loop_stop: Thread %p joined.\n", (void*)timer__thread); #endif #if TIMER__METHOD == TIMER__METHOD_SEMAPHORE /* Destroy semaphore */ if (sem_destroy(&timer__semaphore) != 0) perror("sem_destroy"); #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ } /* The timers job is to run storage function after after every INTERVAL_SECONDS time. */ static void *timer__run(void *thread_arg) { int first_run_skipped = 0; /* do not store the first run because the interval is wrong */ #ifndef NDEBUG fprintf(stderr, "timer__run: Thread started.\n"); #endif while (1) { struct timeval current_time; /* current time is in UTC */ int sample_begin_time; #if TIMER__METHOD == TIMER__METHOD_NSLEEP int sleep_useconds; #elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE struct timespec new_time; int ret; #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ int previously_active; /* Get current time */ if (gettimeofday(&current_time, NULL) != 0) { perror("gettimeofday"); return (void*)-1; } /* Yes, we started sampling when SIGUSR1 fired, so this is correct */ sample_begin_time = current_time.tv_sec - (current_time.tv_sec % INTERVAL_SECONDS); /* Calculate how long to sleep */ #if TIMER__METHOD == TIMER__METHOD_NSLEEP sleep_useconds = (1000000 * (INTERVAL_SECONDS - (current_time.tv_sec % INTERVAL_SECONDS)) - current_time.tv_usec); # ifndef NDEBUG fprintf(stderr, "timer__run: Current time is %i (%02i:%02i:%02i.%06i), " "sleep planned for %i useconds.\n", (int)current_time.tv_sec, (int)(current_time.tv_sec / 3600) % 24, (int)(current_time.tv_sec / 60) % 60, (int)current_time.tv_sec % 60, (int)current_time.tv_usec, sleep_useconds); # endif /* NDEBUG */ #elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE new_time.tv_sec = sample_begin_time + INTERVAL_SECONDS; new_time.tv_nsec = 0; # ifndef NDEBUG fprintf(stderr, "timer__run: Current time is %i (%02i:%02i:%02i.%06i), " "sleep planned until %02i:%02i:%02i.\n", (int)current_time.tv_sec, (int)(current_time.tv_sec / 3600) % 24, (int)(current_time.tv_sec / 60) % 60, (int)current_time.tv_sec % 60, (int)current_time.tv_usec, (int)(new_time.tv_sec / 3600) % 24, (int)(new_time.tv_sec / 60) % 60, (int)new_time.tv_sec % 60); # endif /* NDEBUG */ #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ #if TIMER__METHOD == TIMER__METHOD_NSLEEP /* The sleep in this thread won't wake up (EINTR) from a SIGALRM in the other * thread. Pause/alarm won't work either. We use this crappy polling loop as * an alternative. Observe that the semaphore below method is way more * accurate and probably uses less cpu. */ while (!timer__done && sleep_useconds > 999999) { sleep(1); sleep_useconds -= 1000000; } if (timer__done) break; usleep(sleep_useconds); #elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE /* The sem_timedwait function will sleep happily until the absolutely specified * time has been reached. */ while ((ret = sem_timedwait(&timer__semaphore, &new_time)) == -1 && errno == EINTR) continue; /* restart if interrupted by handler */ if (ret == 0) break; /* if the semaphore was hit, we're done */ if (errno != ETIMEDOUT) perror("sem_timedwait"); #endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */ #ifndef NDEBUG if (gettimeofday(&current_time, NULL) != 0) { perror("gettimeofday"); return (void*)-1; } fprintf(stderr, "timer__run: Awake! Time is now %i (%02i:%02i:%02i.%06i).\n", (int)current_time.tv_sec, (int)(current_time.tv_sec / 3600) % 24, (int)(current_time.tv_sec / 60) % 60, (int)current_time.tv_sec % 60, (int)current_time.tv_usec); #endif /* Poke other thread to switch memory */ previously_active = timer__memory->active; raise(SIGUSR1); sleep(1); /* wait a second to let other thread finish switching memory */ assert(previously_active != timer__memory->active); if (first_run_skipped) { /* Delegate the actual writing to storage. */ out_write(sample_begin_time, INTERVAL_SECONDS, timer__memory->rtphash[previously_active]); } else { /* On first run, we started too late in the interval. Ignore those counts. */ first_run_skipped = 1; } /* Reset mem for next run */ sniff_release(&timer__memory->rtphash[previously_active]); } #ifndef NDEBUG fprintf(stderr, "timer__run: Thread done.\n"); #endif return 0; }
ossobv/rtpsniff
timer_interval.c
C
gpl-3.0
9,457
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to 2013 PrismTech * Limited and its licensees. All rights reserved. See file: * * $OSPL_HOME/LICENSE * * for full copyright notice and license terms. * */ #include <assert.h> #include "c_typebase.h" #include "idl_scope.h" #include "idl_genCxxHelper.h" #include "os_heap.h" #include "os_stdlib.h" #define IDL_MAXSCOPE (20) /* This modules handles the name scopes of objects by providing a scope stack. Each time a name scope is defined, the name is pushed on the stack. Each time the name scope is left, the name is popped from the stack. Name scopes are defined by the IDL definition "module <name>", "struct <name>" and "union <name>". */ /* idl_scopeElement specifies a scope stack element where "scopeName" specifies the name of the scope and "scopeType" specifies the kind of scope, either "idl_tFile" which is currently not used, "idl_tModule" for a module definition, "idl_tStruct" for a structure definition and "idl_tUnion" for a union definition. */ C_STRUCT(idl_scopeElement) { c_char *scopeName; idl_scopeType scopeType; }; /* idl_scope specifies the scope stack where "stack" is an array of "idl_scopeElement", "baseName" specifies the basename of the file that contains the scope stack and "scopePointer" specifies the actual top of the stack (-1 specifies an empty stack). */ C_STRUCT(idl_scope) { idl_scopeElement stack[IDL_MAXSCOPE]; c_char *baseName; c_long scopePointer; }; /* Create a new scope element with the specified name and type */ idl_scopeElement idl_scopeElementNew ( const char *scopeName, idl_scopeType scopeType) { idl_scopeElement element; assert (scopeName); assert (strlen(scopeName)); element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement)); element->scopeName = os_strdup (scopeName); element->scopeType = scopeType; return element; } /* Free a scope element */ void idl_scopeElementFree ( idl_scopeElement element) { assert (element); os_free (element->scopeName); os_free (element); } /* Create a copy of an existing scope element */ idl_scopeElement idl_scopeElementDup ( idl_scopeElement element) { idl_scopeElement new_element; assert (element); new_element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement)); new_element->scopeName = os_strdup (element->scopeName); new_element->scopeType = element->scopeType; return new_element; } /* Return the scope name related to a specific scope element */ c_char * idl_scopeElementName ( idl_scopeElement element) { if (element) { return element->scopeName; } return ""; } /* Return the scope type related to a specific scope element */ idl_scopeType idl_scopeElementType ( idl_scopeElement element) { if (element == NULL) { /* Empty scope stack will deliver NULL scope element */ return idl_tModule; } return element->scopeType; } /* Create a new and empty scope stack, for a specified basename */ idl_scope idl_scopeNew ( const char *baseName) { idl_scope scope = os_malloc ((size_t)C_SIZEOF(idl_scope)); scope->baseName = os_strdup (baseName); scope->scopePointer = -1; return scope; } /* Create a new and empty scope stack, for a specified basename */ idl_scope idl_scopeDup ( idl_scope scope) { idl_scope newScope = idl_scopeNew(idl_scopeBasename(scope)); c_long si; for (si = 0; si < (scope->scopePointer+1); si++) { idl_scopePush (newScope, idl_scopeElementDup(scope->stack[si])); } return newScope; } /* Free a scope stack, also freeing all scope elements */ void idl_scopeFree ( idl_scope scope) { c_long si; assert (scope); for (si = 0; si < (scope->scopePointer+1); si++) { idl_scopeElementFree(scope->stack[si]); } os_free (scope->baseName); os_free (scope); return; } /* Push a scope element on the scope stack */ void idl_scopePush ( idl_scope scope, idl_scopeElement element ) { assert (scope); assert (scope->scopePointer < IDL_MAXSCOPE); assert (element); scope->scopePointer++; scope->stack[scope->scopePointer] = element; } /* Return the size of a scope stack (the amount of scope elements) */ c_long idl_scopeStackSize ( idl_scope scope) { return (scope->scopePointer+1); } /* Remove the top element from a scope stack */ void idl_scopePop ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= 0); scope->scopePointer--; } /* Remove the top element from a scope stack, and free its resources */ void idl_scopePopFree ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= 0); idl_scopeElementFree(scope->stack[scope->scopePointer]); scope->scopePointer--; } /* Return the top element from a scope stack */ idl_scopeElement idl_scopeCur ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= -1); if (scope->scopePointer == -1) { return NULL; } return scope->stack[scope->scopePointer]; } /* Return the element from a scope stack, by index where "index" >= 0 and "index" <= "scopePointer" */ idl_scopeElement idl_scopeIndexed ( idl_scope scope, c_long index) { assert (index >= 0); assert (index <= scope->scopePointer); return scope->stack[index]; } /* Determine if two scope stacks are equal */ c_bool idl_scopeEqual ( idl_scope scope1, idl_scope scope2) { c_long i; /* If the "scopePointer"s are unequal, the stack do not equal */ if (scope1->scopePointer != scope2->scopePointer) { return FALSE; } /* Per stack element compare the names, if any does not equal the stacks are unequal */ for (i = 0; i < (scope1->scopePointer + 1); i++) { if (strcmp(idl_scopeElementName(scope1->stack[i]), idl_scopeElementName(scope2->stack[i])) != 0) { return FALSE; } } return TRUE; } /* Determine if a scope stack is contained by a second stack */ c_bool idl_scopeSub ( idl_scope scope, /* moduleScope */ idl_scope scopeSub) /* keyScope */ { c_long i; /* If the "scopePointer" of the stack is higher than the "scopePointer" of the second stack, the second stack can not contain the first stack */ if (scope->scopePointer > scopeSub->scopePointer) { return FALSE; } /* For all scope elements of the stack with the scope elements of the second stack. If one of them does not equal, the second stack can not contain the first. The scope element types are not compared, this should not a real problem. */ for (i = 0; i < (scope->scopePointer + 1); i++) { if (strcmp(idl_scopeElementName(scope->stack[i]), idl_scopeElementName(scopeSub->stack[i])) != 0) { return FALSE; } } return TRUE; } /* Build a textual representation of a scope stack with a specified seperator and optionally add a user specified identifier */ c_char * idl_scopeStack ( idl_scope scope, const char *scopeSepp, const char *name) { c_long si; c_char *scopeStack; c_char *elName; if (scope && (scope->scopePointer >= 0)) { /* If the stack is not empty */ si = 0; /* copy the first scope element name */ scopeStack = os_strdup (idl_scopeElementName(scope->stack[si])); si++; /* for all scope elements */ while (si <= scope->scopePointer) { elName = idl_scopeElementName(scope->stack[si]); /* allocate space for current scope stack + separator + next scope name */ scopeStack = os_realloc (scopeStack, (size_t)( (int)strlen(scopeStack)+ (int)strlen(scopeSepp)+ (int)strlen(elName)+1)); /* concatinate the separator */ os_strcat (scopeStack, scopeSepp); /* concatinate scope name */ os_strcat (scopeStack, elName); si++; } if (name) { /* if a user identifier is specified, allocate space for current scope stack + separator + user identifier */ scopeStack = os_realloc (scopeStack, (size_t)( (int)strlen(scopeStack)+ (int)strlen(scopeSepp)+ (int)strlen(name)+1)); /* concatinate the separator */ os_strcat (scopeStack, scopeSepp); /* concatinate user identifier */ os_strcat (scopeStack, name); } } else { /* Empty scope stack */ if (name) { /* if a user identifier is specified, copy the user identifier */ scopeStack = os_strdup (name); } else { /* make the scope stack representation empty */ scopeStack = os_strdup(""); } } /* return the scope stack represenation */ return scopeStack; } /* Return the basename related to a scope */ c_char * idl_scopeBasename ( idl_scope scope) { return os_strdup(scope->baseName); }
SanderMertens/opensplice
src/tools/idlpp/code/idl_scope.c
C
gpl-3.0
9,149
/* * * Mouse driver * */ #include <kernel/system.h> #include <kernel/logging.h> #include <kernel/pipe.h> #include <kernel/module.h> #include <kernel/mouse.h> #include <kernel/args.h> static uint8_t mouse_cycle = 0; static uint8_t mouse_byte[4]; #define PACKETS_IN_PIPE 1024 #define DISCARD_POINT 32 #define MOUSE_IRQ 12 #define MOUSE_PORT 0x60 #define MOUSE_STATUS 0x64 #define MOUSE_ABIT 0x02 #define MOUSE_BBIT 0x01 #define MOUSE_WRITE 0xD4 #define MOUSE_F_BIT 0x20 #define MOUSE_V_BIT 0x08 #define MOUSE_DEFAULT 0 #define MOUSE_SCROLLWHEEL 1 #define MOUSE_BUTTONS 2 static int8_t mouse_mode = MOUSE_DEFAULT; static fs_node_t * mouse_pipe; void (*ps2_mouse_alternate)(void) = NULL; static void mouse_wait(uint8_t a_type) { uint32_t timeout = 100000; if (!a_type) { while (--timeout) { if ((inportb(MOUSE_STATUS) & MOUSE_BBIT) == 1) { return; } } debug_print(INFO, "mouse timeout"); return; } else { while (--timeout) { if (!((inportb(MOUSE_STATUS) & MOUSE_ABIT))) { return; } } debug_print(INFO, "mouse timeout"); return; } } static void mouse_write(uint8_t write) { mouse_wait(1); outportb(MOUSE_STATUS, MOUSE_WRITE); mouse_wait(1); outportb(MOUSE_PORT, write); } static uint8_t mouse_read(void) { mouse_wait(0); char t = inportb(MOUSE_PORT); return t; } static int mouse_handler(struct regs *r) { uint8_t status = inportb(MOUSE_STATUS); while ((status & MOUSE_BBIT) && (status & MOUSE_F_BIT)) { if (ps2_mouse_alternate) { ps2_mouse_alternate(); break; } int8_t mouse_in = inportb(MOUSE_PORT); switch (mouse_cycle) { case 0: mouse_byte[0] = mouse_in; if (!(mouse_in & MOUSE_V_BIT)) break; ++mouse_cycle; break; case 1: mouse_byte[1] = mouse_in; ++mouse_cycle; break; case 2: mouse_byte[2] = mouse_in; if (mouse_mode == MOUSE_SCROLLWHEEL || mouse_mode == MOUSE_BUTTONS) { ++mouse_cycle; break; } goto finish_packet; case 3: mouse_byte[3] = mouse_in; goto finish_packet; } goto read_next; finish_packet: mouse_cycle = 0; /* We now have a full mouse packet ready to use */ mouse_device_packet_t packet; packet.magic = MOUSE_MAGIC; int x = mouse_byte[1]; int y = mouse_byte[2]; if (x && mouse_byte[0] & (1 << 4)) { /* Sign bit */ x = x - 0x100; } if (y && mouse_byte[0] & (1 << 5)) { /* Sign bit */ y = y - 0x100; } if (mouse_byte[0] & (1 << 6) || mouse_byte[0] & (1 << 7)) { /* Overflow */ x = 0; y = 0; } packet.x_difference = x; packet.y_difference = y; packet.buttons = 0; if (mouse_byte[0] & 0x01) { packet.buttons |= LEFT_CLICK; } if (mouse_byte[0] & 0x02) { packet.buttons |= RIGHT_CLICK; } if (mouse_byte[0] & 0x04) { packet.buttons |= MIDDLE_CLICK; } if (mouse_mode == MOUSE_SCROLLWHEEL && mouse_byte[3]) { if ((int8_t)mouse_byte[3] > 0) { packet.buttons |= MOUSE_SCROLL_DOWN; } else if ((int8_t)mouse_byte[3] < 0) { packet.buttons |= MOUSE_SCROLL_UP; } } mouse_device_packet_t bitbucket; while (pipe_size(mouse_pipe) > (int)(DISCARD_POINT * sizeof(packet))) { read_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&bitbucket); } write_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&packet); read_next: break; } irq_ack(MOUSE_IRQ); return 1; } static int ioctl_mouse(fs_node_t * node, int request, void * argp) { if (request == 1) { mouse_cycle = 0; return 0; } return -1; } static int mouse_install(void) { debug_print(NOTICE, "Initializing PS/2 mouse interface"); uint8_t status, result; IRQ_OFF; while ((inportb(0x64) & 1)) { inportb(0x60); } mouse_pipe = make_pipe(sizeof(mouse_device_packet_t) * PACKETS_IN_PIPE); mouse_wait(1); outportb(MOUSE_STATUS, 0xA8); mouse_read(); mouse_wait(1); outportb(MOUSE_STATUS, 0x20); mouse_wait(0); status = inportb(0x60) | 3; mouse_wait(1); outportb(MOUSE_STATUS, 0x60); mouse_wait(1); outportb(MOUSE_PORT, status); mouse_write(0xF6); mouse_read(); mouse_write(0xF4); mouse_read(); /* Try to enable scroll wheel (but not buttons) */ if (!args_present("nomousescroll")) { mouse_write(0xF2); mouse_read(); result = mouse_read(); mouse_write(0xF3); mouse_read(); mouse_write(200); mouse_read(); mouse_write(0xF3); mouse_read(); mouse_write(100); mouse_read(); mouse_write(0xF3); mouse_read(); mouse_write(80); mouse_read(); mouse_write(0xF2); mouse_read(); result = mouse_read(); if (result == 3) { mouse_mode = MOUSE_SCROLLWHEEL; } } /* keyboard scancode set */ mouse_wait(1); outportb(MOUSE_PORT, 0xF0); mouse_wait(1); outportb(MOUSE_PORT, 0x02); mouse_wait(1); mouse_read(); irq_install_handler(MOUSE_IRQ, mouse_handler, "ps2 mouse"); IRQ_RES; uint8_t tmp = inportb(0x61); outportb(0x61, tmp | 0x80); outportb(0x61, tmp & 0x7F); inportb(MOUSE_PORT); while ((inportb(0x64) & 1)) { inportb(0x60); } mouse_pipe->flags = FS_CHARDEVICE; mouse_pipe->ioctl = ioctl_mouse; vfs_mount("/dev/mouse", mouse_pipe); return 0; } static int mouse_uninstall(void) { /* TODO */ return 0; } MODULE_DEF(ps2mouse, mouse_install, mouse_uninstall);
jpacanowski/GekonOS
kernel/mouse.c
C
gpl-3.0
5,159
/* * Copyright 2014 Tilera Corporation. All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for * more details. * * * Perf_events support for Tile processor. * * This code is based upon the x86 perf event * code, which is: * * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de> * Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar * Copyright (C) 2009 Jaswinder Singh Rajput * Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter * Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra * Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com> * Copyright (C) 2009 Google, Inc., Stephane Eranian */ #include <linux/kprobes.h> #include <linux/kernel.h> #include <linux/kdebug.h> #include <linux/mutex.h> #include <linux/bitmap.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/perf_event.h> #include <linux/atomic.h> #include <asm/traps.h> #include <asm/stack.h> #include <asm/pmc.h> #include <hv/hypervisor.h> #define TILE_MAX_COUNTERS 4 #define PERF_COUNT_0_IDX 0 #define PERF_COUNT_1_IDX 1 #define AUX_PERF_COUNT_0_IDX 2 #define AUX_PERF_COUNT_1_IDX 3 struct cpu_hw_events { int n_events; struct perf_event *events[TILE_MAX_COUNTERS]; /* counter order */ struct perf_event *event_list[TILE_MAX_COUNTERS]; /* enabled order */ int assign[TILE_MAX_COUNTERS]; unsigned long active_mask[BITS_TO_LONGS(TILE_MAX_COUNTERS)]; unsigned long used_mask; }; /* TILE arch specific performance monitor unit */ struct tile_pmu { const char *name; int version; const int *hw_events; /* generic hw events table */ /* generic hw cache events table */ const int (*cache_events)[PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX]; int (*map_hw_event)(u64); /*method used to map hw events */ int (*map_cache_event)(u64); /*method used to map cache events */ u64 max_period; /* max sampling period */ u64 cntval_mask; /* counter width mask */ int cntval_bits; /* counter width */ int max_events; /* max generic hw events in map */ int num_counters; /* number base + aux counters */ int num_base_counters; /* number base counters */ }; DEFINE_PER_CPU(u64, perf_irqs); static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events); #define TILE_OP_UNSUPP (-1) #ifndef __tilegx__ /* TILEPro hardware events map */ static const int tile_hw_event_map[] = { [PERF_COUNT_HW_CPU_CYCLES] = 0x01, /* ONE */ [PERF_COUNT_HW_INSTRUCTIONS] = 0x06, /* MP_BUNDLE_RETIRED */ [PERF_COUNT_HW_CACHE_REFERENCES] = TILE_OP_UNSUPP, [PERF_COUNT_HW_CACHE_MISSES] = TILE_OP_UNSUPP, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x16, /* MP_CONDITIONAL_BRANCH_ISSUED */ [PERF_COUNT_HW_BRANCH_MISSES] = 0x14, /* MP_CONDITIONAL_BRANCH_MISSPREDICT */ [PERF_COUNT_HW_BUS_CYCLES] = TILE_OP_UNSUPP, }; #else /* TILEGx hardware events map */ static const int tile_hw_event_map[] = { [PERF_COUNT_HW_CPU_CYCLES] = 0x181, /* ONE */ [PERF_COUNT_HW_INSTRUCTIONS] = 0xdb, /* INSTRUCTION_BUNDLE */ [PERF_COUNT_HW_CACHE_REFERENCES] = TILE_OP_UNSUPP, [PERF_COUNT_HW_CACHE_MISSES] = TILE_OP_UNSUPP, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0xd9, /* COND_BRANCH_PRED_CORRECT */ [PERF_COUNT_HW_BRANCH_MISSES] = 0xda, /* COND_BRANCH_PRED_INCORRECT */ [PERF_COUNT_HW_BUS_CYCLES] = TILE_OP_UNSUPP, }; #endif #define C(x) PERF_COUNT_HW_CACHE_##x /* * Generalized hw caching related hw_event table, filled * in on a per model basis. A value of -1 means * 'not supported', any other value means the * raw hw_event ID. */ #ifndef __tilegx__ /* TILEPro hardware cache event map */ static const int tile_cache_event_map[PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x21, /* RD_MISS */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x22, /* WR_MISS */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x12, /* MP_ICACHE_HIT_ISSUED */ [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x1d, /* TLB_CNT */ [C(RESULT_MISS)] = 0x20, /* TLB_EXCEPTION */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x13, /* MP_ITLB_HIT_ISSUED */ [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, }; #else /* TILEGx hardware events map */ static const int tile_cache_event_map[PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { /* * Like some other architectures (e.g. ARM), the performance * counters don't differentiate between read and write * accesses/misses, so this isn't strictly correct, but it's the * best we can do. Writes and reads get combined. */ [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x44, /* RD_MISS */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x45, /* WR_MISS */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x40, /* TLB_CNT */ [C(RESULT_MISS)] = 0x43, /* TLB_EXCEPTION */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x40, /* TLB_CNT */ [C(RESULT_MISS)] = 0x43, /* TLB_EXCEPTION */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0xd4, /* ITLB_MISS_INT */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0xd4, /* ITLB_MISS_INT */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, }; #endif static atomic_t tile_active_events; static DEFINE_MUTEX(perf_intr_reserve_mutex); static int tile_map_hw_event(u64 config); static int tile_map_cache_event(u64 config); static int tile_pmu_handle_irq(struct pt_regs *regs, int fault); /* * To avoid new_raw_count getting larger then pre_raw_count * in tile_perf_event_update(), we limit the value of max_period to 2^31 - 1. */ static const struct tile_pmu tilepmu = { #ifndef __tilegx__ .name = "tilepro", #else .name = "tilegx", #endif .max_events = ARRAY_SIZE(tile_hw_event_map), .map_hw_event = tile_map_hw_event, .hw_events = tile_hw_event_map, .map_cache_event = tile_map_cache_event, .cache_events = &tile_cache_event_map, .cntval_bits = 32, .cntval_mask = (1ULL << 32) - 1, .max_period = (1ULL << 31) - 1, .num_counters = TILE_MAX_COUNTERS, .num_base_counters = TILE_BASE_COUNTERS, }; static const struct tile_pmu *tile_pmu __read_mostly; /* * Check whether perf event is enabled. */ int tile_perf_enabled(void) { return atomic_read(&tile_active_events) != 0; } /* * Read Performance Counters. */ static inline u64 read_counter(int idx) { u64 val = 0; /* __insn_mfspr() only takes an immediate argument */ switch (idx) { case PERF_COUNT_0_IDX: val = __insn_mfspr(SPR_PERF_COUNT_0); break; case PERF_COUNT_1_IDX: val = __insn_mfspr(SPR_PERF_COUNT_1); break; case AUX_PERF_COUNT_0_IDX: val = __insn_mfspr(SPR_AUX_PERF_COUNT_0); break; case AUX_PERF_COUNT_1_IDX: val = __insn_mfspr(SPR_AUX_PERF_COUNT_1); break; default: WARN_ON_ONCE(idx > AUX_PERF_COUNT_1_IDX || idx < PERF_COUNT_0_IDX); } return val; } /* * Write Performance Counters. */ static inline void write_counter(int idx, u64 value) { /* __insn_mtspr() only takes an immediate argument */ switch (idx) { case PERF_COUNT_0_IDX: __insn_mtspr(SPR_PERF_COUNT_0, value); break; case PERF_COUNT_1_IDX: __insn_mtspr(SPR_PERF_COUNT_1, value); break; case AUX_PERF_COUNT_0_IDX: __insn_mtspr(SPR_AUX_PERF_COUNT_0, value); break; case AUX_PERF_COUNT_1_IDX: __insn_mtspr(SPR_AUX_PERF_COUNT_1, value); break; default: WARN_ON_ONCE(idx > AUX_PERF_COUNT_1_IDX || idx < PERF_COUNT_0_IDX); } } /* * Enable performance event by setting * Performance Counter Control registers. */ static inline void tile_pmu_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; unsigned long cfg, mask; int shift, idx = hwc->idx; /* * prevent early activation from tile_pmu_start() in hw_perf_enable */ if (WARN_ON_ONCE(idx == -1)) { return; } if (idx < tile_pmu->num_base_counters) { cfg = __insn_mfspr(SPR_PERF_COUNT_CTL); } else { cfg = __insn_mfspr(SPR_AUX_PERF_COUNT_CTL); } switch (idx) { case PERF_COUNT_0_IDX: case AUX_PERF_COUNT_0_IDX: mask = TILE_EVENT_MASK; shift = 0; break; case PERF_COUNT_1_IDX: case AUX_PERF_COUNT_1_IDX: mask = TILE_EVENT_MASK << 16; shift = 16; break; default: WARN_ON_ONCE(idx < PERF_COUNT_0_IDX || idx > AUX_PERF_COUNT_1_IDX); return; } /* Clear mask bits to enable the event. */ cfg &= ~mask; cfg |= hwc->config << shift; if (idx < tile_pmu->num_base_counters) { __insn_mtspr(SPR_PERF_COUNT_CTL, cfg); } else { __insn_mtspr(SPR_AUX_PERF_COUNT_CTL, cfg); } } /* * Disable performance event by clearing * Performance Counter Control registers. */ static inline void tile_pmu_disable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; unsigned long cfg, mask; int idx = hwc->idx; if (idx == -1) { return; } if (idx < tile_pmu->num_base_counters) { cfg = __insn_mfspr(SPR_PERF_COUNT_CTL); } else { cfg = __insn_mfspr(SPR_AUX_PERF_COUNT_CTL); } switch (idx) { case PERF_COUNT_0_IDX: case AUX_PERF_COUNT_0_IDX: mask = TILE_PLM_MASK; break; case PERF_COUNT_1_IDX: case AUX_PERF_COUNT_1_IDX: mask = TILE_PLM_MASK << 16; break; default: WARN_ON_ONCE(idx < PERF_COUNT_0_IDX || idx > AUX_PERF_COUNT_1_IDX); return; } /* Set mask bits to disable the event. */ cfg |= mask; if (idx < tile_pmu->num_base_counters) { __insn_mtspr(SPR_PERF_COUNT_CTL, cfg); } else { __insn_mtspr(SPR_AUX_PERF_COUNT_CTL, cfg); } } /* * Propagate event elapsed time into the generic event. * Can only be executed on the CPU where the event is active. * Returns the delta events processed. */ static u64 tile_perf_event_update(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int shift = 64 - tile_pmu->cntval_bits; u64 prev_raw_count, new_raw_count; u64 oldval; int idx = hwc->idx; u64 delta; /* * Careful: an NMI might modify the previous event value. * * Our tactic to handle this is to first atomically read and * exchange a new raw count - then add that new-prev delta * count to the generic event atomically: */ again: prev_raw_count = local64_read(&hwc->prev_count); new_raw_count = read_counter(idx); oldval = local64_cmpxchg(&hwc->prev_count, prev_raw_count, new_raw_count); if (oldval != prev_raw_count) { goto again; } /* * Now we have the new raw value and have updated the prev * timestamp already. We can now calculate the elapsed delta * (event-)time and add that to the generic event. * * Careful, not all hw sign-extends above the physical width * of the count. */ delta = (new_raw_count << shift) - (prev_raw_count << shift); delta >>= shift; local64_add(delta, &event->count); local64_sub(delta, &hwc->period_left); return new_raw_count; } /* * Set the next IRQ period, based on the hwc->period_left value. * To be called with the event disabled in hw: */ static int tile_event_set_period(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int idx = hwc->idx; s64 left = local64_read(&hwc->period_left); s64 period = hwc->sample_period; int ret = 0; /* * If we are way outside a reasonable range then just skip forward: */ if (unlikely(left <= -period)) { left = period; local64_set(&hwc->period_left, left); hwc->last_period = period; ret = 1; } if (unlikely(left <= 0)) { left += period; local64_set(&hwc->period_left, left); hwc->last_period = period; ret = 1; } if (left > tile_pmu->max_period) { left = tile_pmu->max_period; } /* * The hw event starts counting from this event offset, * mark it to be able to extra future deltas: */ local64_set(&hwc->prev_count, (u64) - left); write_counter(idx, (u64)(-left) & tile_pmu->cntval_mask); perf_event_update_userpage(event); return ret; } /* * Stop the event but do not release the PMU counter */ static void tile_pmu_stop(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; int idx = hwc->idx; if (__test_and_clear_bit(idx, cpuc->active_mask)) { tile_pmu_disable_event(event); cpuc->events[hwc->idx] = NULL; WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED); hwc->state |= PERF_HES_STOPPED; } if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) { /* * Drain the remaining delta count out of a event * that we are disabling: */ tile_perf_event_update(event); hwc->state |= PERF_HES_UPTODATE; } } /* * Start an event (without re-assigning counter) */ static void tile_pmu_start(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int idx = event->hw.idx; if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED))) { return; } if (WARN_ON_ONCE(idx == -1)) { return; } if (flags & PERF_EF_RELOAD) { WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE)); tile_event_set_period(event); } event->hw.state = 0; cpuc->events[idx] = event; __set_bit(idx, cpuc->active_mask); unmask_pmc_interrupts(); tile_pmu_enable_event(event); perf_event_update_userpage(event); } /* * Add a single event to the PMU. * * The event is added to the group of enabled events * but only if it can be scehduled with existing events. */ static int tile_pmu_add(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc; unsigned long mask; int b, max_cnt; hwc = &event->hw; /* * We are full. */ if (cpuc->n_events == tile_pmu->num_counters) { return -ENOSPC; } cpuc->event_list[cpuc->n_events] = event; cpuc->n_events++; hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED; if (!(flags & PERF_EF_START)) { hwc->state |= PERF_HES_ARCH; } /* * Find first empty counter. */ max_cnt = tile_pmu->num_counters; mask = ~cpuc->used_mask; /* Find next free counter. */ b = find_next_bit(&mask, max_cnt, 0); /* Should not happen. */ if (WARN_ON_ONCE(b == max_cnt)) { return -ENOSPC; } /* * Assign counter to event. */ event->hw.idx = b; __set_bit(b, &cpuc->used_mask); /* * Start if requested. */ if (flags & PERF_EF_START) { tile_pmu_start(event, PERF_EF_RELOAD); } return 0; } /* * Delete a single event from the PMU. * * The event is deleted from the group of enabled events. * If it is the last event, disable PMU interrupt. */ static void tile_pmu_del(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int i; /* * Remove event from list, compact list if necessary. */ for (i = 0; i < cpuc->n_events; i++) { if (cpuc->event_list[i] == event) { while (++i < cpuc->n_events) { cpuc->event_list[i - 1] = cpuc->event_list[i]; } --cpuc->n_events; cpuc->events[event->hw.idx] = NULL; __clear_bit(event->hw.idx, &cpuc->used_mask); tile_pmu_stop(event, PERF_EF_UPDATE); break; } } /* * If there are no events left, then mask PMU interrupt. */ if (cpuc->n_events == 0) { mask_pmc_interrupts(); } perf_event_update_userpage(event); } /* * Propagate event elapsed time into the event. */ static inline void tile_pmu_read(struct perf_event *event) { tile_perf_event_update(event); } /* * Map generic events to Tile PMU. */ static int tile_map_hw_event(u64 config) { if (config >= tile_pmu->max_events) { return -EINVAL; } return tile_pmu->hw_events[config]; } /* * Map generic hardware cache events to Tile PMU. */ static int tile_map_cache_event(u64 config) { unsigned int cache_type, cache_op, cache_result; int code; if (!tile_pmu->cache_events) { return -ENOENT; } cache_type = (config >> 0) & 0xff; if (cache_type >= PERF_COUNT_HW_CACHE_MAX) { return -EINVAL; } cache_op = (config >> 8) & 0xff; if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX) { return -EINVAL; } cache_result = (config >> 16) & 0xff; if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX) { return -EINVAL; } code = (*tile_pmu->cache_events)[cache_type][cache_op][cache_result]; if (code == TILE_OP_UNSUPP) { return -EINVAL; } return code; } static void tile_event_destroy(struct perf_event *event) { if (atomic_dec_return(&tile_active_events) == 0) { release_pmc_hardware(); } } static int __tile_event_init(struct perf_event *event) { struct perf_event_attr *attr = &event->attr; struct hw_perf_event *hwc = &event->hw; int code; switch (attr->type) { case PERF_TYPE_HARDWARE: code = tile_pmu->map_hw_event(attr->config); break; case PERF_TYPE_HW_CACHE: code = tile_pmu->map_cache_event(attr->config); break; case PERF_TYPE_RAW: code = attr->config & TILE_EVENT_MASK; break; default: /* Should not happen. */ return -EOPNOTSUPP; } if (code < 0) { return code; } hwc->config = code; hwc->idx = -1; if (attr->exclude_user) { hwc->config |= TILE_CTL_EXCL_USER; } if (attr->exclude_kernel) { hwc->config |= TILE_CTL_EXCL_KERNEL; } if (attr->exclude_hv) { hwc->config |= TILE_CTL_EXCL_HV; } if (!hwc->sample_period) { hwc->sample_period = tile_pmu->max_period; hwc->last_period = hwc->sample_period; local64_set(&hwc->period_left, hwc->sample_period); } event->destroy = tile_event_destroy; return 0; } static int tile_event_init(struct perf_event *event) { int err = 0; perf_irq_t old_irq_handler = NULL; if (atomic_inc_return(&tile_active_events) == 1) { old_irq_handler = reserve_pmc_hardware(tile_pmu_handle_irq); } if (old_irq_handler) { pr_warn("PMC hardware busy (reserved by oprofile)\n"); atomic_dec(&tile_active_events); return -EBUSY; } switch (event->attr.type) { case PERF_TYPE_RAW: case PERF_TYPE_HARDWARE: case PERF_TYPE_HW_CACHE: break; default: return -ENOENT; } err = __tile_event_init(event); if (err) { if (event->destroy) { event->destroy(event); } } return err; } static struct pmu tilera_pmu = { .event_init = tile_event_init, .add = tile_pmu_add, .del = tile_pmu_del, .start = tile_pmu_start, .stop = tile_pmu_stop, .read = tile_pmu_read, }; /* * PMU's IRQ handler, PMU has 2 interrupts, they share the same handler. */ int tile_pmu_handle_irq(struct pt_regs *regs, int fault) { struct perf_sample_data data; struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_event *event; struct hw_perf_event *hwc; u64 val; unsigned long status; int bit; __this_cpu_inc(perf_irqs); if (!atomic_read(&tile_active_events)) { return 0; } status = pmc_get_overflow(); pmc_ack_overflow(status); for_each_set_bit(bit, &status, tile_pmu->num_counters) { event = cpuc->events[bit]; if (!event) { continue; } if (!test_bit(bit, cpuc->active_mask)) { continue; } hwc = &event->hw; val = tile_perf_event_update(event); if (val & (1ULL << (tile_pmu->cntval_bits - 1))) { continue; } perf_sample_data_init(&data, 0, event->hw.last_period); if (!tile_event_set_period(event)) { continue; } if (perf_event_overflow(event, &data, regs)) { tile_pmu_stop(event, 0); } } return 0; } static bool __init supported_pmu(void) { tile_pmu = &tilepmu; return true; } int __init init_hw_perf_events(void) { supported_pmu(); perf_pmu_register(&tilera_pmu, "cpu", PERF_TYPE_RAW); return 0; } arch_initcall(init_hw_perf_events); /* Callchain handling code. */ /* * Tile specific backtracing code for perf_events. */ static inline void perf_callchain(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs) { struct KBacktraceIterator kbt; unsigned int i; /* * Get the address just after the "jalr" instruction that * jumps to the handler for a syscall. When we find this * address in a backtrace, we silently ignore it, which gives * us a one-step backtrace connection from the sys_xxx() * function in the kernel to the xxx() function in libc. * Otherwise, we lose the ability to properly attribute time * from the libc calls to the kernel implementations, since * oprofile only considers PCs from backtraces a pair at a time. */ unsigned long handle_syscall_pc = handle_syscall_link_address(); KBacktraceIterator_init(&kbt, NULL, regs); kbt.profile = 1; /* * The sample for the pc is already recorded. Now we are adding the * address of the callsites on the stack. Our iterator starts * with the frame of the (already sampled) call site. If our * iterator contained a "return address" field, we could have just * used it and wouldn't have needed to skip the first * frame. That's in effect what the arm and x86 versions do. * Instead we peel off the first iteration to get the equivalent * behavior. */ if (KBacktraceIterator_end(&kbt)) { return; } KBacktraceIterator_next(&kbt); /* * Set stack depth to 16 for user and kernel space respectively, that * is, total 32 stack frames. */ for (i = 0; i < 16; ++i) { unsigned long pc; if (KBacktraceIterator_end(&kbt)) { break; } pc = kbt.it.pc; if (pc != handle_syscall_pc) { perf_callchain_store(entry, pc); } KBacktraceIterator_next(&kbt); } } void perf_callchain_user(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs) { perf_callchain(entry, regs); } void perf_callchain_kernel(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs) { perf_callchain(entry, regs); }
williamfdevine/PrettyLinux
arch/tile/kernel/perf_event.c
C
gpl-3.0
24,932
#include "defs.h" #include "fdefs.h" #include <stdlib.h> void gasify(job) char *job; { char command[MAXCOMM] ; char g_type[MAXCOMM] ; double temp_y ; double temp_slope ; double rho_shock ; double temp_shock ; double gas_frac ; double rhobar ; double metal ; double rho ; int i,j ; int old_nsph ; struct dark_particle *dp ; /* Gas particles are created from dark matter particles. * Masses are gas_frac * masses of dm particles * dm particle masses are multiplied by (1-gas_frac). * Temperatures are set to t=temp_y*(rho/rhobar)^temp_slope, * or to t=temp_shock if rho/rhobar>rho_shock. */ if (!boxes_loaded[0]){ printf("<sorry, no boxes are loaded, %s>\n",title) ; } else { if (sscanf(job,"%s %lf %lf %lf %lf %lf %lf %lf %s",command,&gas_frac, &rhobar,&temp_y,&temp_slope,&rho_shock,&temp_shock, &metal,g_type) == 8) { calc_density(&box0_smx, 1, 0, 0); header.nbodies += boxlist[0].ndark ; old_nsph = header.nsph ; header.nsph += boxlist[0].ndark ; if(header.nsph != 0) { gas_particles = (struct gas_particle *) realloc(gas_particles, header.nsph*sizeof(*gas_particles)); if(gas_particles == NULL) { printf("<sorry, no memory for gas particles, %s>\n",title) ; return ; } mark_gas = (short *)realloc(mark_gas,header.nsph*sizeof(*mark_gas)); if(mark_gas == NULL) { printf("<sorry, no memory for gas particle markers, %s>\n", title) ; return ; } for (i = old_nsph; i < header.nsph; i++) mark_gas[i] = 0; } else gas_particles = NULL; for (i = 0 ;i < boxlist[0].ndark ;i++) { dp = boxlist[0].dp[i] ; gas_particles[i+old_nsph].mass = gas_frac*(dp->mass) ; dp->mass = (1. - gas_frac)*(dp->mass) ; for(j = 0; j < header.ndim; j++){ gas_particles[i+old_nsph].pos[j] = dp->pos[j] ; gas_particles[i+old_nsph].vel[j] = dp->vel[j] ; } gas_particles[i+old_nsph].rho = gas_frac*(box0_smx->kd->p[i].fDensity); gas_particles[i+old_nsph].temp = temp_y* pow((gas_particles[i+old_nsph].rho/rhobar),temp_slope) ; if (gas_particles[i+old_nsph].rho > rhobar*rho_shock) { gas_particles[i+old_nsph].temp = temp_shock ; } gas_particles[i+old_nsph].hsmooth = sqrt(box0_smx->kd->p[i].fBall2)/2.0; gas_particles[i+old_nsph].metals = metal ; gas_particles[i+old_nsph].phi = dp->phi ; } if(box0_smx) { kdFinish(box0_smx->kd); smFinish(box0_smx); box0_smx = NULL; } boxes_loaded[0] = NO ; unload_all() ; active_box = 0 ; binary_loaded = LOADED ; current_project = NO ; current_color = NO ; divv_loaded = NO ; hneutral_loaded = NO ; meanmwt_loaded = NO ; xray_loaded = NO ; dudt_loaded = NO ; starform_loaded = NO ; } else if (sscanf(job,"%s %lf %lf %lf %lf %lf %lf %lf %s",command, &gas_frac,&rhobar,&temp_y,&temp_slope,&rho_shock, &temp_shock,&metal,g_type) == 9) { if (strcmp(g_type,"destroy") != 0 && strcmp(g_type,"d") != 0){ printf("<sorry, %s is not a gasify type, %s",g_type,title) ; return; } calc_density(&box0_smx, 1, 0, 0); printf("<warning, destroying original dark and gas particles, %s>\n", title) ; header.nbodies -= header.nsph ; header.nsph = boxlist[0].ndark ; header.ndark = 0 ; if(header.nsph != 0) { dark_particles = (struct dark_particle *) realloc(dark_particles, header.nsph*sizeof(*gas_particles)); if(dark_particles == NULL) { printf("<sorry, no memory for gas particles, %s>\n",title) ; return ; } gas_particles = (struct gas_particle *)dark_particles ; free(mark_dark) ; if(header.nsph != 0) mark_gas = (short *)calloc(header.nsph, sizeof(*mark_gas)); if(mark_gas == NULL && header.nsph != 0) { printf("<sorry, no memory for gas particle markers, %s>\n", title) ; return ; } for (i = 0; i < header.nsph; i++) mark_gas[i] = 0; } else gas_particles = NULL; for (i = boxlist[0].ndark - 1 ;i >= 0 ;i--) { dp = boxlist[0].dp[i] ; gas_particles[i].phi = dp->phi ; gas_particles[i].metals = metal ; gas_particles[i].hsmooth = sqrt(box0_smx->kd->p[i].fBall2)/2.0; rho = gas_frac*(box0_smx->kd->p[i].fDensity); gas_particles[i].temp = temp_y*pow((rho/rhobar),temp_slope) ; if (rho > rhobar*rho_shock) { gas_particles[i].temp = temp_shock ; } gas_particles[i].rho = rho ; for(j = header.ndim - 1; j >= 0; j--){ gas_particles[i+old_nsph].vel[j] = dp->vel[j] ; } for(j = header.ndim - 1; j >= 0; j--){ gas_particles[i+old_nsph].pos[j] = dp->pos[j] ; } gas_particles[i].mass = gas_frac*(dp->mass) ; } if(box0_smx) { kdFinish(box0_smx->kd); smFinish(box0_smx); box0_smx = NULL; } dark_particles = NULL; boxes_loaded[0] = NO ; unload_all() ; active_box = 0 ; binary_loaded = LOADED ; current_project = NO ; current_color = NO ; divv_loaded = NO ; hneutral_loaded = NO ; meanmwt_loaded = NO ; xray_loaded = NO ; starform_loaded = NO ; dudt_loaded = NO ; } else { input_error(command) ; } } }
FavioVazquez/MexicanNumericalSimulationSchool
preschool/tipsy-2.2.3d/code/gasify.c
C
gpl-3.0
5,301
/* ** AACPlayer - Freeware Advanced Audio (AAC) Player for Android ** Copyright (C) 2011 Spolecne s.r.o., http://www.biophysics.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 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/>. **/ #define AACD_MODULE "Decoder[FFMPEG/WMA]" #include "aac-array-common.h" #include <string.h> #include "libavcodec/avcodec.h" #include "libavcodec/aac_parser.h" #include "libavcodec/get_bits.h" #include "libavcodec/mpeg4audio.h" #include "libavutil/mem.h" #include "libavutil/log.h" #include "libavformat/avformat.h" typedef struct AACDFFmpegInfo { AACDCommonInfo *cinfo; AVInputFormat *avifmt; AVFormatContext *avfctx; AVPacket *avpkt; AVPacket *pkt; int audio_stream_index; unsigned int bytesconsumed; } AACDFFmpegInfo; extern AVCodec wmav1_decoder; extern AVCodec wmav2_decoder; extern AVInputFormat asf_demuxer; static const char* aacd_ffwma_name() { return "FFmpeg/WMA"; } static const char *aacd_ffwma_logname( void *ctx ) { return AACD_MODULE; } /** * Creates a new AVPacket. */ static AVPacket* aacd_ff_create_avpkt() { AVPacket *avpkt = (AVPacket*) av_mallocz( sizeof(AVPacket)); avpkt->data = NULL; avpkt->size = 0; return avpkt; } /** * A wrapper method which reads packets. * It only reads them from the internal pre-fetched buffer in AACDCommonInfo. */ static int aacd_ff_io_read_packet( void *opaque, uint8_t *buf, int buf_size) { AACD_TRACE( "io_read_packet() start" ); AACDFFmpegInfo *ff = (AACDFFmpegInfo*) opaque; AACDCommonInfo *cinfo = ff->cinfo; if (cinfo->bytesleft < buf_size) { // Let's cheat now: AACDArrayInfo *ainfo = (AACDArrayInfo*) cinfo; if (!aacda_read_buffer( ainfo )) { AACD_INFO( "io_read_packet() EOF detected" ); } } int len = buf_size < cinfo->bytesleft ? buf_size : cinfo->bytesleft; if (!len) { AACD_WARN( "read_packet(): no bytes left, returning 0" ); return 0; } memcpy( buf, cinfo->buffer, len ); cinfo->buffer += len; cinfo->bytesleft -= len; ff->bytesconsumed += len; AACD_TRACE( "io_read_packet() stop" ); return len; } /** * Creates a new ByteIOContext. */ static ByteIOContext* aacd_ff_create_byteioctx( AACDFFmpegInfo *ff ) { int buffer_size = ff->cinfo->bbsize; unsigned char *buffer = av_mallocz( buffer_size ); ByteIOContext *pb = av_alloc_put_byte( buffer, buffer_size, 0, ff, aacd_ff_io_read_packet, NULL, NULL); if (!pb) { av_free( buffer ); AACD_WARN( "create_byteioctx(): ByteIOContext could not be created" ); } return pb; } /** * Destroys a ByteIOContext. */ static void aacd_ff_destroy_byteioctx( ByteIOContext *pb ) { if (!pb) return; if (pb->buffer) av_free( pb->buffer ); av_free( pb ); } /** * Destroys our context. */ static void aacd_ff_destroy( AACDFFmpegInfo *ff ) { if ( !ff ) return; AACD_TRACE( "destroy() start" ); AVFormatContext *ic = ff->avfctx; if ( ic ) { if ( ff->audio_stream_index > -1) avcodec_close( ic->streams[ff->audio_stream_index]->codec ); ByteIOContext *pb = ic->pb; av_close_input_stream( ff->avfctx ); if ( pb ) aacd_ff_destroy_byteioctx( pb ); } if (ff->avpkt) av_free( ff->avpkt ); if (ff->pkt) av_free( ff->pkt ); av_free( ff ); AACD_TRACE( "destroy() stop" ); } static void aacd_ffwma_stop( AACDCommonInfo *cinfo, void *ext ) { if ( !ext ) return; AACDFFmpegInfo *ff = (AACDFFmpegInfo*) ext; aacd_ff_destroy( ff ); } /** * Initializes our context. */ static int aacd_ff_init( void **pext, AVInputFormat *fmt ) { AACD_TRACE( "init() start" ); av_log_set_level( AV_LOG_VERBOSE ); AACDFFmpegInfo *ff = (AACDFFmpegInfo*) av_mallocz( sizeof(struct AACDFFmpegInfo)); if (!ff) return -1; ff->avpkt = aacd_ff_create_avpkt(); ff->pkt = aacd_ff_create_avpkt(); if (!ff->avpkt || !ff->pkt) { AACD_ERROR( "init() out of memory error !" ); aacd_ff_destroy( ff ); return -2; } ff->avifmt = fmt; ff->audio_stream_index = -1; av_log( ff->avfctx, AV_LOG_INFO, "Test of AV_LOG_INFO\n" ); av_log( ff->avfctx, AV_LOG_DEBUG, "Test of AV_LOG_DEBUG\n" ); av_log( ff->avfctx, AV_LOG_VERBOSE, "Test of AV_LOG_VERBOSE\n" ); (*pext) = ff; AACD_TRACE( "init() stop" ); return 0; } static int aacd_ffwma_init( void **pext ) { return aacd_ff_init( pext, &asf_demuxer ); } /** * Finds a stream's position or return -1. * This method also discards all streams. */ static int aacd_ff_find_stream( AVFormatContext *ic, enum AVMediaType codec_type ) { int i; int ret = -1; for (i = 0; i < ic->nb_streams; i++) { AVStream *st = ic->streams[i]; AVCodecContext *avctx = st->codec; st->discard = AVDISCARD_ALL; if (ret == -1 && avctx->codec_type == codec_type) ret = i; } return ret; } /** * Simple method for looking up only our supported codecs. */ static AVCodec* aacd_ffwma_find_codec( enum CodecID id ) { switch (id) { case CODEC_ID_WMAV1: return &wmav1_decoder; case CODEC_ID_WMAV2: return &wmav2_decoder; } return NULL; } static long aacd_ffwma_start( AACDCommonInfo *cinfo, void *ext, unsigned char *buffer, unsigned long buffer_size) { AACD_TRACE( "start() start" ); AACDFFmpegInfo *ff = (AACDFFmpegInfo*) ext; ff->cinfo = cinfo; // take control over the input reading: cinfo->input_ctrl = 1; ByteIOContext *pb = aacd_ff_create_byteioctx( ff ); if (!pb) return -1; AACD_TRACE( "start() opening stream" ); ff->bytesconsumed = 0; int err = av_open_input_stream( &ff->avfctx, pb, "filename.asf", ff->avifmt, NULL ); AVFormatContext *ic = ff->avfctx; if (err) { char s[80]; av_strerror( err, s, 80); AACD_ERROR("start() cannot open demuxer - [%d] - $s", err, s ); // we must dealloc what we allocated locally: aacd_ff_destroy_byteioctx( pb ); return -1; } AACD_TRACE( "start() stream opened" ); //err = av_find_stream_info(ic) AACD_DEBUG( "start() streams=%d", ic->nb_streams); dump_format(ic, 0, "", 0); ff->audio_stream_index = aacd_ff_find_stream( ic, AVMEDIA_TYPE_AUDIO ); if (ff->audio_stream_index < 0) { AACD_ERROR( "start() cannot find audio stream" ); return -1; } AVStream *st = ic->streams[ff->audio_stream_index]; st->discard = AVDISCARD_DEFAULT; AVCodecContext *avctx = st->codec; AACD_DEBUG( "start() samplerate=%d channels=%d codec=%x", avctx->sample_rate, avctx->channels, avctx->codec_id); AVCodec *codec = aacd_ffwma_find_codec( avctx->codec_id ); if (!codec) { AACD_ERROR("start() audio - not a WMA codec - %x", avctx->codec_id); return -1; } if (avcodec_open( avctx, codec )) { AACD_ERROR("start() audio cannot open audio codec - %x", avctx->codec_id); return -1; } cinfo->samplerate = avctx->sample_rate; cinfo->channels = avctx->channels; AACD_TRACE( "start() stop - ic->format=%x, ff->avfctx->format=%x", ic->iformat, ff->avfctx->iformat ); // we return more than we consumed: return ff->bytesconsumed; } static int aacd_ffwma_decode( AACDCommonInfo *cinfo, void *ext, unsigned char *buffer, unsigned long buffer_size, jshort *jsamples, jint outLen ) { AACD_TRACE( "decode() start" ); AACDFFmpegInfo *ff = (AACDFFmpegInfo*) ext; AVFormatContext *ic = ff->avfctx; AVPacket *avpkt = ff->avpkt; AVPacket *pkt = ff->pkt; ff->bytesconsumed = 0; #ifdef AACD_LOGLEVEL_TRACE ic->debug = FF_FDEBUG_TS; #endif while (!pkt->size) { AACD_TRACE( "decode() calling av_read_frame..." ); int err = av_read_frame( ic, avpkt ); AACD_TRACE( "decode() av_read_frame returned: %d", err ); if (err < 0) { AACD_ERROR( "decode() cannot read av frame" ); return AACD_DECODE_EOF; } if (avpkt->stream_index == ff->audio_stream_index) { pkt->data = avpkt->data; pkt->size = avpkt->size; break; } // TODO: delete packet's buffer ? AACD_TRACE( "decode() : freeing packet's data" ); av_freep( &avpkt->data ); } AACD_TRACE( "decode() packet demuxed, will decode..." ); AVCodecContext *avctx = ic->streams[ff->audio_stream_index]->codec; AVCodec *codec = avctx->codec; AACD_DEBUG( "decode() frame_size=%d", avctx->frame_size ); // aac_decode_frame int outSize = outLen * 2; int consumed = (*codec->decode)( avctx, jsamples, &outSize, pkt ); if (consumed <= 0) { AACD_ERROR( "decode() cannot decode frame pkt->size=%d, outSize=%d, error: %d", pkt->size, outSize, consumed ); if ( cinfo->frame_samples < outLen * 3 / 2 ) { AACD_WARN( "decode() trying to obtain large output buffer" ); return AACD_DECODE_OUTPUT_NEEDED; } pkt->size = 0; return AACD_DECODE_OTHER; } pkt->data += consumed; pkt->size -= consumed; cinfo->frame_bytesconsumed = consumed; //cinfo->frame_samples = avctx->frame_size * avctx->channels; cinfo->frame_samples = (outSize >> 1); AACD_TRACE( "decode() stop - consumed %d, pkt->size=%d", consumed, pkt->size ); return AACD_DECODE_OK; } static int aacd_ffwma_probe( unsigned char *buffer, int len ) { return 0; } AACDDecoder aacd_ffmpeg_wma_decoder = { aacd_ffwma_name, aacd_ffwma_init, aacd_ffwma_start, aacd_ffwma_decode, aacd_ffwma_stop, aacd_ffwma_probe };
gmavenis/RadioPlayer
jni/aac-decoder/aac-ffmpeg-wma-decoder.c
C
gpl-3.0
10,374
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fap.h> #define EXIT_SUCCESS 0 char *readstdin(void); int main() { char* input; unsigned int input_len; fap_packet_t* packet; char fap_error_output[1024]; fap_init(); /* Get packet to parse from stdin */ input = readstdin(); input_len = strlen(input); /* Process the packet. */ packet = fap_parseaprs(input, input_len, 0); if ( packet->error_code ) { fap_explain_error(*packet->error_code, fap_error_output); printf("Failed to parse packet (%s): %s\n", input, fap_error_output); } else if ( packet->src_callsign ) { printf("Got packet from %s.\n", packet->src_callsign); } fap_free(packet); fap_cleanup(); return EXIT_SUCCESS; } char *readstdin(void) { #define BUF_SIZE 1024 char buffer[BUF_SIZE]; size_t contentSize = 1; /* includes NULL */ /* Preallocate space. We could just allocate one char here, but that wouldn't be efficient. */ char *content = malloc(sizeof(char) * BUF_SIZE); if(content == NULL) { perror("Failed to allocate content"); exit(1); } content[0] = '\0'; /* null-terminated */ while(fgets(buffer, BUF_SIZE, stdin)) { char *old = content; contentSize += strlen(buffer); content = realloc(content, contentSize); if(content == NULL) { perror("Failed to reallocate content"); free(old); exit(2); } strcat(content, buffer); } if(ferror(stdin)) { free(content); perror("Error reading from stdin."); exit(3); } return(content); }
n7nix/dantracker
faptest.c
C
gpl-3.0
1,515
#include <thread.h> #include <processor.h> #include <interrupt.h> #include <printk.h> _Atomic long long min_time = 0; static struct thread *__select_thread(struct processor *proc) { /* throw the old process back on the queue */ spinlock_acquire(&proc->schedlock); if(current_thread->flags & THREAD_DEAD) current_thread->flags |= THREAD_GONE; if(likely(proc->running->state == THREADSTATE_RUNNING && proc->running != &proc->idle_thread)) { if(likely(!(atomic_fetch_or(&proc->running->flags, THREAD_ONQUEUE) & THREAD_ONQUEUE))) { assert(proc->running == current_thread && !(current_thread->flags & THREAD_DEAD)); priqueue_insert(&proc->runqueue, &proc->running->runqueue_node, proc->running, thread_current_priority(proc->running)); } } struct thread *thread = priqueue_pop(&proc->runqueue); if(unlikely(!thread)) thread = &proc->idle_thread; else { thread->flags &= ~THREAD_ONQUEUE; } if(((thread->flags & THREAD_UNINTER) && thread->state != THREADSTATE_RUNNING) || thread->flags & THREAD_DEAD) { thread = &proc->idle_thread; } /* this is a weird edge case (that should probably get fixed up, TODO): * if a thread exits and another thread unblocks that exiting thread (for * example, it gets a signal), then the thread may be added to the runqueue * during its exiting. Threads that are exiting don't "remove" themselves from * the runqueue because that happens in the scheduler above, so they could be * in the runqueue in an unrunnable state. Then, another thread creates a new * thread and the slab allocator returns the recently exited thread. The flags * are cleared and the scheduler is then free to run that "new" thread...with the * old state. Thus allowing the thread to reach the unreachable part of thread_exit. * * So, if a thread's state is INIT, then don't run it. Wait until the creating thread * sets it to runable. */ if(unlikely(thread->state == THREADSTATE_INIT)) { thread = &proc->idle_thread; } proc->running = thread; spinlock_release(&proc->schedlock); return thread; } static void _check_signals(struct thread *thread) { spinlock_acquire(&thread->signal_lock); if(!sigisemptyset(&thread->pending_signals)) { for(int i = 1; i < _NSIG; i++) { if(sigismember(&thread->pending_signals, i)) { sigdelset(&thread->pending_signals, i); thread->signal = i; if(!(thread->flags & THREAD_UNINTER)) { thread->state = THREADSTATE_RUNNING; thread->processor->running = thread; } break; } } } spinlock_release(&thread->signal_lock); } static void __do_schedule(int save_preempt) { int old = arch_interrupt_set(0); struct processor *curproc = processor_get_current(); struct workqueue *wq = &curproc->workqueue; int preempt_old = curproc->preempt_disable - 1 /* -1 for the handle of curproc we hold */; assert(preempt_old >= 0); if(!save_preempt && curproc->preempt_disable > 1) { processor_release(curproc); arch_interrupt_set(old); return; } else { curproc->preempt_disable = 1; } #if CONFIG_DEBUG //assert(current_thread->held_spinlocks == 0); #endif _check_signals(current_thread); struct thread *next = __select_thread(curproc); processor_release(curproc); current_thread->flags &= ~THREAD_RESCHEDULE; if(next != current_thread) { //printk(":%d: %ld -> %ld\n", curproc->id, current_thread->tid, next->tid); arch_thread_context_switch(current_thread, next); _check_signals(current_thread); } if(save_preempt) { /* we're playing fast-and-loose here with references. We know that we'll be * fine since we've disabled interrupts, so we can technically drop the reference * to curproc before we get here... uhg */ curproc->preempt_disable = preempt_old; } arch_interrupt_set(old); /* threads have to do some kernel work! */ if(!save_preempt && !workqueue_empty(wq)) { workqueue_execute(wq); } } void schedule() { __do_schedule(1); } void preempt() { __do_schedule(0); }
Dennisbonke/DB-OS
kernel/schedule.c
C
gpl-3.0
3,944
/*****************************************************************************\ * $Id: ipmiping.c,v 1.75 2010-02-08 22:02:31 chu11 Exp $ ***************************************************************************** * Copyright (C) 2007-2015 Lawrence Livermore National Security, LLC. * Copyright (C) 2003-2007 The Regents of the University of California. * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). * Written by Albert Chu <chu11@llnl.gov> * UCRL-CODE-155448 * * This file is part of Ipmiping, tools for pinging IPMI and RMCP compliant * remote systems. For details, see http://www.llnl.gov/linux/. * * Ipmiping 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. * * Ipmiping 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 Ipmiping. If not, see <http://www.gnu.org/licenses/>. \*****************************************************************************/ #if HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stdlib.h> #if STDC_HEADERS #include <string.h> #endif /* STDC_HEADERS */ #if HAVE_UNISTD_H #include <unistd.h> #endif /* HAVE_UNISTD_H */ #include <assert.h> #include <errno.h> #include <freeipmi/freeipmi.h> #include "freeipmi-portability.h" #include "debug-util.h" #include "ping-tool-common.h" #define _setstr(x) (x) ? "set" : "clear" /* IPMI has a 6 bit sequence number */ #define IPMI_RQ_SEQ_MAX 0x3F int createpacket (const char *destination, void *buf, unsigned int buflen, unsigned int sequence_number, int version, int debug) { fiid_obj_t obj_rmcp_hdr = NULL; fiid_obj_t obj_lan_session_hdr = NULL; fiid_obj_t obj_lan_msg_hdr = NULL; fiid_obj_t obj_cmd = NULL; int len; assert (destination); assert (buf); assert (version == IPMI_PING_VERSION_1_5 || version == IPMI_PING_VERSION_2_0); if (!buflen) return (0); if (!(obj_rmcp_hdr = fiid_obj_create (tmpl_rmcp_hdr))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (!(obj_lan_session_hdr = fiid_obj_create (tmpl_lan_session_hdr))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (!(obj_lan_msg_hdr = fiid_obj_create (tmpl_lan_msg_hdr_rq))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (!(obj_cmd = fiid_obj_create (tmpl_cmd_get_channel_authentication_capabilities_rq))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (fill_rmcp_hdr_ipmi (obj_rmcp_hdr) < 0) ipmi_ping_err_exit ("fill_rmcp_hdr_ipmi: %s", strerror (errno)); if (fill_lan_session_hdr (IPMI_AUTHENTICATION_TYPE_NONE, 0, 0, obj_lan_session_hdr) < 0) ipmi_ping_err_exit ("fill_lan_session_hdr: %s", strerror (errno)); if (fill_lan_msg_hdr (IPMI_SLAVE_ADDRESS_BMC, IPMI_NET_FN_APP_RQ, IPMI_BMC_IPMB_LUN_BMC, sequence_number % (IPMI_RQ_SEQ_MAX+1), obj_lan_msg_hdr) < 0) ipmi_ping_err_exit ("fill_lan_msg_hdr: %s", strerror (errno)); if (version == IPMI_PING_VERSION_1_5) { if (fill_cmd_get_channel_authentication_capabilities (IPMI_CHANNEL_NUMBER_CURRENT_CHANNEL, IPMI_PRIVILEGE_LEVEL_USER, IPMI_GET_IPMI_V15_DATA, obj_cmd) < 0) ipmi_ping_err_exit ("fill_cmd_get_channel_authentication_capabilities: %s", strerror (errno)); } else { if (fill_cmd_get_channel_authentication_capabilities (IPMI_CHANNEL_NUMBER_CURRENT_CHANNEL, IPMI_PRIVILEGE_LEVEL_USER, IPMI_GET_IPMI_V20_EXTENDED_DATA, obj_cmd) < 0) ipmi_ping_err_exit ("fill_cmd_get_channel_authentication_capabilities: %s", strerror (errno)); } if ((len = assemble_ipmi_lan_pkt (obj_rmcp_hdr, obj_lan_session_hdr, obj_lan_msg_hdr, obj_cmd, NULL, 0, buf, buflen, IPMI_INTERFACE_FLAGS_DEFAULT)) < 0) ipmi_ping_err_exit ("assemble_ipmi_lan_pkt: %s", strerror (errno)); if (debug) { char hdrbuf[DEBUG_UTIL_HDR_BUFLEN]; debug_hdr_cmd ((version == IPMI_PING_VERSION_1_5) ? DEBUG_UTIL_TYPE_IPMI_1_5 : DEBUG_UTIL_TYPE_IPMI_2_0, DEBUG_UTIL_DIRECTION_REQUEST, IPMI_NET_FN_APP_RQ, IPMI_CMD_GET_CHANNEL_AUTHENTICATION_CAPABILITIES, 0, hdrbuf, DEBUG_UTIL_HDR_BUFLEN); if (ipmi_dump_lan_packet (STDERR_FILENO, destination, hdrbuf, NULL, buf, len, tmpl_lan_msg_hdr_rq, tmpl_cmd_get_channel_authentication_capabilities_rq) < 0) ipmi_ping_err_exit ("ipmi_dump_lan_packet: %s", strerror (errno)); } fiid_obj_destroy (obj_rmcp_hdr); fiid_obj_destroy (obj_lan_session_hdr); fiid_obj_destroy (obj_lan_msg_hdr); fiid_obj_destroy (obj_cmd); return (len); } int parsepacket (const char *destination, const void *buf, unsigned int buflen, const char *from, unsigned int sequence_number, int verbose, int version, int debug) { fiid_obj_t obj_rmcp_hdr = NULL; fiid_obj_t obj_lan_session_hdr = NULL; fiid_obj_t obj_lan_msg_hdr = NULL; fiid_obj_t obj_cmd = NULL; fiid_obj_t obj_lan_msg_trlr = NULL; uint8_t req_seq, none, md2, md5, straight_password_key, oem, anonymous_login, null_username, non_null_username, user_level_authentication, per_message_authentication, k_g, ipmi_v20_extended_capabilities_available, ipmi_v15, ipmi_v20; uint64_t val; int ret, rv = -1; assert (destination); assert (buf); assert (from); assert (version == IPMI_PING_VERSION_1_5 || version == IPMI_PING_VERSION_2_0); if (!buflen) return (0); if (!(obj_rmcp_hdr = fiid_obj_create (tmpl_rmcp_hdr))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (!(obj_lan_session_hdr = fiid_obj_create (tmpl_lan_session_hdr))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (!(obj_lan_msg_hdr = fiid_obj_create (tmpl_lan_msg_hdr_rs))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (!(obj_cmd = fiid_obj_create (tmpl_cmd_get_channel_authentication_capabilities_rs))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (!(obj_lan_msg_trlr = fiid_obj_create (tmpl_lan_msg_trlr))) ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno)); if (debug) { char hdrbuf[DEBUG_UTIL_HDR_BUFLEN]; debug_hdr_cmd ((version == IPMI_PING_VERSION_1_5) ? DEBUG_UTIL_TYPE_IPMI_1_5 : DEBUG_UTIL_TYPE_IPMI_2_0, DEBUG_UTIL_DIRECTION_RESPONSE, IPMI_NET_FN_APP_RQ, IPMI_CMD_GET_CHANNEL_AUTHENTICATION_CAPABILITIES, 0, hdrbuf, DEBUG_UTIL_HDR_BUFLEN); if (ipmi_dump_lan_packet (STDERR_FILENO, destination, hdrbuf, NULL, buf, buflen, tmpl_lan_msg_hdr_rs, tmpl_cmd_get_channel_authentication_capabilities_rs) < 0) ipmi_ping_err_exit ("ipmi_dump_lan_packet: %s", strerror (errno)); } if ((ret = ipmi_lan_check_packet_checksum (buf, buflen)) < 0) ipmi_ping_err_exit ("ipmi_lan_check_checksum: %s", strerror (errno)); if (!ret) { if (debug) fprintf (stderr, "%s(%d): checksum failed\n", __FUNCTION__, __LINE__); rv = 0; goto cleanup; } if ((ret = unassemble_ipmi_lan_pkt (buf, buflen, obj_rmcp_hdr, obj_lan_session_hdr, obj_lan_msg_hdr, obj_cmd, obj_lan_msg_trlr, IPMI_INTERFACE_FLAGS_DEFAULT)) < 0) ipmi_ping_err_exit ("unassemble_ipmi_lan_pkt: %s", strerror (errno)); if (!ret) { if (debug) fprintf (stderr, "%s(%d): Could not unassemble packet\n", __FUNCTION__, __LINE__); rv = 0; goto cleanup; } if ((ret = ipmi_lan_check_net_fn (obj_lan_msg_hdr, IPMI_NET_FN_APP_RS)) < 0) ipmi_ping_err_exit ("ipmi_lan_check_net_fn: %s", strerror (errno)); if (!ret) { if (debug) fprintf (stderr, "%s(%d): net_fn failed\n", __FUNCTION__, __LINE__); rv = 0; goto cleanup; } if ((ret = ipmi_check_cmd (obj_cmd, IPMI_CMD_GET_CHANNEL_AUTHENTICATION_CAPABILITIES)) < 0) ipmi_ping_err_exit ("ipmi_check_cmd: %s", strerror (errno)); if (!ret) { if (debug) fprintf (stderr, "%s(%d): cmd failed\n", __FUNCTION__, __LINE__); rv = 0; goto cleanup; } if ((ret = ipmi_check_completion_code_success (obj_cmd)) < 0) ipmi_ping_err_exit ("ipmi_check_comp_code: %s", strerror (errno)); if (!ret) { if (debug) fprintf (stderr, "%s(%d): comp_code failed\n", __FUNCTION__, __LINE__); rv = 0; goto cleanup; } if (FIID_OBJ_GET (obj_lan_msg_hdr, "rq_seq", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'rq_seq': %s", fiid_obj_errormsg (obj_lan_msg_hdr)); req_seq = val; if (req_seq != sequence_number % (IPMI_RQ_SEQ_MAX + 1)) { if (debug) fprintf (stderr, "%s(%d): req_seq failed\n", __FUNCTION__, __LINE__); rv = 0; goto cleanup; } printf ("response received from %s: rq_seq=%u", from, req_seq); if (verbose) { if (FIID_OBJ_GET (obj_cmd, "authentication_type.none", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.none': %s", fiid_obj_errormsg (obj_cmd)); none = val; if (FIID_OBJ_GET (obj_cmd, "authentication_type.md2", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.md2': %s", fiid_obj_errormsg (obj_cmd)); md2 = val; if (FIID_OBJ_GET (obj_cmd, "authentication_type.md5", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.md5': %s", fiid_obj_errormsg (obj_cmd)); md5 = val; if (FIID_OBJ_GET (obj_cmd, "authentication_type.straight_password_key", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.straight_password_key': %s", fiid_obj_errormsg (obj_cmd)); straight_password_key = val; if (FIID_OBJ_GET (obj_cmd, "authentication_type.oem_prop", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.oem_prop': %s", fiid_obj_errormsg (obj_cmd)); oem = val; if (FIID_OBJ_GET (obj_cmd, "authentication_status.anonymous_login", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.anonymous_login': %s", fiid_obj_errormsg (obj_cmd)); anonymous_login = val; if (FIID_OBJ_GET (obj_cmd, "authentication_status.null_username", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.null_username': %s", fiid_obj_errormsg (obj_cmd)); null_username = val; if (FIID_OBJ_GET (obj_cmd, "authentication_status.non_null_username", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.non_null_username': %s", fiid_obj_errormsg (obj_cmd)); non_null_username = val; if (FIID_OBJ_GET (obj_cmd, "authentication_status.user_level_authentication", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.user_level_authentication': %s", fiid_obj_errormsg (obj_cmd)); user_level_authentication = val; if (FIID_OBJ_GET (obj_cmd, "authentication_status.per_message_authentication", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.per_message_authentication': %s", fiid_obj_errormsg (obj_cmd)); per_message_authentication = val; if (FIID_OBJ_GET (obj_cmd, "authentication_status.per_message_authentication", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.per_message_authentication': %s", fiid_obj_errormsg (obj_cmd)); per_message_authentication = val; printf (", auth: none=%s md2=%s md5=%s password=%s oem=%s anon=%s null=%s non-null=%s user=%s permsg=%s ", _setstr (none), _setstr (md2), _setstr (md5), _setstr (straight_password_key),_setstr (oem), _setstr (anonymous_login), _setstr (null_username), _setstr (non_null_username), _setstr (user_level_authentication), _setstr (per_message_authentication)); if (version == IPMI_PING_VERSION_2_0) { if (FIID_OBJ_GET (obj_cmd, "authentication_type.ipmi_v2.0_extended_capabilities_available", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.ipmi_v2.0_extended_capabilities_available': %s", fiid_obj_errormsg (obj_cmd)); ipmi_v20_extended_capabilities_available = val; if (FIID_OBJ_GET (obj_cmd, "authentication_status.k_g", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.k_g': %s", fiid_obj_errormsg (obj_cmd)); k_g = val; printf ("k_g=%s ipmi_v2.0_extended_capabilities_available=%s ", _setstr (k_g), _setstr (ipmi_v20_extended_capabilities_available)); if (ipmi_v20_extended_capabilities_available) { if (FIID_OBJ_GET (obj_cmd, "channel_supports_ipmi_v1.5_connections", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'channel_supports_ipmi_v1.5_connections': %s", fiid_obj_errormsg (obj_cmd)); ipmi_v15 = val; if (FIID_OBJ_GET (obj_cmd, "channel_supports_ipmi_v2.0_connections", &val) < 0) ipmi_ping_err_exit ("fiid_obj_get: 'channel_supports_ipmi_v2.0_connections': %s", fiid_obj_errormsg (obj_cmd)); ipmi_v20 = val; printf ("ipmi_v1.5=%s ipmi_v2.0=%s ", _setstr (ipmi_v15), _setstr (ipmi_v20)); } } } printf ("\n"); rv = 1; cleanup: fiid_obj_destroy (obj_rmcp_hdr); fiid_obj_destroy (obj_lan_session_hdr); fiid_obj_destroy (obj_lan_msg_hdr); fiid_obj_destroy (obj_cmd); fiid_obj_destroy (obj_lan_msg_trlr); return (rv); } void latepacket (unsigned int sequence_number) { printf ("response timed out: rq_seq=%u\n", sequence_number % (IPMI_RQ_SEQ_MAX + 1)); } int endresult (const char *progname, const char *dest, unsigned int sent_count, unsigned int recv_count) { double percent = 0; assert (progname); assert (dest); if (sent_count > 0) percent = ((double)(sent_count - recv_count)/sent_count)*100; printf ("--- %s %s statistics ---\n", progname, dest); printf ("%d requests transmitted, %d responses received in time, " "%2.1f%% packet loss\n", sent_count, recv_count, percent); return ((recv_count > 0) ? 0 : 1); } int main (int argc, char **argv) { ipmi_ping_setup (argc, argv, 0, IPMI_RQ_SEQ_MAX, "hVc:i:I:t:vr:s:d"); ipmi_ping_loop (createpacket, parsepacket, latepacket, endresult); exit (EXIT_FAILURE); /* NOT REACHED */ }
chu11/freeipmi
ipmiping/ipmiping.c
C
gpl-3.0
17,845
/* * Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #define USE_OPJ_DEPRECATED /* set this macro to enable profiling for the given test */ /* warning : in order to be effective, openjpeg must have been built with profiling enabled !! */ /*#define _PROFILE*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #ifdef _WIN32 #include <malloc.h> #else #include <stdlib.h> #endif #include "opj_config.h" #include <stdlib.h> #ifdef _WIN32 #include <windows.h> #define strcasecmp _stricmp #define strncasecmp _strnicmp #else #include <strings.h> #endif /* _WIN32 */ #include "openjpeg.h" #include "format_defs.h" /* -------------------------------------------------------------------------- */ /* Declarations */ int get_file_format(const char *filename); static int infile_format(const char *fname); /* -------------------------------------------------------------------------- */ int get_file_format(const char *filename) { unsigned int i; static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" }; static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, RAWL_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT }; char * ext = strrchr(filename, '.'); if (ext == NULL) return -1; ext++; if(ext) { for(i = 0; i < sizeof(format)/sizeof(*format); i++) { if(strcasecmp(ext, extension[i]) == 0) { return format[i]; } } } return -1; } /* -------------------------------------------------------------------------- */ #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a" #define JP2_MAGIC "\x0d\x0a\x87\x0a" /* position 45: "\xff\x52" */ #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51" static int infile_format(const char *fname) { FILE *reader; const char *s, *magic_s; int ext_format, magic_format; unsigned char buf[12]; unsigned int l_nb_read; reader = fopen(fname, "rb"); if (reader == NULL) return -1; memset(buf, 0, 12); l_nb_read = (unsigned int)fread(buf, 1, 12, reader); fclose(reader); if (l_nb_read != 12) return -1; ext_format = get_file_format(fname); if (ext_format == JPT_CFMT) return JPT_CFMT; if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) { magic_format = JP2_CFMT; magic_s = ".jp2"; } else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) { magic_format = J2K_CFMT; magic_s = ".j2k or .jpc or .j2c"; } else return -1; if (magic_format == ext_format) return ext_format; s = fname + strlen(fname) - 4; fputs("\n===========================================\n", stderr); fprintf(stderr, "The extension of this file is incorrect.\n" "FOUND %s. SHOULD BE %s\n", s, magic_s); fputs("===========================================\n", stderr); return magic_format; } /* -------------------------------------------------------------------------- */ /** sample error debug callback expecting no client object */ static void error_callback(const char *msg, void *client_data) { (void)client_data; fprintf(stdout, "[ERROR] %s", msg); } /** sample warning debug callback expecting no client object */ static void warning_callback(const char *msg, void *client_data) { (void)client_data; fprintf(stdout, "[WARNING] %s", msg); } /** sample debug callback expecting no client object */ static void info_callback(const char *msg, void *client_data) { (void)client_data; fprintf(stdout, "[INFO] %s", msg); } /* -------------------------------------------------------------------------- */ int main (int argc, char *argv[]) { opj_dparameters_t l_param; opj_codec_t * l_codec; opj_image_t * l_image; FILE * l_file; opj_stream_t * l_stream; OPJ_UINT32 l_data_size; OPJ_UINT32 l_max_data_size = 1000; OPJ_UINT32 l_tile_index; OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000); OPJ_BOOL l_go_on = OPJ_TRUE; OPJ_UINT32 l_nb_comps=0 ; OPJ_INT32 l_current_tile_x0,l_current_tile_y0,l_current_tile_x1,l_current_tile_y1; int da_x0=0; int da_y0=0; int da_x1=1000; int da_y1=1000; char input_file[64]; /* should be test_tile_decoder 0 0 1000 1000 tte1.j2k */ if( argc == 6 ) { da_x0=atoi(argv[1]); da_y0=atoi(argv[2]); da_x1=atoi(argv[3]); da_y1=atoi(argv[4]); strcpy(input_file,argv[5]); } else { da_x0=0; da_y0=0; da_x1=1000; da_y1=1000; strcpy(input_file,"test.j2k"); } if (! l_data) { return EXIT_FAILURE; } l_file = fopen(input_file,"rb"); if (! l_file) { fprintf(stdout, "ERROR while opening input file\n"); free(l_data); return EXIT_FAILURE; } l_stream = opj_stream_create_default_file_stream(l_file,OPJ_TRUE); if (!l_stream){ fclose(l_file); free(l_data); fprintf(stderr, "ERROR -> failed to create the stream from the file\n"); return EXIT_FAILURE; } /* Set the default decoding parameters */ opj_set_default_decoder_parameters(&l_param); /* */ l_param.decod_format = infile_format(input_file); /** you may here add custom decoding parameters */ /* do not use layer decoding limitations */ l_param.cp_layer = 0; /* do not use resolutions reductions */ l_param.cp_reduce = 0; /* to decode only a part of the image data */ /*opj_restrict_decoding(&l_param,0,0,1000,1000);*/ switch(l_param.decod_format) { case J2K_CFMT: /* JPEG-2000 codestream */ { /* Get a decoder handle */ l_codec = opj_create_decompress(OPJ_CODEC_J2K); break; } case JP2_CFMT: /* JPEG 2000 compressed image data */ { /* Get a decoder handle */ l_codec = opj_create_decompress(OPJ_CODEC_JP2); break; } default: { fprintf(stderr, "ERROR -> Not a valid JPEG2000 file!\n"); fclose(l_file); free(l_data); opj_stream_destroy(l_stream); return EXIT_FAILURE; } } /* catch events using our callbacks and give a local context */ opj_set_info_handler(l_codec, info_callback,00); opj_set_warning_handler(l_codec, warning_callback,00); opj_set_error_handler(l_codec, error_callback,00); /* Setup the decoder decoding parameters using user parameters */ if (! opj_setup_decoder(l_codec, &l_param)) { fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n"); fclose(l_file); free(l_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); return EXIT_FAILURE; } /* Read the main header of the codestream and if necessary the JP2 boxes*/ if (! opj_read_header(l_stream, l_codec, &l_image)) { fprintf(stderr, "ERROR -> j2k_to_image: failed to read the header\n"); fclose(l_file); free(l_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); return EXIT_FAILURE; } if (!opj_set_decode_area(l_codec, l_image, da_x0, da_y0,da_x1, da_y1)){ fprintf(stderr, "ERROR -> j2k_to_image: failed to set the decoded area\n"); fclose(l_file); free(l_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(l_image); return EXIT_FAILURE; } while (l_go_on) { if (! opj_read_tile_header( l_codec, l_stream, &l_tile_index, &l_data_size, &l_current_tile_x0, &l_current_tile_y0, &l_current_tile_x1, &l_current_tile_y1, &l_nb_comps, &l_go_on)) { fclose(l_file); free(l_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(l_image); return EXIT_FAILURE; } if (l_go_on) { if (l_data_size > l_max_data_size) { OPJ_BYTE *l_new_data = (OPJ_BYTE *) realloc(l_data, l_data_size); if (! l_new_data) { fclose(l_file); free(l_new_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(l_image); return EXIT_FAILURE; } l_data = l_new_data; l_max_data_size = l_data_size; } if (! opj_decode_tile_data(l_codec,l_tile_index,l_data,l_data_size,l_stream)) { fclose(l_file); free(l_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(l_image); return EXIT_FAILURE; } /** now should inspect image to know the reduction factor and then how to behave with data */ } } if (! opj_end_decompress(l_codec,l_stream)) { fclose(l_file); free(l_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(l_image); return EXIT_FAILURE; } /* Free memory */ fclose(l_file); free(l_data); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(l_image); /* Print profiling*/ /*PROFPRINT();*/ return EXIT_SUCCESS; }
Alexander-M-Waldman/local_currency_site
geodjango/openjpeg-2.0.1/tests/test_tile_decoder.c
C
gpl-3.0
13,343
/* * G. Rilling, last modification: 3.2007 * gabriel.rilling@ens-lyon.fr * * code based on a student project by T. Boustane and G. Quellec, 11.03.2004 * supervised by P. Chainais (ISIMA - LIMOS - Universite Blaise Pascal - Clermont II * email : pchainai@isima.fr). */ /************************************************************************/ /* */ /* GET INPUT DATA */ /* */ /************************************************************************/ input_t get_input(int nlhs,int nrhs,const mxArray *prhs[]) { input_t input; int n,i; double *x,*y,*y_temp,*third,fourth; input.stop_params.threshold = DEFAULT_THRESHOLD; input.stop_params.tolerance = DEFAULT_TOLERANCE; input.allocated_x=0; #ifdef _ALT_MEXERRMSGTXT_ input.error_flag=0; #endif input.max_imfs=0; input.is_circular=false; /* argument checking*/ if (nrhs>5) mexErrMsgTxt("Too many arguments"); if (nrhs<2) mexErrMsgTxt("Not enough arguments"); if (nlhs>2) mexErrMsgTxt("Too many output arguments"); if (!mxIsEmpty(prhs[0])) if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || (mxGetNumberOfDimensions(prhs[0]) > 2)) mexErrMsgTxt("X must be either empty or a double precision real vector."); if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) || (mxGetNumberOfDimensions(prhs[1]) > 2)) mexErrMsgTxt("Y must be a double precision real vector."); /* input reading: x and y */ n=GREATER(mxGetN(prhs[1]),mxGetM(prhs[1])); /* length of vector x */ if (mxIsEmpty(prhs[0])) { input.allocated_x = 1; x = (double *)malloc(n*sizeof(double)); for(i=0;i<n;i++) x[i] = i; } else x=mxGetPr(prhs[0]); y_temp=mxGetPr(prhs[1]); /* Third argument, circularity */ if (nrhs>=3) { if(!mxIsEmpty(prhs[2])) { if (!mxIsLogical(prhs[2]) || mxGetNumberOfElements(prhs[2])!=1){ mexErrMsgTxt("CIRCULARITY must be boolean element"); } else { input.is_circular = (bool)mxGetScalar(prhs[2]); } } } /* fourth argument */ if (nrhs>=4) { if(!mxIsEmpty(prhs[3])) { if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsDouble(prhs[3]) || (mxGetN(prhs[3])!=1 && mxGetM(prhs[3])!=1)) mexErrMsgTxt("STOP must be a real vector of 1 or 2 elements"); i = GREATER(mxGetN(prhs[3]),mxGetM(prhs[3])); if (i>2) mexErrMsgTxt("STOP must be a vector of 1 or 2 elements"); third=mxGetPr(prhs[3]); switch (i) { case 1 : { if (nrhs==4 && *third==(int)*third && *third > 0) {/* third argument is max_imfs */ input.max_imfs=(int)*third; } else {/* third argument is input.stop_params.threshold */ input.stop_params.threshold=*third; } } break; case 2 : { input.stop_params.threshold=third[0]; input.stop_params.tolerance=third[1]; } } /* input checking */ if (input.stop_params.threshold <= 0){ mexErrMsgTxt("threshold must be a positive number"); } if (input.stop_params.threshold >= 1){ mexWarnMsgTxt("threshold should be lower than 1"); } if (input.stop_params.tolerance < 0 || input.stop_params.tolerance >= 1){ mexErrMsgTxt("tolerance must be a real number in [O,1]"); } } } /* fifth argument */ if (nrhs==5) { if (!mxIsEmpty(prhs[4])) { /* if empty -> do nothing */ if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4]) || mxGetN(prhs[4])!=1 || mxGetM(prhs[4])!=1) mexErrMsgTxt("NB_IMFS must be a positive integer"); fourth=*mxGetPr(prhs[4]); if ((unsigned int)fourth != fourth) mexErrMsgTxt("NB_IMFS must be a positive integer"); input.max_imfs=(int)fourth; } } /* more input checking */ if (!input.allocated_x && (SMALLER(mxGetN(prhs[0]),mxGetM(prhs[0]))!=1 || SMALLER(mxGetN(prhs[1]),mxGetM(prhs[1]))!=1)) mexErrMsgTxt("X and Y must be vectors"); if (GREATER(mxGetN(prhs[1]),mxGetM(prhs[1]))!=n) mexErrMsgTxt("X and Y must have the same length"); i=1; while (i<n && x[i]>x[i-1]) i++; if (i<n) mexErrMsgTxt("Values in X must be non decreasing"); /* copy vector y to avoid erasing input data */ y=(double *)malloc(n*sizeof(double)); for (i=0;i<n;i++){ y[i]=y_temp[i]; } input.n=n; input.x=x; input.y=y; return input; } /************************************************************************/ /* */ /* INITIALIZATION OF THE LIST */ /* */ /************************************************************************/ imf_list_t init_imf_list(int n) { imf_list_t list; list.first=NULL; list.last=NULL; list.n=n; list.m=0; return list; } /************************************************************************/ /* */ /* ADD AN IMF TO THE LIST */ /* */ /************************************************************************/ void add_imf(imf_list_t *list,double *p,int nb_it) { double *v=(double *)malloc(list->n*sizeof(double)); int i; imf_t *mode=(imf_t *)malloc(sizeof(imf_t)); for (i=0;i<list->n;i++) v[i]=p[i]; mode->pointer=v; mode->nb_iterations=nb_it; mode->next=NULL; if (!list->first) { list->first=mode; } else { (list->last)->next=mode; } list->last=mode; list->m++; } /************************************************************************/ /* */ /* FREE MEMORY ALLOCATED FOR THE LIST */ /* */ /************************************************************************/ void free_imf_list(imf_list_t list) { imf_t *current=list.first, *previous; while (current) { previous=current; current=current->next; free(previous->pointer); free(previous); } } /************************************************************************/ /* */ /* OUTPUT INTO MATLAB ARRAY */ /* */ /************************************************************************/ void write_output(imf_list_t list,mxArray *plhs[]) { double *out1,*out2; imf_t *current; int i=0,j,m=list.m,n=list.n; plhs[0]=mxCreateDoubleMatrix(m,n,mxREAL); out1=mxGetPr(plhs[0]); plhs[1]=mxCreateDoubleMatrix(1,m-1,mxREAL); out2=mxGetPr(plhs[1]); for (current=list.first;current;current=current->next) { for (j=0;j<n;j++){ *(out1+j*m+i)=current->pointer[j]; } if (i<m-1) *(out2+i)=current->nb_iterations; i++; } }
pintomollo/asset
MEX/io.c
C
gpl-3.0
7,428
/***************************************************************************** * Written by Chris Dunlap <cdunlap@llnl.gov>. * Copyright (C) 2007-2021 Lawrence Livermore National Security, LLC. * Copyright (C) 2001-2007 The Regents of the University of California. * UCRL-CODE-2002-009. * * This file is part of ConMan: The Console Manager. * For details, see <https://dun.github.io/conman/>. * * ConMan 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. * * ConMan 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 ConMan. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ /* FIXME: * This code does not fully handle the following cases: * - when the watched directory does not yet exist * - when the watched directory is later deleted * In the event of the watched directory not yet existing, this code should * watch the parent directory for its subsequent creation; if the parent * does not yet exist, it should watch the parent's parent, etc., up to the * root. This might be best accomplished by initially registering all of * parent directories up to the root for the directory being watched. * In the event of the watched directory being deleted (event IN_IGNORED), * once the existing watch has been removed, this should degenerate into the * case above where the watched directory does not yet exist. * * Currently, inotify works as expected as long as the parent directory being * watched persists for the lifetime of the daemon. But once that * directory's inode is removed, the daemon falls back to using timers to * periodically resurrect downed objects. */ #if HAVE_CONFIG_H # include <config.h> #endif /* HAVE_CONFIG_H */ /***************************************************************************** * Stubbed Routines for building without <sys/inotify.h>. * * These routines preserve type-checking while allowing any decent compiler * to optimize the case of simply returning a constant integer such that * no function call overhead is incurred. *****************************************************************************/ #if ! HAVE_SYS_INOTIFY_H #include "inevent.h" int inevent_add (const char *filename, inevent_cb_f cb_fnc, void *cb_arg) { return (-1); } int inevent_remove (const char *filename) { return (-1); } int inevent_get_fd (void) { return (-1); } int inevent_process (void) { return (-1); } /***************************************************************************** * Routines for building with <sys/inotify.h> (Linux 2.6.13+). *****************************************************************************/ #else /* HAVE_SYS_INOTIFY_H */ #include <assert.h> #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <unistd.h> #include "inevent.h" #include "list.h" #include "log.h" #include "util-file.h" /***************************************************************************** * Constants *****************************************************************************/ /* Number of bytes for the average inotify event (w/ 16 bytes for name). */ #define INEVENT_SIZE ((sizeof (struct inotify_event)) + 16) /* Number of average inotify events to process per read invocation. */ #define INEVENT_NUM 128 /* Number of bytes to allocate for the inotify event buffer. */ #define INEVENT_BUF_LEN ((INEVENT_SIZE) * (INEVENT_NUM)) /***************************************************************************** * Internal Data Types *****************************************************************************/ struct inevent { char *pathname; /* pathname being watched */ char *dirname; /* directory component of pathname */ char *filename; /* filename component of pathname */ inevent_cb_f cb_fnc; /* callback function */ void *cb_arg; /* callback function arg */ int wd; /* inotify watch descriptor */ }; typedef struct inevent inevent_t; /***************************************************************************** * Private Function Prototypes *****************************************************************************/ static int _inevent_init (void); static void _inevent_fini (void); static inevent_t * _inevent_create (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg); static void _inevent_destroy (inevent_t *inevent_ptr); static int _list_find_by_path (const inevent_t *inevent_ptr, const char *pathname); static int _list_find_by_wd (const inevent_t *inevent_ptr, const int *wd_ptr); static int _list_find_by_event (const inevent_t *inevent_ptr, const struct inotify_event *event_ptr); /***************************************************************************** * Internal Data Variables *****************************************************************************/ static int inevent_fd = -1; /* inotify file descriptor */ static List inevent_list = NULL; /* list of inevent structs */ /***************************************************************************** * Public Functions *****************************************************************************/ int inevent_add (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg) { /* Adds an inotify event for [pathname], causing [cb_fnc] to be invoked with * [cb_arg] whenever the specified file is created. * Returns 0 on success, or -1 on error. */ inevent_t *inevent_ptr; if (pathname == NULL) { log_msg (LOG_ERR, "inotify event pathname not specified"); return (-1); } if (cb_fnc == NULL) { log_msg (LOG_ERR, "inotify event callback not specified"); return (-1); } if (pathname[0] != '/') { log_msg (LOG_ERR, "inotify event path \"%s\" is not absolute", pathname); return (-1); } if (inevent_fd == -1) { if (_inevent_init () < 0) { log_msg (LOG_ERR, "unable to initialize inotify: %s", strerror (errno)); return (-1); } } if (list_find_first (inevent_list, (ListFindF) _list_find_by_path, (void *) pathname)) { log_msg (LOG_ERR, "inotify event path \"%s\" already specified", pathname); return (-1); } inevent_ptr = _inevent_create (pathname, cb_fnc, cb_arg); if (inevent_ptr == NULL) { return (-1); } list_append (inevent_list, inevent_ptr); return (0); } int inevent_remove (const char *pathname) { /* Removes the inotify event (if present) for [pathname]. * Returns 0 on success, or -1 on error. */ ListIterator li = NULL; inevent_t *inevent_ptr; int wd_cnt; if (pathname == NULL) { return (0); } if (inevent_list == NULL) { return (0); } li = list_iterator_create (inevent_list); inevent_ptr = list_find (li, (ListFindF) _list_find_by_path, (void *) pathname); if (inevent_ptr == NULL) { log_msg (LOG_ERR, "inotify event path \"%s\" not registered", pathname); list_iterator_destroy (li); return (0); } (void) list_remove (li); list_iterator_reset (li); wd_cnt = 0; while (list_find (li, (ListFindF) _list_find_by_wd, &(inevent_ptr->wd))) { wd_cnt++; } list_iterator_destroy (li); /* If no other inevents were found with a matching wd, then this inevent * is the only one associated with this watch descriptor. As such, the * watch associated with this watch descriptor can be removed since no * other objects are relying on it. * Note that multiple files may share the same watch descriptor since it * is the file's directory that is watched. */ if ((inevent_ptr->wd >= 0) && (wd_cnt == 0)) { (void) inotify_rm_watch (inevent_fd, inevent_ptr->wd); DPRINTF((10, "Removed inotify watch wd=%d for directory \"%s\".\n", inevent_ptr->wd, inevent_ptr->dirname)); } _inevent_destroy (inevent_ptr); if (list_is_empty (inevent_list)) { _inevent_fini (); } return (0); } int inevent_get_fd (void) { /* Returns the file descriptor associated with the inotify event queue, * or -1 on error. */ return (inevent_fd); } int inevent_process (void) { /* Processes the callback functions for all available events in the inotify * event queue. * Returns the number of events processed on success, or -1 on error. */ char buf [INEVENT_BUF_LEN]; int len; int n = 0; if (inevent_fd == -1) { return (-1); } retry_read: len = read (inevent_fd, buf, sizeof (buf)); if (len < 0) { if (errno == EINTR) { goto retry_read; } log_msg (LOG_ERR, "unable to read inotify fd: %s", strerror (errno)); return (-1); } else if (len == 0) { log_msg (LOG_ERR, "inotify read buffer is too small"); return (-1); } else { unsigned int i = 0; uint32_t event_mask = IN_CREATE | IN_MOVED_TO; while (i < (unsigned int) len) { struct inotify_event *event_ptr; inevent_t *inevent_ptr; event_ptr = (struct inotify_event *) &buf[i]; DPRINTF((15, "Received inotify event wd=%d mask=0x%x len=%u name=\"%s\".\n", event_ptr->wd, event_ptr->mask, event_ptr->len, (event_ptr->len > 0 ? event_ptr->name : ""))); if (event_ptr->mask & IN_IGNORED) { (void) list_delete_all (inevent_list, (ListFindF) _list_find_by_wd, &(event_ptr->wd)); } else if ((event_ptr->mask & event_mask) && (event_ptr->len > 0)) { inevent_ptr = list_find_first (inevent_list, (ListFindF) _list_find_by_event, event_ptr); if ((inevent_ptr != NULL) && (inevent_ptr->cb_fnc != NULL)) { inevent_ptr->cb_fnc (inevent_ptr->cb_arg); } } i += sizeof (struct inotify_event) + event_ptr->len; n++; } } return (n); } /***************************************************************************** * Private Functions *****************************************************************************/ static int _inevent_init (void) { /* Initializes the inotify event subsystem. * Returns 0 on success, or -1 on error (with errno set). */ assert (inevent_fd == -1); assert (inevent_list == NULL); if (inevent_fd == -1) { inevent_fd = inotify_init (); if (inevent_fd == -1) { goto err; } set_fd_closed_on_exec (inevent_fd); set_fd_nonblocking (inevent_fd); } if (inevent_list == NULL) { inevent_list = list_create ((ListDelF) _inevent_destroy); if (inevent_list == NULL) { goto err; } } DPRINTF((5, "Initialized inotify event subsystem.\n")); return (inevent_fd); err: _inevent_fini (); return (-1); } static void _inevent_fini (void) { /* Shuts down the inotify event subsystem. */ assert (inevent_fd >= 0); assert (inevent_list != NULL); if (inevent_fd >= 0) { (void) close (inevent_fd); inevent_fd = -1; } if (inevent_list != NULL) { list_destroy (inevent_list); inevent_list = NULL; } DPRINTF((5, "Shut down inotify event subsystem.\n")); return; } static inevent_t * _inevent_create (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg) { /* Creates an inotify event object for [cb_fnc] to be invoked with [cb_arg] * whenever the file specified by [pathname] is created. * Returns a pointer to the new object on success, or NULL on error * (with errno set). */ inevent_t *inevent_ptr = NULL; char *p; uint32_t event_mask = IN_CREATE | IN_MOVED_TO; assert (pathname != NULL); assert (pathname[0] == '/'); assert (cb_fnc != NULL); inevent_ptr = malloc (sizeof (*inevent_ptr)); if (inevent_ptr == NULL) { goto err; } memset (inevent_ptr, 0, sizeof (*inevent_ptr)); inevent_ptr->wd = -1; inevent_ptr->pathname = strdup (pathname); if (inevent_ptr->pathname == NULL) { goto err; } inevent_ptr->dirname = strdup (pathname); if (inevent_ptr->dirname == NULL) { goto err; } p = strrchr (inevent_ptr->dirname, '/'); inevent_ptr->filename = strdup (p + 1); if (inevent_ptr->filename == NULL) { goto err; } if (p == inevent_ptr->dirname) { /* dirname is root directory ("/") */ *++p = '\0'; } else { *p = '\0'; } inevent_ptr->cb_fnc = cb_fnc; inevent_ptr->cb_arg = cb_arg; inevent_ptr->wd = inotify_add_watch (inevent_fd, inevent_ptr->dirname, event_mask); if (inevent_ptr->wd == -1) { goto err; } DPRINTF((10, "Added inotify watch wd=%d for \"%s\".\n", inevent_ptr->wd, inevent_ptr->pathname)); return (inevent_ptr); err: _inevent_destroy (inevent_ptr); return (NULL); } static void _inevent_destroy (inevent_t *inevent_ptr) { /* Destroys the inotify event object referenced by [inevent_ptr]. */ assert (inevent_ptr != NULL); if (inevent_ptr == NULL) { return; } DPRINTF((10, "Removed inotify watch wd=%d for \"%s\".\n", inevent_ptr->wd, inevent_ptr->pathname)); if (inevent_ptr->pathname != NULL) { free (inevent_ptr->pathname); } if (inevent_ptr->dirname != NULL) { free (inevent_ptr->dirname); } if (inevent_ptr->filename != NULL) { free (inevent_ptr->filename); } free (inevent_ptr); return; } static int _list_find_by_path (const inevent_t *inevent_ptr, const char *pathname) { /* List function helper to match items in a list of inevent_t pointers using * the pathname [pathname] as the key. * Returns non-zero if the key is found; o/w, returns zero. */ assert (inevent_ptr != NULL); assert (pathname != NULL); return (strcmp (inevent_ptr->pathname, pathname) == 0); } static int _list_find_by_wd (const inevent_t *inevent_ptr, const int *wd_ptr) { /* List function helper to match items in a list of inevent_t pointers using * a pointer to an inotify watch descriptor [wd_ptr] as the key. * Returns non-zero if the key is found; o/w, returns zero. */ assert (inevent_ptr != NULL); assert (wd_ptr != NULL); return (inevent_ptr->wd == *wd_ptr); } static int _list_find_by_event (const inevent_t *inevent_ptr, const struct inotify_event *event_ptr) { /* List function helper to match items in a list of inevent_t pointers using * a pointer to an inotify_event struct [event_ptr] as the key. * Returns non-zero if the key is found; o/w, returns zero. */ assert (inevent_ptr != NULL); assert (inevent_ptr->filename != NULL); assert (event_ptr != NULL); assert (event_ptr->len > 0); assert (event_ptr->name != NULL); return ((inevent_ptr->wd == event_ptr->wd) && (strcmp (inevent_ptr->filename, event_ptr->name) == 0)); } #endif /* HAVE_SYS_INOTIFY_H */
dun/conman
inevent.c
C
gpl-3.0
16,114
//cmdtypist: the main of cmdtypist /* Program title: CMDTYPIST Author: Chiatiah Calson License: GPL 3 or later versions Date and Time: 5 July 2017 @ 10:40PM Program Size: 2.8MB */ #include<math.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<ctype.h> #include <unistd.h> //cmdtypist.c: Implementing the main #include"functions_for_cmd_typist.h"//function prototypes and global variables. #include"display.h"//display fixing #include"utils.h"//useful functions #include"files.h"//file manipulations #include"config.h"//configuration #include"terminal.h"//manipulating the terminal char argv[5][18]; int main(int argc, char **argv)//argc=command line counter, argv=pointer to pointer to character(command line arguments) { redirect(); lmt_pg_size(); name_display(); read_message_conf();//welcome message for first time users. int lesson_choice=1;//global variable to hold the number corresponding to the chosen lesson. //char commands[][10]={"0ls","1edituser","2myown","3--help","4man","5mkuser","6mkrand","7mkstd", "8select","9chblk","10sound","11--off","12--on","13cch","14reset","15timeset","16atv","17raw"}; char commands[][10]={"ls","edituser","myown","--help","man","mkuser","mkrand","mkstd", "select","chblk","sound","--off","--on","cch","reset","timeset","atv","raw"}; if(argc<1||argc>3) { fprintf(stderr, "%s\n", "Invalid number of arguments to cmdtypist"); exit(EXIT_FAILURE); } switch(argc)//switching command depending on the number of command line arguments. { case 1: if(read_myown_config()!=0) { lesson_list();//list all lessons present. select_lesson(argc,&lesson_choice); } main_play(argc,&lesson_choice); break; case 2: if(strcmp(argv[1],commands[2])==0) { write_myown_config(0); main_play(argc,&lesson_choice); } else if(strcmp(argv[1],commands[13])==0) { write_myown_config(1); lesson_list(); select_lesson(argc,&lesson_choice); system("clear"); main_play(argc,&lesson_choice); } else if(strcmp(argv[1],commands[3])==0) { FILE *fp; if((fp=fopen("help.md","r"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } while((ch=getc(fp))!=EOF) printf("%c", ch); puts(""); if(fclose(fp)) { fprintf(stderr, "%s\n", "Fatal Error, Unable to close some files\n"); exit(EXIT_FAILURE); } } else if(strcmp(argv[1],commands[4])==0) { FILE *fp; if((fp=fopen("Readme.txt","r"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } while((ch=getc(fp))!=EOF) printf("%c", ch); } else if(strcmp(argv[1],commands[6])==0) write_conf_mode(0); else if(strcmp(argv[1],commands[7])==0) write_conf_mode(1); else if(strcmp(argv[1],commands[14])==0) { printf("%s","Will reset to default; continue? [y/n]:"); if(get_only_char()=='n') exit(EXIT_SUCCESS); reset_default_config(argv[2],argc); printf("%s\n","Settings reset to default"); exit(EXIT_SUCCESS); } else if(strcmp(argv[1],commands[16])==0) { adapt_to_ver(); exit(EXIT_SUCCESS); } else if(strcmp(argv[1],commands[0])==0) { lesson_list(); select_lesson(argc,&lesson_choice); main_play(argc,&lesson_choice); } else fprintf(stderr, "%s\n", "Ensure the second argument is corrrectly spelled"); break; case 3: if(strcmp(argv[1],commands[5])==0) { test_new_user(argv[2]); lesson_list(); select_lesson(argc,&lesson_choice); main_play(argc,&lesson_choice); } else if(strcmp(argv[1],commands[14])==0&&strcmp(argv[2],commands[17])==0) { reset_default_config(argv[2],argc); exit(EXIT_SUCCESS); } else if(strcmp(argv[1],commands[8])==0) { if(read_myown_config()==1) lesson_choice = range_verifier(is_integral(argv[2],argc)); else { lesson_choice=1; fprintf(stderr, "%s\n\n", "You have been redirected here because you are typing in \"myown\""); } main_play(argc,&lesson_choice); } /* else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--on")==0)//modifying system sound { sound_config_write(1); exit(EXIT_SUCCESS); } else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--off")==0) { sound_config_write(0); exit(EXIT_SUCCESS); }*/ else if((strcmp(argv[1],commands[10])==0))//modifying system sound { if(strcmp(argv[2],commands[12])==0) { sound_config_write(1); exit(EXIT_SUCCESS); } else if(strcmp(argv[2],commands[11])==0) { sound_config_write(0); exit(EXIT_SUCCESS); } else { fprintf(stderr, "%s\n", "Check argument 3 for errors, can be \"--on or --off\""); exit(EXIT_SUCCESS); } } else if(strcmp(argv[1],commands[9])==0) { write_conf_block_read(is_integral(argv[2],argc)); exit(EXIT_SUCCESS); } break; /*case 4://later update if((strcmp(argv[1],"timeset")==0))//testing if user wants to play for specific amount of time. { if(strcmp(argv[2],"--on")==0) { time_set=1; main_play(); } else { fprintf(stderr, "%s\n", "Argument 3 invalid or not recognized"); exit(EXIT_SUCCESS); } }*/ default: fprintf(stderr, "%s\n", "Argument is invalid, use \"help\" to find out more"); break; } return 0; } void select_lesson(int argc_cmd, int* user_choice) { char firstarg[81];// if(argc_cmd>0&&argc_cmd<4)//checking on the command line argument. { char ch;// printf("%s", "Enter command >>"); while(scanf("%s",firstarg)!=1||(scanf("%d",&*user_choice))!=1||*user_choice<1||*user_choice>15||strncmp(firstarg,"select",6)!=0)//Ensuring that "select" { //is entered accurately and the selected value is within the correct range. if((strncmp(firstarg,"se",2)==0||strcmp(firstarg,"sel")==0||strcmp(firstarg,"sele")==0||strcmp(firstarg,"selec")==0)&&strcmp(firstarg,"select")!=0) //Making suggestion to help user prevent errors. fprintf(stderr, "\n%s\n%s", "Did you mean \"select usernumber\"","Enter command >>"); else if(ch!=1&&strcmp(firstarg,"select")==0) printf("%s%s", "Lesson number cannot contain symbols or alphas\n","Enter command >>"); else if((*user_choice<1||*user_choice>20)&&strcmp(firstarg,"select")==0) fprintf(stderr, "%s %d\n", "No lesson entry for ",*user_choice); else printf("%s\nEnter command >>", "Command not found"); while(ch=getchar()!='\n');//disposing off wrong input string. } } else { fprintf(stderr, "%s\n", "Invalid number of arguments, consult \"cmdtypist --help\" for more"); exit(EXIT_FAILURE); } /* if(argc_cmd==3) if(strncmp(argv[2],"select",6)!=0||lesson_choice<1||lesson_choice>20) { fprintf(stderr, "%s\n", "Command not found\n"); if(strncmp(argv[2],"se",2)) fprintf(stderr, "%s\n", "Did you mean \"select\""); else if(lesson_choice<1||lesson_choice>20) fprintf(stderr, "%s %d\n", "No lesson entry for ",lesson_choice); //else if(ch!=1) printf("%s", "Lesson number cannot contain symbols or alpha letters.\n"); exit(EXIT_FAILURE); }*/ printf("\n"); } void urs_or_cchl(void) { if(read_myown_config()==0) { strcpy(file_to_read,"my_own.txt"); mode=1; } else if(read_myown_config()==1) strcpy(file_to_read,"noslaclessons.txt"); else { fprintf(stderr, "%s\n", "Fatal Error, lesson file corrupted or does not exist"); exit(EXIT_FAILURE); } } void lesson_position(long *read_this_length,long *point_to,int *my_choice)//setting up the pointer in a position of the file to start reading. { FILE *lesson_point; urs_or_cchl(); if((lesson_point=fopen(file_to_read,"r+"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } if(read_myown_config()==0) { rewind(lesson_point);//return to beginning *read_this_length=read_file_size(lesson_point); *point_to=0; } else switch(*my_choice) { case 1: *point_to=0; if(read_myown_config()==1) *read_this_length=25510; break; case 2: *point_to=25512L; *read_this_length=21660; break; case 3: *point_to=39326L; *read_this_length=397417; break; case 4: *point_to=444591L; *read_this_length=11142; break; case 5: *point_to=455733L; *read_this_length=98588; break; case 6: *point_to=554321L; *read_this_length=19564; break; case 7: *point_to=573885L; *read_this_length=79999; break; case 8: *point_to=653884L; *read_this_length=327523; break; case 9: *point_to=981407L; *read_this_length=208614; break; case 10: *point_to=1190021L; *read_this_length=400980; break; case 11: *point_to=1591001L; *read_this_length=625353; break; case 12: *point_to=2216354L; *read_this_length=1132581; break; default: *point_to=0; } if(fclose(lesson_point)) { fprintf(stderr, "%s\n", "Unable to close lesson file"); exit(EXIT_FAILURE); } } void main_play(int argc_cmd,int *lesson_choice) { //lmt_pg_size(); char terminate=0; long length_to_read;//holds information on how long the text to be read is. long move_lesson_to; lesson_position(&length_to_read,&move_lesson_to,lesson_choice); unsigned short block_count=0; user_test();//test if a user already exists or not. long num_of_chars_typed=0; block_length=read_conf_block_read(); mode=read_conf_mode(); urs_or_cchl();//selects file to read from remove_ext_ascii();//removes any non ascii 7 bits characters from lesson file. unsigned int start_time,elapsed_time=0;//elapsed_time: time used during the typing session measured from start time. unsigned short number_of_lines_count=1;//used to count the total number of lines to print. const unsigned short chars_to_read=77;//total number of characters to read for each line. unsigned int i=0;//counter variable for loop counting. char linetype[150];//char array to hold the total number of characters to to read from file per line. //lesson_list(); //fseek(noslac_lessonsp,25531L,SEEK_SET);//places the pointer to the position of the file to read. int wrong_letters=0;//sums up the total number of wrong characters entered during program run. srand((unsigned)time(NULL));//randomizing seed FILE *noslac_lessonsp;//lesson pointer if((noslac_lessonsp=fopen(file_to_read,"r"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } fseek(noslac_lessonsp,move_lesson_to,SEEK_SET); while(block_count <= (int)(length_to_read/((chars_to_read+1) * block_length)))//testing inorder to read the entire lesson chosen. { num_of_chars_typed=0; char time_checker=0;//changes back to zero after every block typing /*goes =reads a certain number of characters in the file using a loop determined by the random generator and places the pointer at the end of it's reading. thereby making the lesson each time to be random*/ if(mode==0) { int u=0;//counter while(u<=rand()%(length_to_read-((chars_to_read+1)*block_length))&&(ch=getc(noslac_lessonsp))!=EOF)//program feels new u++; do fseek(noslac_lessonsp,-2L,SEEK_CUR); while((ch=getc(noslac_lessonsp))!=' ');//moving backwards from where it is placed //to start reading from where there is a space or has found an uppercase letter. } number_of_lines_count=1; while(number_of_lines_count<=block_length)//testing for number of lines to read. { i=0; char endl = guess(14, 33);//endl holds the char to end a line in place of usual '\n' char startl = guess(14, 33); //guess generates a random char while(i <= chars_to_read)//test on i to get 77 characters. the screen size is exactly 77 characters. { linetype[i] = getc(noslac_lessonsp);//getting characters and placing in the linetype array. if(linetype[0] == ' ')//prevent a the start of a line from ever being a space character linetype[0] = startl; //replace with random char if(linetype[chars_to_read] == ' ')//ensuring a line does not end with a space character. linetype[chars_to_read] = '-';//replacing space character at the end of a line with a - if(i > 1) if(linetype[i-1] == ' ' && linetype[i] == ' ')//preventing two consecutive space characters since text read is random. i -= 2; //checking and eliminating newlines to prevent brakes. if(linetype[i]=='\n'){ linetype[i] = endl; linetype[++i] = ' '; } if(linetype[i]==EOF)//making sure a line does not contain any end of file character by any chance { fprintf(stderr, "%s\n", "Closed unexpectedly, <possibly a corrupt cmdtypist file OR you haven't placed any text in myown.txt>"); exit(EXIT_FAILURE); } i++; } linetype[i]='\0';//Adding string terminator and subtracting the number of spaces removed. if((number_of_lines_count % (block_length)) == 0 && number_of_lines_count != 0) printf(""LAST_LINE_BLUE""); else printf(""RESET""); puts(linetype);//using puts inorder to print the a line and move to the next for the user to follow number_of_lines_count++; i=0;//setting i to 0 to begin new counting. unsigned short error_store[3000], j=0;//error_store: array of ints to note the index of a wrong character. while(i <= chars_to_read+1)//adding 1 for the extra enter key after the 77 letters are entered. { int u=0;//loop counter if((ch=getche())!='\n'&&ch!=EOF)//using getche to prevent printing of enter key. { putchar(ch); if(time_checker==0)//Making sure time is initialized only once { time_checker=1; wrong_letters=0;//setting errors to 0 to start next typing session start_time=(unsigned)time(NULL);//to start timing. } } if(ch==EOF) { fprintf(stderr, "%s\n", "Closed unexpectedly, <an unexpected character keyed in>"); exit(EXIT_FAILURE); } if(ch == 27 || ch == '\t')/*testing for ESC character or a tab to exit program. iscntrl ensures a control character is entered to exit the program*/ { terminate=1; letter_clear(1); puts("\n"); break; } if((ch==127 || ch == 8)&& i == 0)//not using '\b' since most terminals are 'cooked' (keys like backspace are handled by terminal driver) //checking for both delete and backspace. letter_clear(adapt_to_ver_read()); else if((ch == 127 || ch == 8) && i > 0)//testing for delete of backspace { i--;//decremting the number of characters entered when backspaced is pressed. letter_clear(adapt_to_ver_read()); j=wrong_letters; while(j>u)//counting from u to j, to find if there is a wrong character stored in the error_store array of ints. { //printf("j=%d and u=%d\n", j,u); if(error_store[j]==i)//checking through the array for errased wrong charactes initially entered. { //also ensuring before any decrement, wrong_letters>0 wrong_letters--;//decrementing the number of wrong letters. /*if(wrong_letters<0) { printf("finally got a case %d\n",wrong_letters); wrong_letters=0; }*/ error_store[j]=-99;//-99 is a value which will never be reached. //this is to mark the erased index as no longer wrong. break;//Ensuring that immediately there is a match, the while loop is escaped for speed. } j--; } } else if(i==78&&ch!='\n') letter_clear(1); else if(ch!=linetype[i]) { if(ch!='\n')//testing for ENTER to prevent its printing by printf which will cause a newline. { num_of_chars_typed++; letter_clear(1);//clearing the wrong character //printf("\a"RED"%c"RESET"",ch );//to print again with color RED. \a is used to include a beep for wrong charater printf("%s%c",(sound_config_read())==1? "\a"RED"":""RED"",ch);//\a is used to include a beep for wrong character entries wrong_letters++; error_store[wrong_letters]=i;//recording the index of a wrong letter u=0; j++; //Incrementing the backspace counter. i++; //incrementing the number of wrong characters entered. } } else { if(ch!='\n')//Preventing printing of newline which causes an escape from current typing position in the console. { letter_clear(1); num_of_chars_typed++; printf(""GREEN"%c"RESET"", ch);//changing color of correct character to green. i++; } } if(ch=='\n'&&i==78) break;//escaping loop when the user keys in an Enter. } printf("%s","\n" ); //Prints two spaces to ensure the two console spaces left are used, so next printing goes to next line. Game console is 80 and 78 is being used. if(terminate==1||argc_cmd==4) break; } elapsed_time = (unsigned)time(NULL) - start_time;/*getting the final time and subtracting from the initial to get the elapsed time*/ block_count++; //printf("lines=%d block = %d\n",number_of_lines_count,block_length ); if(terminate==1)//exiting on tabs and other systme keys { char user_name[81]; if(elapsed_time <= 10) { fprintf(stderr, "%s\n", "Speed not recorded"); printf(""RESET"\n"); exit(EXIT_SUCCESS); } get_user_name(user_name); printf(""GREEN" "); printf("%s", user_name); if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters. wrong_letters=0; write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed); session_style(elapsed_time,wrong_letters,num_of_chars_typed); exit(EXIT_SUCCESS);//display current typing speed and error } if(((number_of_lines_count-1)%block_length)==0) { char user_name[81]; if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters. wrong_letters=0; printf(""GREEN" "); get_user_name(user_name);//reading user name from file to display in session printf("%s", user_name); session_style(elapsed_time,wrong_letters,num_of_chars_typed);//printing session speed details write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);//writing user speed to speed file } } } /*Wrong letters algorithm: if a user is at the first position of the line and presses backspace, then, that backspace is simply cleared and i not incremented the array error_store[] keeps track of the index(the i position of the wrong character) and increments a counter variable j, which which be used as A stop point in a for loop when this stored inex is searched. When ever backspace keyed in(i!=0), i is first decremented and a search is done through out the loop to see if the decremented i was stored in error store, if so, then the user is erasing a wrong character, so the wrong_letters is decremented.*/ /*solving the case where wrong_letters shows a messy value changing it's type to int and making sure it's always greater than 0 */
Noslac/cmd_typist
cmd_typist.c
C
gpl-3.0
19,200
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[5]; atomic_int atom_1_r1_1; atomic_int atom_1_r13_0; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v3_r3 = v2_r1 ^ v2_r1; int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst); int v7_r6 = v6_r4 ^ v6_r4; int v8_r6 = v7_r6 + 1; atomic_store_explicit(&vars[3], v8_r6, memory_order_seq_cst); int v10_r8 = atomic_load_explicit(&vars[3], memory_order_seq_cst); int v11_cmpeq = (v10_r8 == v10_r8); if (v11_cmpeq) goto lbl_LC00; else goto lbl_LC00; lbl_LC00:; atomic_store_explicit(&vars[4], 1, memory_order_seq_cst); int v13_r11 = atomic_load_explicit(&vars[4], memory_order_seq_cst); int v14_r12 = v13_r11 ^ v13_r11; int v17_r13 = atomic_load_explicit(&vars[0+v14_r12], memory_order_seq_cst); int v21 = (v2_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v21, memory_order_seq_cst); int v22 = (v17_r13 == 0); atomic_store_explicit(&atom_1_r13_0, v22, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[3], 0); atomic_init(&vars[2], 0); atomic_init(&vars[0], 0); atomic_init(&vars[4], 0); atomic_init(&vars[1], 0); atomic_init(&atom_1_r1_1, 0); atomic_init(&atom_1_r13_0, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v18 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v19 = atomic_load_explicit(&atom_1_r13_0, memory_order_seq_cst); int v20_conj = v18 & v19; if (v20_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/MP+PPO073.c
C
gpl-3.0
1,993
#include "CAN.h" #include "led.h" #include "delay.h" #include "usart.h" ////////////////////////////////////////////////////////////////////////////////// //±¾³ÌÐòÖ»¹©Ñ§Ï°Ê¹Óã¬Î´¾­×÷ÕßÐí¿É£¬²»µÃÓÃÓÚÆäËüÈκÎÓÃ; //ALIENTEKÕ½½¢STM32¿ª·¢°å //CANÇý¶¯ ´úÂë //ÕýµãÔ­×Ó@ALIENTEK //¼¼ÊõÂÛ̳:www.openedv.com //ÐÞ¸ÄÈÕÆÚ:2012/9/11 //°æ±¾£ºV1.0 //°æȨËùÓУ¬µÁ°æ±Ø¾¿¡£ //Copyright(C) ¹ãÖÝÊÐÐÇÒíµç×ӿƼ¼ÓÐÏÞ¹«Ë¾ 2009-2019 //All rights reserved ////////////////////////////////////////////////////////////////////////////////// //CAN³õʼ»¯ //tsjw:ÖØÐÂͬ²½ÌøԾʱ¼äµ¥Ôª.·¶Î§:1~3; CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq //tbs2:ʱ¼ä¶Î2µÄʱ¼äµ¥Ôª.·¶Î§:1~8; //tbs1:ʱ¼ä¶Î1µÄʱ¼äµ¥Ôª.·¶Î§:1~16; CAN_BS1_1tq ~CAN_BS1_16tq //brp :²¨ÌØÂÊ·ÖƵÆ÷.·¶Î§:1~1024;(ʵ¼ÊÒª¼Ó1,Ò²¾ÍÊÇ1~1024) tq=(brp)*tpclk1 //×¢ÒâÒÔÉϲÎÊýÈκÎÒ»¸ö¶¼²»ÄÜÉèΪ0,·ñÔò»áÂÒ. //²¨ÌØÂÊ=Fpclk1/((tsjw+tbs1+tbs2)*brp); //mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½; //Fpclk1µÄʱÖÓÔÚ³õʼ»¯µÄʱºòÉèÖÃΪ36M,Èç¹ûÉèÖÃCAN_Normal_Init(1,8,7,5,1); //Ôò²¨ÌØÂÊΪ:36M/((1+8+7)*5)=450Kbps //·µ»ØÖµ:0,³õʼ»¯OK; // ÆäËû,³õʼ»¯Ê§°Ü; u8 CAN_Mode_Init(u8 tsjw,u8 tbs2,u8 tbs1,u16 brp,u8 mode) { GPIO_InitTypeDef GPIO_InitStructure; CAN_InitTypeDef CAN_InitStructure; CAN_FilterInitTypeDef CAN_FilterInitStructure; #if CAN_RX0_INT_ENABLE NVIC_InitTypeDef NVIC_InitStructure; #endif RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//ʹÄÜPORTAʱÖÓ RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN2, ENABLE);//ʹÄÜCAN2ʱÖÓ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //¸´ÓÃÍÆÍì GPIO_Init(GPIOB, &GPIO_InitStructure); //³õʼ»¯IO GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//ÉÏÀ­ÊäÈë GPIO_Init(GPIOB, &GPIO_InitStructure);//³õʼ»¯IO //CANµ¥ÔªÉèÖà CAN_InitStructure.CAN_TTCM=DISABLE; //·Çʱ¼ä´¥·¢Í¨ÐÅģʽ // CAN_InitStructure.CAN_ABOM=DISABLE; //Èí¼þ×Ô¶¯ÀëÏß¹ÜÀí // CAN_InitStructure.CAN_AWUM=DISABLE; //˯Ãßģʽͨ¹ýÈí¼þ»½ÐÑ(Çå³ýCAN->MCRµÄSLEEPλ)// CAN_InitStructure.CAN_NART=ENABLE; //½ûÖ¹±¨ÎÄ×Ô¶¯´«ËÍ // CAN_InitStructure.CAN_RFLM=DISABLE; //±¨ÎIJ»Ëø¶¨,еĸ²¸Ç¾ÉµÄ // CAN_InitStructure.CAN_TXFP=DISABLE; //ÓÅÏȼ¶Óɱ¨Îıêʶ·û¾ö¶¨ // CAN_InitStructure.CAN_Mode= mode; //ģʽÉèÖ㺠mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½; // //ÉèÖò¨ÌØÂÊ CAN_InitStructure.CAN_SJW=tsjw; //ÖØÐÂͬ²½ÌøÔ¾¿í¶È(Tsjw)Ϊtsjw+1¸öʱ¼äµ¥Î» CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq CAN_InitStructure.CAN_BS1=tbs1; //Tbs1=tbs1+1¸öʱ¼äµ¥Î»CAN_BS1_1tq ~CAN_BS1_16tq CAN_InitStructure.CAN_BS2=tbs2;//Tbs2=tbs2+1¸öʱ¼äµ¥Î»CAN_BS2_1tq ~ CAN_BS2_8tq CAN_InitStructure.CAN_Prescaler=brp; //·ÖƵϵÊý(Fdiv)Ϊbrp+1 // CAN_Init(CAN2, &CAN_InitStructure); // ³õʼ»¯CAN1 CAN_FilterInitStructure.CAN_FilterNumber=0; //¹ýÂËÆ÷0 CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask; CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit; //32λ CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;////32λID CAN_FilterInitStructure.CAN_FilterIdLow=0x0000; CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;//32λMASK CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000; CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;//¹ýÂËÆ÷0¹ØÁªµ½FIFO0 CAN_FilterInitStructure.CAN_FilterActivation=ENABLE; //¼¤»î¹ýÂËÆ÷0 CAN_FilterInit(&CAN_FilterInitStructure);//Â˲¨Æ÷³õʼ»¯ return 0; } //can·¢ËÍÒ»×éÊý¾Ý(¹Ì¶¨¸ñʽ:IDΪ0X12,±ê×¼Ö¡,Êý¾ÝÖ¡) //len:Êý¾Ý³¤¶È(×î´óΪ8) //msg:Êý¾ÝÖ¸Õë,×î´óΪ8¸ö×Ö½Ú. //·µ»ØÖµ:0,³É¹¦; // ÆäËû,ʧ°Ü; u8 Can_Send_Msg(u8* msg,u8 len) { u8 mbox; u16 i=0; CanTxMsg TxMessage; TxMessage.StdId=0x12; // ±ê×¼±êʶ·ûΪ0 TxMessage.ExtId=0x12; // ÉèÖÃÀ©Õ¹±êʾ·û£¨29룩 TxMessage.IDE=0; // ʹÓÃÀ©Õ¹±êʶ·û TxMessage.RTR=0; // ÏûÏ¢ÀàÐÍΪÊý¾ÝÖ¡£¬Ò»Ö¡8λ TxMessage.DLC=len; // ·¢ËÍÁ½Ö¡ÐÅÏ¢ for(i=0;i<len;i++) TxMessage.Data[i]=msg[i]; // µÚÒ»Ö¡ÐÅÏ¢ mbox= CAN_Transmit(CAN2, &TxMessage); i=0; while((CAN_TransmitStatus(CAN2, mbox)==CAN_TxStatus_Failed)&&(i<0XFFF))i++; //µÈ´ý·¢ËͽáÊø if(i>=0XFFF)return 1; return 0; } //can¿Ú½ÓÊÕÊý¾Ý²éѯ //buf:Êý¾Ý»º´æÇø; //·µ»ØÖµ:0,ÎÞÊý¾Ý±»ÊÕµ½; // ÆäËû,½ÓÊÕµÄÊý¾Ý³¤¶È; u8 Can_Receive_Msg(u8 *buf) { u32 i; CanRxMsg RxMessage; if( CAN_MessagePending(CAN2,CAN_FIFO0)==0)return 0; //ûÓнÓÊÕµ½Êý¾Ý,Ö±½ÓÍ˳ö CAN_Receive(CAN2, CAN_FIFO0, &RxMessage);//¶ÁÈ¡Êý¾Ý for(i=0;i<8;i++) buf[i]=RxMessage.Data[i]; return RxMessage.DLC; }
chempin/stm32f107-
10.CAN/OV/can.c
C
gpl-3.0
4,689
/* Liquid War 6 is a unique multiplayer wargame. Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Christian Mauduit <ufoot@ufoot.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 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/>. Liquid War 6 homepage : http://www.gnu.org/software/liquidwar6/ Contact author : ufoot@ufoot.org */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include <CUnit/CUnit.h> #include "mat.h" int main (int argc, const char *argv[]) { int ret = 0; lw6sys_context_t *sys_context = NULL; int mode = 0; LW6SYS_MAIN_BEGIN (sys_context); lw6sys_log_clear (sys_context, NULL); mode = lw6sys_arg_test_mode (sys_context, argc, argv); if (CU_initialize_registry () == CUE_SUCCESS) { if (lw6mat_test_register (sys_context, mode)) { ret = lw6mat_test_run (sys_context, mode); } CU_cleanup_registry (); } LW6SYS_TEST_OUTPUT; LW6SYS_MAIN_END (sys_context); return (!ret); }
lijiaqigreat/liquidwar-web
reference/src/lib/mat/mat-testmain.c
C
gpl-3.0
1,546
/* Copyright (C) 2005-2012 by George Williams */ /* * 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 name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "fontforgeui.h" #include "groups.h" #include <unistd.h> #include <ustring.h> #include <utype.h> #include <gkeysym.h> #include <math.h> /******************************************************************************/ /******************************** Group Widget ********************************/ /******************************************************************************/ #define COLOR_CHOOSE (-10) static GTextInfo std_colors[] = { { (unichar_t *) N_("Select by Color"), NULL, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' }, { (unichar_t *) N_("Color|Choose..."), NULL, 0, 0, (void *) COLOR_CHOOSE, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' }, { (unichar_t *) N_("Color|Default"), &def_image, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' }, { NULL, &white_image, 0, 0, (void *) 0xffffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &red_image, 0, 0, (void *) 0xff0000, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &green_image, 0, 0, (void *) 0x00ff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &blue_image, 0, 0, (void *) 0x0000ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &yellow_image, 0, 0, (void *) 0xffff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &cyan_image, 0, 0, (void *) 0x00ffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &magenta_image, 0, 0, (void *) 0xff00ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, GTEXTINFO_EMPTY }; struct groupdlg { unsigned int oked: 1; unsigned int done: 1; unsigned int select_many: 1; /* define groups can only select one group at a time, select/restrict */ /* to groups can select multiple things */ unsigned int select_kids_too: 1; /* When we select a parent group do we want to select all the kids? */ Group *root; Group *oldsel; int open_cnt, lines_page, off_top, off_left, page_width, bmargin; int maxl; GWindow gw,v; GGadget *vsb, *hsb, *cancel, *ok, *compact; GGadget *newsub, *delete, *line1, *gpnamelab, *gpname, *glyphslab, *glyphs; GGadget *idlab, *idname, *iduni, *set, *select, *unique, *colour, *line2; int fh, as; GFont *font; FontView *fv; void (*select_callback)(struct groupdlg *); GTimer *showchange; }; extern int _GScrollBar_Width; static Group *GroupFindLPos(Group *group,int lpos,int *depth) { int i; forever { if ( group->lpos==lpos ) return( group ); if ( !group->open ) return( NULL ); for ( i=0; i<group->kid_cnt-1; ++i ) { if ( lpos<group->kids[i+1]->lpos ) break; } group = group->kids[i]; ++*depth; } } static int GroupPosInParent(Group *group) { Group *parent = group->parent; int i; if ( parent==NULL ) return( 0 ); for ( i=0; i<parent->kid_cnt; ++i ) if ( parent->kids[i]==group ) return( i ); return( -1 ); } static Group *GroupNext(Group *group,int *depth) { if ( group->open && group->kids ) { ++*depth; return( group->kids[0] ); } forever { int pos; if ( group->parent==NULL ) return( NULL ); pos = GroupPosInParent(group); if ( pos+1<group->parent->kid_cnt ) return( group->parent->kids[pos+1] ); group = group->parent; --*depth; } } static Group *GroupPrev(struct groupdlg *grp, Group *group,int *depth) { int pos; while ( group->parent!=NULL && group==group->parent->kids[0] ) { group = group->parent; --*depth; } if ( group->parent==NULL ) return( NULL ); pos = GroupPosInParent(group); group = group->parent->kids[pos-1]; while ( group->open ) { group = group->kids[group->kid_cnt-1]; ++*depth; } return( group ); } static int _GroupSBSizes(struct groupdlg *grp, Group *group, int lpos, int depth) { int i, len; group->lpos = lpos++; len = 5+8*depth+ grp->as + 5 + GDrawGetText8Width(grp->v,group->name,-1); if ( group->glyphs!=NULL ) len += 5 + GDrawGetText8Width(grp->v,group->glyphs,-1); if ( len > grp->maxl ) grp->maxl = len; if ( group->open ) { for ( i=0; i< group->kid_cnt; ++i ) lpos = _GroupSBSizes(grp,group->kids[i],lpos,depth+1); } return( lpos ); } static int GroupSBSizes(struct groupdlg *grp) { int lpos; grp->maxl = 0; GDrawSetFont(grp->v,grp->font); lpos = _GroupSBSizes(grp,grp->root,0,0); grp->maxl += 5; /* margin */ GScrollBarSetBounds(grp->vsb,0,lpos,grp->lines_page); GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width); grp->open_cnt = lpos; return( lpos ); } static void GroupSelectKids(Group *group,int sel) { int i; group->selected = sel; for ( i=0; i<group->kid_cnt; ++i ) GroupSelectKids(group->kids[i],sel); } static void GroupDeselectAllBut(Group *root,Group *group) { int i; if ( root!=group ) root->selected = false; for ( i=0; i<root->kid_cnt; ++i ) GroupDeselectAllBut(root->kids[i],group); } static Group *_GroupCurrentlySelected(Group *group) { int i; Group *sel; if ( group->selected ) return( group ); for ( i=0; i<group->kid_cnt; ++i ) { sel = _GroupCurrentlySelected(group->kids[i]); if ( sel!=NULL ) return( sel ); } return( NULL ); } static Group *GroupCurrentlySelected(struct groupdlg *grp) { if ( grp->select_many ) return( NULL ); return( _GroupCurrentlySelected(grp->root)); } static void GroupWExpose(struct groupdlg *grp,GWindow pixmap,GRect *rect) { int depth, y, len; Group *group; GRect r; Color fg; GDrawFillRect(pixmap,rect,GDrawGetDefaultBackground(NULL)); GDrawSetLineWidth(pixmap,0); r.height = r.width = grp->as; y = (rect->y/grp->fh) * grp->fh + grp->as; depth=0; group = GroupFindLPos(grp->root,rect->y/grp->fh+grp->off_top,&depth); GDrawSetFont(pixmap,grp->font); while ( group!=NULL ) { r.y = y-grp->as+1; r.x = 5+8*depth - grp->off_left; fg = group->selected ? 0xff0000 : 0x000000; if ( group->glyphs==NULL ) { GDrawDrawRect(pixmap,&r,fg); GDrawDrawLine(pixmap,r.x+2,r.y+grp->as/2,r.x+grp->as-2,r.y+grp->as/2, fg); if ( !group->open ) GDrawDrawLine(pixmap,r.x+grp->as/2,r.y+2,r.x+grp->as/2,r.y+grp->as-2, fg); } len = GDrawDrawText8(pixmap,r.x+r.width+5,y,group->name,-1,fg); if ( group->glyphs ) GDrawDrawText8(pixmap,r.x+r.width+5+len+5,y,group->glyphs,-1,fg); group = GroupNext(group,&depth); y += grp->fh; if ( y-grp->fh>rect->y+rect->height ) break; } } static void GroupWMouse(struct groupdlg *grp,GEvent *event) { int x; int depth=0; Group *group; group = GroupFindLPos(grp->root,event->u.mouse.y/grp->fh+grp->off_top,&depth); if ( group==NULL ) return; x = 5+8*depth - grp->off_left; if ( event->u.mouse.x<x ) return; if ( event->u.mouse.x<=x+grp->as ) { if ( group->glyphs != NULL ) return; group->open = !group->open; GroupSBSizes(grp); } else { group->selected = !group->selected; if ( grp->select_kids_too ) GroupSelectKids(group,group->selected); else if ( group->selected && !grp->select_many ) GroupDeselectAllBut(grp->root,group); if ( grp->select_callback!=NULL ) (grp->select_callback)(grp); } GDrawRequestExpose(grp->v,NULL,false); } static void GroupScroll(struct groupdlg *grp,struct sbevent *sb) { int newpos = grp->off_top; switch( sb->type ) { case et_sb_top: newpos = 0; break; case et_sb_uppage: newpos -= grp->lines_page; break; case et_sb_up: --newpos; break; case et_sb_down: ++newpos; break; case et_sb_downpage: newpos += grp->lines_page; break; case et_sb_bottom: newpos = grp->open_cnt-grp->lines_page; break; case et_sb_thumb: case et_sb_thumbrelease: newpos = sb->pos; break; } if ( newpos>grp->open_cnt-grp->lines_page ) newpos = grp->open_cnt-grp->lines_page; if ( newpos<0 ) newpos =0; if ( newpos!=grp->off_top ) { int diff = newpos-grp->off_top; grp->off_top = newpos; GScrollBarSetPos(grp->vsb,grp->off_top); GDrawScroll(grp->v,NULL,0,diff*grp->fh); } } static void GroupHScroll(struct groupdlg *grp,struct sbevent *sb) { int newpos = grp->off_left; switch( sb->type ) { case et_sb_top: newpos = 0; break; case et_sb_uppage: newpos -= grp->page_width; break; case et_sb_up: --newpos; break; case et_sb_down: ++newpos; break; case et_sb_downpage: newpos += grp->page_width; break; case et_sb_bottom: newpos = grp->maxl-grp->page_width; break; case et_sb_thumb: case et_sb_thumbrelease: newpos = sb->pos; break; } if ( newpos>grp->maxl-grp->page_width ) newpos = grp->maxl-grp->page_width; if ( newpos<0 ) newpos =0; if ( newpos!=grp->off_left ) { int diff = newpos-grp->off_left; grp->off_left = newpos; GScrollBarSetPos(grp->hsb,grp->off_left); GDrawScroll(grp->v,NULL,-diff,0); } } static void GroupResize(struct groupdlg *grp,GEvent *event) { GRect size, wsize; int lcnt, offy; int sbsize = GDrawPointsToPixels(grp->gw,_GScrollBar_Width); GDrawGetSize(grp->gw,&size); lcnt = (size.height-grp->bmargin)/grp->fh; GGadgetResize(grp->vsb,sbsize,lcnt*grp->fh); GGadgetMove(grp->vsb,size.width-sbsize,0); GGadgetResize(grp->hsb,size.width-sbsize,sbsize); GGadgetMove(grp->hsb,0,lcnt*grp->fh); GDrawResize(grp->v,size.width-sbsize,lcnt*grp->fh); grp->page_width = size.width-sbsize; grp->lines_page = lcnt; GScrollBarSetBounds(grp->vsb,0,grp->open_cnt,grp->lines_page); GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width); GGadgetGetSize(grp->cancel,&wsize); offy = size.height-wsize.height-6 - wsize.y; GGadgetMove(grp->cancel,size.width-wsize.width-30, wsize.y+offy); GGadgetMove(grp->ok , 30-3,wsize.y+offy-3); if ( grp->newsub!=NULL ) { GGadgetGetSize(grp->newsub,&wsize); GGadgetMove(grp->newsub,wsize.x,wsize.y+offy); GGadgetGetSize(grp->delete,&wsize); GGadgetMove(grp->delete,wsize.x,wsize.y+offy); GGadgetGetSize(grp->line1,&wsize); GGadgetMove(grp->line1,wsize.x,wsize.y+offy); GGadgetGetSize(grp->gpnamelab,&wsize); GGadgetMove(grp->gpnamelab,wsize.x,wsize.y+offy); GGadgetGetSize(grp->gpname,&wsize); GGadgetMove(grp->gpname,wsize.x,wsize.y+offy); GGadgetGetSize(grp->glyphslab,&wsize); GGadgetMove(grp->glyphslab,wsize.x,wsize.y+offy); GGadgetGetSize(grp->glyphs,&wsize); GGadgetMove(grp->glyphs,wsize.x,wsize.y+offy); GGadgetGetSize(grp->idlab,&wsize); GGadgetMove(grp->idlab,wsize.x,wsize.y+offy); GGadgetGetSize(grp->idname,&wsize); GGadgetMove(grp->idname,wsize.x,wsize.y+offy); GGadgetGetSize(grp->iduni,&wsize); GGadgetMove(grp->iduni,wsize.x,wsize.y+offy); GGadgetGetSize(grp->set,&wsize); GGadgetMove(grp->set,wsize.x,wsize.y+offy); GGadgetGetSize(grp->select,&wsize); GGadgetMove(grp->select,wsize.x,wsize.y+offy); GGadgetGetSize(grp->unique,&wsize); GGadgetMove(grp->unique,wsize.x,wsize.y+offy); GGadgetGetSize(grp->colour,&wsize); GGadgetMove(grp->colour,wsize.x,wsize.y+offy); GGadgetGetSize(grp->line2,&wsize); GGadgetMove(grp->line2,wsize.x,wsize.y+offy); } else { GGadgetGetSize(grp->compact,&wsize); GGadgetMove(grp->compact,wsize.x,wsize.y+offy); } GDrawRequestExpose(grp->v,NULL,true); GDrawRequestExpose(grp->gw,NULL,true); } static void GroupWChangeCurrent(struct groupdlg *grp,Group *current,Group *next ) { if ( current!=NULL ) current->selected = false; next->selected = true; if ( next->lpos<grp->off_top || next->lpos>=grp->off_top+grp->lines_page ) { if ( next->lpos>=grp->off_top+grp->lines_page ) grp->off_top = next->lpos; else { grp->off_top = next->lpos-grp->lines_page-1; if ( grp->off_top<0 ) grp->off_top = 0; } GScrollBarSetPos(grp->vsb,grp->off_top); GDrawRequestExpose(grp->v,NULL,false); } } static int GroupChar(struct groupdlg *grp,GEvent *event) { int depth = 0; int pos; Group *current = GroupCurrentlySelected(grp); switch (event->u.chr.keysym) { case GK_F1: case GK_Help: help("groups.html"); return( true ); case GK_Return: case GK_KP_Enter: if ( current!=NULL ) { current->open = !current->open; GroupSBSizes(grp); GDrawRequestExpose(grp->v,NULL,false); } return( true ); case GK_Page_Down: case GK_KP_Page_Down: pos = grp->off_top+(grp->lines_page<=1?1:grp->lines_page-1); if ( pos >= grp->open_cnt-grp->lines_page ) pos = grp->open_cnt-grp->lines_page; if ( pos<0 ) pos = 0; grp->off_top = pos; GScrollBarSetPos(grp->vsb,pos); GDrawRequestExpose(grp->v,NULL,false); return( true ); case GK_Down: case GK_KP_Down: if ( current==NULL || (event->u.chr.state&ksm_control)) { if ( grp->off_top<grp->open_cnt-1 ) { ++grp->off_top; GScrollBarSetPos(grp->vsb,grp->off_top); GDrawScroll(grp->v,NULL,0,grp->fh); } } else GroupWChangeCurrent(grp,current,GroupNext(current,&depth)); return( true ); case GK_Up: case GK_KP_Up: if ( current==NULL || (event->u.chr.state&ksm_control)) { if (grp->off_top!=0 ) { --grp->off_top; GScrollBarSetPos(grp->vsb,grp->off_top); GDrawScroll(grp->v,NULL,0,-grp->fh); } } else GroupWChangeCurrent(grp,current,GroupPrev(grp,current,&depth)); return( true ); case GK_Page_Up: case GK_KP_Page_Up: pos = grp->off_top-(grp->lines_page<=1?1:grp->lines_page-1); if ( pos<0 ) pos = 0; grp->off_top = pos; GScrollBarSetPos(grp->vsb,pos); GDrawRequestExpose(grp->v,NULL,false); return( true ); case GK_Left: case GK_KP_Left: if ( !grp->select_many && current!=NULL ) GroupWChangeCurrent(grp,current,current->parent); return( true ); case GK_Right: case GK_KP_Right: if ( !grp->select_many && current != NULL && current->kid_cnt!=0 ) { if ( !current->open ) { current->open = !current->open; GroupSBSizes(grp); } GroupWChangeCurrent(grp,current,current->kids[0]); } return( true ); case GK_Home: case GK_KP_Home: if ( grp->off_top!=0 ) { grp->off_top = 0; GScrollBarSetPos(grp->vsb,0); GDrawRequestExpose(grp->v,NULL,false); } if ( !grp->select_many ) GroupWChangeCurrent(grp,current,grp->root); return( true ); case GK_End: case GK_KP_End: pos = grp->open_cnt-grp->lines_page; if ( pos<0 ) pos = 0; if ( pos!=grp->off_top ) { grp->off_top = pos; GScrollBarSetPos(grp->vsb,pos); GDrawRequestExpose(grp->v,NULL,false); } if ( !grp->select_many ) GroupWChangeCurrent(grp,current,GroupFindLPos(grp->root,grp->open_cnt-1,&depth)); return( true ); } return( false ); } static int grpv_e_h(GWindow gw, GEvent *event) { struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw); if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(grp->vsb,event)); } switch ( event->type ) { case et_expose: GroupWExpose(grp,gw,&event->u.expose.rect); break; case et_char: return( GroupChar(grp,event)); case et_mouseup: GroupWMouse(grp,event); break; } return( true ); } static void GroupWCreate(struct groupdlg *grp,GRect *pos) { FontRequest rq; int as, ds, ld; GGadgetCreateData gcd[5]; GTextInfo label[4]; int sbsize = GDrawPointsToPixels(NULL,_GScrollBar_Width); GWindowAttrs wattrs; static GFont *font=NULL; if ( font==NULL ) { memset(&rq,'\0',sizeof(rq)); rq.utf8_family_name = SANS_UI_FAMILIES; rq.point_size = 12; rq.weight = 400; font = GDrawInstanciateFont(grp->gw,&rq); font = GResourceFindFont("Groups.Font",font); } grp->font = font; GDrawWindowFontMetrics(grp->gw,grp->font,&as,&ds,&ld); grp->fh = as+ds; grp->as = as; grp->lines_page = (pos->height-grp->bmargin)/grp->fh; grp->page_width = pos->width-sbsize; wattrs.mask = wam_events|wam_cursor/*|wam_bordwidth|wam_bordcol*/; wattrs.event_masks = ~0; wattrs.border_width = 1; wattrs.border_color = 0x000000; wattrs.cursor = ct_pointer; pos->x = 0; pos->y = 0; pos->width -= sbsize; pos->height = grp->lines_page*grp->fh; grp->v = GWidgetCreateSubWindow(grp->gw,pos,grpv_e_h,grp,&wattrs); GDrawSetVisible(grp->v,true); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); gcd[0].gd.pos.x = pos->width; gcd[0].gd.pos.y = 0; gcd[0].gd.pos.width = sbsize; gcd[0].gd.pos.height = pos->height; gcd[0].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels | gg_sb_vert; gcd[0].creator = GScrollBarCreate; gcd[1].gd.pos.x = 0; gcd[1].gd.pos.y = pos->height; gcd[1].gd.pos.height = sbsize; gcd[1].gd.pos.width = pos->width; gcd[1].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels; gcd[1].creator = GScrollBarCreate; GGadgetsCreate(grp->gw,gcd); grp->vsb = gcd[0].ret; grp->hsb = gcd[1].ret; } /******************************************************************************/ /******************************** Group Dialogs *******************************/ /******************************************************************************/ static int FindDuplicateNumberInString(int seek,char *str) { char *start; if ( str==NULL ) return( false ); while ( *str!='\0' ) { while ( *str==' ' ) ++str; start = str; while ( *str!=' ' && *str!='\0' ) ++str; if ( start==str ) break; if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) { char *end; int val = strtol(start+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } if ( seek>=val && seek<=val2 ) return( true ); } } return( false ); } static int FindDuplicateNameInString(char *name,char *str) { char *start; if ( str==NULL ) return( false ); while ( *str!='\0' ) { while ( *str==' ' ) ++str; start = str; while ( *str!=' ' && *str!='\0' ) ++str; if ( start==str ) break; if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) /* Skip it */; else { int ch = *str; *str = '\0'; if ( strcmp(name,start)==0 ) { *str = ch; return( true ); } *str = ch; } } return( false ); } static Group *FindDuplicateNumber(Group *top,int val,Group *cur,char *str) { int i; Group *grp; if ( FindDuplicateNumberInString(val,str)) return( cur ); if ( top==cur ) return( NULL ); if ( FindDuplicateNumberInString(val,top->glyphs)) return( top ); for ( i=0; i<top->kid_cnt; ++i ) if ( (grp = FindDuplicateNumber(top->kids[i],val,cur,NULL))!=NULL ) return( grp ); return( NULL ); } static Group *FindDuplicateName(Group *top,char *name,Group *cur,char *str) { int i; Group *grp; if ( FindDuplicateNameInString(name,str)) return( cur ); if ( top==cur ) return( NULL ); if ( FindDuplicateNameInString(name,top->glyphs)) return( top ); for ( i=0; i<top->kid_cnt; ++i ) if ( (grp = FindDuplicateName(top->kids[i],name,cur,NULL))!=NULL ) return( grp ); return( NULL ); } static int GroupValidateGlyphs(Group *cur,char *g,const unichar_t *gu,int unique) { char *gpt, *start; Group *top, *grp; if ( gu!=NULL ) { for ( ; *gu!='\0'; ++gu ) { if ( *gu<' ' || *gu>=0x7f || *gu=='(' || *gu==')' || *gu=='[' || *gu==']' || *gu=='{' || *gu=='}' || *gu=='<' || *gu=='>' || *gu=='%' || *gu=='/' ) { ff_post_error(_("Glyph names must be valid postscript names"),_("Glyph names must be valid postscript names")); return( false ); } } } if ( unique ) { /* Can't use cur->unique because it hasn't been set yet */ top = cur; while ( top->parent!=NULL && top->parent->unique ) top = top->parent; for ( gpt=g; *gpt!='\0' ; ) { while ( *gpt==' ' ) ++gpt; start = gpt; while ( *gpt!=' ' && *gpt!='\0' ) ++gpt; if ( start==gpt ) break; if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) { char *end; int val = strtol(start+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } if ( val2<val ) { ff_post_error(_("Bad Range"),_("Bad Range, start (%1$04X) is greater than end (%2$04X)"), val, val2 ); return( false ); } for ( ; val<=val2; ++val ) if ( (grp=FindDuplicateNumber(top,val,cur,gpt))!=NULL ) { ff_post_error(_("Duplicate Name"),_("The code point U+%1$04X occurs in groups %2$.30s and %3$.30s"), val, cur->name, grp->name); return( false ); } } else { int ch = *gpt; *gpt = '\0'; if ( (grp=FindDuplicateName(top,start,cur,ch!='\0'?gpt+1:NULL))!=NULL ) { ff_post_error(_("Duplicate Name"),_("The glyph name \"%1$.30s\" occurs in groups %2$.30s and %3$.30s"), start, cur->name, grp->name); *gpt = ch; return( false ); } *gpt = ch; } } } return( true ); } static int GroupSetKidsUnique(Group *group) { int i; group->unique = true; for ( i=0; i<group->kid_cnt; ++i ) if ( !GroupSetKidsUnique(group->kids[i])) return( false ); if ( group->glyphs!=NULL ) { if ( !GroupValidateGlyphs(group,group->glyphs,NULL,true)) return( false ); } return( true ); } static int GroupFinishOld(struct groupdlg *grp) { if ( grp->oldsel!=NULL ) { const unichar_t *gu = _GGadgetGetTitle(grp->glyphs); char *g = cu_copy(gu); int oldunique = grp->oldsel->unique; if ( !GroupValidateGlyphs(grp->oldsel,g,gu,GGadgetIsChecked(grp->unique))) { free(g); return( false ); } free(grp->oldsel->name); grp->oldsel->name = GGadgetGetTitle8(grp->gpname); free(grp->oldsel->glyphs); if ( *g=='\0' ) { grp->oldsel->glyphs = NULL; free(g); } else grp->oldsel->glyphs = g; grp->oldsel->unique = GGadgetIsChecked(grp->unique); if ( grp->oldsel->unique && !oldunique ) { /* The just set the unique bit. We must force it set in all */ /* kids. We really should check for uniqueness too!!!!! */ if ( !GroupSetKidsUnique(grp->oldsel)) return( false ); } } return( true ); } static void GroupSelected(struct groupdlg *grp) { Group *current = GroupCurrentlySelected(grp); if ( !GroupFinishOld(grp)) { if ( current!=NULL ) current->selected=false; if ( grp->oldsel!=NULL ) grp->oldsel->selected = true; return; } grp->oldsel = current; if ( current == NULL ) { GGadgetSetEnabled(grp->newsub,false); GGadgetSetEnabled(grp->delete,false); GGadgetSetEnabled(grp->gpnamelab,false); GGadgetSetEnabled(grp->gpname,false); GGadgetSetEnabled(grp->glyphslab,false); GGadgetSetEnabled(grp->glyphs,false); GGadgetSetEnabled(grp->set,false); GGadgetSetEnabled(grp->select,false); GGadgetSetEnabled(grp->unique,false); GGadgetSetEnabled(grp->colour,false); } else { unichar_t *glyphs = uc_copy(current->glyphs); GGadgetSetTitle8(grp->gpname,current->name); if ( glyphs==NULL ) glyphs = uc_copy(""); GGadgetSetTitle(grp->glyphs,glyphs); free(glyphs); GGadgetSetChecked(grp->unique,current->unique); GGadgetSetEnabled(grp->newsub,current->glyphs==NULL || *current->glyphs=='\0'); GGadgetSetEnabled(grp->delete,current->parent!=NULL); GGadgetSetEnabled(grp->gpnamelab,true); GGadgetSetEnabled(grp->gpname,true); GGadgetSetEnabled(grp->glyphslab,current->kid_cnt==0); GGadgetSetEnabled(grp->glyphs,current->kid_cnt==0); GGadgetSetEnabled(grp->set,current->kid_cnt==0); GGadgetSetEnabled(grp->select,current->kid_cnt==0); GGadgetSetEnabled(grp->unique,current->parent==NULL || !current->parent->unique); GGadgetSetEnabled(grp->colour,current->kid_cnt==0); } } static void GroupShowChange(struct groupdlg *grp) { if ( GroupFinishOld(grp)) GDrawRequestExpose(grp->v,NULL,false); grp->showchange = NULL; } static int Group_GlyphListChanged(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); const unichar_t *glyphs = _GGadgetGetTitle(g); GGadgetSetEnabled(grp->newsub,*glyphs=='\0'); if ( grp->showchange!=NULL ) GDrawCancelTimer(grp->showchange); grp->showchange = GDrawRequestTimer(grp->gw,500,0,NULL); } return( true ); } static int Group_ToSelection(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); const unichar_t *ret = _GGadgetGetTitle(grp->glyphs); SplineFont *sf = grp->fv->b.sf; FontView *fv = grp->fv; const unichar_t *end; int pos, found=-1; char *nm; GDrawSetVisible(fv->gw,true); GDrawRaise(fv->gw); memset(fv->b.selected,0,fv->b.map->enccount); while ( *ret ) { end = u_strchr(ret,' '); if ( end==NULL ) end = ret+u_strlen(ret); nm = cu_copybetween(ret,end); for ( ret = end; isspace(*ret); ++ret); if ( (nm[0]=='U' || nm[0]=='u') && nm[1]=='+' ) { char *end; int val = strtol(nm+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } for ( ; val<=val2; ++val ) { if (( pos = SFFindSlot(sf,fv->b.map,val,NULL))!=-1 ) { if ( found==-1 ) found = pos; if ( pos!=-1 ) fv->b.selected[pos] = true; } } } else if ( strncasecmp(nm,"color=#",strlen("color=#"))==0 ) { Color col = strtoul(nm+strlen("color=#"),NULL,16); int gid; SplineChar *sc; for ( pos=0; pos<fv->b.map->enccount; ++pos ) if ( (gid=fv->b.map->map[pos])!=-1 && (sc = sf->glyphs[gid])!=NULL && sc->color == col ) fv->b.selected[pos] = true; } else { if (( pos = SFFindSlot(sf,fv->b.map,-1,nm))!=-1 ) { if ( found==-1 ) found = pos; if ( pos!=-1 ) fv->b.selected[pos] = true; } } free(nm); } if ( found!=-1 ) FVScrollToChar(fv,found); GDrawRequestExpose(fv->v,NULL,false); } return( true ); } static int Group_FromSelection(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); SplineFont *sf = grp->fv->b.sf; FontView *fv = grp->fv; unichar_t *vals, *pt; int i, len, max, gid, k; SplineChar *sc, dummy; char buffer[20]; if ( GGadgetIsChecked(grp->idname) ) { for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) { gid = fv->b.map->map[i]; if ( gid!=-1 && sf->glyphs[gid]!=NULL ) sc = sf->glyphs[gid]; else sc = SCBuildDummy(&dummy,sf,fv->b.map,i); len += strlen(sc->name)+1; if ( fv->b.selected[i]>max ) max = fv->b.selected[i]; } pt = vals = galloc((len+1)*sizeof(unichar_t)); *pt = '\0'; for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) { gid = fv->b.map->map[i]; if ( gid!=-1 && sf->glyphs[gid]!=NULL ) sc = sf->glyphs[gid]; else sc = SCBuildDummy(&dummy,sf,fv->b.map,i); uc_strcpy(pt,sc->name); pt += u_strlen(pt); *pt++ = ' '; } if ( pt>vals ) pt[-1]='\0'; } else { vals = NULL; for ( k=0; k<2; ++k ) { int last=-2, start=-2; len = 0; for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) { gid = fv->b.map->map[i]; if ( gid!=-1 && sf->glyphs[gid]!=NULL ) sc = sf->glyphs[gid]; else sc = SCBuildDummy(&dummy,sf,fv->b.map,i); if ( sc->unicodeenc==-1 ) continue; if ( sc->unicodeenc==last+1 ) last = sc->unicodeenc; else { if ( last!=-2 ) { if ( start!=last ) sprintf( buffer, "U+%04X-U+%04X ", start, last ); else sprintf( buffer, "U+%04X ", start ); if ( vals!=NULL ) uc_strcpy(vals+len,buffer); len += strlen(buffer); } start = last = sc->unicodeenc; } } if ( last!=-2 ) { if ( start!=last ) sprintf( buffer, "U+%04X-U+%04X ", start, last ); else sprintf( buffer, "U+%04X ", start ); if ( vals!=NULL ) uc_strcpy(vals+len,buffer); len += strlen(buffer); } if ( !k ) vals = galloc((len+1)*sizeof(unichar_t)); else if ( len!=0 ) vals[len-1] = '\0'; else *vals = '\0'; } } GGadgetSetTitle(grp->glyphs,vals); free(vals); } return( true ); } static int Group_AddColor(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); GTextInfo *ti = GGadgetGetListItemSelected(g); int set=false; Color xcol=0; if ( ti==NULL ) /* Can't happen */; else if ( ti->userdata == (void *) COLOR_CHOOSE ) { struct hslrgb col, font_cols[6]; memset(&col,0,sizeof(col)); col = GWidgetColor(_("Pick a color"),&col,SFFontCols(grp->fv->b.sf,font_cols)); if ( col.rgb ) { xcol = (((int) rint(255.*col.r))<<16 ) | (((int) rint(255.*col.g))<<8 ) | (((int) rint(255.*col.b)) ); set = true; } } else { xcol = (intpt) ti->userdata; set = true; } if ( set ) { char buffer[40]; unichar_t ubuf[40]; sprintf(buffer," color=#%06x", xcol ); uc_strcpy(ubuf,buffer); GTextFieldReplace(grp->glyphs,ubuf); if ( grp->showchange==NULL ) GroupShowChange(grp); } GGadgetSelectOneListItem(g,0); } return( true ); } static int Group_NewSubGroup(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); Group *new_grp; if ( !GroupFinishOld(grp)) return( true ); GDrawRequestExpose(grp->v,NULL,false); if ( grp->oldsel==NULL ) return( true ); if ( grp->oldsel->glyphs!=NULL && grp->oldsel->glyphs!='\0' ) { GGadgetSetEnabled(grp->newsub,false); return( true ); } grp->oldsel->kids = grealloc(grp->oldsel->kids,(++grp->oldsel->kid_cnt)*sizeof(Group *)); grp->oldsel->kids[grp->oldsel->kid_cnt-1] = new_grp = chunkalloc(sizeof(Group)); new_grp->parent = grp->oldsel; new_grp->unique = grp->oldsel->unique; new_grp->name = copy(_("UntitledGroup")); grp->oldsel->selected = false; grp->oldsel->open = true; new_grp->selected = true; GroupSBSizes(grp); GroupSelected(grp); GDrawRequestExpose(grp->v,NULL,false); } return( true ); } static int Group_Delete(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); Group *parent; int pos, i; if ( grp->oldsel==NULL || grp->oldsel->parent==NULL ) return( true ); parent = grp->oldsel->parent; pos = GroupPosInParent(grp->oldsel); if ( pos==-1 ) return( true ); for ( i=pos; i<parent->kid_cnt-1; ++i ) parent->kids[i] = parent->kids[i+1]; --parent->kid_cnt; GroupFree(grp->oldsel); grp->oldsel = NULL; GroupSBSizes(grp); GroupSelected(grp); GDrawRequestExpose(grp->v,NULL,false); } return( true ); } static int displaygrp_e_h(GWindow gw, GEvent *event) { struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw); if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(grp->vsb,event)); } if ( grp==NULL ) return( true ); switch ( event->type ) { case et_expose: break; case et_char: return( GroupChar(grp,event)); break; case et_timer: GroupShowChange(grp); break; case et_resize: if ( event->u.resize.sized ) GroupResize(grp,event); break; case et_controlevent: switch ( event->u.control.subtype ) { case et_scrollbarchange: if ( event->u.control.g == grp->vsb ) GroupScroll(grp,&event->u.control.u.sb); else GroupHScroll(grp,&event->u.control.u.sb); break; case et_buttonactivate: grp->done = true; grp->oked = event->u.control.g == grp->ok; break; } break; case et_close: grp->done = true; break; case et_destroy: if ( grp->newsub!=NULL ) free(grp); return( true ); } if ( grp->done && grp->newsub!=NULL ) { if ( grp->oked ) { if ( !GroupFinishOld(grp)) { grp->done = grp->oked = false; return( true ); } GroupFree(group_root); if ( grp->root->kid_cnt==0 && grp->root->glyphs==NULL ) { group_root = NULL; GroupFree(grp->root); } else group_root = grp->root; SaveGroupList(); } else GroupFree(grp->root); GDrawDestroyWindow(grp->gw); } return( true ); } void DefineGroups(FontView *fv) { struct groupdlg *grp; GRect pos; GWindowAttrs wattrs; GGadgetCreateData gcd[20]; GTextInfo label[19]; int h, k,kk; grp = gcalloc(1,sizeof(*grp)); grp->fv = fv; grp->select_many = grp->select_kids_too = false; grp->select_callback = GroupSelected; if ( group_root==NULL ) { grp->root = chunkalloc(sizeof(Group)); grp->root->name = copy(_("Groups")); } else grp->root = GroupCopy(group_root); memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.is_dlg = true; wattrs.restrict_input_to_me = false; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Define Groups"); pos.x = pos.y = 0; pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200)); pos.height = h = GDrawPointsToPixels(NULL,482); grp->gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,grp,&wattrs); grp->bmargin = GDrawPointsToPixels(NULL,248)+GDrawPointsToPixels(grp->gw,_GScrollBar_Width); GroupWCreate(grp,&pos); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); k = 0; gcd[k].gd.pos.x = 20; gcd[k].gd.pos.y = GDrawPixelsToPoints(NULL,h-grp->bmargin)+12; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("New Sub-Group"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = Group_NewSubGroup; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.width = -1; gcd[k].gd.pos.x = GDrawPixelsToPoints(NULL,(pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor))); gcd[k].gd.pos.y = gcd[k-1].gd.pos.y; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("_Delete"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = Group_Delete; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLineCreate; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+8; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("Group Name:"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GLabelCreate; gcd[k].gd.pos.x = 80; gcd[k].gd.pos.width = 115; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-3; gcd[k].gd.flags = gg_visible; gcd[k++].creator = GTextFieldCreate; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-2].gd.pos.y+16; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("Glyphs:"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GLabelCreate; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+14; gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-10; gcd[k].gd.pos.height = 4*13+4; gcd[k].gd.flags = gg_visible | gg_enabled | gg_textarea_wrap; gcd[k].gd.handle_controlevent = Group_GlyphListChanged; gcd[k++].creator = GTextAreaCreate; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+gcd[k-1].gd.pos.height+5; gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; label[k].text = (unichar_t *) _("Identify by"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired."); gcd[k++].creator = GLabelCreate; gcd[k].gd.pos.x = 90; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-2; label[k].text = (unichar_t *) _("Name"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = (gg_visible | gg_enabled | gg_cb_on | gg_utf8_popup); gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired."); gcd[k++].creator = GRadioCreate; gcd[k].gd.pos.x = 140; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y; label[k].text = (unichar_t *) _("Unicode"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired."); gcd[k++].creator = GRadioCreate; label[k].text = (unichar_t *) _("Set From Font"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+18; gcd[k].gd.popup_msg = (unichar_t *) _("Set this glyph list to be the glyphs selected in the fontview"); gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k].gd.handle_controlevent = Group_FromSelection; gcd[k++].creator = GButtonCreate; label[k].text = (unichar_t *) _("Select In Font"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 110; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y; gcd[k].gd.popup_msg = (unichar_t *) _("Set the fontview's selection to be the glyphs named here"); gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k].gd.handle_controlevent = Group_ToSelection; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26; label[k].text = (unichar_t *) _("No Glyph Duplicates"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Glyph names (or unicode code points) may occur at most once in this group and any of its sub-groups"); gcd[k++].creator = GCheckBoxCreate; for ( kk=0; kk<3; ++kk ) std_colors[kk].text = (unichar_t *) S_((char *) std_colors[kk].text); std_colors[1].image = GGadgetImageCache("colorwheel.png"); std_colors[0].selected = true; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+15; gcd[k].gd.label = &std_colors[0]; gcd[k].gd.u.list = std_colors; gcd[k].gd.handle_controlevent = Group_AddColor; gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k++].creator = GListButtonCreate; gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+28; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLineCreate; gcd[k].gd.pos.width = -1; gcd[k].gd.pos.x = 30; gcd[k].gd.pos.y = h-GDrawPointsToPixels(NULL,32); gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels; label[k].text = (unichar_t *) _("_OK"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.width = -1; gcd[k].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor)); gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+3; gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels; label[k].text = (unichar_t *) _("_Cancel"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GButtonCreate; GGadgetsCreate(grp->gw,gcd); grp->newsub = gcd[0].ret; grp->delete = gcd[1].ret; grp->line1 = gcd[2].ret; grp->gpnamelab = gcd[3].ret; grp->gpname = gcd[4].ret; grp->glyphslab = gcd[5].ret; grp->glyphs = gcd[6].ret; grp->idlab = gcd[7].ret; grp->idname = gcd[8].ret; grp->iduni = gcd[9].ret; grp->set = gcd[10].ret; grp->select = gcd[11].ret; grp->unique = gcd[12].ret; grp->colour = gcd[13].ret; grp->line2 = gcd[14].ret; grp->ok = gcd[15].ret; grp->cancel = gcd[16].ret; GroupSBSizes(grp); GroupResize(grp,NULL); GDrawSetVisible(grp->gw,true); } static void MapEncAddGid(EncMap *map,SplineFont *sf, int compacted, int gid, int uni, char *name) { if ( compacted && gid==-1 ) return; if ( gid!=-1 && map->backmap[gid]==-1 ) map->backmap[gid] = map->enccount; if ( map->enccount>=map->encmax ) map->map = grealloc(map->map,(map->encmax+=100)*sizeof(int)); map->map[map->enccount++] = gid; if ( !compacted ) { Encoding *enc = map->enc; if ( enc->char_cnt>=enc->char_max ) { enc->unicode = grealloc(enc->unicode,(enc->char_max+=256)*sizeof(int)); enc->psnames = grealloc(enc->psnames,enc->char_max*sizeof(char *)); } if ( uni==-1 && name!=NULL ) { if ( gid!=-1 && sf->glyphs[gid]!=NULL ) uni = sf->glyphs[gid]->unicodeenc; else uni = UniFromName(name,ui_none,&custom); } enc->unicode[enc->char_cnt] = uni; enc->psnames[enc->char_cnt++] = copy( name ); } } static void MapAddGroupGlyph(EncMap *map,SplineFont *sf,char *name, int compacted) { int gid; if ( (name[0]=='u' || name[0]=='U') && name[1]=='+' && ishexdigit(name[2])) { char *end; int val = strtol(name+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } for ( ; val<=val2; ++val ) { gid = SFFindExistingSlot(sf,val,NULL); MapEncAddGid(map,sf,compacted,gid,val,NULL); } } else if ( strncasecmp(name,"color=#",strlen("color=#"))==0 ) { Color col = strtoul(name+strlen("color=#"),NULL,16); int gid; SplineChar *sc; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc = sf->glyphs[gid])!=NULL && sc->color == col ) MapEncAddGid(map,sf,compacted,gid,sc->unicodeenc,NULL); } else { gid = SFFindExistingSlot(sf,-1,name); MapEncAddGid(map,sf,compacted,gid,-1,name); } } static int MapAddSelectedGroups(EncMap *map,SplineFont *sf,Group *group, int compacted) { int i, cnt=0; char *start, *pt; int ch; if ( group->glyphs==NULL ) { for ( i=0; i<group->kid_cnt; ++i ) cnt += MapAddSelectedGroups(map,sf,group->kids[i], compacted); } else if ( group->selected ) { for ( pt=group->glyphs; *pt!='\0'; ) { while ( *pt==' ' ) ++pt; start = pt; while ( *pt!=' ' && *pt!='\0' ) ++pt; ch = *pt; *pt='\0'; if ( *start!='\0' ) MapAddGroupGlyph(map,sf,start, compacted); *pt=ch; } ++cnt; } return( cnt ); } static int GroupSelCnt(Group *group, Group **first, Group **second) { int cnt = 0, i; if ( group->glyphs==NULL ) { for ( i=0; i<group->kid_cnt; ++i ) cnt += GroupSelCnt(group->kids[i],first,second); } else if ( group->selected ) { if ( *first==NULL ) *first = group; else if ( *second==NULL ) *second = group; ++cnt; } return( cnt ); } static char *EncNameFromGroups(Group *group) { Group *first = NULL, *second = NULL; int cnt = GroupSelCnt(group,&first,&second); char *prefix = P_("Group","Groups",cnt); char *ret; switch ( cnt ) { case 0: return( copy( _("No Groups")) ); case 1: ret = galloc(strlen(prefix) + strlen(first->name) + 3 ); sprintf( ret, "%s: %s", prefix, first->name); break; case 2: ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 5 ); sprintf( ret, "%s: %s, %s", prefix, first->name, second->name ); break; default: ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 9 ); sprintf( ret, "%s: %s, %s ...", prefix, first->name, second->name ); break; } return( ret ); } static void EncodeToGroups(FontView *fv,Group *group, int compacted) { SplineFont *sf = fv->b.sf; EncMap *map; if ( compacted ) map = EncMapNew(0,sf->glyphcnt,&custom); else { Encoding *enc = gcalloc(1,sizeof(Encoding)); enc->enc_name = EncNameFromGroups(group); enc->is_temporary = true; enc->char_max = 256; enc->unicode = galloc(256*sizeof(int32)); enc->psnames = galloc(256*sizeof(char *)); map = EncMapNew(0,sf->glyphcnt,enc); } if ( MapAddSelectedGroups(map,sf,group,compacted)==0 ) { ff_post_error(_("Nothing Selected"),_("Nothing Selected")); EncMapFree(map); } else if ( map->enccount==0 ) { ff_post_error(_("Nothing Selected"),_("None of the glyphs in the current font match any names or code points in the selected groups")); EncMapFree(map); } else { fv->b.selected = grealloc(fv->b.selected,map->enccount); memset(fv->b.selected,0,map->enccount); EncMapFree(fv->b.map); fv->b.map = map; FVSetTitle((FontViewBase *) fv); FontViewReformatOne((FontViewBase *) fv); } } void DisplayGroups(FontView *fv) { struct groupdlg grp; GRect pos; GWindowAttrs wattrs; GGadgetCreateData gcd[6]; GTextInfo label[5]; int h; memset( &grp,0,sizeof(grp)); grp.fv = fv; grp.select_many = grp.select_kids_too = true; grp.root = group_root; if ( grp.root==NULL ) { grp.root = chunkalloc(sizeof(Group)); grp.root->name = copy(_("Groups")); } memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.is_dlg = true; wattrs.restrict_input_to_me = 1; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Display By Groups"); pos.x = pos.y = 0; pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200)); pos.height = h = GDrawPointsToPixels(NULL,317); grp.gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,&grp,&wattrs); grp.bmargin = GDrawPointsToPixels(NULL,50)+GDrawPointsToPixels(grp.gw,_GScrollBar_Width); GroupWCreate(&grp,&pos); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); gcd[0].gd.pos.width = -1; gcd[0].gd.pos.x = 30; gcd[0].gd.pos.y = h-GDrawPointsToPixels(NULL,30); gcd[0].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels; label[0].text = (unichar_t *) _("_OK"); label[0].text_is_1byte = true; label[0].text_in_resource = true; gcd[0].gd.label = &label[0]; gcd[0].creator = GButtonCreate; gcd[1].gd.pos.width = -1; gcd[1].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor)); gcd[1].gd.pos.y = gcd[0].gd.pos.y+3; gcd[1].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels; label[1].text = (unichar_t *) _("_Cancel"); label[1].text_is_1byte = true; label[1].text_in_resource = true; gcd[1].gd.label = &label[1]; gcd[1].creator = GButtonCreate; gcd[2].gd.pos.width = -1; gcd[2].gd.pos.x = 10; gcd[2].gd.pos.y = gcd[0].gd.pos.y-GDrawPointsToPixels(NULL,17); gcd[2].gd.flags = gg_visible | gg_enabled | gg_cb_on | gg_pos_in_pixels; label[2].text = (unichar_t *) _("Compacted"); label[2].text_is_1byte = true; label[2].text_in_resource = true; gcd[2].gd.label = &label[2]; gcd[2].creator = GCheckBoxCreate; GGadgetsCreate(grp.gw,gcd); grp.ok = gcd[0].ret; grp.cancel = gcd[1].ret; grp.compact = gcd[2].ret; GroupSBSizes(&grp); GDrawSetVisible(grp.gw,true); while ( !grp.done ) GDrawProcessOneEvent(NULL); GDrawSetUserData(grp.gw,NULL); if ( grp.oked ) EncodeToGroups(fv,grp.root, GGadgetIsChecked(gcd[2].ret)); if ( grp.root!=group_root ) GroupFree(grp.root); GDrawDestroyWindow(grp.gw); }
rakeshyeka/PDFprocessor
pdf2htmlEX/fontforge-pdf2htmlEX/fontforgeexe/groupsdlg.c
C
gpl-3.0
50,023
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[5]; atomic_int atom_1_r1_1; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v3_r3 = v2_r1 ^ v2_r1; int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst); int v7_r6 = v6_r4 ^ v6_r4; atomic_store_explicit(&vars[3+v7_r6], 1, memory_order_seq_cst); int v9_r9 = atomic_load_explicit(&vars[3], memory_order_seq_cst); int v10_r10 = v9_r9 ^ v9_r9; atomic_store_explicit(&vars[4+v10_r10], 1, memory_order_seq_cst); int v12_r13 = atomic_load_explicit(&vars[4], memory_order_seq_cst); int v13_cmpeq = (v12_r13 == v12_r13); if (v13_cmpeq) goto lbl_LC00; else goto lbl_LC00; lbl_LC00:; atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); int v18 = (v2_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v18, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[3], 0); atomic_init(&vars[1], 0); atomic_init(&vars[0], 0); atomic_init(&vars[2], 0); atomic_init(&vars[4], 0); atomic_init(&atom_1_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v14 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v15 = (v14 == 2); int v16 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v17_conj = v15 & v16; if (v17_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/S+PPO645.c
C
gpl-3.0
1,822
/* ============================================================================ Name : lcd_scroll_text.c Author : Kiran N <niekiran@gmail.com > Version : 1.0 Copyright : Your copyright notice Description : This application prints pre-stored strings on a LCD panel with shifting/scrolling effect TODOs for the students 1) Take multiple strings as a command line argumentsinstead of pre-stored. ============================================================================*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <poll.h> #include<stdint.h> #include <time.h> #include <math.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <arpa/inet.h> #include "lcd_driver.h" #include "gpio_driver.h" #include "lcd_text_scroll.h" /*========================================================================================================= BBB_expansion_heade_P8_pins GPIO number 16x2 LCD pin Purpose =========================================================================================================== P8.7 GPIO_66 4(RS) Register selection (Character vs. Command) P8.8 GPIO_67 5(RW) Read/write P8.9 GPIO_69 6(EN) Enable P8.10 GPIO_68 7(D4) Data line 4 P8.11 GPIO_45 8(D5) Data line 5 P8.12 GPIO_44 9(D6) Data line 6 P8.14 GPIO_26 10(D7) Data line 7 P8.16 GPIO_46 15(BKLTA) Backlight anode P9.15 GPIO_48 16(BKLTK) Backlight cathode ============================================================================================================= */ char* some_strings[]= { "Mahatma Gandhi said,", "First they ignore you,", "then they laugh at you ", "then they fight with you,", "then you win !", }; /* This function initializes all the gpios for this application * TODO : Error handling implementation */ int initialize_all_gpios(void) { /* first lets export all the GPIOs */ gpio_export(GPIO_66_P8_7_RS_4); gpio_export(GPIO_67_P8_8_RW_5); gpio_export(GPIO_69_P8_9_EN_6); gpio_export(GPIO_68_P8_10_D4_11); gpio_export(GPIO_45_P8_11_D5_12); gpio_export(GPIO_44_P8_12_D6_13); gpio_export(GPIO_26_P8_14_D7_14); /*first configure the direction for LCD pins */ gpio_configure_dir(GPIO_66_P8_7_RS_4,GPIO_DIR_OUT); gpio_configure_dir(GPIO_67_P8_8_RW_5,GPIO_DIR_OUT); gpio_configure_dir(GPIO_69_P8_9_EN_6,GPIO_DIR_OUT); gpio_configure_dir(GPIO_68_P8_10_D4_11,GPIO_DIR_OUT); gpio_configure_dir(GPIO_45_P8_11_D5_12,GPIO_DIR_OUT); gpio_configure_dir(GPIO_44_P8_12_D6_13,GPIO_DIR_OUT); gpio_configure_dir(GPIO_26_P8_14_D7_14,GPIO_DIR_OUT); return 0; } /* This function gathers the ip address of the system and prints it on LCD */ int print_ip_address() { int fd; struct ifreq ifr; char iface[] = "usb0"; fd = socket(AF_INET, SOCK_DGRAM, 0); //Type of address to retrieve - IPv4 IP address ifr.ifr_addr.sa_family = AF_INET; //Copy the interface name in the ifreq structure strncpy(ifr.ifr_name , iface , IFNAMSIZ-1); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); //display result lcd_printf("%s - %s\n" , iface , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) ); return 0; } /* Some silly graphics :) */ void tansition_graphics(void) { sleep(1); lcd_set_cursor(1,1); lcd_send_command(LCD_CMD_CLEAR_DISPLAY); for (uint8_t n =0 ; n < 2 ; n++) { for(uint8_t i=0;i<16;i++) { lcd_print_char('*'); usleep(75*1000); } lcd_set_cursor(2,16); lcd_send_command(0x04); } lcd_set_cursor(1,1); lcd_send_command(0x06); usleep(450 * 1000); lcd_send_command(LCD_CMD_CLEAR_DISPLAY); } int main(int argc, char *argv[]) { printf("Application to print text in scrollable fashion on LCD\n"); initialize_all_gpios(); gpio_write_value(GPIO_66_P8_7_RS_4,LOW_VALUE); /*The RW pin is always tied to ground in this implementation, meaning that you are only writing to the display and never reading from it.*/ gpio_write_value(GPIO_67_P8_8_RW_5,LOW_VALUE); /*• The EN pin is used to tell the LCD when data is ready*/ gpio_write_value(GPIO_69_P8_9_EN_6,LOW_VALUE); /*Data pins 4~7 are used for actually transmitting data, and data pins 0~3 are left unconnected*/ gpio_write_value(GPIO_68_P8_10_D4_11,LOW_VALUE); gpio_write_value(GPIO_45_P8_11_D5_12,LOW_VALUE); gpio_write_value(GPIO_44_P8_12_D6_13,LOW_VALUE); gpio_write_value(GPIO_26_P8_14_D7_14,LOW_VALUE); /* You can illuminate the backlight by connecting the anode pin to 5V and the cathode pin to ground if you are using an LCD with a built-in resistor for the backlight. If you are not, you must put a current-limiting resistor in-line with the anode or cathode pin. The datasheet for your device will generally tell you if you need to do this. */ uint8_t cmd=0; lcd_init(); //setting function // only single line mode is chosen here , that means all the 80 characters of the DDRAM will be mapped to lcd line 1. cmd= LCD_CMD_FUNCTION_SET | DATA_LEN_4 | DISPLAY_1_LINE | MATRIX_5_X_8; lcd_send_command(cmd); //3.display on/off control , no cursor cmd = LCD_CMD_DISPLAY_CURSOR_ONOFF_CONTROL |DISPLAY_ON |CURSOR_OFF ; lcd_send_command(cmd); lcd_send_command(LCD_CMD_CLEAR_DISPLAY yo); //lets start printing from extreme right end of first row of the lcd. . lcd_set_cursor( 1,17); #if 1 char *ptr = NULL; uint8_t i; while(1) { //we have total five strings. for ( i = 0 ;i < 5 ; i++) { //print till each string meets NULL char ptr= some_strings[i]; while( *ptr != '\0' ) { lcd_print_char((uint8_t)*ptr); //printing one character at a time and then left shifting by sending this command. cmd = LCD_CMD_CURSOR_DISPLAY_SHIFT_CONTROL | DISPLAY_SHIFT | SHIFT_TO_LEFT ; lcd_send_command(cmd); ptr++; usleep(500 * 1000); } } } #endif }
niekiran/EmbeddedLinuxBBB
Project_Src/lcd_scrollable_text/src/lcd_text_scroll.c
C
gpl-3.0
6,531
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[3]; atomic_int atom_0_r3_2; atomic_int atom_1_r1_1; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v3_r4 = v2_r3 ^ v2_r3; atomic_store_explicit(&vars[1+v3_r4], 1, memory_order_seq_cst); atomic_store_explicit(&vars[2], 1, memory_order_seq_cst); int v14 = (v2_r3 == 2); atomic_store_explicit(&atom_0_r3_2, v14, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v5_r1 = atomic_load_explicit(&vars[2], memory_order_seq_cst); int v6_r3 = v5_r1 ^ v5_r1; int v7_r3 = v6_r3 + 1; atomic_store_explicit(&vars[0], v7_r3, memory_order_seq_cst); int v15 = (v5_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v15, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[0], 0); atomic_init(&vars[2], 0); atomic_init(&vars[1], 0); atomic_init(&atom_0_r3_2, 0); atomic_init(&atom_1_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v8 = atomic_load_explicit(&atom_0_r3_2, memory_order_seq_cst); int v9 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v10 = (v9 == 2); int v11 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v12_conj = v10 & v11; int v13_conj = v8 & v12_conj; if (v13_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/DETOUR0477.c
C
gpl-3.0
1,695
/* * Copyright (C) 2006-2009 Daniel Prevost <dprevost@photonsoftware.org> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ #include "Common/Options.h" #include "Tests/PrintError.h" const bool expectedToPass = false; /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ int main() { #if defined(USE_DBC) int errcode = 0; char dummyArgs[100]; char *dummyPtrs[10]; psocOptionHandle handle; bool ok; struct psocOptStruct opts[5] = { { '3', "three", 1, "", "repeat the loop three times" }, { 'a', "address", 0, "QUASAR_ADDRESS", "tcp/ip port number of the server" }, { 'x', "", 1, "DISPLAY", "X display to use" }, { 'v', "verbose", 1, "", "try to explain what is going on" }, { 'z', "zzz", 1, "", "go to sleep..." } }; ok = psocSetSupportedOptions( 5, opts, &handle ); if ( ok != true ) { ERROR_EXIT( expectedToPass, NULL, ; ); } strcpy( dummyArgs, "OptionTest2 --address 12345 -v --zzz" ); /* 012345678901234567890123456789012345 */ dummyPtrs[0] = dummyArgs; dummyPtrs[1] = &dummyArgs[12]; dummyPtrs[2] = &dummyArgs[22]; dummyPtrs[3] = &dummyArgs[28]; dummyPtrs[4] = &dummyArgs[31]; dummyArgs[11] = 0; dummyArgs[21] = 0; dummyArgs[27] = 0; dummyArgs[30] = 0; errcode = psocValidateUserOptions( handle, 5, dummyPtrs, 1 ); if ( errcode != 0 ) { ERROR_EXIT( expectedToPass, NULL, ; ); } psocIsShortOptPresent( NULL, 'a' ); ERROR_EXIT( expectedToPass, NULL, ; ); #else return 1; #endif } /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
dprevost/photon
src/Common/Tests/Options/IsShortPresentNullHandle.c
C
gpl-3.0
2,353
/* glpapi16.c (basic graph and network routines) */ /*********************************************************************** * This code is part of GLPK (GNU Linear Programming Kit). * * Copyright (C) 2000,01,02,03,04,05,06,07,08,2009 Andrew Makhorin, * Department for Applied Informatics, Moscow Aviation Institute, * Moscow, Russia. All rights reserved. E-mail: <mao@mai2.rcnet.ru>. * * GLPK 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. * * GLPK 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 GLPK. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************/ #include "glpapi.h" /* CAUTION: DO NOT CHANGE THE LIMITS BELOW */ #define NV_MAX 100000000 /* = 100*10^6 */ /* maximal number of vertices in the graph */ #define NA_MAX 500000000 /* = 500*10^6 */ /* maximal number of arcs in the graph */ /*********************************************************************** * NAME * * glp_create_graph - create graph * * SYNOPSIS * * glp_graph *glp_create_graph(int v_size, int a_size); * * DESCRIPTION * * The routine creates a new graph, which initially is empty, i.e. has * no vertices and arcs. * * The parameter v_size specifies the size of data associated with each * vertex of the graph (0 to 256 bytes). * * The parameter a_size specifies the size of data associated with each * arc of the graph (0 to 256 bytes). * * RETURNS * * The routine returns a pointer to the graph created. */ static void create_graph(glp_graph *G, int v_size, int a_size) { G->pool = dmp_create_pool(); G->name = NULL; G->nv_max = 50; G->nv = G->na = 0; G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *)); G->index = NULL; G->v_size = v_size; G->a_size = a_size; return; } glp_graph *glp_create_graph(int v_size, int a_size) { glp_graph *G; if (!(0 <= v_size && v_size <= 256)) xerror("glp_create_graph: v_size = %d; invalid size of vertex " "data\n", v_size); if (!(0 <= a_size && a_size <= 256)) xerror("glp_create_graph: a_size = %d; invalid size of arc dat" "a\n", a_size); G = xmalloc(sizeof(glp_graph)); create_graph(G, v_size, a_size); return G; } /*********************************************************************** * NAME * * glp_set_graph_name - assign (change) graph name * * SYNOPSIS * * void glp_set_graph_name(glp_graph *G, const char *name); * * DESCRIPTION * * The routine glp_set_graph_name assigns a symbolic name specified by * the character string name (1 to 255 chars) to the graph. * * If the parameter name is NULL or an empty string, the routine erases * the existing symbolic name of the graph. */ void glp_set_graph_name(glp_graph *G, const char *name) { if (G->name != NULL) { dmp_free_atom(G->pool, G->name, strlen(G->name)+1); G->name = NULL; } if (!(name == NULL || name[0] == '\0')) { int j; for (j = 0; name[j] != '\0'; j++) { if (j == 256) xerror("glp_set_graph_name: graph name too long\n"); if (iscntrl((unsigned char)name[j])) xerror("glp_set_graph_name: graph name contains invalid " "character(s)\n"); } G->name = dmp_get_atom(G->pool, strlen(name)+1); strcpy(G->name, name); } return; } /*********************************************************************** * NAME * * glp_add_vertices - add new vertices to graph * * SYNOPSIS * * int glp_add_vertices(glp_graph *G, int nadd); * * DESCRIPTION * * The routine glp_add_vertices adds nadd vertices to the specified * graph. New vertices are always added to the end of the vertex list, * so ordinal numbers of existing vertices remain unchanged. * * Being added each new vertex is isolated (has no incident arcs). * * RETURNS * * The routine glp_add_vertices returns an ordinal number of the first * new vertex added to the graph. */ int glp_add_vertices(glp_graph *G, int nadd) { int i, nv_new; if (nadd < 1) xerror("glp_add_vertices: nadd = %d; invalid number of vertice" "s\n", nadd); if (nadd > NV_MAX - G->nv) xerror("glp_add_vertices: nadd = %d; too many vertices\n", nadd); /* determine new number of vertices */ nv_new = G->nv + nadd; /* increase the room, if necessary */ if (G->nv_max < nv_new) { glp_vertex **save = G->v; while (G->nv_max < nv_new) { G->nv_max += G->nv_max; xassert(G->nv_max > 0); } G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *)); memcpy(&G->v[1], &save[1], G->nv * sizeof(glp_vertex *)); xfree(save); } /* add new vertices to the end of the vertex list */ for (i = G->nv+1; i <= nv_new; i++) { glp_vertex *v; G->v[i] = v = dmp_get_atom(G->pool, sizeof(glp_vertex)); v->i = i; v->name = NULL; v->entry = NULL; if (G->v_size == 0) v->data = NULL; else { v->data = dmp_get_atom(G->pool, G->v_size); memset(v->data, 0, G->v_size); } v->temp = NULL; v->in = v->out = NULL; } /* set new number of vertices */ G->nv = nv_new; /* return the ordinal number of the first vertex added */ return nv_new - nadd + 1; } /**********************************************************************/ void glp_set_vertex_name(glp_graph *G, int i, const char *name) { /* assign (change) vertex name */ glp_vertex *v; if (!(1 <= i && i <= G->nv)) xerror("glp_set_vertex_name: i = %d; vertex number out of rang" "e\n", i); v = G->v[i]; if (v->name != NULL) { if (v->entry != NULL) { xassert(G->index != NULL); avl_delete_node(G->index, v->entry); v->entry = NULL; } dmp_free_atom(G->pool, v->name, strlen(v->name)+1); v->name = NULL; } if (!(name == NULL || name[0] == '\0')) { int k; for (k = 0; name[k] != '\0'; k++) { if (k == 256) xerror("glp_set_vertex_name: i = %d; vertex name too lon" "g\n", i); if (iscntrl((unsigned char)name[k])) xerror("glp_set_vertex_name: i = %d; vertex name contain" "s invalid character(s)\n", i); } v->name = dmp_get_atom(G->pool, strlen(name)+1); strcpy(v->name, name); if (G->index != NULL) { xassert(v->entry == NULL); v->entry = avl_insert_node(G->index, v->name); avl_set_node_link(v->entry, v); } } return; } /*********************************************************************** * NAME * * glp_add_arc - add new arc to graph * * SYNOPSIS * * glp_arc *glp_add_arc(glp_graph *G, int i, int j); * * DESCRIPTION * * The routine glp_add_arc adds a new arc to the specified graph. * * The parameters i and j specify the ordinal numbers of, resp., tail * and head vertices of the arc. Note that self-loops and multiple arcs * are allowed. * * RETURNS * * The routine glp_add_arc returns a pointer to the arc added. */ glp_arc *glp_add_arc(glp_graph *G, int i, int j) { glp_arc *a; if (!(1 <= i && i <= G->nv)) xerror("glp_add_arc: i = %d; tail vertex number out of range\n" , i); if (!(1 <= j && j <= G->nv)) xerror("glp_add_arc: j = %d; head vertex number out of range\n" , j); if (G->na == NA_MAX) xerror("glp_add_arc: too many arcs\n"); a = dmp_get_atom(G->pool, sizeof(glp_arc)); a->tail = G->v[i]; a->head = G->v[j]; if (G->a_size == 0) a->data = NULL; else { a->data = dmp_get_atom(G->pool, G->a_size); memset(a->data, 0, G->a_size); } a->temp = NULL; a->t_prev = NULL; a->t_next = G->v[i]->out; if (a->t_next != NULL) a->t_next->t_prev = a; a->h_prev = NULL; a->h_next = G->v[j]->in; if (a->h_next != NULL) a->h_next->h_prev = a; G->v[i]->out = G->v[j]->in = a; G->na++; return a; } /*********************************************************************** * NAME * * glp_del_vertices - delete vertices from graph * * SYNOPSIS * * void glp_del_vertices(glp_graph *G, int ndel, const int num[]); * * DESCRIPTION * * The routine glp_del_vertices deletes vertices along with all * incident arcs from the specified graph. Ordinal numbers of vertices * to be deleted should be placed in locations num[1], ..., num[ndel], * ndel > 0. * * Note that deleting vertices involves changing ordinal numbers of * other vertices remaining in the graph. New ordinal numbers of the * remaining vertices are assigned under the assumption that the * original order of vertices is not changed. */ void glp_del_vertices(glp_graph *G, int ndel, const int num[]) { glp_vertex *v; int i, k, nv_new; /* scan the list of vertices to be deleted */ if (!(1 <= ndel && ndel <= G->nv)) xerror("glp_del_vertices: ndel = %d; invalid number of vertice" "s\n", ndel); for (k = 1; k <= ndel; k++) { /* take the number of vertex to be deleted */ i = num[k]; /* obtain pointer to i-th vertex */ if (!(1 <= i && i <= G->nv)) xerror("glp_del_vertices: num[%d] = %d; vertex number out o" "f range\n", k, i); v = G->v[i]; /* check that the vertex is not marked yet */ if (v->i == 0) xerror("glp_del_vertices: num[%d] = %d; duplicate vertex nu" "mbers not allowed\n", k, i); /* erase symbolic name assigned to the vertex */ glp_set_vertex_name(G, i, NULL); xassert(v->name == NULL); xassert(v->entry == NULL); /* free vertex data, if allocated */ if (v->data != NULL) dmp_free_atom(G->pool, v->data, G->v_size); /* delete all incoming arcs */ while (v->in != NULL) glp_del_arc(G, v->in); /* delete all outgoing arcs */ while (v->out != NULL) glp_del_arc(G, v->out); /* mark the vertex to be deleted */ v->i = 0; } /* delete all marked vertices from the vertex list */ nv_new = 0; for (i = 1; i <= G->nv; i++) { /* obtain pointer to i-th vertex */ v = G->v[i]; /* check if the vertex is marked */ if (v->i == 0) { /* it is marked, delete it */ dmp_free_atom(G->pool, v, sizeof(glp_vertex)); } else { /* it is not marked, keep it */ v->i = ++nv_new; G->v[v->i] = v; } } /* set new number of vertices in the graph */ G->nv = nv_new; return; } /*********************************************************************** * NAME * * glp_del_arc - delete arc from graph * * SYNOPSIS * * void glp_del_arc(glp_graph *G, glp_arc *a); * * DESCRIPTION * * The routine glp_del_arc deletes an arc from the specified graph. * The arc to be deleted must exist. */ void glp_del_arc(glp_graph *G, glp_arc *a) { /* some sanity checks */ xassert(G->na > 0); xassert(1 <= a->tail->i && a->tail->i <= G->nv); xassert(a->tail == G->v[a->tail->i]); xassert(1 <= a->head->i && a->head->i <= G->nv); xassert(a->head == G->v[a->head->i]); /* remove the arc from the list of incoming arcs */ if (a->h_prev == NULL) a->head->in = a->h_next; else a->h_prev->h_next = a->h_next; if (a->h_next == NULL) ; else a->h_next->h_prev = a->h_prev; /* remove the arc from the list of outgoing arcs */ if (a->t_prev == NULL) a->tail->out = a->t_next; else a->t_prev->t_next = a->t_next; if (a->t_next == NULL) ; else a->t_next->t_prev = a->t_prev; /* free arc data, if allocated */ if (a->data != NULL) dmp_free_atom(G->pool, a->data, G->a_size); /* delete the arc from the graph */ dmp_free_atom(G->pool, a, sizeof(glp_arc)); G->na--; return; } /*********************************************************************** * NAME * * glp_erase_graph - erase graph content * * SYNOPSIS * * void glp_erase_graph(glp_graph *G, int v_size, int a_size); * * DESCRIPTION * * The routine glp_erase_graph erases the content of the specified * graph. The effect of this operation is the same as if the graph * would be deleted with the routine glp_delete_graph and then created * anew with the routine glp_create_graph, with exception that the * handle (pointer) to the graph remains valid. */ static void delete_graph(glp_graph *G) { dmp_delete_pool(G->pool); xfree(G->v); if (G->index != NULL) avl_delete_tree(G->index); return; } void glp_erase_graph(glp_graph *G, int v_size, int a_size) { if (!(0 <= v_size && v_size <= 256)) xerror("glp_erase_graph: v_size = %d; invalid size of vertex d" "ata\n", v_size); if (!(0 <= a_size && a_size <= 256)) xerror("glp_erase_graph: a_size = %d; invalid size of arc data" "\n", a_size); delete_graph(G); create_graph(G, v_size, a_size); return; } /*********************************************************************** * NAME * * glp_delete_graph - delete graph * * SYNOPSIS * * void glp_delete_graph(glp_graph *G); * * DESCRIPTION * * The routine glp_delete_graph deletes the specified graph and frees * all the memory allocated to this program object. */ void glp_delete_graph(glp_graph *G) { delete_graph(G); xfree(G); return; } /**********************************************************************/ void glp_create_v_index(glp_graph *G) { /* create vertex name index */ glp_vertex *v; int i; if (G->index == NULL) { G->index = avl_create_tree(avl_strcmp, NULL); for (i = 1; i <= G->nv; i++) { v = G->v[i]; xassert(v->entry == NULL); if (v->name != NULL) { v->entry = avl_insert_node(G->index, v->name); avl_set_node_link(v->entry, v); } } } return; } int glp_find_vertex(glp_graph *G, const char *name) { /* find vertex by its name */ AVLNODE *node; int i = 0; if (G->index == NULL) xerror("glp_find_vertex: vertex name index does not exist\n"); if (!(name == NULL || name[0] == '\0' || strlen(name) > 255)) { node = avl_find_node(G->index, name); if (node != NULL) i = ((glp_vertex *)avl_get_node_link(node))->i; } return i; } void glp_delete_v_index(glp_graph *G) { /* delete vertex name index */ int i; if (G->index != NULL) { avl_delete_tree(G->index), G->index = NULL; for (i = 1; i <= G->nv; i++) G->v[i]->entry = NULL; } return; } /*********************************************************************** * NAME * * glp_read_graph - read graph from plain text file * * SYNOPSIS * * int glp_read_graph(glp_graph *G, const char *fname); * * DESCRIPTION * * The routine glp_read_graph reads a graph from a plain text file. * * RETURNS * * If the operation was successful, the routine returns zero. Otherwise * it prints an error message and returns non-zero. */ int glp_read_graph(glp_graph *G, const char *fname) { glp_data *data; jmp_buf jump; int nv, na, i, j, k, ret; glp_erase_graph(G, G->v_size, G->a_size); xprintf("Reading graph from `%s'...\n", fname); data = glp_sdf_open_file(fname); if (data == NULL) { ret = 1; goto done; } if (setjmp(jump)) { ret = 1; goto done; } glp_sdf_set_jump(data, jump); nv = glp_sdf_read_int(data); if (nv < 0) glp_sdf_error(data, "invalid number of vertices\n"); na = glp_sdf_read_int(data); if (na < 0) glp_sdf_error(data, "invalid number of arcs\n"); xprintf("Graph has %d vert%s and %d arc%s\n", nv, nv == 1 ? "ex" : "ices", na, na == 1 ? "" : "s"); if (nv > 0) glp_add_vertices(G, nv); for (k = 1; k <= na; k++) { i = glp_sdf_read_int(data); if (!(1 <= i && i <= nv)) glp_sdf_error(data, "tail vertex number out of range\n"); j = glp_sdf_read_int(data); if (!(1 <= j && j <= nv)) glp_sdf_error(data, "head vertex number out of range\n"); glp_add_arc(G, i, j); } xprintf("%d lines were read\n", glp_sdf_line(data)); ret = 0; done: if (data != NULL) glp_sdf_close_file(data); return ret; } /*********************************************************************** * NAME * * glp_write_graph - write graph to plain text file * * SYNOPSIS * * int glp_write_graph(glp_graph *G, const char *fname). * * DESCRIPTION * * The routine glp_write_graph writes the specified graph to a plain * text file. * * RETURNS * * If the operation was successful, the routine returns zero. Otherwise * it prints an error message and returns non-zero. */ int glp_write_graph(glp_graph *G, const char *fname) { XFILE *fp; glp_vertex *v; glp_arc *a; int i, count, ret; xprintf("Writing graph to `%s'...\n", fname); fp = xfopen(fname, "w"), count = 0; if (fp == NULL) { xprintf("Unable to create `%s' - %s\n", fname, xerrmsg()); ret = 1; goto done; } xfprintf(fp, "%d %d\n", G->nv, G->na), count++; for (i = 1; i <= G->nv; i++) { v = G->v[i]; for (a = v->out; a != NULL; a = a->t_next) xfprintf(fp, "%d %d\n", a->tail->i, a->head->i), count++; } xfflush(fp); if (xferror(fp)) { xprintf("Write error on `%s' - %s\n", fname, xerrmsg()); ret = 1; goto done; } xprintf("%d lines were written\n", count); ret = 0; done: if (fp != NULL) xfclose(fp); return ret; } /* eof */
macmanes-lab/BinPacker
glpk-4.40/src/glpapi16.c
C
gpl-3.0
18,723
#include "report_mib_feature.h" #include "mib_feature_definition.h" #include "report_manager.h" #include "protocol.h" #include "bus_slave.h" #include "momo_config.h" #include "report_log.h" #include "report_comm_stream.h" #include "system_log.h" #include <string.h> #define BASE64_REPORT_MAX_LENGTH 160 //( 4 * ( ( RAW_REPORT_MAX_LENGTH + 2 ) / 3) ) extern char base64_report_buffer[BASE64_REPORT_MAX_LENGTH+1]; static void start_scheduled_reporting(void) { set_momo_state_flag( kStateFlagReportingEnabled, true ); start_report_scheduling(); } static void stop_scheduled_reporting(void) { set_momo_state_flag( kStateFlagReportingEnabled, false ); stop_report_scheduling(); } static void get_scheduled_reporting(void) { bus_slave_return_int16( get_momo_state_flag( kStateFlagReportingEnabled ) ); } static void send_report(void) { taskloop_add( post_report, NULL ); } static void set_reporting_interval(void) { set_report_scheduling_interval( plist_get_int16(0) ); } static void get_reporting_interval(void) { bus_slave_return_int16( current_momo_state.report_config.report_interval ); } static void set_reporting_route(void) { update_report_route( (plist_get_int16(0) >> 8) & 0xFF , plist_get_int16(0) & 0xFF , (const char*)plist_get_buffer(1) , plist_get_buffer_length() ); } static void get_reporting_route(void) { const char* route = get_report_route( ( plist_get_int16(0) >> 8 ) & 0xFF ); if ( !route ) { bus_slave_seterror( kUnknownError ); return; } uint8 start = plist_get_int16(0) & 0xFF; uint8 len = strlen( route ) - start; if ( len < 0 ) { bus_slave_seterror( kCallbackError ); return; } if ( len > kBusMaxMessageSize ) len = kBusMaxMessageSize; bus_slave_return_buffer( route + start, len ); } static void set_reporting_apn(void) { set_gprs_apn( (const char*)plist_get_buffer(0), plist_get_buffer_length() ); } static void get_reporting_apn(void) { bus_slave_return_buffer( current_momo_state.report_config.gprs_apn, strlen(current_momo_state.report_config.gprs_apn) ); } static void set_reporting_flags(void) { current_momo_state.report_config.report_flags = plist_get_int16(0); } static void get_reporting_flags(void) { bus_slave_return_int16( current_momo_state.report_config.report_flags ); } static void set_reporting_aggregates(void) { current_momo_state.report_config.bulk_aggregates = plist_get_int16(0); current_momo_state.report_config.interval_aggregates = plist_get_int16(1); } static void get_reporting_aggregates(void) { plist_set_int16( 0, current_momo_state.report_config.bulk_aggregates ); plist_set_int16( 1, current_momo_state.report_config.interval_aggregates ); bus_slave_setreturn( pack_return_status( kNoMIBError, 4 ) ); } static void build_report() { construct_report(); } static void get_report() { uint16 offset = plist_get_int16(0); memcpy(plist_get_buffer(0), base64_report_buffer+offset, 20); bus_slave_setreturn( pack_return_status(kNoMIBError, 20 )); } static void get_reporting_sequence(void) { bus_slave_return_int16( current_momo_state.report_config.transmit_sequence ); } static BYTE report_buffer[RAW_REPORT_MAX_LENGTH]; static void read_report_log_mib(void) { uint16 index = plist_get_int16(0); uint16 offset = plist_get_int16(1); if ( offset >= RAW_REPORT_MAX_LENGTH ) { bus_slave_seterror( kCallbackError ); return; } uint8 length = RAW_REPORT_MAX_LENGTH - offset; if ( length > kBusMaxMessageSize ) length = kBusMaxMessageSize; if ( report_log_read( index, (void*)&report_buffer, 1 ) == 0 ) { // No more entries bus_slave_seterror( kCallbackError ); return; } bus_slave_return_buffer( report_buffer+offset, length ); } static void count_report_log_mib(void) { bus_slave_return_int16( report_log_count() ); } static void clear_report_log_mib(void) { report_log_clear(); } static void handle_report_stream_success(void) { notify_report_success(); } static void handle_report_stream_failure(void) { notify_report_failure(); } DEFINE_MIB_FEATURE_COMMANDS(reporting) { { 0x00, send_report, plist_spec_empty() }, { 0x01, start_scheduled_reporting, plist_spec_empty() }, { 0x02, stop_scheduled_reporting, plist_spec_empty() }, { 0x03, set_reporting_interval, plist_spec(1, false) }, { 0x04, get_reporting_interval, plist_spec_empty() }, { 0x05, set_reporting_route, plist_spec(1, true) }, { 0x06, get_reporting_route, plist_spec(1, false) }, { 0x07, set_reporting_flags, plist_spec(1, false) }, { 0x08, get_reporting_flags, plist_spec_empty() }, { 0x09, set_reporting_aggregates, plist_spec(2, false) }, { 0x0A, get_reporting_aggregates, plist_spec_empty() }, { 0x0B, get_reporting_sequence, plist_spec_empty() }, { 0x0C, build_report, plist_spec_empty() }, { 0x0D, get_report, plist_spec(1, false) }, { 0x0E, get_scheduled_reporting, plist_spec_empty() }, { 0x0F, read_report_log_mib, plist_spec(2, false) }, { 0x10, count_report_log_mib, plist_spec_empty() }, { 0x11, clear_report_log_mib, plist_spec_empty() }, { 0x12, init_report_config, plist_spec_empty() }, { 0x13, set_reporting_apn, plist_spec(0,true) }, { 0x14, get_reporting_apn, plist_spec_empty() }, { 0xF0, handle_report_stream_success, plist_spec_empty() }, { 0xF1, handle_report_stream_failure, plist_spec_empty() } }; DEFINE_MIB_FEATURE(reporting);
WellDone/MoMo-Firmware
momo_modules/mainboard/src/mib/commands/report_mib_feature.c
C
gpl-3.0
5,340
/** * \file stack.c * * Time-stamp: "2012-03-31 13:16:41 bkorb" * * This is a special option processing routine that will save the * argument to an option in a FIFO queue. * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. * AutoOpts is Copyright (c) 1992-2012 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control * of the user of the license. * * The GNU Lesser General Public License, version 3 or later * See the files "COPYING.lgplv3" and "COPYING.gplv3" * * The Modified Berkeley Software Distribution License * See the file "COPYING.mbsd" * * These files have the following md5sums: * * 43b91e8ca915626ed3818ffb1b71248b pkg/libopts/COPYING.gplv3 * 06a1a2e4760c90ea5e1dad8dfaac4d39 pkg/libopts/COPYING.lgplv3 * 66a5cedaf62c4b2637025f049f9b826f pkg/libopts/COPYING.mbsd */ #ifdef WITH_LIBREGEX # include REGEX_HEADER #endif /*=export_func optionUnstackArg * private: * * what: Remove option args from a stack * arg: + tOptions* + pOpts + program options descriptor + * arg: + tOptDesc* + pOptDesc + the descriptor for this arg + * * doc: * Invoked for options that are equivalenced to stacked options. =*/ void optionUnstackArg(tOptions * pOpts, tOptDesc * pOptDesc) { tArgList * pAL; (void)pOpts; if ((pOptDesc->fOptState & OPTST_RESET) != 0) return; pAL = (tArgList*)pOptDesc->optCookie; /* * IF we don't have any stacked options, * THEN indicate that we don't have any of these options */ if (pAL == NULL) { pOptDesc->fOptState &= OPTST_PERSISTENT_MASK; if ((pOptDesc->fOptState & OPTST_INITENABLED) == 0) pOptDesc->fOptState |= OPTST_DISABLED; return; } #ifdef WITH_LIBREGEX { regex_t re; int i, ct, dIdx; if (regcomp(&re, pOptDesc->optArg.argString, REG_NOSUB) != 0) return; /* * search the list for the entry(s) to remove. Entries that * are removed are *not* copied into the result. The source * index is incremented every time. The destination only when * we are keeping a define. */ for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) { char const * pzSrc = pAL->apzArgs[ i ]; char * pzEq = strchr(pzSrc, '='); int res; if (pzEq != NULL) *pzEq = NUL; res = regexec(&re, pzSrc, (size_t)0, NULL, 0); switch (res) { case 0: /* * Remove this entry by reducing the in-use count * and *not* putting the string pointer back into * the list. */ AGFREE(pzSrc); pAL->useCt--; break; default: case REG_NOMATCH: if (pzEq != NULL) *pzEq = '='; /* * IF we have dropped an entry * THEN we have to move the current one. */ if (dIdx != i) pAL->apzArgs[ dIdx ] = pzSrc; dIdx++; } } regfree(&re); } #else /* not WITH_LIBREGEX */ { int i, ct, dIdx; /* * search the list for the entry(s) to remove. Entries that * are removed are *not* copied into the result. The source * index is incremented every time. The destination only when * we are keeping a define. */ for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) { tCC* pzSrc = pAL->apzArgs[ i ]; char* pzEq = strchr(pzSrc, '='); if (pzEq != NULL) *pzEq = NUL; if (strcmp(pzSrc, pOptDesc->optArg.argString) == 0) { /* * Remove this entry by reducing the in-use count * and *not* putting the string pointer back into * the list. */ AGFREE(pzSrc); pAL->useCt--; } else { if (pzEq != NULL) *pzEq = '='; /* * IF we have dropped an entry * THEN we have to move the current one. */ if (dIdx != i) pAL->apzArgs[ dIdx ] = pzSrc; dIdx++; } } } #endif /* WITH_LIBREGEX */ /* * IF we have unstacked everything, * THEN indicate that we don't have any of these options */ if (pAL->useCt == 0) { pOptDesc->fOptState &= OPTST_PERSISTENT_MASK; if ((pOptDesc->fOptState & OPTST_INITENABLED) == 0) pOptDesc->fOptState |= OPTST_DISABLED; AGFREE((void*)pAL); pOptDesc->optCookie = NULL; } } /* * Put an entry into an argument list. The first argument points to * a pointer to the argument list structure. It gets passed around * as an opaque address. */ LOCAL void addArgListEntry(void** ppAL, void* entry) { tArgList* pAL = *(void**)ppAL; /* * IF we have never allocated one of these, * THEN allocate one now */ if (pAL == NULL) { pAL = (tArgList*)AGALOC(sizeof(*pAL), "new option arg stack"); if (pAL == NULL) return; pAL->useCt = 0; pAL->allocCt = MIN_ARG_ALLOC_CT; *ppAL = (void*)pAL; } /* * ELSE if we are out of room * THEN make it bigger */ else if (pAL->useCt >= pAL->allocCt) { size_t sz = sizeof(*pAL); pAL->allocCt += INCR_ARG_ALLOC_CT; /* * The base structure contains space for MIN_ARG_ALLOC_CT * pointers. We subtract it off to find our augment size. */ sz += sizeof(char*) * (pAL->allocCt - MIN_ARG_ALLOC_CT); pAL = (tArgList*)AGREALOC((void*)pAL, sz, "expanded opt arg stack"); if (pAL == NULL) return; *ppAL = (void*)pAL; } /* * Insert the new argument into the list */ pAL->apzArgs[ (pAL->useCt)++ ] = entry; } /*=export_func optionStackArg * private: * * what: put option args on a stack * arg: + tOptions* + pOpts + program options descriptor + * arg: + tOptDesc* + pOptDesc + the descriptor for this arg + * * doc: * Keep an entry-ordered list of option arguments. =*/ void optionStackArg(tOptions * pOpts, tOptDesc * pOD) { char * pz; (void)pOpts; if ((pOD->fOptState & OPTST_RESET) != 0) { tArgList* pAL = (void*)pOD->optCookie; int ix; if (pAL == NULL) return; ix = pAL->useCt; while (--ix >= 0) AGFREE(pAL->apzArgs[ix]); AGFREE(pAL); } else { if (pOD->optArg.argString == NULL) return; AGDUPSTR(pz, pOD->optArg.argString, "stack arg"); addArgListEntry(&(pOD->optCookie), (void*)pz); } } /* * Local Variables: * mode: C * c-file-style: "stroustrup" * indent-tabs-mode: nil * End: * end of autoopts/stack.c */
nobled/gnutls
src/libopts/stack.c
C
gpl-3.0
7,335
/** ****************************************************************************** * @file LibJPEG/LibJPEG_Encoding/Src/encode.c * @author MCD Application Team * @version V1.1.0 * @date 17-February-2017 * @brief This file contain the compress method. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution 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 STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "encode.h" /* Private typedef -----------------------------------------------------------*/ /* This struct contains the JPEG compression parameters */ static struct jpeg_compress_struct cinfo; /* This struct represents a JPEG error handler */ static struct jpeg_error_mgr jerr; /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ extern RGB_typedef *RGB_matrix; /** * @brief Jpeg Encode * @param file: pointer to the bmp file * @param file1: pointer to the jpg file * @param width: image width * @param height: image height * @param image_quality: image quality * @param buff: pointer to the image line * @retval None */ void jpeg_encode(JFILE *file, JFILE *file1, uint32_t width, uint32_t height, uint32_t image_quality, uint8_t * buff) { /* Encode BMP Image to JPEG */ JSAMPROW row_pointer; /* Pointer to a single row */ uint32_t bytesread; /* Step 1: allocate and initialize JPEG compression object */ /* Set up the error handler */ cinfo.err = jpeg_std_error(&jerr); /* Initialize the JPEG compression object */ jpeg_create_compress(&cinfo); /* Step 2: specify data destination */ jpeg_stdio_dest(&cinfo, file1); /* Step 3: set parameters for compression */ cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; /* Set default compression parameters */ jpeg_set_defaults(&cinfo); cinfo.dct_method = JDCT_FLOAT; jpeg_set_quality(&cinfo, image_quality, TRUE); /* Step 4: start compressor */ jpeg_start_compress(&cinfo, TRUE); /* Bypass the header bmp file */ f_read(file, buff, 54, (UINT*)&bytesread); while (cinfo.next_scanline < cinfo.image_height) { /* In this application, the input file is a BMP, which first encodes the bottom of the picture */ /* JPEG encodes the highest part of the picture first. We need to read the lines upside down */ /* Move the read pointer to 'last line of the picture - next_scanline' */ f_lseek(file, ((cinfo.image_height-1-cinfo.next_scanline)*width*3)+54); if(f_read(file, buff, width*3, (UINT*)&bytesread) == FR_OK) { row_pointer = (JSAMPROW)buff; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } } /* Step 5: finish compression */ jpeg_finish_compress(&cinfo); /* Step 6: release JPEG compression object */ jpeg_destroy_compress(&cinfo); } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
TRothfelder/Multicopter
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32469I_EVAL/Applications/LibJPEG/LibJPEG_Encoding/Src/encode.c
C
gpl-3.0
5,814
/* ptinit.c - ptinit */ #include <xinu.h> struct ptnode *ptfree; /* list of free message nodes */ struct ptentry porttab[NPORTS]; /* port table */ int32 ptnextid; /* next table entry to try */ /*------------------------------------------------------------------------ * ptinit -- initialize all ports *------------------------------------------------------------------------ */ syscall ptinit( int32 maxmsgs /* total messages in all ports */ ) { int32 i; /* runs through port table */ struct ptnode *next, *prev; /* used to build free list */ ptfree = (struct ptnode *)getmem(maxmsgs*sizeof(struct ptnode)); if (ptfree == (struct ptnode *)SYSERR) { panic("pinit - insufficient memory"); } /* Initialize all port table entries to free */ for (i=0 ; i<NPORTS ; i++) { porttab[i].ptstate = PT_FREE; porttab[i].ptseq = 0; } ptnextid = 0; /* Create free list of message pointer nodes */ for ( prev=next=ptfree ; --maxmsgs > 0 ; prev=next ) prev->ptnext = ++next; prev->ptnext = NULL; return(OK); }
rhexsel/xinu-cMIPS
xinu/system/ptinit.c
C
gpl-3.0
1,044