--- /dev/null
+#
+# Copyright (C) 2006 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=goldfish-qemu
+PKG_VERSION:=20090429
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=git://android.git.kernel.org/platform/external/qemu
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_VERSION:=2b8ea29e2bd12f876a4d06647e6077bf72de567e
+PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)
+PKG_TARGETS:=bin
+
+include $(INCLUDE_DIR)/package.mk
+
+define Package/goldfish-qemu
+ SECTION:=emulator
+ CATEGORY:=Emulators
+ DEPENDS:=@TARGET_goldfish
+ TITLE:=A modified version of the Google Android Emulator
+ URL:=http://www.android.com/
+endef
+
+LIBSDL_PATCHED:=sdl-1.2.12-android-20080919
+
+define Download/libsdl-patched
+ FILE:=$(LIBSDL_PATCHED).tar.gz
+ URL:=http://android.git.kernel.org/pub
+ MD5SUM:=22df8cbb2ecb811938eba8410e861650
+endef
+$(eval $(call Download,libsdl-patched))
+
+Build/Exports=
+
+define Build/Prepare
+ $(call Build/Prepare/Default)
+ zcat $(DL_DIR)/$(LIBSDL_PATCHED).tar.gz | tar x -C $(PKG_BUILD_DIR)
+endef
+
+define Build/Configure
+ [ -x $(PKG_BUILD_DIR)/libsdl/bin/sdl-config ] || ( \
+ cd $(PKG_BUILD_DIR)/$(LIBSDL_PATCHED); \
+ ./android-configure --prefix=$(PKG_BUILD_DIR)/libsdl; \
+ make all install; \
+ )
+endef
+
+define Build/Compile
+ (cd $(PKG_BUILD_DIR); \
+ [ -f $(PKG_BUILD_DIR)/objs/config.make ] || \
+ ./android-configure.sh --sdl-config=$(PKG_BUILD_DIR)/libsdl/bin/sdl-config \
+ )
+ $(MAKE) -C $(PKG_BUILD_DIR)
+endef
+
+define Package/goldfish-qemu/install
+ $(INSTALL_DIR) $(1)
+ $(CP) $(PKG_BUILD_DIR)/objs/emulator $(1)/
+endef
+
+$(eval $(call BuildPackage,goldfish-qemu))
--- /dev/null
+--- a/android-configure.sh
++++ b/android-configure.sh
+@@ -656,6 +656,9 @@ case "$CPU" in
+ *) HOST_CPU=$CPU
+ ;;
+ esac
++case "$OS" in
++ darwin*) echo "#define _BSD 1" >> $config_h;;
++esac
+ echo "#define HOST_$HOST_CPU 1" >> $config_h
+ log "Generate : $config_h"
+
+--- a/android/utils/display-quartz.m
++++ b/android/utils/display-quartz.m
+@@ -34,6 +34,7 @@ get_monitor_resolution( int *px_dpi, in
+ int
+ get_nearest_monitor_rect( int *x, int *y, int *width, int *height )
+ {
++#if 0
+ SDL_SysWMinfo info;
+ NSWindow* window;
+
+@@ -108,4 +109,7 @@ get_nearest_monitor_rect( int *x, int
+ }
+ return 0;
+ }
++#else
++ return -1;
++#endif
+ };
--- /dev/null
+--- a/android/cmdline-option.c
++++ b/android/cmdline-option.c
+@@ -50,16 +50,6 @@ android_parse_options( int *pargc, char
+ char arg2_tab[64], *arg2 = arg2_tab;
+ int nn;
+
+- /* process @<name> as a special exception meaning
+- * '-avd <name>'
+- */
+- if (aread[0][0] == '@') {
+- opt->avd = aread[0]+1;
+- nargs--;
+- aread++;
+- continue;
+- }
+-
+ /* anything that isn't an option past this points
+ * exits the loop
+ */
+--- a/android/cmdline-options.h
++++ b/android/cmdline-options.h
+@@ -60,21 +60,16 @@
+ */
+
+ CFG_PARAM( sysdir, "<dir>", "search for system disk images in <dir>" )
+-CFG_PARAM( system, "<file>", "read initial system image from <file>" )
+-CFG_PARAM( datadir, "<dir>", "write user data into <dir>" )
+-CFG_PARAM( kernel, "<file>", "use specific emulated kernel" )
+-CFG_PARAM( ramdisk, "<file>", "ramdisk image (default <system>/ramdisk.img" )
+-CFG_PARAM( image, "<file>", "obsolete, use -system <file> instead" )
+-CFG_PARAM( init_data, "<file>", "initial data image (default <system>/userdata.img" )
+-CFG_PARAM( initdata, "<file>", "same as '-init-data <file>'" )
+-CFG_PARAM( data, "<file>", "data image (default <datadir>/userdata-qemu.img" )
++CFG_PARAM( system, "<file>", "read system image from <file>, default: <system>/system.img" )
++CFG_PARAM( data, "<file>", "data image, default: <system>/data.img" )
++CFG_PARAM( kernel, "<file>", "use specific emulated kernel, default: kernel.bin" )
++CFG_PARAM( ramdisk, "<file>", "ramdisk image (default <system>/ramdisk.bin" )
+ CFG_PARAM( partition_size, "<size>", "system/data partition size in MBs" )
+ CFG_PARAM( cache, "<file>", "cache partition image (default is temporary file)" )
+ CFG_FLAG ( no_cache, "disable the cache partition" )
+ CFG_FLAG ( nocache, "same as -no-cache" )
+ OPT_PARAM( sdcard, "<file>", "SD card image (default <system>/sdcard.img")
+ OPT_FLAG ( wipe_data, "reset the use data image (copy it from initdata)" )
+-CFG_PARAM( avd, "<name>", "use a specific android virtual device" )
+ CFG_PARAM( skindir, "<dir>", "search skins in <dir> (default <system>/skins)" )
+ CFG_PARAM( skin, "<name>", "select a given skin" )
+ CFG_FLAG ( no_skin, "don't use any emulator skin" )
+--- a/android/main.c
++++ b/android/main.c
+@@ -1606,6 +1606,7 @@ report_console( const char* proto_port,
+ * containing 'fileName'. this is *not* the full
+ * path to 'fileName'.
+ */
++
+ static char*
+ _getSdkImagePath( const char* fileName )
+ {
+@@ -1617,8 +1618,6 @@ _getSdkImagePath( const char* fileName
+
+ static const char* const searchPaths[] = {
+ "", /* program's directory */
+- "/lib/images", /* this is for SDK 1.0 */
+- "/../platforms/android-1.1/images", /* this is for SDK 1.1 */
+ NULL
+ };
+
+@@ -1841,25 +1840,7 @@ int main(int argc, char **argv)
+ }
+ }
+
+- /* legacy support: we used to use -system <dir> and -image <file>
+- * instead of -sysdir <dir> and -system <file>, so handle this by checking
+- * whether the options point to directories or files.
+- */
+- if (opts->image != NULL) {
+- if (opts->system != NULL) {
+- if (opts->sysdir != NULL) {
+- derror( "You can't use -sysdir, -system and -image at the same time.\n"
+- "You should probably use '-sysdir <path> -system <file>'.\n" );
+- exit(2);
+- }
+- }
+- dwarning( "Please note that -image is obsolete and that -system is now used to point\n"
+- "to the system image. Next time, try using '-sysdir <path> -system <file>' instead.\n" );
+- opts->sysdir = opts->system;
+- opts->system = opts->image;
+- opts->image = NULL;
+- }
+- else if (opts->system != NULL && path_is_dir(opts->system)) {
++ if (opts->system != NULL && path_is_dir(opts->system)) {
+ if (opts->sysdir != NULL) {
+ derror( "Option -system should now be followed by a file path, not a directory one.\n"
+ "Please use '-sysdir <path>' to point to the system directory.\n" );
+@@ -1885,49 +1866,11 @@ int main(int argc, char **argv)
+ if (opts->noskin)
+ opts->no_skin = opts->noskin;
+
+- if (opts->initdata) {
+- opts->init_data = opts->initdata;
+- opts->initdata = NULL;
+- }
+-
+- /* If no AVD name was given, try to find the top of the
+- * Android build tree
+- */
+- if (opts->avd == NULL) {
+- do {
+- char* out = getenv("ANDROID_PRODUCT_OUT");
+-
+- if (out == NULL || out[0] == 0)
+- break;
+-
+- if (!path_exists(out)) {
+- derror("Can't access ANDROID_PRODUCT_OUT as '%s'\n"
+- "You need to build the Android system before launching the emulator",
+- out);
+- exit(2);
+- }
+-
+- android_build_root = path_parent( out, 4 );
+- if (android_build_root == NULL || !path_exists(android_build_root)) {
+- derror("Can't find the Android build root from '%s'\n"
+- "Please check the definition of the ANDROID_PRODUCT_OUT variable.\n"
+- "It should point to your product-specific build output directory.\n",
+- out );
+- exit(2);
+- }
+- android_build_out = out;
+- D( "found Android build root: %s", android_build_root );
+- D( "found Android build out: %s", android_build_out );
+- } while (0);
+- }
+ /* if no virtual device name is given, and we're not in the
+ * Android build system, we'll need to perform some auto-detection
+ * magic :-)
+ */
+- if (opts->avd == NULL && !android_build_out)
+ {
+- char dataDirIsSystem = 0;
+-
+ if (!opts->sysdir) {
+ opts->sysdir = _getSdkImagePath("system.img");
+ if (!opts->sysdir) {
+@@ -1945,47 +1888,30 @@ int main(int argc, char **argv)
+ }
+
+ if (!opts->system) {
+- opts->system = _getSdkSystemImage(opts->sysdir, "-image", "system.img");
+- D("autoconfig: -image %s", opts->image);
++ opts->system = _getSdkSystemImage(opts->sysdir, "-system", "system.img");
++ D("autoconfig: -system %s", opts->system);
+ }
+
+ if (!opts->kernel) {
+- opts->kernel = _getSdkSystemImage(opts->sysdir, "-kernel", "kernel-qemu");
++ opts->kernel = _getSdkSystemImage(opts->sysdir, "-kernel", "kernel.bin");
+ D("autoconfig: -kernel %s", opts->kernel);
+ }
+
+ if (!opts->ramdisk) {
+- opts->ramdisk = _getSdkSystemImage(opts->sysdir, "-ramdisk", "ramdisk.img");
++ opts->ramdisk = _getSdkSystemImage(opts->sysdir, "-ramdisk", "ramdisk.bin");
+ D("autoconfig: -ramdisk %s", opts->ramdisk);
+ }
+
+- /* if no data directory is specified, use the system directory */
+- if (!opts->datadir) {
+- opts->datadir = qemu_strdup(opts->sysdir);
+- dataDirIsSystem = 1;
+- D("autoconfig: -datadir %s", opts->sysdir);
+- }
+-
+ if (!opts->data) {
+ /* check for userdata-qemu.img in the data directory */
+- bufprint(tmp, tmpend, "%s/userdata-qemu.img", opts->datadir);
+- if (!path_exists(tmp)) {
+- derror(
+- "You did not provide the name of an Android Virtual Device\n"
+- "with the '-avd <name>' option. Read -help-avd for more information.\n\n"
+-
+- "If you *really* want to *NOT* run an AVD, consider using '-data <file>'\n"
+- "to specify a data partition image file (I hope you know what you're doing).\n"
+- );
+- exit(2);
+- }
++ bufprint(tmp, tmpend, "%s/data.img", opts->sysdir);
+
+ opts->data = qemu_strdup(tmp);
+ D("autoconfig: -data %s", opts->data);
+ }
+
+- if (!opts->sdcard && opts->datadir) {
+- bufprint(tmp, tmpend, "%s/sdcard.img", opts->datadir);
++ if (!opts->sdcard && opts->sysdir) {
++ bufprint(tmp, tmpend, "%s/sdcard.img", opts->sysdir);
+ if (path_exists(tmp)) {
+ opts->sdcard = qemu_strdup(tmp);
+ D("autoconfig: -sdcard %s", opts->sdcard);
+@@ -2029,19 +1955,6 @@ int main(int argc, char **argv)
+ android_avdParams->skinName = opts->skin;
+ android_avdParams->skinRootPath = opts->skindir;
+
+- /* setup the virtual device differently depending on whether
+- * we are in the Android build system or not
+- */
+- if (opts->avd != NULL)
+- {
+- android_avdInfo = avdInfo_new( opts->avd, android_avdParams );
+- if (android_avdInfo == NULL) {
+- /* an error message has already been printed */
+- dprint("could not find virtual device named '%s'", opts->avd);
+- exit(1);
+- }
+- }
+- else
+ {
+ if (!android_build_out) {
+ android_build_out = android_build_root = opts->sysdir;
+--- a/android/avd/info.c
++++ b/android/avd/info.c
+@@ -1233,10 +1233,8 @@ _getBuildImagePaths( AvdInfo* i, AvdInf
+ ** take care of checking the state
+ **/
+ imageLoader_set ( l, AVD_IMAGE_INITSYSTEM );
+- imageLoader_load( l, IMAGE_REQUIRED | IMAGE_DONT_LOCK );
+-
+- /* force the system image to read-only status */
+- l->pState[0] = IMAGE_STATE_READONLY;
++ l->pState[0] = IMAGE_STATE_MUSTLOCK;
++ imageLoader_load( l, IMAGE_REQUIRED );
+
+ /** cache partition handling
+ **/
--- /dev/null
+#
+# Copyright (C) 2006-2009 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+ARCH:=arm
+BOARD:=goldfish
+BOARDNAME:=Goldfish (Android Emulator)
+FEATURES:=
+CFLAGS:=-O2 -pipe -march=armv5te -mtune=xscale -funit-at-a-time
+
+LINUX_VERSION:=2.6.30
+
+DEVICE_TYPE=phone
+
+define Target/Description
+ Android emulator virtual platform
+endef
+
+include $(INCLUDE_DIR)/target.mk
+
+$(eval $(call BuildTarget))
--- /dev/null
+CONFIG_AEABI=y
+CONFIG_ALIGNMENT_TRAP=y
+CONFIG_ARCH_GOLDFISH=y
+# CONFIG_ARCH_HAS_HOLES_MEMORYMODEL is not set
+# CONFIG_ARCH_HAS_ILOG2_U32 is not set
+# CONFIG_ARCH_HAS_ILOG2_U64 is not set
+# CONFIG_ARCH_SELECT_MEMORY_MODEL is not set
+# CONFIG_ARCH_SPARSEMEM_DEFAULT is not set
+# CONFIG_ARCH_SUPPORTS_MSI is not set
+CONFIG_ARCH_SUSPEND_POSSIBLE=y
+CONFIG_ARM=y
+CONFIG_ARM_THUMB=y
+# CONFIG_BACKTRACE_SELF_TEST is not set
+CONFIG_BASE_SMALL=0
+# CONFIG_BATTERY_DS2760 is not set
+CONFIG_BATTERY_GOLDFISH=y
+# CONFIG_BINARY_PRINTF is not set
+CONFIG_BITREVERSE=y
+# CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC is not set
+CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC_VALUE=0
+# CONFIG_BOOT_PRINTK_DELAY is not set
+CONFIG_CMDLINE="console=/dev/ttyS0 root=mtdblock0 rootdelay=1 rootfstype=yaffs2"
+CONFIG_CONSOLE_TRANSLATIONS=y
+CONFIG_CPU_32=y
+CONFIG_CPU_32v5=y
+CONFIG_CPU_ABRT_EV5TJ=y
+CONFIG_CPU_ARM926T=y
+# CONFIG_CPU_CACHE_ROUND_ROBIN is not set
+CONFIG_CPU_CACHE_VIVT=y
+CONFIG_CPU_COPY_V4WB=y
+CONFIG_CPU_CP15=y
+CONFIG_CPU_CP15_MMU=y
+# CONFIG_CPU_DCACHE_WRITETHROUGH is not set
+# CONFIG_CPU_ICACHE_DISABLE is not set
+CONFIG_CPU_PABRT_NOIFAR=y
+CONFIG_CPU_TLB_V4WBI=y
+CONFIG_CRYPTO_AEAD2=y
+CONFIG_CRYPTO_BLKCIPHER2=y
+CONFIG_CRYPTO_HASH2=y
+CONFIG_CRYPTO_MANAGER2=y
+CONFIG_CRYPTO_RNG2=y
+CONFIG_CRYPTO_WORKQUEUE=y
+# CONFIG_DEBUG_BLOCK_EXT_DEVT is not set
+CONFIG_DEBUG_BUGVERBOSE=y
+# CONFIG_DEBUG_DEVRES is not set
+# CONFIG_DEBUG_DRIVER is not set
+# CONFIG_DEBUG_ERRORS is not set
+# CONFIG_DEBUG_INFO is not set
+CONFIG_DEBUG_KERNEL=y
+# CONFIG_DEBUG_KOBJECT is not set
+# CONFIG_DEBUG_LIST is not set
+# CONFIG_DEBUG_LL is not set
+# CONFIG_DEBUG_LOCKING_API_SELFTESTS is not set
+# CONFIG_DEBUG_LOCK_ALLOC is not set
+# CONFIG_DEBUG_MUTEXES is not set
+# CONFIG_DEBUG_NOTIFIERS is not set
+# CONFIG_DEBUG_OBJECTS is not set
+# CONFIG_DEBUG_RT_MUTEXES is not set
+# CONFIG_DEBUG_SG is not set
+# CONFIG_DEBUG_SHIRQ is not set
+# CONFIG_DEBUG_SLAB is not set
+# CONFIG_DEBUG_SPINLOCK is not set
+# CONFIG_DEBUG_SPINLOCK_SLEEP is not set
+# CONFIG_DEBUG_STACK_USAGE is not set
+# CONFIG_DEBUG_USER is not set
+# CONFIG_DEBUG_VM is not set
+# CONFIG_DEBUG_WRITECOUNT is not set
+# CONFIG_DETECT_HUNG_TASK is not set
+CONFIG_DETECT_SOFTLOCKUP=y
+CONFIG_DEVKMEM=y
+# CONFIG_DM9000 is not set
+CONFIG_DUMMY_CONSOLE=y
+# CONFIG_FAULT_INJECTION is not set
+CONFIG_FB=y
+# CONFIG_FB_BACKLIGHT is not set
+# CONFIG_FB_BOOT_VESA_SUPPORT is not set
+# CONFIG_FB_BROADSHEET is not set
+CONFIG_FB_CFB_COPYAREA=y
+CONFIG_FB_CFB_FILLRECT=y
+CONFIG_FB_CFB_IMAGEBLIT=y
+# CONFIG_FB_CFB_REV_PIXELS_IN_BYTE is not set
+# CONFIG_FB_DDC is not set
+# CONFIG_FB_FOREIGN_ENDIAN is not set
+CONFIG_FB_GOLDFISH=y
+# CONFIG_FB_MACMODES is not set
+# CONFIG_FB_MB862XX is not set
+# CONFIG_FB_METRONOME is not set
+CONFIG_FB_MODE_HELPERS=y
+# CONFIG_FB_S1D13XXX is not set
+# CONFIG_FB_SVGALIB is not set
+# CONFIG_FB_SYS_COPYAREA is not set
+# CONFIG_FB_SYS_FILLRECT is not set
+# CONFIG_FB_SYS_FOPS is not set
+# CONFIG_FB_SYS_IMAGEBLIT is not set
+CONFIG_FB_TILEBLITTING=y
+# CONFIG_FB_VIRTUAL is not set
+# CONFIG_FIRMWARE_EDID is not set
+# CONFIG_FONTS is not set
+CONFIG_FONT_8x16=y
+CONFIG_FONT_8x8=y
+CONFIG_FRAMEBUFFER_CONSOLE=y
+CONFIG_FRAMEBUFFER_CONSOLE_DETECT_PRIMARY=y
+CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y
+CONFIG_FRAME_POINTER=y
+CONFIG_GENERIC_CLOCKEVENTS=y
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
+CONFIG_GENERIC_FIND_LAST_BIT=y
+# CONFIG_GENERIC_GPIO is not set
+CONFIG_GENERIC_HARDIRQS_NO__DO_IRQ=y
+CONFIG_GOLDFISH_TTY=y
+# CONFIG_HAMRADIO is not set
+CONFIG_HARDIRQS_SW_RESEND=y
+CONFIG_HAS_DMA=y
+CONFIG_HAS_IOMEM=y
+CONFIG_HAS_IOPORT=y
+CONFIG_HAVE_AOUT=y
+CONFIG_HAVE_ARCH_KGDB=y
+CONFIG_HAVE_FUNCTION_TRACER=y
+CONFIG_HAVE_GENERIC_DMA_COHERENT=y
+CONFIG_HAVE_IDE=y
+CONFIG_HAVE_KPROBES=y
+CONFIG_HAVE_KRETPROBES=y
+CONFIG_HAVE_LATENCYTOP_SUPPORT=y
+CONFIG_HAVE_MLOCK=y
+CONFIG_HAVE_OPROFILE=y
+CONFIG_HID=y
+CONFIG_HID_SUPPORT=y
+CONFIG_HW_CONSOLE=y
+# CONFIG_HW_RANDOM is not set
+# CONFIG_I2C is not set
+CONFIG_INITRAMFS_SOURCE=""
+CONFIG_INPUT=y
+CONFIG_INPUT_EVDEV=y
+CONFIG_INPUT_GPIO=y
+CONFIG_INPUT_KEYBOARD=y
+CONFIG_INPUT_KEYRESET=y
+CONFIG_INPUT_MOUSEDEV=y
+CONFIG_INPUT_MOUSEDEV_PSAUX=y
+CONFIG_INPUT_MOUSEDEV_SCREEN_X=1024
+CONFIG_INPUT_MOUSEDEV_SCREEN_Y=768
+CONFIG_INPUT_TOUCHSCREEN=y
+# CONFIG_ISDN is not set
+# CONFIG_JFFS2_CMODE_PRIORITY is not set
+CONFIG_JFFS2_CMODE_SIZE=y
+# CONFIG_KEYBOARD_ATKBD is not set
+CONFIG_KEYBOARD_GOLDFISH_EVENTS=y
+# CONFIG_KEYBOARD_LKKBD is not set
+# CONFIG_KEYBOARD_NEWTON is not set
+# CONFIG_KEYBOARD_STOWAWAY is not set
+# CONFIG_KEYBOARD_SUNKBD is not set
+# CONFIG_KEYBOARD_XTKBD is not set
+# CONFIG_KGDB is not set
+# CONFIG_LOCK_STAT is not set
+# CONFIG_LOGO is not set
+CONFIG_MACH_GOLDFISH=y
+# CONFIG_MTD_CFI is not set
+# CONFIG_MTD_COMPLEX_MAPPINGS is not set
+CONFIG_MTD_CONCAT=y
+CONFIG_MTD_GOLDFISH_NAND=y
+CONFIG_MTD_NAND=y
+CONFIG_MTD_UBI=y
+CONFIG_MTD_UBI_BEB_RESERVE=1
+# CONFIG_MTD_UBI_DEBUG is not set
+CONFIG_MTD_UBI_GLUEBI=y
+CONFIG_MTD_UBI_WL_THRESHOLD=4096
+# CONFIG_NETDEV_1000 is not set
+# CONFIG_NO_IOPORT is not set
+# CONFIG_OABI_COMPAT is not set
+# CONFIG_OUTER_CACHE is not set
+CONFIG_PAGEFLAGS_EXTENDED=y
+CONFIG_PAGE_OFFSET=0xC0000000
+# CONFIG_PAGE_POISONING is not set
+# CONFIG_PCI_SYSCALL is not set
+# CONFIG_PDA_POWER is not set
+CONFIG_POWER_SUPPLY=y
+# CONFIG_POWER_SUPPLY_DEBUG is not set
+# CONFIG_PROVE_LOCKING is not set
+CONFIG_QEMU_TRACE=y
+# CONFIG_RCU_TORTURE_TEST is not set
+# CONFIG_RD_LZMA is not set
+# CONFIG_RT_MUTEX_TESTER is not set
+# CONFIG_SCHEDSTATS is not set
+CONFIG_SCHED_DEBUG=y
+# CONFIG_SCSI_DMA is not set
+# CONFIG_SERIAL_8250 is not set
+# CONFIG_SLOW_WORK is not set
+CONFIG_SMC91X=y
+CONFIG_SPLIT_PTLOCK_CPUS=4096
+CONFIG_SYS_SUPPORTS_APM_EMULATION=y
+CONFIG_TICK_ONESHOT=y
+# CONFIG_TIMER_STATS is not set
+# CONFIG_TOUCHSCREEN_AD7879 is not set
+# CONFIG_TOUCHSCREEN_ELO is not set
+# CONFIG_TOUCHSCREEN_FUJITSU is not set
+# CONFIG_TOUCHSCREEN_GUNZE is not set
+# CONFIG_TOUCHSCREEN_INEXIO is not set
+# CONFIG_TOUCHSCREEN_MK712 is not set
+# CONFIG_TOUCHSCREEN_MTOUCH is not set
+# CONFIG_TOUCHSCREEN_PENMOUNT is not set
+# CONFIG_TOUCHSCREEN_TOUCHIT213 is not set
+# CONFIG_TOUCHSCREEN_TOUCHRIGHT is not set
+# CONFIG_TOUCHSCREEN_TOUCHWIN is not set
+# CONFIG_TOUCHSCREEN_WACOM_W8001 is not set
+CONFIG_TRACING_SUPPORT=y
+# CONFIG_UBIFS_FS is not set
+CONFIG_UEVENT_HELPER_PATH=""
+CONFIG_UID16=y
+CONFIG_VECTORS_BASE=0xffff0000
+CONFIG_VFP=y
+# CONFIG_VGA_CONSOLE is not set
+CONFIG_VIDEO_OUTPUT_CONTROL=y
+CONFIG_VT=y
+CONFIG_VT_CONSOLE=y
+CONFIG_VT_HW_CONSOLE_BINDING=y
+# CONFIG_WATCHDOG is not set
+CONFIG_ZBOOT_ROM_BSS=0
+CONFIG_ZBOOT_ROM_TEXT=0
+CONFIG_ZONE_DMA_FLAG=0
--- /dev/null
+#
+# Copyright (C) 2006 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+include $(INCLUDE_DIR)/image.mk
+
+JFFS2_BLOCKSIZE=124k
+JFFS2OPTS += -n -s 2048
+
+_PREFIX=openwrt-goldfish-
+
+define Image/BuildKernel
+ $(TARGET_CROSS)objcopy -O binary -R .note -R .comment -S \
+ $(LINUX_DIR)/arch/arm/boot/compressed/vmlinux $(BIN_DIR)/$(_PREFIX)kernel.bin
+ $(if $(CONFIG_TARGET_ROOTFS_INITRAMFS), \
+ $(CP) $(LINUX_DIR)/usr/initramfs_data.cpio.gz, \
+ gzip -c < $(LINUX_DIR)/usr/initramfs_data.cpio > \
+ ) $(BIN_DIR)/$(_PREFIX)ramdisk.bin
+ $(CP) ./run-emulator.sh $(BIN_DIR)/
+endef
+
+define Image/Build/jffs2-124k
+ $(CP) ./ubinize.cfg $(KDIR)/
+ (cd $(KDIR); \
+ ubinize \
+ -o $(BIN_DIR)/$(_PREFIX)$(1).img \
+ -p 128KiB -m 2KiB -s 2KiB ubinize.cfg; \
+ )
+ nand_ecc \
+ $(BIN_DIR)/$(_PREFIX)$(1).img \
+ $(BIN_DIR)/$(_PREFIX)system.bin
+endef
+
+define Image/Build
+ $(call Image/Build/$(1),$(1))
+endef
+
+
+$(eval $(call BuildImage))
--- /dev/null
+PREFIX=openwrt-goldfish-
+touch ${PREFIX}data.bin
+./goldfish-qemu/emulator -sysdir . -ramdisk ${PREFIX}ramdisk.bin -kernel ${PREFIX}kernel.bin -system ${PREFIX}system.bin -data ${PREFIX}data.bin -show-kernel -partition-size 100 -qemu -append "console=ttyS0 ubi.mtd=0 root=/dev/mtdblock3 rootfstype=jffs2 bootdelay=1 init=/etc/preinit" -net nic,vlan=0,model=smc91c111 -net user,vlan=0,hostname=OpenWrt
--- /dev/null
+[rootfs]
+# Volume mode (other option is static)
+mode=ubi
+# Source image
+image=root.jffs2-124k
+# Volume ID in UBI image
+vol_id=0
+# Allow for dynamic resize
+vol_type=dynamic
+# Volume name
+vol_name=rootfs
+# Autoresize volume at first mount
+vol_flags=autoresize
+
--- /dev/null
+From 0c61b75f9da1a0889959a0f9bd0b8b63f936ddf3 Mon Sep 17 00:00:00 2001
+From: Tony Lindgren <tony@atomide.com>
+Date: Mon, 9 May 2005 14:10:26 -0700
+Subject: [PATCH 042/134] ARM: Make low-level printk work
+
+Makes low-level printk work.
+
+Signed-off-by: Tony Lindgren <tony@atomide.com>
+---
+ kernel/printk.c | 8 ++++++++
+ 1 files changed, 8 insertions(+), 0 deletions(-)
+
+--- a/kernel/printk.c
++++ b/kernel/printk.c
+@@ -45,6 +45,10 @@ void asmlinkage __attribute__((weak)) ea
+
+ #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
+
++#ifdef CONFIG_DEBUG_LL
++extern void printascii(char *);
++#endif
++
+ /* printk's without a loglevel use this.. */
+ #define DEFAULT_MESSAGE_LOGLEVEL 4 /* KERN_WARNING */
+
+@@ -687,6 +691,10 @@ asmlinkage int vprintk(const char *fmt,
+ sizeof(printk_buf) - printed_len, fmt, args);
+
+
++#ifdef CONFIG_DEBUG_LL
++ printascii(printk_buf);
++#endif
++
+ /*
+ * Copy the output into log_buf. If the caller didn't provide
+ * appropriate log level tags, we insert them here
--- /dev/null
+From 3742e6638bdb7325c6432e2a145ad985ee47d052 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Mon, 26 Jan 2009 19:13:47 -0800
+Subject: [PATCH 052/134] lowmemorykiller: Only iterate over process list when needed.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Use NR_ACTIVE plus NR_INACTIVE as a size estimate for our fake cache
+instead the sum of rss. Neither method is accurate.
+
+Also skip the process scan, if the amount of memory available is above
+the largest threshold set.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ drivers/staging/android/lowmemorykiller.c | 35 +++++++++++++++++-----------
+ 1 files changed, 21 insertions(+), 14 deletions(-)
+
+diff --git a/drivers/staging/android/lowmemorykiller.c b/drivers/staging/android/lowmemorykiller.c
+index 3715d56..b9a2e84 100644
+--- a/drivers/staging/android/lowmemorykiller.c
++++ b/drivers/staging/android/lowmemorykiller.c
+@@ -71,23 +71,30 @@ static int lowmem_shrink(int nr_to_scan, gfp_t gfp_mask)
+ }
+ if(nr_to_scan > 0)
+ lowmem_print(3, "lowmem_shrink %d, %x, ofree %d, ma %d\n", nr_to_scan, gfp_mask, other_free, min_adj);
++ rem = global_page_state(NR_ACTIVE) + global_page_state(NR_INACTIVE);
++ if (nr_to_scan <= 0 || min_adj == OOM_ADJUST_MAX + 1) {
++ lowmem_print(5, "lowmem_shrink %d, %x, return %d\n", nr_to_scan, gfp_mask, rem);
++ return rem;
++ }
++
+ read_lock(&tasklist_lock);
+ for_each_process(p) {
+- if(p->oomkilladj >= 0 && p->mm) {
+- tasksize = get_mm_rss(p->mm);
+- if(nr_to_scan > 0 && tasksize > 0 && p->oomkilladj >= min_adj) {
+- if(selected == NULL ||
+- p->oomkilladj > selected->oomkilladj ||
+- (p->oomkilladj == selected->oomkilladj &&
+- tasksize > selected_tasksize)) {
+- selected = p;
+- selected_tasksize = tasksize;
+- lowmem_print(2, "select %d (%s), adj %d, size %d, to kill\n",
+- p->pid, p->comm, p->oomkilladj, tasksize);
+- }
+- }
+- rem += tasksize;
++ if (p->oomkilladj < min_adj || !p->mm)
++ continue;
++ tasksize = get_mm_rss(p->mm);
++ if (tasksize <= 0)
++ continue;
++ if (selected) {
++ if (p->oomkilladj < selected->oomkilladj)
++ continue;
++ if (p->oomkilladj == selected->oomkilladj &&
++ tasksize <= selected_tasksize)
++ continue;
+ }
++ selected = p;
++ selected_tasksize = tasksize;
++ lowmem_print(2, "select %d (%s), adj %d, size %d, to kill\n",
++ p->pid, p->comm, p->oomkilladj, tasksize);
+ }
+ if(selected != NULL) {
+ lowmem_print(1, "send sigkill to %d (%s), adj %d, size %d\n",
+--
+1.6.2
+
--- /dev/null
+From f82da10dcae73652a6f0355e4398b4be1af17e6b Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Mon, 26 Jan 2009 19:22:19 -0800
+Subject: [PATCH 053/134] lowmemorykiller: Don't count free space unless it meets the specified limit by itself
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+This allows processes to be killed when the kernel evict cache pages in
+an attempt to get more contiguous free memory.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ drivers/staging/android/lowmemorykiller.c | 13 +++++++++----
+ 1 files changed, 9 insertions(+), 4 deletions(-)
+
+diff --git a/drivers/staging/android/lowmemorykiller.c b/drivers/staging/android/lowmemorykiller.c
+index b9a2e84..b2ab7fa 100644
+--- a/drivers/staging/android/lowmemorykiller.c
++++ b/drivers/staging/android/lowmemorykiller.c
+@@ -58,20 +58,25 @@ static int lowmem_shrink(int nr_to_scan, gfp_t gfp_mask)
+ int min_adj = OOM_ADJUST_MAX + 1;
+ int selected_tasksize = 0;
+ int array_size = ARRAY_SIZE(lowmem_adj);
+- int other_free = global_page_state(NR_FREE_PAGES) + global_page_state(NR_FILE_PAGES);
++ int other_free = global_page_state(NR_FREE_PAGES);
++ int other_file = global_page_state(NR_FILE_PAGES);
+ if(lowmem_adj_size < array_size)
+ array_size = lowmem_adj_size;
+ if(lowmem_minfree_size < array_size)
+ array_size = lowmem_minfree_size;
+ for(i = 0; i < array_size; i++) {
+- if(other_free < lowmem_minfree[i]) {
++ if (other_free < lowmem_minfree[i] &&
++ other_file < lowmem_minfree[i]) {
+ min_adj = lowmem_adj[i];
+ break;
+ }
+ }
+ if(nr_to_scan > 0)
+- lowmem_print(3, "lowmem_shrink %d, %x, ofree %d, ma %d\n", nr_to_scan, gfp_mask, other_free, min_adj);
+- rem = global_page_state(NR_ACTIVE) + global_page_state(NR_INACTIVE);
++ lowmem_print(3, "lowmem_shrink %d, %x, ofree %d %d, ma %d\n", nr_to_scan, gfp_mask, other_free, other_file, min_adj);
++ rem = global_page_state(NR_ACTIVE_ANON) +
++ global_page_state(NR_ACTIVE_FILE) +
++ global_page_state(NR_INACTIVE_ANON) +
++ global_page_state(NR_INACTIVE_FILE);
+ if (nr_to_scan <= 0 || min_adj == OOM_ADJUST_MAX + 1) {
+ lowmem_print(5, "lowmem_shrink %d, %x, return %d\n", nr_to_scan, gfp_mask, rem);
+ return rem;
+--
+1.6.2
+
--- /dev/null
+From e4c9c5d7d6d5deb124083678fe5d839d3133f60a Mon Sep 17 00:00:00 2001
+From: Mike Lockwood <lockwood@android.com>
+Date: Mon, 12 Jan 2009 13:25:05 -0500
+Subject: [PATCH 054/134] timed_gpio: Separate timed_output class into a separate driver.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Signed-off-by: Mike Lockwood <lockwood@android.com>
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ drivers/staging/android/Kconfig | 6 ++-
+ drivers/staging/android/Makefile | 1 +
+ drivers/staging/android/timed_gpio.c | 98 +++++++++++--------------
+ drivers/staging/android/timed_gpio.h | 4 +-
+ drivers/staging/android/timed_output.c | 121 ++++++++++++++++++++++++++++++++
+ drivers/staging/android/timed_output.h | 37 ++++++++++
+ 6 files changed, 210 insertions(+), 57 deletions(-)
+ create mode 100644 drivers/staging/android/timed_output.c
+ create mode 100644 drivers/staging/android/timed_output.h
+
+diff --git a/drivers/staging/android/Kconfig b/drivers/staging/android/Kconfig
+index 604bd1e..1784508 100644
+--- a/drivers/staging/android/Kconfig
++++ b/drivers/staging/android/Kconfig
+@@ -73,9 +73,13 @@ config ANDROID_RAM_CONSOLE_EARLY_SIZE
+ default 0
+ depends on ANDROID_RAM_CONSOLE_EARLY_INIT
+
++config ANDROID_TIMED_OUTPUT
++ bool "Timed output class driver"
++ default y
++
+ config ANDROID_TIMED_GPIO
+ tristate "Android timed gpio driver"
+- depends on GENERIC_GPIO
++ depends on GENERIC_GPIO && ANDROID_TIMED_OUTPUT
+ default n
+
+ config ANDROID_LOW_MEMORY_KILLER
+diff --git a/drivers/staging/android/Makefile b/drivers/staging/android/Makefile
+index 95209d6..8e057e6 100644
+--- a/drivers/staging/android/Makefile
++++ b/drivers/staging/android/Makefile
+@@ -1,5 +1,6 @@
+ obj-$(CONFIG_ANDROID_BINDER_IPC) += binder.o
+ obj-$(CONFIG_ANDROID_LOGGER) += logger.o
+ obj-$(CONFIG_ANDROID_RAM_CONSOLE) += ram_console.o
++obj-$(CONFIG_ANDROID_TIMED_OUTPUT) += timed_output.o
+ obj-$(CONFIG_ANDROID_TIMED_GPIO) += timed_gpio.o
+ obj-$(CONFIG_ANDROID_LOW_MEMORY_KILLER) += lowmemorykiller.o
+diff --git a/drivers/staging/android/timed_gpio.c b/drivers/staging/android/timed_gpio.c
+index 33daff0..be7cdaa 100644
+--- a/drivers/staging/android/timed_gpio.c
++++ b/drivers/staging/android/timed_gpio.c
+@@ -20,13 +20,12 @@
+ #include <linux/err.h>
+ #include <linux/gpio.h>
+
++#include "timed_output.h"
+ #include "timed_gpio.h"
+
+
+-static struct class *timed_gpio_class;
+-
+ struct timed_gpio_data {
+- struct device *dev;
++ struct timed_output_dev dev;
+ struct hrtimer timer;
+ spinlock_t lock;
+ unsigned gpio;
+@@ -36,70 +35,62 @@ struct timed_gpio_data {
+
+ static enum hrtimer_restart gpio_timer_func(struct hrtimer *timer)
+ {
+- struct timed_gpio_data *gpio_data = container_of(timer, struct timed_gpio_data, timer);
++ struct timed_gpio_data *data =
++ container_of(timer, struct timed_gpio_data, timer);
+
+- gpio_direction_output(gpio_data->gpio, gpio_data->active_low ? 1 : 0);
++ gpio_direction_output(data->gpio, data->active_low ? 1 : 0);
+ return HRTIMER_NORESTART;
+ }
+
+-static ssize_t gpio_enable_show(struct device *dev, struct device_attribute *attr, char *buf)
++static int gpio_get_time(struct timed_output_dev *dev)
+ {
+- struct timed_gpio_data *gpio_data = dev_get_drvdata(dev);
+- int remaining;
++ struct timed_gpio_data *data =
++ container_of(dev, struct timed_gpio_data, dev);
+
+- if (hrtimer_active(&gpio_data->timer)) {
+- ktime_t r = hrtimer_get_remaining(&gpio_data->timer);
++ if (hrtimer_active(&data->timer)) {
++ ktime_t r = hrtimer_get_remaining(&data->timer);
+ struct timeval t = ktime_to_timeval(r);
+- remaining = t.tv_sec * 1000 + t.tv_usec / 1000;
++ return t.tv_sec * 1000 + t.tv_usec / 1000;
+ } else
+- remaining = 0;
+-
+- return sprintf(buf, "%d\n", remaining);
++ return 0;
+ }
+
+-static ssize_t gpio_enable_store(
+- struct device *dev, struct device_attribute *attr,
+- const char *buf, size_t size)
++static void gpio_enable(struct timed_output_dev *dev, int value)
+ {
+- struct timed_gpio_data *gpio_data = dev_get_drvdata(dev);
+- int value;
++ struct timed_gpio_data *data =
++ container_of(dev, struct timed_gpio_data, dev);
+ unsigned long flags;
+
+- sscanf(buf, "%d", &value);
+-
+- spin_lock_irqsave(&gpio_data->lock, flags);
++ spin_lock_irqsave(&data->lock, flags);
+
+ /* cancel previous timer and set GPIO according to value */
+- hrtimer_cancel(&gpio_data->timer);
+- gpio_direction_output(gpio_data->gpio, gpio_data->active_low ? !value : !!value);
++ hrtimer_cancel(&data->timer);
++ gpio_direction_output(data->gpio, data->active_low ? !value : !!value);
+
+ if (value > 0) {
+- if (value > gpio_data->max_timeout)
+- value = gpio_data->max_timeout;
++ if (value > data->max_timeout)
++ value = data->max_timeout;
+
+- hrtimer_start(&gpio_data->timer,
+- ktime_set(value / 1000, (value % 1000) * 1000000),
+- HRTIMER_MODE_REL);
++ hrtimer_start(&data->timer,
++ ktime_set(value / 1000, (value % 1000) * 1000000),
++ HRTIMER_MODE_REL);
+ }
+
+- spin_unlock_irqrestore(&gpio_data->lock, flags);
+-
+- return size;
++ spin_unlock_irqrestore(&data->lock, flags);
+ }
+
+-static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, gpio_enable_show, gpio_enable_store);
+-
+ static int timed_gpio_probe(struct platform_device *pdev)
+ {
+ struct timed_gpio_platform_data *pdata = pdev->dev.platform_data;
+ struct timed_gpio *cur_gpio;
+ struct timed_gpio_data *gpio_data, *gpio_dat;
+- int i, ret = 0;
++ int i, j, ret = 0;
+
+ if (!pdata)
+ return -EBUSY;
+
+- gpio_data = kzalloc(sizeof(struct timed_gpio_data) * pdata->num_gpios, GFP_KERNEL);
++ gpio_data = kzalloc(sizeof(struct timed_gpio_data) * pdata->num_gpios,
++ GFP_KERNEL);
+ if (!gpio_data)
+ return -ENOMEM;
+
+@@ -107,23 +98,26 @@ static int timed_gpio_probe(struct platform_device *pdev)
+ cur_gpio = &pdata->gpios[i];
+ gpio_dat = &gpio_data[i];
+
+- hrtimer_init(&gpio_dat->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
++ hrtimer_init(&gpio_dat->timer, CLOCK_MONOTONIC,
++ HRTIMER_MODE_REL);
+ gpio_dat->timer.function = gpio_timer_func;
+ spin_lock_init(&gpio_dat->lock);
+
++ gpio_dat->dev.name = cur_gpio->name;
++ gpio_dat->dev.get_time = gpio_get_time;
++ gpio_dat->dev.enable = gpio_enable;
++ ret = timed_output_dev_register(&gpio_dat->dev);
++ if (ret < 0) {
++ for (j = 0; j < i; j++)
++ timed_output_dev_unregister(&gpio_data[i].dev);
++ kfree(gpio_data);
++ return ret;
++ }
++
+ gpio_dat->gpio = cur_gpio->gpio;
+ gpio_dat->max_timeout = cur_gpio->max_timeout;
+ gpio_dat->active_low = cur_gpio->active_low;
+ gpio_direction_output(gpio_dat->gpio, gpio_dat->active_low);
+-
+- gpio_dat->dev = device_create(timed_gpio_class, &pdev->dev, 0, "%s", cur_gpio->name);
+- if (unlikely(IS_ERR(gpio_dat->dev)))
+- return PTR_ERR(gpio_dat->dev);
+-
+- dev_set_drvdata(gpio_dat->dev, gpio_dat);
+- ret = device_create_file(gpio_dat->dev, &dev_attr_enable);
+- if (ret)
+- return ret;
+ }
+
+ platform_set_drvdata(pdev, gpio_data);
+@@ -137,10 +131,8 @@ static int timed_gpio_remove(struct platform_device *pdev)
+ struct timed_gpio_data *gpio_data = platform_get_drvdata(pdev);
+ int i;
+
+- for (i = 0; i < pdata->num_gpios; i++) {
+- device_remove_file(gpio_data[i].dev, &dev_attr_enable);
+- device_unregister(gpio_data[i].dev);
+- }
++ for (i = 0; i < pdata->num_gpios; i++)
++ timed_output_dev_unregister(&gpio_data[i].dev);
+
+ kfree(gpio_data);
+
+@@ -151,22 +143,18 @@ static struct platform_driver timed_gpio_driver = {
+ .probe = timed_gpio_probe,
+ .remove = timed_gpio_remove,
+ .driver = {
+- .name = "timed-gpio",
++ .name = TIMED_GPIO_NAME,
+ .owner = THIS_MODULE,
+ },
+ };
+
+ static int __init timed_gpio_init(void)
+ {
+- timed_gpio_class = class_create(THIS_MODULE, "timed_output");
+- if (IS_ERR(timed_gpio_class))
+- return PTR_ERR(timed_gpio_class);
+ return platform_driver_register(&timed_gpio_driver);
+ }
+
+ static void __exit timed_gpio_exit(void)
+ {
+- class_destroy(timed_gpio_class);
+ platform_driver_unregister(&timed_gpio_driver);
+ }
+
+diff --git a/drivers/staging/android/timed_gpio.h b/drivers/staging/android/timed_gpio.h
+index 78449b2..a0e15f8 100644
+--- a/drivers/staging/android/timed_gpio.h
++++ b/drivers/staging/android/timed_gpio.h
+@@ -16,10 +16,12 @@
+ #ifndef _LINUX_TIMED_GPIO_H
+ #define _LINUX_TIMED_GPIO_H
+
++#define TIMED_GPIO_NAME "timed-gpio"
++
+ struct timed_gpio {
+ const char *name;
+ unsigned gpio;
+- int max_timeout;
++ int max_timeout;
+ u8 active_low;
+ };
+
+diff --git a/drivers/staging/android/timed_output.c b/drivers/staging/android/timed_output.c
+new file mode 100644
+index 0000000..62e7918
+--- /dev/null
++++ b/drivers/staging/android/timed_output.c
+@@ -0,0 +1,121 @@
++/* drivers/misc/timed_output.c
++ *
++ * Copyright (C) 2009 Google, Inc.
++ * Author: Mike Lockwood <lockwood@android.com>
++ *
++ * 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/module.h>
++#include <linux/types.h>
++#include <linux/device.h>
++#include <linux/fs.h>
++#include <linux/err.h>
++
++#include "timed_output.h"
++
++static struct class *timed_output_class;
++static atomic_t device_count;
++
++static ssize_t enable_show(struct device *dev, struct device_attribute *attr,
++ char *buf)
++{
++ struct timed_output_dev *tdev = dev_get_drvdata(dev);
++ int remaining = tdev->get_time(tdev);
++
++ return sprintf(buf, "%d\n", remaining);
++}
++
++static ssize_t enable_store(
++ struct device *dev, struct device_attribute *attr,
++ const char *buf, size_t size)
++{
++ struct timed_output_dev *tdev = dev_get_drvdata(dev);
++ int value;
++
++ sscanf(buf, "%d", &value);
++ tdev->enable(tdev, value);
++
++ return size;
++}
++
++static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, enable_show, enable_store);
++
++static int create_timed_output_class(void)
++{
++ if (!timed_output_class) {
++ timed_output_class = class_create(THIS_MODULE, "timed_output");
++ if (IS_ERR(timed_output_class))
++ return PTR_ERR(timed_output_class);
++ atomic_set(&device_count, 0);
++ }
++
++ return 0;
++}
++
++int timed_output_dev_register(struct timed_output_dev *tdev)
++{
++ int ret;
++
++ if (!tdev || !tdev->name || !tdev->enable || !tdev->get_time)
++ return -EINVAL;
++
++ ret = create_timed_output_class();
++ if (ret < 0)
++ return ret;
++
++ tdev->index = atomic_inc_return(&device_count);
++ tdev->dev = device_create(timed_output_class, NULL,
++ MKDEV(0, tdev->index), NULL, tdev->name);
++ if (IS_ERR(tdev->dev))
++ return PTR_ERR(tdev->dev);
++
++ ret = device_create_file(tdev->dev, &dev_attr_enable);
++ if (ret < 0)
++ goto err_create_file;
++
++ dev_set_drvdata(tdev->dev, tdev);
++ tdev->state = 0;
++ return 0;
++
++err_create_file:
++ device_destroy(timed_output_class, MKDEV(0, tdev->index));
++ printk(KERN_ERR "timed_output: Failed to register driver %s\n",
++ tdev->name);
++
++ return ret;
++}
++EXPORT_SYMBOL_GPL(timed_output_dev_register);
++
++void timed_output_dev_unregister(struct timed_output_dev *tdev)
++{
++ device_remove_file(tdev->dev, &dev_attr_enable);
++ device_destroy(timed_output_class, MKDEV(0, tdev->index));
++ dev_set_drvdata(tdev->dev, NULL);
++}
++EXPORT_SYMBOL_GPL(timed_output_dev_unregister);
++
++static int __init timed_output_init(void)
++{
++ return create_timed_output_class();
++}
++
++static void __exit timed_output_exit(void)
++{
++ class_destroy(timed_output_class);
++}
++
++module_init(timed_output_init);
++module_exit(timed_output_exit);
++
++MODULE_AUTHOR("Mike Lockwood <lockwood@android.com>");
++MODULE_DESCRIPTION("timed output class driver");
++MODULE_LICENSE("GPL");
+diff --git a/drivers/staging/android/timed_output.h b/drivers/staging/android/timed_output.h
+new file mode 100644
+index 0000000..ec907ab
+--- /dev/null
++++ b/drivers/staging/android/timed_output.h
+@@ -0,0 +1,37 @@
++/* include/linux/timed_output.h
++ *
++ * Copyright (C) 2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++*/
++
++#ifndef _LINUX_TIMED_OUTPUT_H
++#define _LINUX_TIMED_OUTPUT_H
++
++struct timed_output_dev {
++ const char *name;
++
++ /* enable the output and set the timer */
++ void (*enable)(struct timed_output_dev *sdev, int timeout);
++
++ /* returns the current number of milliseconds remaining on the timer */
++ int (*get_time)(struct timed_output_dev *sdev);
++
++ /* private data */
++ struct device *dev;
++ int index;
++ int state;
++};
++
++extern int timed_output_dev_register(struct timed_output_dev *dev);
++extern void timed_output_dev_unregister(struct timed_output_dev *dev);
++
++#endif
+--
+1.6.2
+
--- /dev/null
+From d620f695290e4ffb1586420ba1dbbb5b2c8c075d Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Tue, 17 Feb 2009 14:51:02 -0800
+Subject: [PATCH 055/134] mm: Add min_free_order_shift tunable.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+By default the kernel tries to keep half as much memory free at each
+order as it does for one order below. This can be too agressive when
+running without swap.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ kernel/sysctl.c | 9 +++++++++
+ mm/page_alloc.c | 3 ++-
+ 2 files changed, 11 insertions(+), 1 deletions(-)
+
+--- a/kernel/sysctl.c
++++ b/kernel/sysctl.c
+@@ -77,6 +77,7 @@ extern int suid_dumpable;
+ extern char core_pattern[];
+ extern int pid_max;
+ extern int min_free_kbytes;
++extern int min_free_order_shift;
+ extern int pid_max_min, pid_max_max;
+ extern int sysctl_drop_caches;
+ extern int percpu_pagelist_fraction;
+@@ -1109,6 +1110,14 @@ static struct ctl_table vm_table[] = {
+ .extra1 = &zero,
+ },
+ {
++ .ctl_name = CTL_UNNUMBERED,
++ .procname = "min_free_order_shift",
++ .data = &min_free_order_shift,
++ .maxlen = sizeof(min_free_order_shift),
++ .mode = 0644,
++ .proc_handler = &proc_dointvec
++ },
++ {
+ .ctl_name = VM_PERCPU_PAGELIST_FRACTION,
+ .procname = "percpu_pagelist_fraction",
+ .data = &percpu_pagelist_fraction,
+--- a/mm/page_alloc.c
++++ b/mm/page_alloc.c
+@@ -119,6 +119,7 @@ static char * const zone_names[MAX_NR_ZO
+ };
+
+ int min_free_kbytes = 1024;
++int min_free_order_shift = 1;
+
+ unsigned long __meminitdata nr_kernel_pages;
+ unsigned long __meminitdata nr_all_pages;
+@@ -1253,7 +1254,7 @@ int zone_watermark_ok(struct zone *z, in
+ free_pages -= z->free_area[o].nr_free << o;
+
+ /* Require fewer higher order pages to be free */
+- min >>= 1;
++ min >>= min_free_order_shift;
+
+ if (free_pages <= min)
+ return 0;
--- /dev/null
+From a4eb204a8029320c2dd748daf4f51fd48d337c3d Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Wed, 18 Mar 2009 17:27:31 -0700
+Subject: [PATCH 056/134] mm: Check if any page in a pageblock is reserved before marking it MIGRATE_RESERVE
+
+This fixes a problem where the first pageblock got marked MIGRATE_RESERVE even
+though it only had a few free pages. This in turn caused no contiguous memory
+to be reserved and frequent kswapd wakeups that emptied the caches to get more
+contiguous memory.
+---
+ mm/page_alloc.c | 16 +++++++++++++++-
+ 1 files changed, 15 insertions(+), 1 deletions(-)
+
+--- a/mm/page_alloc.c
++++ b/mm/page_alloc.c
+@@ -2545,6 +2545,20 @@ static inline unsigned long wait_table_b
+ #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
+
+ /*
++ * Check if a pageblock contains reserved pages
++ */
++static int pageblock_is_reserved(unsigned long start_pfn)
++{
++ unsigned long end_pfn = start_pfn + pageblock_nr_pages;
++ unsigned long pfn;
++
++ for (pfn = start_pfn; pfn < end_pfn; pfn++)
++ if (PageReserved(pfn_to_page(pfn)))
++ return 1;
++ return 0;
++}
++
++/*
+ * Mark a number of pageblocks as MIGRATE_RESERVE. The number
+ * of blocks reserved is based on zone->pages_min. The memory within the
+ * reserve will tend to store contiguous free pages. Setting min_free_kbytes
+@@ -2573,7 +2587,7 @@ static void setup_zone_migrate_reserve(s
+ continue;
+
+ /* Blocks with reserved pages will never free, skip them. */
+- if (PageReserved(page))
++ if (pageblock_is_reserved(pfn))
+ continue;
+
+ block_migratetype = get_pageblock_migratetype(page);
--- /dev/null
+From 10276fd993c6e4c92d8086a6ccd0c9e0ff53b053 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Wed, 10 Dec 2008 20:06:28 -0800
+Subject: [PATCH 058/134] sched: Enable might_sleep before initializing drivers.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+This allows detection of init bugs in built-in drivers.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ kernel/sched.c | 14 ++++++++++++--
+ 1 files changed, 12 insertions(+), 2 deletions(-)
+
+--- a/kernel/sched.c
++++ b/kernel/sched.c
+@@ -9064,13 +9064,23 @@ void __init sched_init(void)
+ }
+
+ #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
++static int __might_sleep_init_called;
++int __init __might_sleep_init(void)
++{
++ __might_sleep_init_called = 1;
++ return 0;
++}
++early_initcall(__might_sleep_init);
++
+ void __might_sleep(char *file, int line)
+ {
+ #ifdef in_atomic
+ static unsigned long prev_jiffy; /* ratelimiting */
+
+- if ((!in_atomic() && !irqs_disabled()) ||
+- system_state != SYSTEM_RUNNING || oops_in_progress)
++ if ((!in_atomic() && !irqs_disabled()) || oops_in_progress)
++ return;
++ if (system_state != SYSTEM_RUNNING &&
++ (!__might_sleep_init_called || system_state != SYSTEM_BOOTING))
+ return;
+ if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
+ return;
--- /dev/null
+From d52bcb0a807dde87057f330dbe95aa6d221a4b85 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Mon, 9 Apr 2007 17:13:02 +0700
+Subject: [PATCH 060/134] [ARM] Add code to prevent system calls from being restarted muliple times before returning from the kernel.
+
+Fixes crashes with thumb syscalls.
+---
+ arch/arm/kernel/signal.c | 9 +++++++++
+ 1 files changed, 9 insertions(+), 0 deletions(-)
+
+--- a/arch/arm/kernel/signal.c
++++ b/arch/arm/kernel/signal.c
+@@ -534,6 +534,14 @@ setup_rt_frame(int usig, struct k_sigact
+
+ static inline void restart_syscall(struct pt_regs *regs)
+ {
++ if (regs->ARM_ORIG_r0 == -ERESTARTNOHAND ||
++ regs->ARM_ORIG_r0 == -ERESTARTSYS ||
++ regs->ARM_ORIG_r0 == -ERESTARTNOINTR ||
++ regs->ARM_ORIG_r0 == -ERESTART_RESTARTBLOCK) {
++ /* the syscall cannot be safely restarted, return -EINTR instead */
++ regs->ARM_r0 = -EINTR;
++ return;
++ }
+ regs->ARM_r0 = regs->ARM_ORIG_r0;
+ regs->ARM_pc -= thumb_mode(regs) ? 2 : 4;
+ }
+@@ -650,6 +658,7 @@ static int do_signal(sigset_t *oldset, s
+ */
+ if (syscall) {
+ if (regs->ARM_r0 == -ERESTART_RESTARTBLOCK) {
++ regs->ARM_r0 = -EAGAIN; /* prevent multiple restarts */
+ if (thumb_mode(regs)) {
+ regs->ARM_r7 = __NR_restart_syscall - __NR_SYSCALL_BASE;
+ regs->ARM_pc -= 2;
--- /dev/null
+From 784b170a69906c48a688a9ffa7512fc858f8836c Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Sun, 30 Mar 2008 21:36:29 -0700
+Subject: [PATCH 061/134] [ARM] Save thread registers in coredumps
+
+Signed-off-by: Brian Swetland <swetland@google.com>
+---
+ arch/arm/include/asm/elf.h | 6 ++++++
+ arch/arm/kernel/process.c | 10 ++++++++++
+ 2 files changed, 16 insertions(+), 0 deletions(-)
+
+--- a/arch/arm/include/asm/elf.h
++++ b/arch/arm/include/asm/elf.h
+@@ -86,6 +86,10 @@ extern char elf_platform[];
+
+ struct elf32_hdr;
+
++struct task_struct;
++
++extern int dump_task_regs (struct task_struct *, elf_gregset_t *);
++
+ /*
+ * This is used to ensure we don't load something for the wrong architecture.
+ */
+@@ -113,4 +117,6 @@ extern int arm_elf_read_implies_exec(con
+ extern void elf_set_personality(const struct elf32_hdr *);
+ #define SET_PERSONALITY(ex) elf_set_personality(&(ex))
+
++#define ELF_CORE_COPY_TASK_REGS(tsk, elf_regs) dump_task_regs(tsk, elf_regs)
++
+ #endif
+--- a/arch/arm/kernel/process.c
++++ b/arch/arm/kernel/process.c
+@@ -337,6 +337,16 @@ int dump_fpu (struct pt_regs *regs, stru
+ EXPORT_SYMBOL(dump_fpu);
+
+ /*
++ * Capture the user space registers if the task is not running (in user space)
++ */
++int dump_task_regs(struct task_struct *tsk, elf_gregset_t *regs)
++{
++ struct pt_regs ptregs = *task_pt_regs(tsk);
++ elf_core_copy_regs(regs, &ptregs);
++ return 1;
++}
++
++/*
+ * Shuffle the argument into the correct register before calling the
+ * thread function. r1 is the thread argument, r2 is the pointer to
+ * the thread function, and r3 points to the exit function.
--- /dev/null
+From e93bd714c424d9fe907cb1d8ec5ce784767a3b16 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Fri, 26 Sep 2008 22:10:56 -0700
+Subject: [PATCH 064/134] PM: Add wake lock api.
+
+---
+ include/linux/wakelock.h | 91 ++++++++++++++++++++++++++++++++++++++++++++++
+ 1 files changed, 91 insertions(+), 0 deletions(-)
+ create mode 100755 include/linux/wakelock.h
+
+--- /dev/null
++++ b/include/linux/wakelock.h
+@@ -0,0 +1,91 @@
++/* include/linux/wakelock.h
++ *
++ * Copyright (C) 2007-2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#ifndef _LINUX_WAKELOCK_H
++#define _LINUX_WAKELOCK_H
++
++#include <linux/list.h>
++#include <linux/ktime.h>
++
++/* A wake_lock prevents the system from entering suspend or other low power
++ * states when active. If the type is set to WAKE_LOCK_SUSPEND, the wake_lock
++ * prevents a full system suspend. If the type is WAKE_LOCK_IDLE, low power
++ * states that cause large interrupt latencies or that disable a set of
++ * interrupts will not entered from idle until the wake_locks are released.
++ */
++
++enum {
++ WAKE_LOCK_SUSPEND, /* Prevent suspend */
++ WAKE_LOCK_IDLE, /* Prevent low power idle */
++ WAKE_LOCK_TYPE_COUNT
++};
++
++struct wake_lock {
++#ifdef CONFIG_HAS_WAKELOCK
++ struct list_head link;
++ int flags;
++ const char *name;
++ unsigned long expires;
++#ifdef CONFIG_WAKELOCK_STAT
++ struct {
++ int count;
++ int expire_count;
++ int wakeup_count;
++ ktime_t total_time;
++ ktime_t prevent_suspend_time;
++ ktime_t max_time;
++ ktime_t last_time;
++ } stat;
++#endif
++#endif
++};
++
++#ifdef CONFIG_HAS_WAKELOCK
++
++void wake_lock_init(struct wake_lock *lock, int type, const char *name);
++void wake_lock_destroy(struct wake_lock *lock);
++void wake_lock(struct wake_lock *lock);
++void wake_lock_timeout(struct wake_lock *lock, long timeout);
++void wake_unlock(struct wake_lock *lock);
++
++/* wake_lock_active returns a non-zero value if the wake_lock is currently
++ * locked. If the wake_lock has a timeout, it does not check the timeout
++ * but if the timeout had aready been checked it will return 0.
++ */
++int wake_lock_active(struct wake_lock *lock);
++
++/* has_wake_lock returns 0 if no wake locks of the specified type are active,
++ * and non-zero if one or more wake locks are held. Specifically it returns
++ * -1 if one or more wake locks with no timeout are active or the
++ * number of jiffies until all active wake locks time out.
++ */
++long has_wake_lock(int type);
++
++#else
++
++static inline void wake_lock_init(struct wake_lock *lock, int type,
++ const char *name) {}
++static inline void wake_lock_destroy(struct wake_lock *lock) {}
++static inline void wake_lock(struct wake_lock *lock) {}
++static inline void wake_lock_timeout(struct wake_lock *lock, long timeout) {}
++static inline void wake_unlock(struct wake_lock *lock) {}
++
++static inline int wake_lock_active(struct wake_lock *lock) { return 0; }
++static inline long has_wake_lock(int type) { return 0; }
++
++#endif
++
++#endif
++
--- /dev/null
+From 4f76252afe98fd017894e61c296bc61836e67a4a Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Fri, 26 Sep 2008 22:10:56 -0700
+Subject: [PATCH 065/134] PM: Add early suspend api.
+
+---
+ include/linux/earlysuspend.h | 56 ++++++++++++++++++++++++++++++++++++++++++
+ 1 files changed, 56 insertions(+), 0 deletions(-)
+ create mode 100755 include/linux/earlysuspend.h
+
+--- /dev/null
++++ b/include/linux/earlysuspend.h
+@@ -0,0 +1,56 @@
++/* include/linux/earlysuspend.h
++ *
++ * Copyright (C) 2007-2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#ifndef _LINUX_EARLYSUSPEND_H
++#define _LINUX_EARLYSUSPEND_H
++
++#ifdef CONFIG_HAS_EARLYSUSPEND
++#include <linux/list.h>
++#endif
++
++/* The early_suspend structure defines suspend and resume hooks to be called
++ * when the user visible sleep state of the system changes, and a level to
++ * control the order. They can be used to turn off the screen and input
++ * devices that are not used for wakeup.
++ * Suspend handlers are called in low to high level order, resume handlers are
++ * called in the opposite order. If, when calling register_early_suspend,
++ * the suspend handlers have already been called without a matching call to the
++ * resume handlers, the suspend handler will be called directly from
++ * register_early_suspend. This direct call can violate the normal level order.
++ */
++enum {
++ EARLY_SUSPEND_LEVEL_BLANK_SCREEN = 50,
++ EARLY_SUSPEND_LEVEL_STOP_DRAWING = 100,
++ EARLY_SUSPEND_LEVEL_DISABLE_FB = 150,
++};
++struct early_suspend {
++#ifdef CONFIG_HAS_EARLYSUSPEND
++ struct list_head link;
++ int level;
++ void (*suspend)(struct early_suspend *h);
++ void (*resume)(struct early_suspend *h);
++#endif
++};
++
++#ifdef CONFIG_HAS_EARLYSUSPEND
++void register_early_suspend(struct early_suspend *handler);
++void unregister_early_suspend(struct early_suspend *handler);
++#else
++#define register_early_suspend(handler) do { } while (0)
++#define unregister_early_suspend(handler) do { } while (0)
++#endif
++
++#endif
++
--- /dev/null
+From eef7f012d480142a3eccff91e0ae73ecb13220b3 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Tue, 9 Sep 2008 22:14:34 -0700
+Subject: [PATCH 066/134] PM: Implement wakelock api.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+PM: wakelock: Replace expire work with a timer
+
+The expire work function did not work in the normal case.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ kernel/power/Kconfig | 19 ++
+ kernel/power/Makefile | 1 +
+ kernel/power/power.h | 7 +
+ kernel/power/wakelock.c | 598 +++++++++++++++++++++++++++++++++++++++++++++++
+ 4 files changed, 625 insertions(+), 0 deletions(-)
+ create mode 100644 kernel/power/wakelock.c
+
+--- a/kernel/power/Kconfig
++++ b/kernel/power/Kconfig
+@@ -116,6 +116,25 @@ config SUSPEND_FREEZER
+
+ Turning OFF this setting is NOT recommended! If in doubt, say Y.
+
++config HAS_WAKELOCK
++ bool
++
++config WAKELOCK
++ bool "Wake lock"
++ depends on PM && RTC_CLASS
++ default n
++ select HAS_WAKELOCK
++ ---help---
++ Enable wakelocks. When user space request a sleep state the
++ sleep request will be delayed until no wake locks are held.
++
++config WAKELOCK_STAT
++ bool "Wake lock stats"
++ depends on WAKELOCK
++ default y
++ ---help---
++ Report wake lock stats in /proc/wakelocks
++
+ config HIBERNATION
+ bool "Hibernation (aka 'suspend to disk')"
+ depends on PM && SWAP && ARCH_HIBERNATION_POSSIBLE
+--- a/kernel/power/Makefile
++++ b/kernel/power/Makefile
+@@ -6,6 +6,7 @@ endif
+ obj-$(CONFIG_PM) += main.o
+ obj-$(CONFIG_PM_SLEEP) += console.o
+ obj-$(CONFIG_FREEZER) += process.o
++obj-$(CONFIG_WAKELOCK) += wakelock.o
+ obj-$(CONFIG_HIBERNATION) += swsusp.o disk.o snapshot.o swap.o user.o
+
+ obj-$(CONFIG_MAGIC_SYSRQ) += poweroff.o
+--- a/kernel/power/power.h
++++ b/kernel/power/power.h
+@@ -223,3 +223,10 @@ static inline void suspend_thaw_processe
+ {
+ }
+ #endif
++
++#ifdef CONFIG_WAKELOCK
++/* kernel/power/wakelock.c */
++extern struct workqueue_struct *suspend_work_queue;
++extern struct wake_lock main_wake_lock;
++extern suspend_state_t requested_suspend_state;
++#endif
+--- /dev/null
++++ b/kernel/power/wakelock.c
+@@ -0,0 +1,598 @@
++/* kernel/power/wakelock.c
++ *
++ * Copyright (C) 2005-2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/module.h>
++#include <linux/platform_device.h>
++#include <linux/rtc.h>
++#include <linux/suspend.h>
++#include <linux/syscalls.h> /* sys_sync */
++#include <linux/wakelock.h>
++#ifdef CONFIG_WAKELOCK_STAT
++#include <linux/proc_fs.h>
++#endif
++#include "power.h"
++
++enum {
++ DEBUG_EXIT_SUSPEND = 1U << 0,
++ DEBUG_WAKEUP = 1U << 1,
++ DEBUG_SUSPEND = 1U << 2,
++ DEBUG_EXPIRE = 1U << 3,
++ DEBUG_WAKE_LOCK = 1U << 4,
++};
++static int debug_mask = DEBUG_EXIT_SUSPEND | DEBUG_WAKEUP;
++module_param_named(debug_mask, debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
++
++#define WAKE_LOCK_TYPE_MASK (0x0f)
++#define WAKE_LOCK_INITIALIZED (1U << 8)
++#define WAKE_LOCK_ACTIVE (1U << 9)
++#define WAKE_LOCK_AUTO_EXPIRE (1U << 10)
++#define WAKE_LOCK_PREVENTING_SUSPEND (1U << 11)
++
++static DEFINE_SPINLOCK(list_lock);
++static LIST_HEAD(inactive_locks);
++static struct list_head active_wake_locks[WAKE_LOCK_TYPE_COUNT];
++static int current_event_num;
++struct workqueue_struct *suspend_work_queue;
++struct wake_lock main_wake_lock;
++suspend_state_t requested_suspend_state = PM_SUSPEND_MEM;
++static struct wake_lock unknown_wakeup;
++
++#ifdef CONFIG_WAKELOCK_STAT
++static struct wake_lock deleted_wake_locks;
++static ktime_t last_sleep_time_update;
++static int wait_for_wakeup;
++
++int get_expired_time(struct wake_lock *lock, ktime_t *expire_time)
++{
++ struct timespec ts;
++ struct timespec kt;
++ struct timespec tomono;
++ struct timespec delta;
++ unsigned long seq;
++ long timeout;
++
++ if (!(lock->flags & WAKE_LOCK_AUTO_EXPIRE))
++ return 0;
++ do {
++ seq = read_seqbegin(&xtime_lock);
++ timeout = lock->expires - jiffies;
++ if (timeout > 0)
++ return 0;
++ kt = current_kernel_time();
++ tomono = wall_to_monotonic;
++ } while (read_seqretry(&xtime_lock, seq));
++ jiffies_to_timespec(-timeout, &delta);
++ set_normalized_timespec(&ts, kt.tv_sec + tomono.tv_sec - delta.tv_sec,
++ kt.tv_nsec + tomono.tv_nsec - delta.tv_nsec);
++ *expire_time = timespec_to_ktime(ts);
++ return 1;
++}
++
++
++static int print_lock_stat(char *buf, struct wake_lock *lock)
++{
++ int lock_count = lock->stat.count;
++ int expire_count = lock->stat.expire_count;
++ ktime_t active_time = ktime_set(0, 0);
++ ktime_t total_time = lock->stat.total_time;
++ ktime_t max_time = lock->stat.max_time;
++ ktime_t prevent_suspend_time = lock->stat.prevent_suspend_time;
++ if (lock->flags & WAKE_LOCK_ACTIVE) {
++ ktime_t now, add_time;
++ int expired = get_expired_time(lock, &now);
++ if (!expired)
++ now = ktime_get();
++ add_time = ktime_sub(now, lock->stat.last_time);
++ lock_count++;
++ if (!expired)
++ active_time = add_time;
++ else
++ expire_count++;
++ total_time = ktime_add(total_time, add_time);
++ if (lock->flags & WAKE_LOCK_PREVENTING_SUSPEND)
++ prevent_suspend_time = ktime_add(prevent_suspend_time,
++ ktime_sub(now, last_sleep_time_update));
++ if (add_time.tv64 > max_time.tv64)
++ max_time = add_time;
++ }
++
++ return sprintf(buf, "\"%s\"\t%d\t%d\t%d\t%lld\t%lld\t%lld\t%lld\t"
++ "%lld\n", lock->name, lock_count, expire_count,
++ lock->stat.wakeup_count, ktime_to_ns(active_time),
++ ktime_to_ns(total_time),
++ ktime_to_ns(prevent_suspend_time), ktime_to_ns(max_time),
++ ktime_to_ns(lock->stat.last_time));
++}
++
++
++static int wakelocks_read_proc(char *page, char **start, off_t off,
++ int count, int *eof, void *data)
++{
++ unsigned long irqflags;
++ struct wake_lock *lock;
++ int len = 0;
++ char *p = page;
++ int type;
++
++ spin_lock_irqsave(&list_lock, irqflags);
++
++ p += sprintf(p, "name\tcount\texpire_count\twake_count\tactive_since"
++ "\ttotal_time\tsleep_time\tmax_time\tlast_change\n");
++ list_for_each_entry(lock, &inactive_locks, link) {
++ p += print_lock_stat(p, lock);
++ }
++ for (type = 0; type < WAKE_LOCK_TYPE_COUNT; type++) {
++ list_for_each_entry(lock, &active_wake_locks[type], link)
++ p += print_lock_stat(p, lock);
++ }
++ spin_unlock_irqrestore(&list_lock, irqflags);
++
++ *start = page + off;
++
++ len = p - page;
++ if (len > off)
++ len -= off;
++ else
++ len = 0;
++
++ return len < count ? len : count;
++}
++
++static void wake_unlock_stat_locked(struct wake_lock *lock, int expired)
++{
++ ktime_t duration;
++ ktime_t now;
++ if (!(lock->flags & WAKE_LOCK_ACTIVE))
++ return;
++ if (get_expired_time(lock, &now))
++ expired = 1;
++ else
++ now = ktime_get();
++ lock->stat.count++;
++ if (expired)
++ lock->stat.expire_count++;
++ duration = ktime_sub(now, lock->stat.last_time);
++ lock->stat.total_time = ktime_add(lock->stat.total_time, duration);
++ if (ktime_to_ns(duration) > ktime_to_ns(lock->stat.max_time))
++ lock->stat.max_time = duration;
++ lock->stat.last_time = ktime_get();
++ if (lock->flags & WAKE_LOCK_PREVENTING_SUSPEND) {
++ duration = ktime_sub(now, last_sleep_time_update);
++ lock->stat.prevent_suspend_time = ktime_add(
++ lock->stat.prevent_suspend_time, duration);
++ lock->flags &= ~WAKE_LOCK_PREVENTING_SUSPEND;
++ }
++}
++
++static void update_sleep_wait_stats_locked(int done)
++{
++ struct wake_lock *lock;
++ ktime_t now, etime, elapsed, add;
++ int expired;
++
++ now = ktime_get();
++ elapsed = ktime_sub(now, last_sleep_time_update);
++ list_for_each_entry(lock, &active_wake_locks[WAKE_LOCK_SUSPEND], link) {
++ expired = get_expired_time(lock, &etime);
++ if (lock->flags & WAKE_LOCK_PREVENTING_SUSPEND) {
++ if (expired)
++ add = ktime_sub(etime, last_sleep_time_update);
++ else
++ add = elapsed;
++ lock->stat.prevent_suspend_time = ktime_add(
++ lock->stat.prevent_suspend_time, add);
++ }
++ if (done || expired)
++ lock->flags &= ~WAKE_LOCK_PREVENTING_SUSPEND;
++ else
++ lock->flags |= WAKE_LOCK_PREVENTING_SUSPEND;
++ }
++ last_sleep_time_update = now;
++}
++#endif
++
++
++static void expire_wake_lock(struct wake_lock *lock)
++{
++#ifdef CONFIG_WAKELOCK_STAT
++ wake_unlock_stat_locked(lock, 1);
++#endif
++ lock->flags &= ~(WAKE_LOCK_ACTIVE | WAKE_LOCK_AUTO_EXPIRE);
++ list_del(&lock->link);
++ list_add(&lock->link, &inactive_locks);
++ if (debug_mask & (DEBUG_WAKE_LOCK | DEBUG_EXPIRE))
++ pr_info("expired wake lock %s\n", lock->name);
++}
++
++static void print_active_locks(int type)
++{
++ unsigned long irqflags;
++ struct wake_lock *lock;
++
++ BUG_ON(type >= WAKE_LOCK_TYPE_COUNT);
++ spin_lock_irqsave(&list_lock, irqflags);
++ list_for_each_entry(lock, &active_wake_locks[type], link) {
++ if (lock->flags & WAKE_LOCK_AUTO_EXPIRE) {
++ long timeout = lock->expires - jiffies;
++ if (timeout <= 0)
++ pr_info("wake lock %s, expired\n", lock->name);
++ else
++ pr_info("active wake lock %s, time left %ld\n",
++ lock->name, timeout);
++ } else
++ pr_info("active wake lock %s\n", lock->name);
++ }
++ spin_unlock_irqrestore(&list_lock, irqflags);
++}
++
++static long has_wake_lock_locked(int type)
++{
++ struct wake_lock *lock, *n;
++ long max_timeout = 0;
++
++ BUG_ON(type >= WAKE_LOCK_TYPE_COUNT);
++ list_for_each_entry_safe(lock, n, &active_wake_locks[type], link) {
++ if (lock->flags & WAKE_LOCK_AUTO_EXPIRE) {
++ long timeout = lock->expires - jiffies;
++ if (timeout <= 0)
++ expire_wake_lock(lock);
++ else if (timeout > max_timeout)
++ max_timeout = timeout;
++ } else
++ return -1;
++ }
++ return max_timeout;
++}
++
++long has_wake_lock(int type)
++{
++ long ret;
++ unsigned long irqflags;
++ spin_lock_irqsave(&list_lock, irqflags);
++ ret = has_wake_lock_locked(type);
++ spin_unlock_irqrestore(&list_lock, irqflags);
++ return ret;
++}
++
++static void suspend(struct work_struct *work)
++{
++ int ret;
++ int entry_event_num;
++
++ if (has_wake_lock(WAKE_LOCK_SUSPEND)) {
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("suspend: abort suspend\n");
++ return;
++ }
++
++ entry_event_num = current_event_num;
++ sys_sync();
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("suspend: enter suspend\n");
++ ret = pm_suspend(requested_suspend_state);
++ if (debug_mask & DEBUG_EXIT_SUSPEND) {
++ struct timespec ts;
++ struct rtc_time tm;
++ getnstimeofday(&ts);
++ rtc_time_to_tm(ts.tv_sec, &tm);
++ pr_info("suspend: exit suspend, ret = %d "
++ "(%d-%02d-%02d %02d:%02d:%02d.%09lu UTC)\n", ret,
++ tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
++ tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec);
++ }
++ if (current_event_num == entry_event_num) {
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("suspend: pm_suspend returned with no event\n");
++ wake_lock_timeout(&unknown_wakeup, HZ / 2);
++ }
++}
++static DECLARE_WORK(suspend_work, suspend);
++
++static void expire_wake_locks(unsigned long data)
++{
++ long has_lock;
++ unsigned long irqflags;
++ if (debug_mask & DEBUG_EXPIRE)
++ pr_info("expire_wake_locks: start\n");
++ if (debug_mask & DEBUG_SUSPEND)
++ print_active_locks(WAKE_LOCK_SUSPEND);
++ spin_lock_irqsave(&list_lock, irqflags);
++ has_lock = has_wake_lock_locked(WAKE_LOCK_SUSPEND);
++ if (debug_mask & DEBUG_EXPIRE)
++ pr_info("expire_wake_locks: done, has_lock %ld\n", has_lock);
++ if (has_lock == 0)
++ queue_work(suspend_work_queue, &suspend_work);
++ spin_unlock_irqrestore(&list_lock, irqflags);
++}
++static DEFINE_TIMER(expire_timer, expire_wake_locks, 0, 0);
++
++static int power_suspend_late(struct platform_device *pdev, pm_message_t state)
++{
++ int ret = has_wake_lock(WAKE_LOCK_SUSPEND) ? -EAGAIN : 0;
++#ifdef CONFIG_WAKELOCK_STAT
++ wait_for_wakeup = 1;
++#endif
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("power_suspend_late return %d\n", ret);
++ return ret;
++}
++
++static struct platform_driver power_driver = {
++ .driver.name = "power",
++ .suspend_late = power_suspend_late,
++};
++static struct platform_device power_device = {
++ .name = "power",
++};
++
++void wake_lock_init(struct wake_lock *lock, int type, const char *name)
++{
++ unsigned long irqflags = 0;
++
++ if (name)
++ lock->name = name;
++ BUG_ON(!lock->name);
++
++ if (debug_mask & DEBUG_WAKE_LOCK)
++ pr_info("wake_lock_init name=%s\n", lock->name);
++#ifdef CONFIG_WAKELOCK_STAT
++ lock->stat.count = 0;
++ lock->stat.expire_count = 0;
++ lock->stat.wakeup_count = 0;
++ lock->stat.total_time = ktime_set(0, 0);
++ lock->stat.prevent_suspend_time = ktime_set(0, 0);
++ lock->stat.max_time = ktime_set(0, 0);
++ lock->stat.last_time = ktime_set(0, 0);
++#endif
++ lock->flags = (type & WAKE_LOCK_TYPE_MASK) | WAKE_LOCK_INITIALIZED;
++
++ INIT_LIST_HEAD(&lock->link);
++ spin_lock_irqsave(&list_lock, irqflags);
++ list_add(&lock->link, &inactive_locks);
++ spin_unlock_irqrestore(&list_lock, irqflags);
++}
++EXPORT_SYMBOL(wake_lock_init);
++
++void wake_lock_destroy(struct wake_lock *lock)
++{
++ unsigned long irqflags;
++ if (debug_mask & DEBUG_WAKE_LOCK)
++ pr_info("wake_lock_destroy name=%s\n", lock->name);
++ spin_lock_irqsave(&list_lock, irqflags);
++ lock->flags &= ~WAKE_LOCK_INITIALIZED;
++#ifdef CONFIG_WAKELOCK_STAT
++ if (lock->stat.count) {
++ deleted_wake_locks.stat.count += lock->stat.count;
++ deleted_wake_locks.stat.expire_count += lock->stat.expire_count;
++ deleted_wake_locks.stat.total_time =
++ ktime_add(deleted_wake_locks.stat.total_time,
++ lock->stat.total_time);
++ deleted_wake_locks.stat.prevent_suspend_time =
++ ktime_add(deleted_wake_locks.stat.prevent_suspend_time,
++ lock->stat.prevent_suspend_time);
++ deleted_wake_locks.stat.max_time =
++ ktime_add(deleted_wake_locks.stat.max_time,
++ lock->stat.max_time);
++ }
++#endif
++ list_del(&lock->link);
++ spin_unlock_irqrestore(&list_lock, irqflags);
++}
++EXPORT_SYMBOL(wake_lock_destroy);
++
++static void wake_lock_internal(
++ struct wake_lock *lock, long timeout, int has_timeout)
++{
++ int type;
++ unsigned long irqflags;
++ long expire_in;
++
++ spin_lock_irqsave(&list_lock, irqflags);
++ type = lock->flags & WAKE_LOCK_TYPE_MASK;
++ BUG_ON(type >= WAKE_LOCK_TYPE_COUNT);
++ BUG_ON(!(lock->flags & WAKE_LOCK_INITIALIZED));
++#ifdef CONFIG_WAKELOCK_STAT
++ if (type == WAKE_LOCK_SUSPEND && wait_for_wakeup) {
++ if (debug_mask & DEBUG_WAKEUP)
++ pr_info("wakeup wake lock: %s\n", lock->name);
++ wait_for_wakeup = 0;
++ lock->stat.wakeup_count++;
++ }
++ if ((lock->flags & WAKE_LOCK_AUTO_EXPIRE) &&
++ (long)(lock->expires - jiffies) <= 0) {
++ wake_unlock_stat_locked(lock, 0);
++ lock->stat.last_time = ktime_get();
++ }
++#endif
++ if (!(lock->flags & WAKE_LOCK_ACTIVE)) {
++ lock->flags |= WAKE_LOCK_ACTIVE;
++#ifdef CONFIG_WAKELOCK_STAT
++ lock->stat.last_time = ktime_get();
++#endif
++ }
++ list_del(&lock->link);
++ if (has_timeout) {
++ if (debug_mask & DEBUG_WAKE_LOCK)
++ pr_info("wake_lock: %s, type %d, timeout %ld.%03lu\n",
++ lock->name, type, timeout / HZ,
++ (timeout % HZ) * MSEC_PER_SEC / HZ);
++ lock->expires = jiffies + timeout;
++ lock->flags |= WAKE_LOCK_AUTO_EXPIRE;
++ list_add_tail(&lock->link, &active_wake_locks[type]);
++ } else {
++ if (debug_mask & DEBUG_WAKE_LOCK)
++ pr_info("wake_lock: %s, type %d\n", lock->name, type);
++ lock->expires = LONG_MAX;
++ lock->flags &= ~WAKE_LOCK_AUTO_EXPIRE;
++ list_add(&lock->link, &active_wake_locks[type]);
++ }
++ if (type == WAKE_LOCK_SUSPEND) {
++ current_event_num++;
++#ifdef CONFIG_WAKELOCK_STAT
++ if (lock == &main_wake_lock)
++ update_sleep_wait_stats_locked(1);
++ else if (!wake_lock_active(&main_wake_lock))
++ update_sleep_wait_stats_locked(0);
++#endif
++ if (has_timeout)
++ expire_in = has_wake_lock_locked(type);
++ else
++ expire_in = -1;
++ if (expire_in > 0) {
++ if (debug_mask & DEBUG_EXPIRE)
++ pr_info("wake_lock: %s, start expire timer, "
++ "%ld\n", lock->name, expire_in);
++ mod_timer(&expire_timer, jiffies + expire_in);
++ } else {
++ if (del_timer(&expire_timer))
++ if (debug_mask & DEBUG_EXPIRE)
++ pr_info("wake_lock: %s, stop expire timer\n",
++ lock->name);
++ if (expire_in == 0)
++ queue_work(suspend_work_queue, &suspend_work);
++ }
++ }
++ spin_unlock_irqrestore(&list_lock, irqflags);
++}
++
++void wake_lock(struct wake_lock *lock)
++{
++ wake_lock_internal(lock, 0, 0);
++}
++EXPORT_SYMBOL(wake_lock);
++
++void wake_lock_timeout(struct wake_lock *lock, long timeout)
++{
++ wake_lock_internal(lock, timeout, 1);
++}
++EXPORT_SYMBOL(wake_lock_timeout);
++
++void wake_unlock(struct wake_lock *lock)
++{
++ int type;
++ unsigned long irqflags;
++ spin_lock_irqsave(&list_lock, irqflags);
++ type = lock->flags & WAKE_LOCK_TYPE_MASK;
++#ifdef CONFIG_WAKELOCK_STAT
++ wake_unlock_stat_locked(lock, 0);
++#endif
++ if (debug_mask & DEBUG_WAKE_LOCK)
++ pr_info("wake_unlock: %s\n", lock->name);
++ lock->flags &= ~(WAKE_LOCK_ACTIVE | WAKE_LOCK_AUTO_EXPIRE);
++ list_del(&lock->link);
++ list_add(&lock->link, &inactive_locks);
++ if (type == WAKE_LOCK_SUSPEND) {
++ long has_lock = has_wake_lock_locked(type);
++ if (has_lock > 0) {
++ if (debug_mask & DEBUG_EXPIRE)
++ pr_info("wake_unlock: %s, start expire timer, "
++ "%ld\n", lock->name, has_lock);
++ mod_timer(&expire_timer, jiffies + has_lock);
++ } else {
++ if (del_timer(&expire_timer))
++ if (debug_mask & DEBUG_EXPIRE)
++ pr_info("wake_unlock: %s, stop expire "
++ "timer\n", lock->name);
++ if (has_lock == 0)
++ queue_work(suspend_work_queue, &suspend_work);
++ }
++ if (lock == &main_wake_lock) {
++ if (debug_mask & DEBUG_SUSPEND)
++ print_active_locks(WAKE_LOCK_SUSPEND);
++#ifdef CONFIG_WAKELOCK_STAT
++ update_sleep_wait_stats_locked(0);
++#endif
++ }
++ }
++ spin_unlock_irqrestore(&list_lock, irqflags);
++}
++EXPORT_SYMBOL(wake_unlock);
++
++int wake_lock_active(struct wake_lock *lock)
++{
++ return !!(lock->flags & WAKE_LOCK_ACTIVE);
++}
++EXPORT_SYMBOL(wake_lock_active);
++
++static int __init wakelocks_init(void)
++{
++ int ret;
++ int i;
++
++ for (i = 0; i < ARRAY_SIZE(active_wake_locks); i++)
++ INIT_LIST_HEAD(&active_wake_locks[i]);
++
++#ifdef CONFIG_WAKELOCK_STAT
++ wake_lock_init(&deleted_wake_locks, WAKE_LOCK_SUSPEND,
++ "deleted_wake_locks");
++#endif
++ wake_lock_init(&main_wake_lock, WAKE_LOCK_SUSPEND, "main");
++ wake_lock(&main_wake_lock);
++ wake_lock_init(&unknown_wakeup, WAKE_LOCK_SUSPEND, "unknown_wakeups");
++
++ ret = platform_device_register(&power_device);
++ if (ret) {
++ pr_err("wakelocks_init: platform_device_register failed\n");
++ goto err_platform_device_register;
++ }
++ ret = platform_driver_register(&power_driver);
++ if (ret) {
++ pr_err("wakelocks_init: platform_driver_register failed\n");
++ goto err_platform_driver_register;
++ }
++
++ suspend_work_queue = create_singlethread_workqueue("suspend");
++ if (suspend_work_queue == NULL) {
++ ret = -ENOMEM;
++ goto err_suspend_work_queue;
++ }
++
++#ifdef CONFIG_WAKELOCK_STAT
++ create_proc_read_entry("wakelocks", S_IRUGO, NULL,
++ wakelocks_read_proc, NULL);
++#endif
++
++ return 0;
++
++err_suspend_work_queue:
++ platform_driver_unregister(&power_driver);
++err_platform_driver_register:
++ platform_device_unregister(&power_device);
++err_platform_device_register:
++ wake_lock_destroy(&unknown_wakeup);
++ wake_lock_destroy(&main_wake_lock);
++#ifdef CONFIG_WAKELOCK_STAT
++ wake_lock_destroy(&deleted_wake_locks);
++#endif
++ return ret;
++}
++
++static void __exit wakelocks_exit(void)
++{
++#ifdef CONFIG_WAKELOCK_STAT
++ remove_proc_entry("wakelocks", NULL);
++#endif
++ destroy_workqueue(suspend_work_queue);
++ platform_driver_unregister(&power_driver);
++ platform_device_unregister(&power_device);
++ wake_lock_destroy(&unknown_wakeup);
++ wake_lock_destroy(&main_wake_lock);
++#ifdef CONFIG_WAKELOCK_STAT
++ wake_lock_destroy(&deleted_wake_locks);
++#endif
++}
++
++core_initcall(wakelocks_init);
++module_exit(wakelocks_exit);
--- /dev/null
+From 2d4a25785ad1aa51bad967543e1ab20e9ed4a046 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Tue, 7 Oct 2008 20:48:01 -0700
+Subject: [PATCH 067/134] PM: Implement early suspend api
+
+---
+ kernel/power/Kconfig | 12 +++
+ kernel/power/Makefile | 1 +
+ kernel/power/earlysuspend.c | 178 +++++++++++++++++++++++++++++++++++++++++++
+ kernel/power/power.h | 6 ++
+ 4 files changed, 197 insertions(+), 0 deletions(-)
+ create mode 100644 kernel/power/earlysuspend.c
+
+--- a/kernel/power/Kconfig
++++ b/kernel/power/Kconfig
+@@ -119,6 +119,9 @@ config SUSPEND_FREEZER
+ config HAS_WAKELOCK
+ bool
+
++config HAS_EARLYSUSPEND
++ bool
++
+ config WAKELOCK
+ bool "Wake lock"
+ depends on PM && RTC_CLASS
+@@ -135,6 +138,15 @@ config WAKELOCK_STAT
+ ---help---
+ Report wake lock stats in /proc/wakelocks
+
++config EARLYSUSPEND
++ bool "Early suspend"
++ depends on WAKELOCK
++ default y
++ select HAS_EARLYSUSPEND
++ ---help---
++ Call early suspend handlers when the user requested sleep state
++ changes.
++
+ config HIBERNATION
+ bool "Hibernation (aka 'suspend to disk')"
+ depends on PM && SWAP && ARCH_HIBERNATION_POSSIBLE
+--- a/kernel/power/Makefile
++++ b/kernel/power/Makefile
+@@ -7,6 +7,7 @@ obj-$(CONFIG_PM) += main.o
+ obj-$(CONFIG_PM_SLEEP) += console.o
+ obj-$(CONFIG_FREEZER) += process.o
+ obj-$(CONFIG_WAKELOCK) += wakelock.o
++obj-$(CONFIG_EARLYSUSPEND) += earlysuspend.o
+ obj-$(CONFIG_HIBERNATION) += swsusp.o disk.o snapshot.o swap.o user.o
+
+ obj-$(CONFIG_MAGIC_SYSRQ) += poweroff.o
+--- /dev/null
++++ b/kernel/power/earlysuspend.c
+@@ -0,0 +1,178 @@
++/* kernel/power/earlysuspend.c
++ *
++ * Copyright (C) 2005-2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/earlysuspend.h>
++#include <linux/module.h>
++#include <linux/mutex.h>
++#include <linux/rtc.h>
++#include <linux/syscalls.h> /* sys_sync */
++#include <linux/wakelock.h>
++#include <linux/workqueue.h>
++
++#include "power.h"
++
++enum {
++ DEBUG_USER_STATE = 1U << 0,
++ DEBUG_SUSPEND = 1U << 2,
++};
++static int debug_mask = DEBUG_USER_STATE;
++module_param_named(debug_mask, debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
++
++static DEFINE_MUTEX(early_suspend_lock);
++static LIST_HEAD(early_suspend_handlers);
++static void early_suspend(struct work_struct *work);
++static void late_resume(struct work_struct *work);
++static DECLARE_WORK(early_suspend_work, early_suspend);
++static DECLARE_WORK(late_resume_work, late_resume);
++static DEFINE_SPINLOCK(state_lock);
++enum {
++ SUSPEND_REQUESTED = 0x1,
++ SUSPENDED = 0x2,
++ SUSPEND_REQUESTED_AND_SUSPENDED = SUSPEND_REQUESTED | SUSPENDED,
++};
++static int state;
++
++void register_early_suspend(struct early_suspend *handler)
++{
++ struct list_head *pos;
++
++ mutex_lock(&early_suspend_lock);
++ list_for_each(pos, &early_suspend_handlers) {
++ struct early_suspend *e;
++ e = list_entry(pos, struct early_suspend, link);
++ if (e->level > handler->level)
++ break;
++ }
++ list_add_tail(&handler->link, pos);
++ if ((state & SUSPENDED) && handler->suspend)
++ handler->suspend(handler);
++ mutex_unlock(&early_suspend_lock);
++}
++EXPORT_SYMBOL(register_early_suspend);
++
++void unregister_early_suspend(struct early_suspend *handler)
++{
++ mutex_lock(&early_suspend_lock);
++ list_del(&handler->link);
++ mutex_unlock(&early_suspend_lock);
++}
++EXPORT_SYMBOL(unregister_early_suspend);
++
++static void early_suspend(struct work_struct *work)
++{
++ struct early_suspend *pos;
++ unsigned long irqflags;
++ int abort = 0;
++
++ mutex_lock(&early_suspend_lock);
++ spin_lock_irqsave(&state_lock, irqflags);
++ if (state == SUSPEND_REQUESTED)
++ state |= SUSPENDED;
++ else
++ abort = 1;
++ spin_unlock_irqrestore(&state_lock, irqflags);
++
++ if (abort) {
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("early_suspend: abort, state %d\n", state);
++ mutex_unlock(&early_suspend_lock);
++ goto abort;
++ }
++
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("early_suspend: call handlers\n");
++ list_for_each_entry(pos, &early_suspend_handlers, link) {
++ if (pos->suspend != NULL)
++ pos->suspend(pos);
++ }
++ mutex_unlock(&early_suspend_lock);
++
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("early_suspend: sync\n");
++
++ sys_sync();
++abort:
++ spin_lock_irqsave(&state_lock, irqflags);
++ if (state == SUSPEND_REQUESTED_AND_SUSPENDED)
++ wake_unlock(&main_wake_lock);
++ spin_unlock_irqrestore(&state_lock, irqflags);
++}
++
++static void late_resume(struct work_struct *work)
++{
++ struct early_suspend *pos;
++ unsigned long irqflags;
++ int abort = 0;
++
++ mutex_lock(&early_suspend_lock);
++ spin_lock_irqsave(&state_lock, irqflags);
++ if (state == SUSPENDED)
++ state &= ~SUSPENDED;
++ else
++ abort = 1;
++ spin_unlock_irqrestore(&state_lock, irqflags);
++
++ if (abort) {
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("late_resume: abort, state %d\n", state);
++ goto abort;
++ }
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("late_resume: call handlers\n");
++ list_for_each_entry_reverse(pos, &early_suspend_handlers, link)
++ if (pos->resume != NULL)
++ pos->resume(pos);
++ if (debug_mask & DEBUG_SUSPEND)
++ pr_info("late_resume: done\n");
++abort:
++ mutex_unlock(&early_suspend_lock);
++}
++
++void request_suspend_state(suspend_state_t new_state)
++{
++ unsigned long irqflags;
++ int old_sleep;
++
++ spin_lock_irqsave(&state_lock, irqflags);
++ old_sleep = state & SUSPEND_REQUESTED;
++ if (debug_mask & DEBUG_USER_STATE) {
++ struct timespec ts;
++ struct rtc_time tm;
++ getnstimeofday(&ts);
++ rtc_time_to_tm(ts.tv_sec, &tm);
++ pr_info("request_suspend_state: %s (%d->%d) at %lld "
++ "(%d-%02d-%02d %02d:%02d:%02d.%09lu UTC)\n",
++ new_state != PM_SUSPEND_ON ? "sleep" : "wakeup",
++ requested_suspend_state, new_state,
++ ktime_to_ns(ktime_get()),
++ tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
++ tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec);
++ }
++ if (!old_sleep && new_state != PM_SUSPEND_ON) {
++ state |= SUSPEND_REQUESTED;
++ queue_work(suspend_work_queue, &early_suspend_work);
++ } else if (old_sleep && new_state == PM_SUSPEND_ON) {
++ state &= ~SUSPEND_REQUESTED;
++ wake_lock(&main_wake_lock);
++ queue_work(suspend_work_queue, &late_resume_work);
++ }
++ requested_suspend_state = new_state;
++ spin_unlock_irqrestore(&state_lock, irqflags);
++}
++
++suspend_state_t get_suspend_state(void)
++{
++ return requested_suspend_state;
++}
+--- a/kernel/power/power.h
++++ b/kernel/power/power.h
+@@ -230,3 +230,9 @@ extern struct workqueue_struct *suspend_
+ extern struct wake_lock main_wake_lock;
+ extern suspend_state_t requested_suspend_state;
+ #endif
++
++#ifdef CONFIG_EARLYSUSPEND
++/* kernel/power/earlysuspend.c */
++void request_suspend_state(suspend_state_t state);
++suspend_state_t get_suspend_state(void);
++#endif
--- /dev/null
+From 7b236e69bb4403f20fbdef81907d46b4d32d4af8 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Thu, 9 Oct 2008 19:17:11 -0700
+Subject: [PATCH 068/134] PM: Enable early suspend through /sys/power/state
+
+If EARLYSUSPEND is enabled then writes to /sys/power/state no longer
+blocks, and the kernel will try to enter the requested state every
+time no wakelocks are held. Write "on" to resume normal operation.
+---
+ kernel/power/main.c | 14 ++++++++++++++
+ 1 files changed, 14 insertions(+), 0 deletions(-)
+
+--- a/kernel/power/main.c
++++ b/kernel/power/main.c
+@@ -408,6 +408,9 @@ static void suspend_finish(void)
+
+
+ static const char * const pm_states[PM_SUSPEND_MAX] = {
++#ifdef CONFIG_EARLYSUSPEND
++ [PM_SUSPEND_ON] = "on",
++#endif
+ [PM_SUSPEND_STANDBY] = "standby",
+ [PM_SUSPEND_MEM] = "mem",
+ };
+@@ -525,7 +528,11 @@ static ssize_t state_store(struct kobjec
+ const char *buf, size_t n)
+ {
+ #ifdef CONFIG_SUSPEND
++#ifdef CONFIG_EARLYSUSPEND
++ suspend_state_t state = PM_SUSPEND_ON;
++#else
+ suspend_state_t state = PM_SUSPEND_STANDBY;
++#endif
+ const char * const *s;
+ #endif
+ char *p;
+@@ -547,8 +554,15 @@ static ssize_t state_store(struct kobjec
+ break;
+ }
+ if (state < PM_SUSPEND_MAX && *s)
++#ifdef CONFIG_EARLYSUSPEND
++ if (state == PM_SUSPEND_ON || valid_state(state)) {
++ error = 0;
++ request_suspend_state(state);
++ }
++#else
+ error = enter_state(state);
+ #endif
++#endif
+
+ Exit:
+ return error ? error : n;
--- /dev/null
+From 48e1af2bdd11204f11b3770a6c8d3eee64aee2e8 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Thu, 9 Oct 2008 21:01:46 -0700
+Subject: [PATCH 069/134] PM: Add user-space wake lock api.
+
+This adds /sys/power/wake_lock and /sys/power/wake_unlock.
+Writing a string to wake_lock creates a wake lock the
+first time is sees a string and locks it. Optionally, the
+string can be followed by a timeout.
+To unlock the wake lock, write the same string to wake_unlock.
+---
+ kernel/power/Kconfig | 10 ++
+ kernel/power/Makefile | 1 +
+ kernel/power/main.c | 9 ++
+ kernel/power/power.h | 11 ++
+ kernel/power/userwakelock.c | 218 +++++++++++++++++++++++++++++++++++++++++++
+ 5 files changed, 249 insertions(+), 0 deletions(-)
+ create mode 100644 kernel/power/userwakelock.c
+
+--- a/kernel/power/Kconfig
++++ b/kernel/power/Kconfig
+@@ -138,6 +138,16 @@ config WAKELOCK_STAT
+ ---help---
+ Report wake lock stats in /proc/wakelocks
+
++config USER_WAKELOCK
++ bool "Userspace wake locks"
++ depends on WAKELOCK
++ default y
++ ---help---
++ User-space wake lock api. Write "lockname" or "lockname timeout"
++ to /sys/power/wake_lock lock and if needed create a wake lock.
++ Write "lockname" to /sys/power/wake_unlock to unlock a user wake
++ lock.
++
+ config EARLYSUSPEND
+ bool "Early suspend"
+ depends on WAKELOCK
+--- a/kernel/power/Makefile
++++ b/kernel/power/Makefile
+@@ -7,6 +7,7 @@ obj-$(CONFIG_PM) += main.o
+ obj-$(CONFIG_PM_SLEEP) += console.o
+ obj-$(CONFIG_FREEZER) += process.o
+ obj-$(CONFIG_WAKELOCK) += wakelock.o
++obj-$(CONFIG_USER_WAKELOCK) += userwakelock.o
+ obj-$(CONFIG_EARLYSUSPEND) += earlysuspend.o
+ obj-$(CONFIG_HIBERNATION) += swsusp.o disk.o snapshot.o swap.o user.o
+
+--- a/kernel/power/main.c
++++ b/kernel/power/main.c
+@@ -595,6 +595,11 @@ pm_trace_store(struct kobject *kobj, str
+ power_attr(pm_trace);
+ #endif /* CONFIG_PM_TRACE */
+
++#ifdef CONFIG_USER_WAKELOCK
++power_attr(wake_lock);
++power_attr(wake_unlock);
++#endif
++
+ static struct attribute * g[] = {
+ &state_attr.attr,
+ #ifdef CONFIG_PM_TRACE
+@@ -603,6 +608,10 @@ static struct attribute * g[] = {
+ #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PM_DEBUG)
+ &pm_test_attr.attr,
+ #endif
++#ifdef CONFIG_USER_WAKELOCK
++ &wake_lock_attr.attr,
++ &wake_unlock_attr.attr,
++#endif
+ NULL,
+ };
+
+--- a/kernel/power/power.h
++++ b/kernel/power/power.h
+@@ -231,6 +231,17 @@ extern struct wake_lock main_wake_lock;
+ extern suspend_state_t requested_suspend_state;
+ #endif
+
++#ifdef CONFIG_USER_WAKELOCK
++ssize_t wake_lock_show(struct kobject *kobj, struct kobj_attribute *attr,
++ char *buf);
++ssize_t wake_lock_store(struct kobject *kobj, struct kobj_attribute *attr,
++ const char *buf, size_t n);
++ssize_t wake_unlock_show(struct kobject *kobj, struct kobj_attribute *attr,
++ char *buf);
++ssize_t wake_unlock_store(struct kobject *kobj, struct kobj_attribute *attr,
++ const char *buf, size_t n);
++#endif
++
+ #ifdef CONFIG_EARLYSUSPEND
+ /* kernel/power/earlysuspend.c */
+ void request_suspend_state(suspend_state_t state);
+--- /dev/null
++++ b/kernel/power/userwakelock.c
+@@ -0,0 +1,218 @@
++/* kernel/power/userwakelock.c
++ *
++ * Copyright (C) 2005-2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/ctype.h>
++#include <linux/module.h>
++#include <linux/wakelock.h>
++
++#include "power.h"
++
++enum {
++ DEBUG_FAILURE = BIT(0),
++ DEBUG_ERROR = BIT(1),
++ DEBUG_NEW = BIT(2),
++ DEBUG_ACCESS = BIT(3),
++ DEBUG_LOOKUP = BIT(4),
++};
++static int debug_mask = DEBUG_FAILURE;
++module_param_named(debug_mask, debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
++
++static DEFINE_MUTEX(tree_lock);
++
++struct user_wake_lock {
++ struct rb_node node;
++ struct wake_lock wake_lock;
++ char name[0];
++};
++struct rb_root user_wake_locks;
++
++static struct user_wake_lock *lookup_wake_lock_name(
++ const char *buf, int allocate, long *timeoutptr)
++{
++ struct rb_node **p = &user_wake_locks.rb_node;
++ struct rb_node *parent = NULL;
++ struct user_wake_lock *l;
++ int diff;
++ u64 timeout;
++ int name_len;
++ const char *arg;
++
++ /* Find length of lock name and start of optional timeout string */
++ arg = buf;
++ while (*arg && !isspace(*arg))
++ arg++;
++ name_len = arg - buf;
++ if (!name_len)
++ goto bad_arg;
++ while (isspace(*arg))
++ arg++;
++
++ /* Process timeout string */
++ if (timeoutptr && *arg) {
++ timeout = simple_strtoull(arg, (char **)&arg, 0);
++ while (isspace(*arg))
++ arg++;
++ if (*arg)
++ goto bad_arg;
++ /* convert timeout from nanoseconds to jiffies > 0 */
++ timeout += (NSEC_PER_SEC / HZ) - 1;
++ do_div(timeout, (NSEC_PER_SEC / HZ));
++ if (timeout <= 0)
++ timeout = 1;
++ *timeoutptr = timeout;
++ } else if (*arg)
++ goto bad_arg;
++ else if (timeoutptr)
++ *timeoutptr = 0;
++
++ /* Lookup wake lock in rbtree */
++ while (*p) {
++ parent = *p;
++ l = rb_entry(parent, struct user_wake_lock, node);
++ diff = strncmp(buf, l->name, name_len);
++ if (!diff && l->name[name_len])
++ diff = -1;
++ if (debug_mask & DEBUG_ERROR)
++ pr_info("lookup_wake_lock_name: compare %.*s %s %d\n",
++ name_len, buf, l->name, diff);
++
++ if (diff < 0)
++ p = &(*p)->rb_left;
++ else if (diff > 0)
++ p = &(*p)->rb_right;
++ else
++ return l;
++ }
++
++ /* Allocate and add new wakelock to rbtree */
++ if (!allocate) {
++ if (debug_mask & DEBUG_ERROR)
++ pr_info("lookup_wake_lock_name: %.*s not found\n",
++ name_len, buf);
++ return ERR_PTR(-EINVAL);
++ }
++ l = kzalloc(sizeof(*l) + name_len + 1, GFP_KERNEL);
++ if (l == NULL) {
++ if (debug_mask & DEBUG_FAILURE)
++ pr_err("lookup_wake_lock_name: failed to allocate "
++ "memory for %.*s\n", name_len, buf);
++ return ERR_PTR(-ENOMEM);
++ }
++ memcpy(l->name, buf, name_len);
++ if (debug_mask & DEBUG_NEW)
++ pr_info("lookup_wake_lock_name: new wake lock %s\n", l->name);
++ wake_lock_init(&l->wake_lock, WAKE_LOCK_SUSPEND, l->name);
++ rb_link_node(&l->node, parent, p);
++ rb_insert_color(&l->node, &user_wake_locks);
++ return l;
++
++bad_arg:
++ if (debug_mask & DEBUG_ERROR)
++ pr_info("lookup_wake_lock_name: wake lock, %.*s, bad arg, %s\n",
++ name_len, buf, arg);
++ return ERR_PTR(-EINVAL);
++}
++
++ssize_t wake_lock_show(
++ struct kobject *kobj, struct kobj_attribute *attr, char *buf)
++{
++ char *s = buf;
++ char *end = buf + PAGE_SIZE;
++ struct rb_node *n;
++ struct user_wake_lock *l;
++
++ mutex_lock(&tree_lock);
++
++ for (n = rb_first(&user_wake_locks); n != NULL; n = rb_next(n)) {
++ l = rb_entry(n, struct user_wake_lock, node);
++ if (wake_lock_active(&l->wake_lock))
++ s += scnprintf(s, end - s, "%s ", l->name);
++ }
++ s += scnprintf(s, end - s, "\n");
++
++ mutex_unlock(&tree_lock);
++ return (s - buf);
++}
++
++ssize_t wake_lock_store(
++ struct kobject *kobj, struct kobj_attribute *attr,
++ const char *buf, size_t n)
++{
++ long timeout;
++ struct user_wake_lock *l;
++
++ mutex_lock(&tree_lock);
++ l = lookup_wake_lock_name(buf, 1, &timeout);
++ if (IS_ERR(l)) {
++ n = PTR_ERR(l);
++ goto bad_name;
++ }
++
++ if (debug_mask & DEBUG_ACCESS)
++ pr_info("wake_lock_store: %s, timeout %ld\n", l->name, timeout);
++
++ if (timeout)
++ wake_lock_timeout(&l->wake_lock, timeout);
++ else
++ wake_lock(&l->wake_lock);
++bad_name:
++ mutex_unlock(&tree_lock);
++ return n;
++}
++
++
++ssize_t wake_unlock_show(
++ struct kobject *kobj, struct kobj_attribute *attr, char *buf)
++{
++ char *s = buf;
++ char *end = buf + PAGE_SIZE;
++ struct rb_node *n;
++ struct user_wake_lock *l;
++
++ mutex_lock(&tree_lock);
++
++ for (n = rb_first(&user_wake_locks); n != NULL; n = rb_next(n)) {
++ l = rb_entry(n, struct user_wake_lock, node);
++ if (!wake_lock_active(&l->wake_lock))
++ s += scnprintf(s, end - s, "%s ", l->name);
++ }
++ s += scnprintf(s, end - s, "\n");
++
++ mutex_unlock(&tree_lock);
++ return (s - buf);
++}
++
++ssize_t wake_unlock_store(
++ struct kobject *kobj, struct kobj_attribute *attr,
++ const char *buf, size_t n)
++{
++ struct user_wake_lock *l;
++
++ mutex_lock(&tree_lock);
++ l = lookup_wake_lock_name(buf, 0, NULL);
++ if (IS_ERR(l)) {
++ n = PTR_ERR(l);
++ goto not_found;
++ }
++
++ if (debug_mask & DEBUG_ACCESS)
++ pr_info("wake_unlock_store: %s\n", l->name);
++
++ wake_unlock(&l->wake_lock);
++not_found:
++ mutex_unlock(&tree_lock);
++ return n;
++}
++
--- /dev/null
+From 3f8e407c418205252f00615da4d0182e8c960344 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Tue, 14 Oct 2008 16:02:39 -0700
+Subject: [PATCH 070/134] PM: wakelock: Abort task freezing if a wake lock is held.
+
+Avoids a problem where the device sometimes hangs for 20 seconds
+before the screen is turned on.
+---
+ kernel/power/process.c | 23 ++++++++++++++++++-----
+ 1 files changed, 18 insertions(+), 5 deletions(-)
+
+--- a/kernel/power/process.c
++++ b/kernel/power/process.c
+@@ -13,6 +13,7 @@
+ #include <linux/module.h>
+ #include <linux/syscalls.h>
+ #include <linux/freezer.h>
++#include <linux/wakelock.h>
+
+ /*
+ * Timeout for stopping processes
+@@ -36,6 +37,7 @@ static int try_to_freeze_tasks(bool sig_
+ struct timeval start, end;
+ u64 elapsed_csecs64;
+ unsigned int elapsed_csecs;
++ unsigned int wakeup = 0;
+
+ do_gettimeofday(&start);
+
+@@ -62,6 +64,10 @@ static int try_to_freeze_tasks(bool sig_
+ } while_each_thread(g, p);
+ read_unlock(&tasklist_lock);
+ yield(); /* Yield is okay here */
++ if (todo && has_wake_lock(WAKE_LOCK_SUSPEND)) {
++ wakeup = 1;
++ break;
++ }
+ if (time_after(jiffies, end_time))
+ break;
+ } while (todo);
+@@ -77,11 +83,18 @@ static int try_to_freeze_tasks(bool sig_
+ * and caller must call thaw_processes() if something fails),
+ * but it cleans up leftover PF_FREEZE requests.
+ */
+- printk("\n");
+- printk(KERN_ERR "Freezing of tasks failed after %d.%02d seconds "
+- "(%d tasks refusing to freeze):\n",
+- elapsed_csecs / 100, elapsed_csecs % 100, todo);
+- show_state();
++ if(wakeup) {
++ printk("\n");
++ printk(KERN_ERR "Freezing of %s aborted\n",
++ sig_only ? "user space " : "tasks ");
++ }
++ else {
++ printk("\n");
++ printk(KERN_ERR "Freezing of tasks failed after %d.%02d seconds "
++ "(%d tasks refusing to freeze):\n",
++ elapsed_csecs / 100, elapsed_csecs % 100, todo);
++ show_state();
++ }
+ read_lock(&tasklist_lock);
+ do_each_thread(g, p) {
+ task_lock(p);
--- /dev/null
+From 0083b2afe89dea4a06bfd967b164318ad0bccd11 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Wed, 15 Oct 2008 17:52:20 -0700
+Subject: [PATCH 071/134] PM: earlysuspend: Add console switch when user requested sleep state changes.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ kernel/power/Kconfig | 17 ++++++++
+ kernel/power/Makefile | 1 +
+ kernel/power/consoleearlysuspend.c | 78 ++++++++++++++++++++++++++++++++++++
+ 3 files changed, 96 insertions(+), 0 deletions(-)
+ create mode 100644 kernel/power/consoleearlysuspend.c
+
+--- a/kernel/power/Kconfig
++++ b/kernel/power/Kconfig
+@@ -157,6 +157,23 @@ config EARLYSUSPEND
+ Call early suspend handlers when the user requested sleep state
+ changes.
+
++choice
++ prompt "User-space screen access"
++ default CONSOLE_EARLYSUSPEND
++ depends on HAS_EARLYSUSPEND
++
++ config NO_USER_SPACE_SCREEN_ACCESS_CONTROL
++ bool "None"
++
++ config CONSOLE_EARLYSUSPEND
++ bool "Console switch on early-suspend"
++ depends on HAS_EARLYSUSPEND && VT
++ ---help---
++ Register early suspend handler to perform a console switch to
++ when user-space should stop drawing to the screen and a switch
++ back when it should resume.
++endchoice
++
+ config HIBERNATION
+ bool "Hibernation (aka 'suspend to disk')"
+ depends on PM && SWAP && ARCH_HIBERNATION_POSSIBLE
+--- a/kernel/power/Makefile
++++ b/kernel/power/Makefile
+@@ -9,6 +9,7 @@ obj-$(CONFIG_FREEZER) += process.o
+ obj-$(CONFIG_WAKELOCK) += wakelock.o
+ obj-$(CONFIG_USER_WAKELOCK) += userwakelock.o
+ obj-$(CONFIG_EARLYSUSPEND) += earlysuspend.o
++obj-$(CONFIG_CONSOLE_EARLYSUSPEND) += consoleearlysuspend.o
+ obj-$(CONFIG_HIBERNATION) += swsusp.o disk.o snapshot.o swap.o user.o
+
+ obj-$(CONFIG_MAGIC_SYSRQ) += poweroff.o
+--- /dev/null
++++ b/kernel/power/consoleearlysuspend.c
+@@ -0,0 +1,78 @@
++/* kernel/power/consoleearlysuspend.c
++ *
++ * Copyright (C) 2005-2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/console.h>
++#include <linux/earlysuspend.h>
++#include <linux/kbd_kern.h>
++#include <linux/module.h>
++#include <linux/vt_kern.h>
++#include <linux/wait.h>
++
++#define EARLY_SUSPEND_CONSOLE (MAX_NR_CONSOLES-1)
++
++static int orig_fgconsole;
++static void console_early_suspend(struct early_suspend *h)
++{
++ acquire_console_sem();
++ orig_fgconsole = fg_console;
++ if (vc_allocate(EARLY_SUSPEND_CONSOLE))
++ goto err;
++ if (set_console(EARLY_SUSPEND_CONSOLE))
++ goto err;
++ release_console_sem();
++
++ if (vt_waitactive(EARLY_SUSPEND_CONSOLE))
++ pr_warning("console_early_suspend: Can't switch VCs.\n");
++ return;
++err:
++ pr_warning("console_early_suspend: Can't set console\n");
++ release_console_sem();
++}
++
++static void console_late_resume(struct early_suspend *h)
++{
++ int ret;
++ acquire_console_sem();
++ ret = set_console(orig_fgconsole);
++ release_console_sem();
++ if (ret) {
++ pr_warning("console_late_resume: Can't set console.\n");
++ return;
++ }
++
++ if (vt_waitactive(orig_fgconsole))
++ pr_warning("console_late_resume: Can't switch VCs.\n");
++}
++
++static struct early_suspend console_early_suspend_desc = {
++ .level = EARLY_SUSPEND_LEVEL_STOP_DRAWING,
++ .suspend = console_early_suspend,
++ .resume = console_late_resume,
++};
++
++static int __init console_early_suspend_init(void)
++{
++ register_early_suspend(&console_early_suspend_desc);
++ return 0;
++}
++
++static void __exit console_early_suspend_exit(void)
++{
++ unregister_early_suspend(&console_early_suspend_desc);
++}
++
++module_init(console_early_suspend_init);
++module_exit(console_early_suspend_exit);
++
--- /dev/null
+From ba801aa66e869f1f9f9d3a1610a2165baa024e4b Mon Sep 17 00:00:00 2001
+From: Rebecca Schultz <rschultz@google.com>
+Date: Thu, 17 Jul 2008 18:14:55 -0700
+Subject: [PATCH 072/134] PM: earlysuspend: Removing dependence on console.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Rather than signaling a full update of the display from userspace via a
+console switch, this patch introduces 2 files int /sys/power,
+wait_for_fb_sleep and wait_for_fb_wake. Reading these files will block
+until the requested state has been entered. When a read from
+wait_for_fb_sleep returns userspace should stop drawing. When
+wait_for_fb_wake returns, it should do a full update. If either are called
+when the fb driver is already in the requested state, they will return
+immediately.
+
+Signed-off-by: Rebecca Schultz <rschultz@google.com>
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ kernel/power/Kconfig | 9 +++
+ kernel/power/Makefile | 1 +
+ kernel/power/fbearlysuspend.c | 153 +++++++++++++++++++++++++++++++++++++++++
+ 3 files changed, 163 insertions(+), 0 deletions(-)
+ create mode 100644 kernel/power/fbearlysuspend.c
+
+--- a/kernel/power/Kconfig
++++ b/kernel/power/Kconfig
+@@ -159,6 +159,7 @@ config EARLYSUSPEND
+
+ choice
+ prompt "User-space screen access"
++ default FB_EARLYSUSPEND if !FRAMEBUFFER_CONSOLE
+ default CONSOLE_EARLYSUSPEND
+ depends on HAS_EARLYSUSPEND
+
+@@ -172,6 +173,14 @@ choice
+ Register early suspend handler to perform a console switch to
+ when user-space should stop drawing to the screen and a switch
+ back when it should resume.
++
++ config FB_EARLYSUSPEND
++ bool "Sysfs interface"
++ depends on HAS_EARLYSUSPEND
++ ---help---
++ Register early suspend handler that notifies and waits for
++ user-space through sysfs when user-space should stop drawing
++ to the screen and notifies user-space when it should resume.
+ endchoice
+
+ config HIBERNATION
+--- a/kernel/power/Makefile
++++ b/kernel/power/Makefile
+@@ -10,6 +10,7 @@ obj-$(CONFIG_WAKELOCK) += wakelock.o
+ obj-$(CONFIG_USER_WAKELOCK) += userwakelock.o
+ obj-$(CONFIG_EARLYSUSPEND) += earlysuspend.o
+ obj-$(CONFIG_CONSOLE_EARLYSUSPEND) += consoleearlysuspend.o
++obj-$(CONFIG_FB_EARLYSUSPEND) += fbearlysuspend.o
+ obj-$(CONFIG_HIBERNATION) += swsusp.o disk.o snapshot.o swap.o user.o
+
+ obj-$(CONFIG_MAGIC_SYSRQ) += poweroff.o
+--- /dev/null
++++ b/kernel/power/fbearlysuspend.c
+@@ -0,0 +1,153 @@
++/* kernel/power/fbearlysuspend.c
++ *
++ * Copyright (C) 2005-2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/earlysuspend.h>
++#include <linux/module.h>
++#include <linux/wait.h>
++
++#include "power.h"
++
++static wait_queue_head_t fb_state_wq;
++static DEFINE_SPINLOCK(fb_state_lock);
++static enum {
++ FB_STATE_STOPPED_DRAWING,
++ FB_STATE_REQUEST_STOP_DRAWING,
++ FB_STATE_DRAWING_OK,
++} fb_state;
++
++/* tell userspace to stop drawing, wait for it to stop */
++static void stop_drawing_early_suspend(struct early_suspend *h)
++{
++ int ret;
++ unsigned long irq_flags;
++
++ spin_lock_irqsave(&fb_state_lock, irq_flags);
++ fb_state = FB_STATE_REQUEST_STOP_DRAWING;
++ spin_unlock_irqrestore(&fb_state_lock, irq_flags);
++
++ wake_up_all(&fb_state_wq);
++ ret = wait_event_timeout(fb_state_wq,
++ fb_state == FB_STATE_STOPPED_DRAWING,
++ HZ);
++ if (unlikely(fb_state != FB_STATE_STOPPED_DRAWING))
++ pr_warning("stop_drawing_early_suspend: timeout waiting for "
++ "userspace to stop drawing\n");
++}
++
++/* tell userspace to start drawing */
++static void start_drawing_late_resume(struct early_suspend *h)
++{
++ unsigned long irq_flags;
++
++ spin_lock_irqsave(&fb_state_lock, irq_flags);
++ fb_state = FB_STATE_DRAWING_OK;
++ spin_unlock_irqrestore(&fb_state_lock, irq_flags);
++ wake_up(&fb_state_wq);
++}
++
++static struct early_suspend stop_drawing_early_suspend_desc = {
++ .level = EARLY_SUSPEND_LEVEL_STOP_DRAWING,
++ .suspend = stop_drawing_early_suspend,
++ .resume = start_drawing_late_resume,
++};
++
++static ssize_t wait_for_fb_sleep_show(struct kobject *kobj,
++ struct kobj_attribute *attr, char *buf)
++{
++ char *s = buf;
++ int ret;
++
++ ret = wait_event_interruptible(fb_state_wq,
++ fb_state != FB_STATE_DRAWING_OK);
++ if (ret && fb_state == FB_STATE_DRAWING_OK)
++ return ret;
++ else
++ s += sprintf(buf, "sleeping");
++ return s - buf;
++}
++
++static ssize_t wait_for_fb_wake_show(struct kobject *kobj,
++ struct kobj_attribute *attr, char *buf)
++{
++ char *s = buf;
++ int ret;
++ unsigned long irq_flags;
++
++ spin_lock_irqsave(&fb_state_lock, irq_flags);
++ if (fb_state == FB_STATE_REQUEST_STOP_DRAWING) {
++ fb_state = FB_STATE_STOPPED_DRAWING;
++ wake_up(&fb_state_wq);
++ }
++ spin_unlock_irqrestore(&fb_state_lock, irq_flags);
++
++ ret = wait_event_interruptible(fb_state_wq,
++ fb_state == FB_STATE_DRAWING_OK);
++ if (ret && fb_state != FB_STATE_DRAWING_OK)
++ return ret;
++ else
++ s += sprintf(buf, "awake");
++
++ return s - buf;
++}
++
++#define power_ro_attr(_name) \
++static struct kobj_attribute _name##_attr = { \
++ .attr = { \
++ .name = __stringify(_name), \
++ .mode = 0444, \
++ }, \
++ .show = _name##_show, \
++ .store = NULL, \
++}
++
++power_ro_attr(wait_for_fb_sleep);
++power_ro_attr(wait_for_fb_wake);
++
++static struct attribute *g[] = {
++ &wait_for_fb_sleep_attr.attr,
++ &wait_for_fb_wake_attr.attr,
++ NULL,
++};
++
++static struct attribute_group attr_group = {
++ .attrs = g,
++};
++
++static int __init android_power_init(void)
++{
++ int ret;
++
++ init_waitqueue_head(&fb_state_wq);
++ fb_state = FB_STATE_DRAWING_OK;
++
++ ret = sysfs_create_group(power_kobj, &attr_group);
++ if (ret) {
++ pr_err("android_power_init: sysfs_create_group failed\n");
++ return ret;
++ }
++
++ register_early_suspend(&stop_drawing_early_suspend_desc);
++ return 0;
++}
++
++static void __exit android_power_exit(void)
++{
++ unregister_early_suspend(&stop_drawing_early_suspend_desc);
++ sysfs_remove_group(power_kobj, &attr_group);
++}
++
++module_init(android_power_init);
++module_exit(android_power_exit);
++
--- /dev/null
+From 2df5996350da51bcdee798c00ae1f2415fd9ad20 Mon Sep 17 00:00:00 2001
+From: Robert Love <rlove@google.com>
+Date: Mon, 12 May 2008 17:08:29 -0400
+Subject: [PATCH 081/134] net: socket ioctl to reset connections matching local address
+
+Introduce a new socket ioctl, SIOCKILLADDR, that nukes all sockets
+bound to the same local address. This is useful in situations with
+dynamic IPs, to kill stuck connections.
+
+Signed-off-by: Brian Swetland <swetland@google.com>
+
+net: fix tcp_v4_nuke_addr
+
+Signed-off-by: Dima Zavin <dima@android.com>
+---
+ include/linux/sockios.h | 1 +
+ include/net/tcp.h | 2 ++
+ net/ipv4/af_inet.c | 1 +
+ net/ipv4/devinet.c | 9 ++++++++-
+ net/ipv4/tcp_ipv4.c | 31 +++++++++++++++++++++++++++++++
+ 5 files changed, 43 insertions(+), 1 deletions(-)
+
+--- a/include/linux/sockios.h
++++ b/include/linux/sockios.h
+@@ -65,6 +65,7 @@
+ #define SIOCDIFADDR 0x8936 /* delete PA address */
+ #define SIOCSIFHWBROADCAST 0x8937 /* set hardware broadcast addr */
+ #define SIOCGIFCOUNT 0x8938 /* get number of devices */
++#define SIOCKILLADDR 0x8939 /* kill sockets with this local addr */
+
+ #define SIOCGIFBR 0x8940 /* Bridging support */
+ #define SIOCSIFBR 0x8941 /* Set bridging options */
+--- a/include/net/tcp.h
++++ b/include/net/tcp.h
+@@ -1381,6 +1381,8 @@ extern struct sk_buff **tcp4_gro_receive
+ extern int tcp_gro_complete(struct sk_buff *skb);
+ extern int tcp4_gro_complete(struct sk_buff *skb);
+
++extern void tcp_v4_nuke_addr(__u32 saddr);
++
+ #ifdef CONFIG_PROC_FS
+ extern int tcp4_proc_init(void);
+ extern void tcp4_proc_exit(void);
+--- a/net/ipv4/af_inet.c
++++ b/net/ipv4/af_inet.c
+@@ -825,6 +825,7 @@ int inet_ioctl(struct socket *sock, unsi
+ case SIOCSIFPFLAGS:
+ case SIOCGIFPFLAGS:
+ case SIOCSIFFLAGS:
++ case SIOCKILLADDR:
+ err = devinet_ioctl(net, cmd, (void __user *)arg);
+ break;
+ default:
+--- a/net/ipv4/devinet.c
++++ b/net/ipv4/devinet.c
+@@ -57,6 +57,7 @@
+
+ #include <net/arp.h>
+ #include <net/ip.h>
++#include <net/tcp.h>
+ #include <net/route.h>
+ #include <net/ip_fib.h>
+ #include <net/rtnetlink.h>
+@@ -631,6 +632,7 @@ int devinet_ioctl(struct net *net, unsig
+ case SIOCSIFBRDADDR: /* Set the broadcast address */
+ case SIOCSIFDSTADDR: /* Set the destination address */
+ case SIOCSIFNETMASK: /* Set the netmask for the interface */
++ case SIOCKILLADDR: /* Nuke all sockets on this address */
+ ret = -EACCES;
+ if (!capable(CAP_NET_ADMIN))
+ goto out;
+@@ -680,7 +682,8 @@ int devinet_ioctl(struct net *net, unsig
+ }
+
+ ret = -EADDRNOTAVAIL;
+- if (!ifa && cmd != SIOCSIFADDR && cmd != SIOCSIFFLAGS)
++ if (!ifa && cmd != SIOCSIFADDR && cmd != SIOCSIFFLAGS
++ && cmd != SIOCKILLADDR)
+ goto done;
+
+ switch (cmd) {
+@@ -804,6 +807,10 @@ int devinet_ioctl(struct net *net, unsig
+ inet_insert_ifa(ifa);
+ }
+ break;
++ case SIOCKILLADDR: /* Nuke all connections on this address */
++ ret = 0;
++ tcp_v4_nuke_addr(sin->sin_addr.s_addr);
++ break;
+ }
+ done:
+ rtnl_unlock();
+--- a/net/ipv4/tcp_ipv4.c
++++ b/net/ipv4/tcp_ipv4.c
+@@ -1845,6 +1845,37 @@ void tcp_v4_destroy_sock(struct sock *sk
+
+ EXPORT_SYMBOL(tcp_v4_destroy_sock);
+
++/*
++ * tcp_v4_nuke_addr - destroy all sockets on the given local address
++ */
++void tcp_v4_nuke_addr(__u32 saddr)
++{
++ unsigned int bucket;
++
++ for (bucket = 0; bucket < tcp_hashinfo.ehash_size; bucket++) {
++ struct hlist_nulls_node *node;
++ struct sock *sk;
++ spinlock_t *lock = inet_ehash_lockp(&tcp_hashinfo, bucket);
++
++ spin_lock_bh(lock);
++ sk_nulls_for_each(sk, node, &tcp_hashinfo.ehash[bucket].chain) {
++ struct inet_sock *inet = inet_sk(sk);
++
++ if (inet->rcv_saddr != saddr)
++ continue;
++ if (sysctl_ip_dynaddr && sk->sk_state == TCP_SYN_SENT)
++ continue;
++ if (sock_flag(sk, SOCK_DEAD))
++ continue;
++
++ sk->sk_err = ETIMEDOUT;
++ sk->sk_error_report(sk);
++ tcp_done(sk);
++ }
++ spin_unlock_bh(lock);
++ }
++}
++
+ #ifdef CONFIG_PROC_FS
+ /* Proc filesystem TCP sock list dumping. */
+
--- /dev/null
+From 75090d40ffbd9b4863238e1d62b43f8598da5e5e Mon Sep 17 00:00:00 2001
+From: Robert Love <rlove@google.com>
+Date: Thu, 31 Jul 2008 11:12:44 -0400
+Subject: [PATCH 082/134] sysfs_net_ipv4: Add sysfs-based knobs for controlling TCP window size
+
+Add a family of knobs to /sys/kernel/ipv4 for controlling the TCP window size:
+
+ tcp_wmem_min
+ tcp_wmem_def
+ tcp_wmem_max
+ tcp_rmem_min
+ tcp_rmem_def
+ tcp_rmem_max
+
+This six values mirror the sysctl knobs in /proc/sys/net/ipv4/tcp_wmem and
+/proc/sys/net/ipv4/tcp_rmem.
+
+Sysfs, unlike sysctl, allows us to set and manage the files' permissions and
+owners.
+
+Signed-off-by: Robert Love <rlove@google.com>
+---
+ net/ipv4/Makefile | 1 +
+ net/ipv4/sysfs_net_ipv4.c | 88 +++++++++++++++++++++++++++++++++++++++++++++
+ 2 files changed, 89 insertions(+), 0 deletions(-)
+ create mode 100644 net/ipv4/sysfs_net_ipv4.c
+
+--- a/net/ipv4/Makefile
++++ b/net/ipv4/Makefile
+@@ -14,6 +14,7 @@ obj-y := route.o inetpeer.o protocol
+ inet_fragment.o
+
+ obj-$(CONFIG_SYSCTL) += sysctl_net_ipv4.o
++obj-$(CONFIG_SYSFS) += sysfs_net_ipv4.o
+ obj-$(CONFIG_IP_FIB_HASH) += fib_hash.o
+ obj-$(CONFIG_IP_FIB_TRIE) += fib_trie.o
+ obj-$(CONFIG_PROC_FS) += proc.o
+--- /dev/null
++++ b/net/ipv4/sysfs_net_ipv4.c
+@@ -0,0 +1,88 @@
++/*
++ * net/ipv4/sysfs_net_ipv4.c
++ *
++ * sysfs-based networking knobs (so we can, unlike with sysctl, control perms)
++ *
++ * Copyright (C) 2008 Google, Inc.
++ *
++ * Robert Love <rlove@google.com>
++ *
++ * 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/kobject.h>
++#include <linux/string.h>
++#include <linux/sysfs.h>
++#include <linux/init.h>
++#include <net/tcp.h>
++
++#define CREATE_IPV4_FILE(_name, _var) \
++static ssize_t _name##_show(struct kobject *kobj, \
++ struct kobj_attribute *attr, char *buf) \
++{ \
++ return sprintf(buf, "%d\n", _var); \
++} \
++static ssize_t _name##_store(struct kobject *kobj, \
++ struct kobj_attribute *attr, \
++ const char *buf, size_t count) \
++{ \
++ int val, ret; \
++ ret = sscanf(buf, "%d", &val); \
++ if (ret != 1) \
++ return -EINVAL; \
++ if (val < 0) \
++ return -EINVAL; \
++ _var = val; \
++ return count; \
++} \
++static struct kobj_attribute _name##_attr = \
++ __ATTR(_name, 0644, _name##_show, _name##_store)
++
++CREATE_IPV4_FILE(tcp_wmem_min, sysctl_tcp_wmem[0]);
++CREATE_IPV4_FILE(tcp_wmem_def, sysctl_tcp_wmem[1]);
++CREATE_IPV4_FILE(tcp_wmem_max, sysctl_tcp_wmem[2]);
++
++CREATE_IPV4_FILE(tcp_rmem_min, sysctl_tcp_rmem[0]);
++CREATE_IPV4_FILE(tcp_rmem_def, sysctl_tcp_rmem[1]);
++CREATE_IPV4_FILE(tcp_rmem_max, sysctl_tcp_rmem[2]);
++
++static struct attribute *ipv4_attrs[] = {
++ &tcp_wmem_min_attr.attr,
++ &tcp_wmem_def_attr.attr,
++ &tcp_wmem_max_attr.attr,
++ &tcp_rmem_min_attr.attr,
++ &tcp_rmem_def_attr.attr,
++ &tcp_rmem_max_attr.attr,
++ NULL
++};
++
++static struct attribute_group ipv4_attr_group = {
++ .attrs = ipv4_attrs,
++};
++
++static __init int sysfs_ipv4_init(void)
++{
++ struct kobject *ipv4_kobject;
++ int ret;
++
++ ipv4_kobject = kobject_create_and_add("ipv4", kernel_kobj);
++ if (!ipv4_kobject)
++ return -ENOMEM;
++
++ ret = sysfs_create_group(ipv4_kobject, &ipv4_attr_group);
++ if (ret) {
++ kobject_put(ipv4_kobject);
++ return ret;
++ }
++
++ return 0;
++}
++
++subsys_initcall(sysfs_ipv4_init);
--- /dev/null
+From 6730377482c05a1742abb92f1463701f5d084a27 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Wed, 15 Oct 2008 18:23:47 -0700
+Subject: [PATCH 086/134] Input: Generic GPIO Input device.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Supports keyboard matrixces, direct inputs, direct outputs and axes connected to gpios.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+Signed-off-by: Nick Pelly <npelly@google.com>
+---
+ drivers/input/misc/Kconfig | 5 +
+ drivers/input/misc/Makefile | 1 +
+ drivers/input/misc/gpio_axis.c | 180 +++++++++++++++++
+ drivers/input/misc/gpio_event.c | 224 +++++++++++++++++++++
+ drivers/input/misc/gpio_input.c | 343 ++++++++++++++++++++++++++++++++
+ drivers/input/misc/gpio_matrix.c | 406 ++++++++++++++++++++++++++++++++++++++
+ drivers/input/misc/gpio_output.c | 84 ++++++++
+ include/linux/gpio_event.h | 154 ++++++++++++++
+ 8 files changed, 1397 insertions(+), 0 deletions(-)
+ create mode 100644 drivers/input/misc/gpio_axis.c
+ create mode 100644 drivers/input/misc/gpio_event.c
+ create mode 100644 drivers/input/misc/gpio_input.c
+ create mode 100644 drivers/input/misc/gpio_matrix.c
+ create mode 100644 drivers/input/misc/gpio_output.c
+ create mode 100644 include/linux/gpio_event.h
+
+--- a/drivers/input/misc/Kconfig
++++ b/drivers/input/misc/Kconfig
+@@ -212,6 +212,11 @@ config INPUT_SGI_BTNS
+ To compile this driver as a module, choose M here: the
+ module will be called sgi_btns.
+
++config INPUT_GPIO
++ tristate "GPIO driver support"
++ help
++ Say Y here if you want to support gpio based keys, wheels etc...
++
+ config HP_SDC_RTC
+ tristate "HP SDC Real Time Clock"
+ depends on (GSC || HP300) && SERIO
+--- a/drivers/input/misc/Makefile
++++ b/drivers/input/misc/Makefile
+@@ -25,3 +25,5 @@ obj-$(CONFIG_INPUT_UINPUT) += uinput.o
+ obj-$(CONFIG_INPUT_WISTRON_BTNS) += wistron_btns.o
+ obj-$(CONFIG_INPUT_YEALINK) += yealink.o
+ obj-$(CONFIG_INPUT_GPIO_BUTTONS) += gpio_buttons.o
++obj-$(CONFIG_INPUT_GPIO) += gpio_event.o gpio_matrix.o gpio_input.o gpio_output.o gpio_axis.o
++
+--- /dev/null
++++ b/drivers/input/misc/gpio_axis.c
+@@ -0,0 +1,180 @@
++/* drivers/input/misc/gpio_axis.c
++ *
++ * Copyright (C) 2007 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/kernel.h>
++#include <linux/gpio.h>
++#include <linux/gpio_event.h>
++#include <linux/interrupt.h>
++
++struct gpio_axis_state {
++ struct input_dev *input_dev;
++ struct gpio_event_axis_info *info;
++ uint32_t pos;
++};
++
++uint16_t gpio_axis_4bit_gray_map_table[] = {
++ [0x0] = 0x0, [0x1] = 0x1, /* 0000 0001 */
++ [0x3] = 0x2, [0x2] = 0x3, /* 0011 0010 */
++ [0x6] = 0x4, [0x7] = 0x5, /* 0110 0111 */
++ [0x5] = 0x6, [0x4] = 0x7, /* 0101 0100 */
++ [0xc] = 0x8, [0xd] = 0x9, /* 1100 1101 */
++ [0xf] = 0xa, [0xe] = 0xb, /* 1111 1110 */
++ [0xa] = 0xc, [0xb] = 0xd, /* 1010 1011 */
++ [0x9] = 0xe, [0x8] = 0xf, /* 1001 1000 */
++};
++uint16_t gpio_axis_4bit_gray_map(struct gpio_event_axis_info *info, uint16_t in)
++{
++ return gpio_axis_4bit_gray_map_table[in];
++}
++
++uint16_t gpio_axis_5bit_singletrack_map_table[] = {
++ [0x10] = 0x00, [0x14] = 0x01, [0x1c] = 0x02, /* 10000 10100 11100 */
++ [0x1e] = 0x03, [0x1a] = 0x04, [0x18] = 0x05, /* 11110 11010 11000 */
++ [0x08] = 0x06, [0x0a] = 0x07, [0x0e] = 0x08, /* 01000 01010 01110 */
++ [0x0f] = 0x09, [0x0d] = 0x0a, [0x0c] = 0x0b, /* 01111 01101 01100 */
++ [0x04] = 0x0c, [0x05] = 0x0d, [0x07] = 0x0e, /* 00100 00101 00111 */
++ [0x17] = 0x0f, [0x16] = 0x10, [0x06] = 0x11, /* 10111 10110 00110 */
++ [0x02] = 0x12, [0x12] = 0x13, [0x13] = 0x14, /* 00010 10010 10011 */
++ [0x1b] = 0x15, [0x0b] = 0x16, [0x03] = 0x17, /* 11011 01011 00011 */
++ [0x01] = 0x18, [0x09] = 0x19, [0x19] = 0x1a, /* 00001 01001 11001 */
++ [0x1d] = 0x1b, [0x15] = 0x1c, [0x11] = 0x1d, /* 11101 10101 10001 */
++};
++uint16_t gpio_axis_5bit_singletrack_map(
++ struct gpio_event_axis_info *info, uint16_t in)
++{
++ return gpio_axis_5bit_singletrack_map_table[in];
++}
++
++static void gpio_event_update_axis(struct gpio_axis_state *as, int report)
++{
++ struct gpio_event_axis_info *ai = as->info;
++ int i;
++ int change;
++ uint16_t state = 0;
++ uint16_t pos;
++ uint16_t old_pos = as->pos;
++ for (i = ai->count - 1; i >= 0; i--)
++ state = (state << 1) | gpio_get_value(ai->gpio[i]);
++ pos = ai->map(ai, state);
++ if (ai->flags & GPIOEAF_PRINT_RAW)
++ pr_info("axis %d-%d raw %x, pos %d -> %d\n",
++ ai->type, ai->code, state, old_pos, pos);
++ if (report && pos != old_pos) {
++ if (ai->type == EV_REL) {
++ change = (ai->decoded_size + pos - old_pos) %
++ ai->decoded_size;
++ if (change > ai->decoded_size / 2)
++ change -= ai->decoded_size;
++ if (change == ai->decoded_size / 2) {
++ if (ai->flags & GPIOEAF_PRINT_EVENT)
++ pr_info("axis %d-%d unknown direction, "
++ "pos %d -> %d\n", ai->type,
++ ai->code, old_pos, pos);
++ change = 0; /* no closest direction */
++ }
++ if (ai->flags & GPIOEAF_PRINT_EVENT)
++ pr_info("axis %d-%d change %d\n",
++ ai->type, ai->code, change);
++ input_report_rel(as->input_dev, ai->code, change);
++ } else {
++ if (ai->flags & GPIOEAF_PRINT_EVENT)
++ pr_info("axis %d-%d now %d\n",
++ ai->type, ai->code, pos);
++ input_event(as->input_dev, ai->type, ai->code, pos);
++ }
++ input_sync(as->input_dev);
++ }
++ as->pos = pos;
++}
++
++static irqreturn_t gpio_axis_irq_handler(int irq, void *dev_id)
++{
++ struct gpio_axis_state *as = dev_id;
++ gpio_event_update_axis(as, 1);
++ return IRQ_HANDLED;
++}
++
++int gpio_event_axis_func(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data, int func)
++{
++ int ret;
++ int i;
++ int irq;
++ struct gpio_event_axis_info *ai;
++ struct gpio_axis_state *as;
++
++ ai = container_of(info, struct gpio_event_axis_info, info);
++ if (func == GPIO_EVENT_FUNC_SUSPEND) {
++ for (i = 0; i < ai->count; i++)
++ disable_irq(gpio_to_irq(ai->gpio[i]));
++ return 0;
++ }
++ if (func == GPIO_EVENT_FUNC_RESUME) {
++ for (i = 0; i < ai->count; i++)
++ enable_irq(gpio_to_irq(ai->gpio[i]));
++ return 0;
++ }
++
++ if (func == GPIO_EVENT_FUNC_INIT) {
++ *data = as = kmalloc(sizeof(*as), GFP_KERNEL);
++ if (as == NULL) {
++ ret = -ENOMEM;
++ goto err_alloc_axis_state_failed;
++ }
++ as->input_dev = input_dev;
++ as->info = ai;
++
++ input_set_capability(input_dev, ai->type, ai->code);
++ if (ai->type == EV_ABS) {
++ input_set_abs_params(input_dev, ai->code, 0,
++ ai->decoded_size - 1, 0, 0);
++ }
++ for (i = 0; i < ai->count; i++) {
++ ret = gpio_request(ai->gpio[i], "gpio_event_axis");
++ if (ret < 0)
++ goto err_request_gpio_failed;
++ ret = gpio_direction_input(ai->gpio[i]);
++ if (ret < 0)
++ goto err_gpio_direction_input_failed;
++ ret = irq = gpio_to_irq(ai->gpio[i]);
++ if (ret < 0)
++ goto err_get_irq_num_failed;
++ ret = request_irq(irq, gpio_axis_irq_handler,
++ IRQF_TRIGGER_RISING |
++ IRQF_TRIGGER_FALLING,
++ "gpio_event_axis", as);
++ if (ret < 0)
++ goto err_request_irq_failed;
++ }
++ gpio_event_update_axis(as, 0);
++ return 0;
++ }
++
++ ret = 0;
++ as = *data;
++ for (i = ai->count - 1; i >= 0; i--) {
++ free_irq(gpio_to_irq(ai->gpio[i]), as);
++err_request_irq_failed:
++err_get_irq_num_failed:
++err_gpio_direction_input_failed:
++ gpio_free(ai->gpio[i]);
++err_request_gpio_failed:
++ ;
++ }
++ kfree(as);
++ *data = NULL;
++err_alloc_axis_state_failed:
++ return ret;
++}
+--- /dev/null
++++ b/drivers/input/misc/gpio_event.c
+@@ -0,0 +1,224 @@
++/* drivers/input/misc/gpio_event.c
++ *
++ * Copyright (C) 2007 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/earlysuspend.h>
++#include <linux/module.h>
++#include <linux/input.h>
++#include <linux/gpio_event.h>
++#include <linux/hrtimer.h>
++#include <linux/platform_device.h>
++
++struct gpio_event {
++ struct input_dev *input_dev;
++ const struct gpio_event_platform_data *info;
++ struct early_suspend early_suspend;
++ void *state[0];
++};
++
++static int gpio_input_event(
++ struct input_dev *dev, unsigned int type, unsigned int code, int value)
++{
++ int i;
++ int ret = 0;
++ int tmp_ret;
++ struct gpio_event_info **ii;
++ struct gpio_event *ip = input_get_drvdata(dev);
++
++ for (i = 0, ii = ip->info->info; i < ip->info->info_count; i++, ii++) {
++ if ((*ii)->event) {
++ tmp_ret = (*ii)->event(ip->input_dev, *ii,
++ &ip->state[i], type, code, value);
++ if (tmp_ret)
++ ret = tmp_ret;
++ }
++ }
++ return ret;
++}
++
++static int gpio_event_call_all_func(struct gpio_event *ip, int func)
++{
++ int i;
++ int ret;
++ struct gpio_event_info **ii;
++
++ if (func == GPIO_EVENT_FUNC_INIT || func == GPIO_EVENT_FUNC_RESUME) {
++ ii = ip->info->info;
++ for (i = 0; i < ip->info->info_count; i++, ii++) {
++ if ((*ii)->func == NULL) {
++ ret = -ENODEV;
++ pr_err("gpio_event_probe: Incomplete pdata, "
++ "no function\n");
++ goto err_no_func;
++ }
++ ret = (*ii)->func(ip->input_dev, *ii, &ip->state[i],
++ func);
++ if (ret) {
++ pr_err("gpio_event_probe: function failed\n");
++ goto err_func_failed;
++ }
++ }
++ return 0;
++ }
++
++ ret = 0;
++ i = ip->info->info_count;
++ ii = ip->info->info + i;
++ while (i > 0) {
++ i--;
++ ii--;
++ (*ii)->func(ip->input_dev, *ii, &ip->state[i], func & ~1);
++err_func_failed:
++err_no_func:
++ ;
++ }
++ return ret;
++}
++
++#ifdef CONFIG_HAS_EARLYSUSPEND
++void gpio_event_suspend(struct early_suspend *h)
++{
++ struct gpio_event *ip;
++ ip = container_of(h, struct gpio_event, early_suspend);
++ gpio_event_call_all_func(ip, GPIO_EVENT_FUNC_SUSPEND);
++ ip->info->power(ip->info, 0);
++}
++
++void gpio_event_resume(struct early_suspend *h)
++{
++ struct gpio_event *ip;
++ ip = container_of(h, struct gpio_event, early_suspend);
++ ip->info->power(ip->info, 1);
++ gpio_event_call_all_func(ip, GPIO_EVENT_FUNC_RESUME);
++}
++#endif
++
++static int __init gpio_event_probe(struct platform_device *pdev)
++{
++ int err;
++ struct gpio_event *ip;
++ struct input_dev *input_dev;
++ struct gpio_event_platform_data *event_info;
++
++ event_info = pdev->dev.platform_data;
++ if (event_info == NULL) {
++ pr_err("gpio_event_probe: No pdata\n");
++ return -ENODEV;
++ }
++ if (event_info->name == NULL ||
++ event_info->info == NULL ||
++ event_info->info_count == 0) {
++ pr_err("gpio_event_probe: Incomplete pdata\n");
++ return -ENODEV;
++ }
++ ip = kzalloc(sizeof(*ip) +
++ sizeof(ip->state[0]) * event_info->info_count, GFP_KERNEL);
++ if (ip == NULL) {
++ err = -ENOMEM;
++ pr_err("gpio_event_probe: Failed to allocate private data\n");
++ goto err_kp_alloc_failed;
++ }
++ platform_set_drvdata(pdev, ip);
++
++ input_dev = input_allocate_device();
++ if (input_dev == NULL) {
++ err = -ENOMEM;
++ pr_err("gpio_event_probe: Failed to allocate input device\n");
++ goto err_input_dev_alloc_failed;
++ }
++ input_set_drvdata(input_dev, ip);
++ ip->input_dev = input_dev;
++ ip->info = event_info;
++ if (event_info->power) {
++#ifdef CONFIG_HAS_EARLYSUSPEND
++ ip->early_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 1;
++ ip->early_suspend.suspend = gpio_event_suspend;
++ ip->early_suspend.resume = gpio_event_resume;
++ register_early_suspend(&ip->early_suspend);
++#endif
++ ip->info->power(ip->info, 1);
++ }
++
++ input_dev->name = ip->info->name;
++ input_dev->event = gpio_input_event;
++
++ err = gpio_event_call_all_func(ip, GPIO_EVENT_FUNC_INIT);
++ if (err)
++ goto err_call_all_func_failed;
++
++ err = input_register_device(input_dev);
++ if (err) {
++ pr_err("gpio_event_probe: Unable to register %s input device\n",
++ input_dev->name);
++ goto err_input_register_device_failed;
++ }
++
++ return 0;
++
++err_input_register_device_failed:
++ gpio_event_call_all_func(ip, GPIO_EVENT_FUNC_UNINIT);
++err_call_all_func_failed:
++ if (event_info->power) {
++#ifdef CONFIG_HAS_EARLYSUSPEND
++ unregister_early_suspend(&ip->early_suspend);
++#endif
++ ip->info->power(ip->info, 0);
++ }
++ input_free_device(input_dev);
++err_input_dev_alloc_failed:
++ kfree(ip);
++err_kp_alloc_failed:
++ return err;
++}
++
++static int gpio_event_remove(struct platform_device *pdev)
++{
++ struct gpio_event *ip = platform_get_drvdata(pdev);
++
++ gpio_event_call_all_func(ip, GPIO_EVENT_FUNC_UNINIT);
++ if (ip->info->power) {
++#ifdef CONFIG_HAS_EARLYSUSPEND
++ unregister_early_suspend(&ip->early_suspend);
++#endif
++ ip->info->power(ip->info, 0);
++ }
++ input_unregister_device(ip->input_dev);
++ kfree(ip);
++ return 0;
++}
++
++static struct platform_driver gpio_event_driver = {
++ .probe = gpio_event_probe,
++ .remove = gpio_event_remove,
++ .driver = {
++ .name = GPIO_EVENT_DEV_NAME,
++ },
++};
++
++static int __devinit gpio_event_init(void)
++{
++ return platform_driver_register(&gpio_event_driver);
++}
++
++static void __exit gpio_event_exit(void)
++{
++ platform_driver_unregister(&gpio_event_driver);
++}
++
++module_init(gpio_event_init);
++module_exit(gpio_event_exit);
++
++MODULE_DESCRIPTION("GPIO Event Driver");
++MODULE_LICENSE("GPL");
++
+--- /dev/null
++++ b/drivers/input/misc/gpio_input.c
+@@ -0,0 +1,343 @@
++/* drivers/input/misc/gpio_input.c
++ *
++ * Copyright (C) 2007 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/kernel.h>
++#include <linux/gpio.h>
++#include <linux/gpio_event.h>
++#include <linux/hrtimer.h>
++#include <linux/input.h>
++#include <linux/interrupt.h>
++#include <linux/wakelock.h>
++
++enum {
++ DEBOUNCE_UNSTABLE = BIT(0), /* Got irq, while debouncing */
++ DEBOUNCE_PRESSED = BIT(1),
++ DEBOUNCE_NOTPRESSED = BIT(2),
++ DEBOUNCE_WAIT_IRQ = BIT(3), /* Stable irq state */
++ DEBOUNCE_POLL = BIT(4), /* Stable polling state */
++
++ DEBOUNCE_UNKNOWN =
++ DEBOUNCE_PRESSED | DEBOUNCE_NOTPRESSED,
++};
++
++struct gpio_key_state {
++ struct gpio_input_state *ds;
++ uint8_t debounce;
++};
++
++struct gpio_input_state {
++ struct input_dev *input_dev;
++ const struct gpio_event_input_info *info;
++ struct hrtimer timer;
++ int use_irq;
++ int debounce_count;
++ spinlock_t irq_lock;
++ struct wake_lock wake_lock;
++ struct gpio_key_state key_state[0];
++};
++
++static enum hrtimer_restart gpio_event_input_timer_func(struct hrtimer *timer)
++{
++ int i;
++ int pressed;
++ struct gpio_input_state *ds =
++ container_of(timer, struct gpio_input_state, timer);
++ unsigned gpio_flags = ds->info->flags;
++ unsigned npolarity;
++ int nkeys = ds->info->keymap_size;
++ const struct gpio_event_direct_entry *key_entry;
++ struct gpio_key_state *key_state;
++ unsigned long irqflags;
++ uint8_t debounce;
++
++#if 0
++ key_entry = kp->keys_info->keymap;
++ key_state = kp->key_state;
++ for (i = 0; i < nkeys; i++, key_entry++, key_state++)
++ pr_info("gpio_read_detect_status %d %d\n", key_entry->gpio,
++ gpio_read_detect_status(key_entry->gpio));
++#endif
++ key_entry = ds->info->keymap;
++ key_state = ds->key_state;
++ spin_lock_irqsave(&ds->irq_lock, irqflags);
++ for (i = 0; i < nkeys; i++, key_entry++, key_state++) {
++ debounce = key_state->debounce;
++ if (debounce & DEBOUNCE_WAIT_IRQ)
++ continue;
++ if (key_state->debounce & DEBOUNCE_UNSTABLE) {
++ debounce = key_state->debounce = DEBOUNCE_UNKNOWN;
++ enable_irq(gpio_to_irq(key_entry->gpio));
++ pr_info("gpio_keys_scan_keys: key %x-%x, %d "
++ "(%d) continue debounce\n",
++ ds->info->type, key_entry->code,
++ i, key_entry->gpio);
++ }
++ npolarity = !(gpio_flags & GPIOEDF_ACTIVE_HIGH);
++ pressed = gpio_get_value(key_entry->gpio) ^ npolarity;
++ if (debounce & DEBOUNCE_POLL) {
++ if (pressed == !(debounce & DEBOUNCE_PRESSED)) {
++ ds->debounce_count++;
++ key_state->debounce = DEBOUNCE_UNKNOWN;
++ if (gpio_flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
++ pr_info("gpio_keys_scan_keys: key %x-"
++ "%x, %d (%d) start debounce\n",
++ ds->info->type, key_entry->code,
++ i, key_entry->gpio);
++ }
++ continue;
++ }
++ if (pressed && (debounce & DEBOUNCE_NOTPRESSED)) {
++ if (gpio_flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
++ pr_info("gpio_keys_scan_keys: key %x-%x, %d "
++ "(%d) debounce pressed 1\n",
++ ds->info->type, key_entry->code,
++ i, key_entry->gpio);
++ key_state->debounce = DEBOUNCE_PRESSED;
++ continue;
++ }
++ if (!pressed && (debounce & DEBOUNCE_PRESSED)) {
++ if (gpio_flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
++ pr_info("gpio_keys_scan_keys: key %x-%x, %d "
++ "(%d) debounce pressed 0\n",
++ ds->info->type, key_entry->code,
++ i, key_entry->gpio);
++ key_state->debounce = DEBOUNCE_NOTPRESSED;
++ continue;
++ }
++ /* key is stable */
++ ds->debounce_count--;
++ if (ds->use_irq)
++ key_state->debounce |= DEBOUNCE_WAIT_IRQ;
++ else
++ key_state->debounce |= DEBOUNCE_POLL;
++ if (gpio_flags & GPIOEDF_PRINT_KEYS)
++ pr_info("gpio_keys_scan_keys: key %x-%x, %d (%d) "
++ "changed to %d\n", ds->info->type,
++ key_entry->code, i, key_entry->gpio, pressed);
++ input_event(ds->input_dev, ds->info->type,
++ key_entry->code, pressed);
++ }
++
++#if 0
++ key_entry = kp->keys_info->keymap;
++ key_state = kp->key_state;
++ for (i = 0; i < nkeys; i++, key_entry++, key_state++) {
++ pr_info("gpio_read_detect_status %d %d\n", key_entry->gpio,
++ gpio_read_detect_status(key_entry->gpio));
++ }
++#endif
++
++ if (ds->debounce_count)
++ hrtimer_start(timer, ds->info->debounce_time, HRTIMER_MODE_REL);
++ else if (!ds->use_irq)
++ hrtimer_start(timer, ds->info->poll_time, HRTIMER_MODE_REL);
++ else
++ wake_unlock(&ds->wake_lock);
++
++ spin_unlock_irqrestore(&ds->irq_lock, irqflags);
++
++ return HRTIMER_NORESTART;
++}
++
++static irqreturn_t gpio_event_input_irq_handler(int irq, void *dev_id)
++{
++ struct gpio_key_state *ks = dev_id;
++ struct gpio_input_state *ds = ks->ds;
++ int keymap_index = ks - ds->key_state;
++ const struct gpio_event_direct_entry *key_entry;
++ unsigned long irqflags;
++ int pressed;
++
++ if (!ds->use_irq)
++ return IRQ_HANDLED;
++
++ key_entry = &ds->info->keymap[keymap_index];
++
++ if (ds->info->debounce_time.tv64) {
++ spin_lock_irqsave(&ds->irq_lock, irqflags);
++ if (ks->debounce & DEBOUNCE_WAIT_IRQ) {
++ ks->debounce = DEBOUNCE_UNKNOWN;
++ if (ds->debounce_count++ == 0) {
++ wake_lock(&ds->wake_lock);
++ hrtimer_start(
++ &ds->timer, ds->info->debounce_time,
++ HRTIMER_MODE_REL);
++ }
++ if (ds->info->flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
++ pr_info("gpio_event_input_irq_handler: "
++ "key %x-%x, %d (%d) start debounce\n",
++ ds->info->type, key_entry->code,
++ keymap_index, key_entry->gpio);
++ } else {
++ disable_irq(irq);
++ ks->debounce = DEBOUNCE_UNSTABLE;
++ }
++ spin_unlock_irqrestore(&ds->irq_lock, irqflags);
++ } else {
++ pressed = gpio_get_value(key_entry->gpio) ^
++ !(ds->info->flags & GPIOEDF_ACTIVE_HIGH);
++ if (ds->info->flags & GPIOEDF_PRINT_KEYS)
++ pr_info("gpio_event_input_irq_handler: key %x-%x, %d "
++ "(%d) changed to %d\n",
++ ds->info->type, key_entry->code, keymap_index,
++ key_entry->gpio, pressed);
++ input_event(ds->input_dev, ds->info->type,
++ key_entry->code, pressed);
++ }
++ return IRQ_HANDLED;
++}
++
++static int gpio_event_input_request_irqs(struct gpio_input_state *ds)
++{
++ int i;
++ int err;
++ unsigned int irq;
++ unsigned long req_flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
++
++ for (i = 0; i < ds->info->keymap_size; i++) {
++ err = irq = gpio_to_irq(ds->info->keymap[i].gpio);
++ if (err < 0)
++ goto err_gpio_get_irq_num_failed;
++ err = request_irq(irq, gpio_event_input_irq_handler,
++ req_flags, "gpio_keys", &ds->key_state[i]);
++ if (err) {
++ pr_err("gpio_event_input_request_irqs: request_irq "
++ "failed for input %d, irq %d\n",
++ ds->info->keymap[i].gpio, irq);
++ goto err_request_irq_failed;
++ }
++ enable_irq_wake(irq);
++ }
++ return 0;
++
++ for (i = ds->info->keymap_size - 1; i >= 0; i--) {
++ free_irq(gpio_to_irq(ds->info->keymap[i].gpio),
++ &ds->key_state[i]);
++err_request_irq_failed:
++err_gpio_get_irq_num_failed:
++ ;
++ }
++ return err;
++}
++
++int gpio_event_input_func(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data, int func)
++{
++ int ret;
++ int i;
++ unsigned long irqflags;
++ struct gpio_event_input_info *di;
++ struct gpio_input_state *ds = *data;
++
++ di = container_of(info, struct gpio_event_input_info, info);
++
++ if (func == GPIO_EVENT_FUNC_SUSPEND) {
++ spin_lock_irqsave(&ds->irq_lock, irqflags);
++ if (ds->use_irq)
++ for (i = 0; i < di->keymap_size; i++)
++ disable_irq(gpio_to_irq(di->keymap[i].gpio));
++ spin_unlock_irqrestore(&ds->irq_lock, irqflags);
++ hrtimer_cancel(&ds->timer);
++ return 0;
++ }
++ if (func == GPIO_EVENT_FUNC_RESUME) {
++ spin_lock_irqsave(&ds->irq_lock, irqflags);
++ if (ds->use_irq)
++ for (i = 0; i < di->keymap_size; i++)
++ enable_irq(gpio_to_irq(di->keymap[i].gpio));
++ hrtimer_start(&ds->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
++ spin_unlock_irqrestore(&ds->irq_lock, irqflags);
++ return 0;
++ }
++
++ if (func == GPIO_EVENT_FUNC_INIT) {
++ if (ktime_to_ns(di->poll_time) <= 0)
++ di->poll_time = ktime_set(0, 20 * NSEC_PER_MSEC);
++
++ *data = ds = kzalloc(sizeof(*ds) + sizeof(ds->key_state[0]) *
++ di->keymap_size, GFP_KERNEL);
++ if (ds == NULL) {
++ ret = -ENOMEM;
++ pr_err("gpio_event_input_func: "
++ "Failed to allocate private data\n");
++ goto err_ds_alloc_failed;
++ }
++ ds->debounce_count = di->keymap_size;
++ ds->input_dev = input_dev;
++ ds->info = di;
++ wake_lock_init(&ds->wake_lock, WAKE_LOCK_SUSPEND, "gpio_input");
++ spin_lock_init(&ds->irq_lock);
++
++ for (i = 0; i < di->keymap_size; i++) {
++ input_set_capability(input_dev, di->type,
++ di->keymap[i].code);
++ ds->key_state[i].ds = ds;
++ ds->key_state[i].debounce = DEBOUNCE_UNKNOWN;
++ }
++
++ for (i = 0; i < di->keymap_size; i++) {
++ ret = gpio_request(di->keymap[i].gpio, "gpio_kp_in");
++ if (ret) {
++ pr_err("gpio_event_input_func: gpio_request "
++ "failed for %d\n", di->keymap[i].gpio);
++ goto err_gpio_request_failed;
++ }
++ ret = gpio_direction_input(di->keymap[i].gpio);
++ if (ret) {
++ pr_err("gpio_event_input_func: "
++ "gpio_direction_input failed for %d\n",
++ di->keymap[i].gpio);
++ goto err_gpio_configure_failed;
++ }
++ }
++
++ ret = gpio_event_input_request_irqs(ds);
++
++ spin_lock_irqsave(&ds->irq_lock, irqflags);
++ ds->use_irq = ret == 0;
++
++ pr_info("GPIO Input Driver: Start gpio inputs for %s in %s "
++ "mode\n",
++ input_dev->name, ret == 0 ? "interrupt" : "polling");
++
++ hrtimer_init(&ds->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
++ ds->timer.function = gpio_event_input_timer_func;
++ hrtimer_start(&ds->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
++ spin_unlock_irqrestore(&ds->irq_lock, irqflags);
++ return 0;
++ }
++
++ ret = 0;
++ spin_lock_irqsave(&ds->irq_lock, irqflags);
++ hrtimer_cancel(&ds->timer);
++ if (ds->use_irq) {
++ for (i = di->keymap_size - 1; i >= 0; i--) {
++ free_irq(gpio_to_irq(di->keymap[i].gpio),
++ &ds->key_state[i]);
++ }
++ }
++ spin_unlock_irqrestore(&ds->irq_lock, irqflags);
++
++ for (i = di->keymap_size - 1; i >= 0; i--) {
++err_gpio_configure_failed:
++ gpio_free(di->keymap[i].gpio);
++err_gpio_request_failed:
++ ;
++ }
++ wake_lock_destroy(&ds->wake_lock);
++ kfree(ds);
++err_ds_alloc_failed:
++ return ret;
++}
+--- /dev/null
++++ b/drivers/input/misc/gpio_matrix.c
+@@ -0,0 +1,406 @@
++/* drivers/input/misc/gpio_matrix.c
++ *
++ * Copyright (C) 2007 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/kernel.h>
++#include <linux/gpio.h>
++#include <linux/gpio_event.h>
++#include <linux/hrtimer.h>
++#include <linux/interrupt.h>
++#include <linux/wakelock.h>
++
++struct gpio_kp {
++ struct input_dev *input_dev;
++ struct gpio_event_matrix_info *keypad_info;
++ struct hrtimer timer;
++ struct wake_lock wake_lock;
++ int current_output;
++ unsigned int use_irq:1;
++ unsigned int key_state_changed:1;
++ unsigned int last_key_state_changed:1;
++ unsigned int some_keys_pressed:2;
++ unsigned long keys_pressed[0];
++};
++
++static void clear_phantom_key(struct gpio_kp *kp, int out, int in)
++{
++ struct gpio_event_matrix_info *mi = kp->keypad_info;
++ int key_index = out * mi->ninputs + in;
++ unsigned short keycode = mi->keymap[key_index];;
++
++ if (!test_bit(keycode, kp->input_dev->key)) {
++ if (mi->flags & GPIOKPF_PRINT_PHANTOM_KEYS)
++ pr_info("gpiomatrix: phantom key %x, %d-%d (%d-%d) "
++ "cleared\n", keycode, out, in,
++ mi->output_gpios[out], mi->input_gpios[in]);
++ __clear_bit(key_index, kp->keys_pressed);
++ } else {
++ if (mi->flags & GPIOKPF_PRINT_PHANTOM_KEYS)
++ pr_info("gpiomatrix: phantom key %x, %d-%d (%d-%d) "
++ "not cleared\n", keycode, out, in,
++ mi->output_gpios[out], mi->input_gpios[in]);
++ }
++}
++
++static int restore_keys_for_input(struct gpio_kp *kp, int out, int in)
++{
++ int rv = 0;
++ int key_index;
++
++ key_index = out * kp->keypad_info->ninputs + in;
++ while (out < kp->keypad_info->noutputs) {
++ if (test_bit(key_index, kp->keys_pressed)) {
++ rv = 1;
++ clear_phantom_key(kp, out, in);
++ }
++ key_index += kp->keypad_info->ninputs;
++ out++;
++ }
++ return rv;
++}
++
++static void remove_phantom_keys(struct gpio_kp *kp)
++{
++ int out, in, inp;
++ int key_index;
++
++ if (kp->some_keys_pressed < 3)
++ return;
++
++ for (out = 0; out < kp->keypad_info->noutputs; out++) {
++ inp = -1;
++ key_index = out * kp->keypad_info->ninputs;
++ for (in = 0; in < kp->keypad_info->ninputs; in++, key_index++) {
++ if (test_bit(key_index, kp->keys_pressed)) {
++ if (inp == -1) {
++ inp = in;
++ continue;
++ }
++ if (inp >= 0) {
++ if (!restore_keys_for_input(kp, out + 1,
++ inp))
++ break;
++ clear_phantom_key(kp, out, inp);
++ inp = -2;
++ }
++ restore_keys_for_input(kp, out, in);
++ }
++ }
++ }
++}
++
++static void report_key(struct gpio_kp *kp, int key_index, int out, int in)
++{
++ struct gpio_event_matrix_info *mi = kp->keypad_info;
++ int pressed = test_bit(key_index, kp->keys_pressed);
++ unsigned short keycode = mi->keymap[key_index];
++ if (pressed != test_bit(keycode, kp->input_dev->key)) {
++ if (keycode == KEY_RESERVED) {
++ if (mi->flags & GPIOKPF_PRINT_UNMAPPED_KEYS)
++ pr_info("gpiomatrix: unmapped key, %d-%d "
++ "(%d-%d) changed to %d\n",
++ out, in, mi->output_gpios[out],
++ mi->input_gpios[in], pressed);
++ } else {
++ if (mi->flags & GPIOKPF_PRINT_MAPPED_KEYS)
++ pr_info("gpiomatrix: key %x, %d-%d (%d-%d) "
++ "changed to %d\n", keycode,
++ out, in, mi->output_gpios[out],
++ mi->input_gpios[in], pressed);
++ input_report_key(kp->input_dev, keycode, pressed);
++ }
++ }
++}
++
++static enum hrtimer_restart gpio_keypad_timer_func(struct hrtimer *timer)
++{
++ int out, in;
++ int key_index;
++ int gpio;
++ struct gpio_kp *kp = container_of(timer, struct gpio_kp, timer);
++ struct gpio_event_matrix_info *mi = kp->keypad_info;
++ unsigned gpio_keypad_flags = mi->flags;
++ unsigned polarity = !!(gpio_keypad_flags & GPIOKPF_ACTIVE_HIGH);
++
++ out = kp->current_output;
++ if (out == mi->noutputs) {
++ out = 0;
++ kp->last_key_state_changed = kp->key_state_changed;
++ kp->key_state_changed = 0;
++ kp->some_keys_pressed = 0;
++ } else {
++ key_index = out * mi->ninputs;
++ for (in = 0; in < mi->ninputs; in++, key_index++) {
++ gpio = mi->input_gpios[in];
++ if (gpio_get_value(gpio) ^ !polarity) {
++ if (kp->some_keys_pressed < 3)
++ kp->some_keys_pressed++;
++ kp->key_state_changed |= !__test_and_set_bit(
++ key_index, kp->keys_pressed);
++ } else
++ kp->key_state_changed |= __test_and_clear_bit(
++ key_index, kp->keys_pressed);
++ }
++ gpio = mi->output_gpios[out];
++ if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
++ gpio_set_value(gpio, !polarity);
++ else
++ gpio_direction_input(gpio);
++ out++;
++ }
++ kp->current_output = out;
++ if (out < mi->noutputs) {
++ gpio = mi->output_gpios[out];
++ if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
++ gpio_set_value(gpio, polarity);
++ else
++ gpio_direction_output(gpio, polarity);
++ hrtimer_start(timer, mi->settle_time, HRTIMER_MODE_REL);
++ return HRTIMER_NORESTART;
++ }
++ if (gpio_keypad_flags & GPIOKPF_DEBOUNCE) {
++ if (kp->key_state_changed) {
++ hrtimer_start(&kp->timer, mi->debounce_delay,
++ HRTIMER_MODE_REL);
++ return HRTIMER_NORESTART;
++ }
++ kp->key_state_changed = kp->last_key_state_changed;
++ }
++ if (kp->key_state_changed) {
++ if (gpio_keypad_flags & GPIOKPF_REMOVE_SOME_PHANTOM_KEYS)
++ remove_phantom_keys(kp);
++ key_index = 0;
++ for (out = 0; out < mi->noutputs; out++)
++ for (in = 0; in < mi->ninputs; in++, key_index++)
++ report_key(kp, key_index, out, in);
++ }
++ if (!kp->use_irq || kp->some_keys_pressed) {
++ hrtimer_start(timer, mi->poll_time, HRTIMER_MODE_REL);
++ return HRTIMER_NORESTART;
++ }
++
++ /* No keys are pressed, reenable interrupt */
++ for (out = 0; out < mi->noutputs; out++) {
++ if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
++ gpio_set_value(mi->output_gpios[out], polarity);
++ else
++ gpio_direction_output(mi->output_gpios[out], polarity);
++ }
++ for (in = 0; in < mi->ninputs; in++)
++ enable_irq(gpio_to_irq(mi->input_gpios[in]));
++ wake_unlock(&kp->wake_lock);
++ return HRTIMER_NORESTART;
++}
++
++static irqreturn_t gpio_keypad_irq_handler(int irq_in, void *dev_id)
++{
++ int i;
++ struct gpio_kp *kp = dev_id;
++ struct gpio_event_matrix_info *mi = kp->keypad_info;
++ unsigned gpio_keypad_flags = mi->flags;
++
++ if (!kp->use_irq) /* ignore interrupt while registering the handler */
++ return IRQ_HANDLED;
++
++ for (i = 0; i < mi->ninputs; i++)
++ disable_irq(gpio_to_irq(mi->input_gpios[i]));
++ for (i = 0; i < mi->noutputs; i++) {
++ if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
++ gpio_set_value(mi->output_gpios[i],
++ !(gpio_keypad_flags & GPIOKPF_ACTIVE_HIGH));
++ else
++ gpio_direction_input(mi->output_gpios[i]);
++ }
++ wake_lock(&kp->wake_lock);
++ hrtimer_start(&kp->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
++ return IRQ_HANDLED;
++}
++
++static int gpio_keypad_request_irqs(struct gpio_kp *kp)
++{
++ int i;
++ int err;
++ unsigned int irq;
++ unsigned long request_flags;
++ struct gpio_event_matrix_info *mi = kp->keypad_info;
++
++ switch (mi->flags & (GPIOKPF_ACTIVE_HIGH|GPIOKPF_LEVEL_TRIGGERED_IRQ)) {
++ default:
++ request_flags = IRQF_TRIGGER_FALLING;
++ break;
++ case GPIOKPF_ACTIVE_HIGH:
++ request_flags = IRQF_TRIGGER_RISING;
++ break;
++ case GPIOKPF_LEVEL_TRIGGERED_IRQ:
++ request_flags = IRQF_TRIGGER_LOW;
++ break;
++ case GPIOKPF_LEVEL_TRIGGERED_IRQ | GPIOKPF_ACTIVE_HIGH:
++ request_flags = IRQF_TRIGGER_HIGH;
++ break;
++ }
++
++ for (i = 0; i < mi->ninputs; i++) {
++ err = irq = gpio_to_irq(mi->input_gpios[i]);
++ if (err < 0)
++ goto err_gpio_get_irq_num_failed;
++ err = request_irq(irq, gpio_keypad_irq_handler, request_flags,
++ "gpio_kp", kp);
++ if (err) {
++ pr_err("gpiomatrix: request_irq failed for input %d, "
++ "irq %d\n", mi->input_gpios[i], irq);
++ goto err_request_irq_failed;
++ }
++ err = set_irq_wake(irq, 1);
++ if (err) {
++ pr_err("gpiomatrix: set_irq_wake failed for input %d, "
++ "irq %d\n", mi->input_gpios[i], irq);
++ }
++ disable_irq(irq);
++ }
++ return 0;
++
++ for (i = mi->noutputs - 1; i >= 0; i--) {
++ free_irq(gpio_to_irq(mi->input_gpios[i]), kp);
++err_request_irq_failed:
++err_gpio_get_irq_num_failed:
++ ;
++ }
++ return err;
++}
++
++int gpio_event_matrix_func(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data, int func)
++{
++ int i;
++ int err;
++ int key_count;
++ struct gpio_kp *kp;
++ struct gpio_event_matrix_info *mi;
++
++ mi = container_of(info, struct gpio_event_matrix_info, info);
++ if (func == GPIO_EVENT_FUNC_SUSPEND || func == GPIO_EVENT_FUNC_RESUME) {
++ /* TODO: disable scanning */
++ return 0;
++ }
++
++ if (func == GPIO_EVENT_FUNC_INIT) {
++ if (mi->keymap == NULL ||
++ mi->input_gpios == NULL ||
++ mi->output_gpios == NULL) {
++ err = -ENODEV;
++ pr_err("gpiomatrix: Incomplete pdata\n");
++ goto err_invalid_platform_data;
++ }
++ key_count = mi->ninputs * mi->noutputs;
++
++ *data = kp = kzalloc(sizeof(*kp) + sizeof(kp->keys_pressed[0]) *
++ BITS_TO_LONGS(key_count), GFP_KERNEL);
++ if (kp == NULL) {
++ err = -ENOMEM;
++ pr_err("gpiomatrix: Failed to allocate private data\n");
++ goto err_kp_alloc_failed;
++ }
++ kp->input_dev = input_dev;
++ kp->keypad_info = mi;
++ set_bit(EV_KEY, input_dev->evbit);
++ for (i = 0; i < key_count; i++) {
++ if (mi->keymap[i])
++ set_bit(mi->keymap[i] & KEY_MAX,
++ input_dev->keybit);
++ }
++
++ for (i = 0; i < mi->noutputs; i++) {
++ if (gpio_cansleep(mi->output_gpios[i])) {
++ pr_err("gpiomatrix: unsupported output gpio %d,"
++ " can sleep\n", mi->output_gpios[i]);
++ err = -EINVAL;
++ goto err_request_output_gpio_failed;
++ }
++ err = gpio_request(mi->output_gpios[i], "gpio_kp_out");
++ if (err) {
++ pr_err("gpiomatrix: gpio_request failed for "
++ "output %d\n", mi->output_gpios[i]);
++ goto err_request_output_gpio_failed;
++ }
++ if (mi->flags & GPIOKPF_DRIVE_INACTIVE)
++ err = gpio_direction_output(mi->output_gpios[i],
++ !(mi->flags & GPIOKPF_ACTIVE_HIGH));
++ else
++ err = gpio_direction_input(mi->output_gpios[i]);
++ if (err) {
++ pr_err("gpiomatrix: gpio_configure failed for "
++ "output %d\n", mi->output_gpios[i]);
++ goto err_output_gpio_configure_failed;
++ }
++ }
++ for (i = 0; i < mi->ninputs; i++) {
++ err = gpio_request(mi->input_gpios[i], "gpio_kp_in");
++ if (err) {
++ pr_err("gpiomatrix: gpio_request failed for "
++ "input %d\n", mi->input_gpios[i]);
++ goto err_request_input_gpio_failed;
++ }
++ err = gpio_direction_input(mi->input_gpios[i]);
++ if (err) {
++ pr_err("gpiomatrix: gpio_direction_input failed"
++ " for input %d\n", mi->input_gpios[i]);
++ goto err_gpio_direction_input_failed;
++ }
++ }
++ kp->current_output = mi->noutputs;
++ kp->key_state_changed = 1;
++
++ hrtimer_init(&kp->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
++ kp->timer.function = gpio_keypad_timer_func;
++ wake_lock_init(&kp->wake_lock, WAKE_LOCK_SUSPEND, "gpio_kp");
++ err = gpio_keypad_request_irqs(kp);
++ kp->use_irq = err == 0;
++
++ pr_info("GPIO Matrix Keypad Driver: Start keypad matrix for %s "
++ "in %s mode\n", input_dev->name,
++ kp->use_irq ? "interrupt" : "polling");
++
++ if (kp->use_irq)
++ wake_lock(&kp->wake_lock);
++ hrtimer_start(&kp->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
++
++ return 0;
++ }
++
++ err = 0;
++ kp = *data;
++
++ if (kp->use_irq)
++ for (i = mi->noutputs - 1; i >= 0; i--)
++ free_irq(gpio_to_irq(mi->input_gpios[i]), kp);
++
++ hrtimer_cancel(&kp->timer);
++ wake_lock_destroy(&kp->wake_lock);
++ for (i = mi->noutputs - 1; i >= 0; i--) {
++err_gpio_direction_input_failed:
++ gpio_free(mi->input_gpios[i]);
++err_request_input_gpio_failed:
++ ;
++ }
++ for (i = mi->noutputs - 1; i >= 0; i--) {
++err_output_gpio_configure_failed:
++ gpio_free(mi->output_gpios[i]);
++err_request_output_gpio_failed:
++ ;
++ }
++ kfree(kp);
++err_kp_alloc_failed:
++err_invalid_platform_data:
++ return err;
++}
+--- /dev/null
++++ b/drivers/input/misc/gpio_output.c
+@@ -0,0 +1,84 @@
++/* drivers/input/misc/gpio_output.c
++ *
++ * Copyright (C) 2007 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/kernel.h>
++#include <linux/gpio.h>
++#include <linux/gpio_event.h>
++
++int gpio_event_output_event(
++ struct input_dev *input_dev, struct gpio_event_info *info, void **data,
++ unsigned int type, unsigned int code, int value)
++{
++ int i;
++ struct gpio_event_output_info *oi;
++ oi = container_of(info, struct gpio_event_output_info, info);
++ if (type != oi->type)
++ return 0;
++ if (!(oi->flags & GPIOEDF_ACTIVE_HIGH))
++ value = !value;
++ for (i = 0; i < oi->keymap_size; i++)
++ if (code == oi->keymap[i].code)
++ gpio_set_value(oi->keymap[i].gpio, value);
++ return 0;
++}
++
++int gpio_event_output_func(
++ struct input_dev *input_dev, struct gpio_event_info *info, void **data,
++ int func)
++{
++ int ret;
++ int i;
++ struct gpio_event_output_info *oi;
++ oi = container_of(info, struct gpio_event_output_info, info);
++
++ if (func == GPIO_EVENT_FUNC_SUSPEND || func == GPIO_EVENT_FUNC_RESUME)
++ return 0;
++
++ if (func == GPIO_EVENT_FUNC_INIT) {
++ int output_level = !(oi->flags & GPIOEDF_ACTIVE_HIGH);
++ for (i = 0; i < oi->keymap_size; i++)
++ input_set_capability(input_dev, oi->type,
++ oi->keymap[i].code);
++
++ for (i = 0; i < oi->keymap_size; i++) {
++ ret = gpio_request(oi->keymap[i].gpio,
++ "gpio_event_output");
++ if (ret) {
++ pr_err("gpio_event_output_func: gpio_request "
++ "failed for %d\n", oi->keymap[i].gpio);
++ goto err_gpio_request_failed;
++ }
++ ret = gpio_direction_output(oi->keymap[i].gpio,
++ output_level);
++ if (ret) {
++ pr_err("gpio_event_output_func: "
++ "gpio_direction_output failed for %d\n",
++ oi->keymap[i].gpio);
++ goto err_gpio_direction_output_failed;
++ }
++ }
++ return 0;
++ }
++
++ ret = 0;
++ for (i = oi->keymap_size - 1; i >= 0; i--) {
++err_gpio_direction_output_failed:
++ gpio_free(oi->keymap[i].gpio);
++err_gpio_request_failed:
++ ;
++ }
++ return ret;
++}
++
+--- /dev/null
++++ b/include/linux/gpio_event.h
+@@ -0,0 +1,154 @@
++/* include/linux/gpio_event.h
++ *
++ * Copyright (C) 2007 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#ifndef _LINUX_GPIO_EVENT_H
++#define _LINUX_GPIO_EVENT_H
++
++#include <linux/input.h>
++
++enum {
++ GPIO_EVENT_FUNC_UNINIT = 0x0,
++ GPIO_EVENT_FUNC_INIT = 0x1,
++ GPIO_EVENT_FUNC_SUSPEND = 0x2,
++ GPIO_EVENT_FUNC_RESUME = 0x3,
++};
++struct gpio_event_info {
++ int (*func)(struct input_dev *input_dev,
++ struct gpio_event_info *info,
++ void **data, int func);
++ int (*event)(struct input_dev *input_dev,
++ struct gpio_event_info *info,
++ void **data, unsigned int type,
++ unsigned int code, int value); /* out events */
++};
++
++struct gpio_event_platform_data {
++ const char *name;
++ struct gpio_event_info **info;
++ size_t info_count;
++ int (*power)(const struct gpio_event_platform_data *pdata, bool on);
++};
++
++#define GPIO_EVENT_DEV_NAME "gpio-event"
++
++/* Key matrix */
++
++enum gpio_event_matrix_flags {
++ /* unset: drive active output low, set: drive active output high */
++ GPIOKPF_ACTIVE_HIGH = 1U << 0,
++ GPIOKPF_DEBOUNCE = 1U << 1,
++ GPIOKPF_REMOVE_SOME_PHANTOM_KEYS = 1U << 2,
++ GPIOKPF_REMOVE_PHANTOM_KEYS = GPIOKPF_REMOVE_SOME_PHANTOM_KEYS |
++ GPIOKPF_DEBOUNCE,
++ GPIOKPF_DRIVE_INACTIVE = 1U << 3,
++ GPIOKPF_LEVEL_TRIGGERED_IRQ = 1U << 4,
++ GPIOKPF_PRINT_UNMAPPED_KEYS = 1U << 16,
++ GPIOKPF_PRINT_MAPPED_KEYS = 1U << 17,
++ GPIOKPF_PRINT_PHANTOM_KEYS = 1U << 18,
++};
++
++extern int gpio_event_matrix_func(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data, int func);
++struct gpio_event_matrix_info {
++ /* initialize to gpio_event_matrix_func */
++ struct gpio_event_info info;
++ /* size must be ninputs * noutputs */
++ const unsigned short *keymap;
++ unsigned int *input_gpios;
++ unsigned int *output_gpios;
++ unsigned int ninputs;
++ unsigned int noutputs;
++ /* time to wait before reading inputs after driving each output */
++ ktime_t settle_time;
++ /* time to wait before scanning the keypad a second time */
++ ktime_t debounce_delay;
++ ktime_t poll_time;
++ unsigned flags;
++};
++
++/* Directly connected inputs and outputs */
++
++enum gpio_event_direct_flags {
++ GPIOEDF_ACTIVE_HIGH = 1U << 0,
++/* GPIOEDF_USE_DOWN_IRQ = 1U << 1, */
++/* GPIOEDF_USE_IRQ = (1U << 2) | GPIOIDF_USE_DOWN_IRQ, */
++ GPIOEDF_PRINT_KEYS = 1U << 8,
++ GPIOEDF_PRINT_KEY_DEBOUNCE = 1U << 9,
++};
++
++struct gpio_event_direct_entry {
++ uint32_t gpio:23;
++ uint32_t code:9;
++};
++
++/* inputs */
++extern int gpio_event_input_func(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data, int func);
++struct gpio_event_input_info {
++ /* initialize to gpio_event_input_func */
++ struct gpio_event_info info;
++ ktime_t debounce_time;
++ ktime_t poll_time;
++ uint16_t flags;
++ uint16_t type;
++ const struct gpio_event_direct_entry *keymap;
++ size_t keymap_size;
++};
++
++/* outputs */
++extern int gpio_event_output_func(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data, int func);
++extern int gpio_event_output_event(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data,
++ unsigned int type, unsigned int code, int value);
++struct gpio_event_output_info {
++ /* initialize to gpio_event_output_func and gpio_event_output_event */
++ struct gpio_event_info info;
++ uint16_t flags;
++ uint16_t type;
++ const struct gpio_event_direct_entry *keymap;
++ size_t keymap_size;
++};
++
++
++/* axes */
++
++enum gpio_event_axis_flags {
++ GPIOEAF_PRINT_UNKNOWN_DIRECTION = 1U << 16,
++ GPIOEAF_PRINT_RAW = 1U << 17,
++ GPIOEAF_PRINT_EVENT = 1U << 18,
++};
++
++extern int gpio_event_axis_func(struct input_dev *input_dev,
++ struct gpio_event_info *info, void **data, int func);
++struct gpio_event_axis_info {
++ /* initialize to gpio_event_axis_func */
++ struct gpio_event_info info;
++ uint8_t count;
++ uint8_t type; /* EV_REL or EV_ABS */
++ uint16_t code;
++ uint16_t decoded_size;
++ uint16_t (*map)(struct gpio_event_axis_info *info, uint16_t in);
++ uint32_t *gpio;
++ uint32_t flags;
++};
++#define gpio_axis_2bit_gray_map gpio_axis_4bit_gray_map
++#define gpio_axis_3bit_gray_map gpio_axis_4bit_gray_map
++uint16_t gpio_axis_4bit_gray_map(
++ struct gpio_event_axis_info *info, uint16_t in);
++uint16_t gpio_axis_5bit_singletrack_map(
++ struct gpio_event_axis_info *info, uint16_t in);
++
++#endif
--- /dev/null
+From 0d1077627288e51b5604f270eae6cf9f5ccd3871 Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Fri, 17 Oct 2008 15:20:55 -0700
+Subject: [PATCH 087/134] Input: Hold wake lock while event queue is not empty.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Allows userspace code to process input events while
+the device appears to be asleep.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ drivers/input/evdev.c | 7 +++++++
+ 1 files changed, 7 insertions(+), 0 deletions(-)
+
+--- a/drivers/input/evdev.c
++++ b/drivers/input/evdev.c
+@@ -19,6 +19,7 @@
+ #include <linux/input.h>
+ #include <linux/major.h>
+ #include <linux/device.h>
++#include <linux/wakelock.h>
+ #include "input-compat.h"
+
+ struct evdev {
+@@ -43,6 +44,7 @@ struct evdev_client {
+ struct fasync_struct *fasync;
+ struct evdev *evdev;
+ struct list_head node;
++ struct wake_lock wake_lock;
+ };
+
+ static struct evdev *evdev_table[EVDEV_MINORS];
+@@ -55,6 +57,7 @@ static void evdev_pass_event(struct evde
+ * Interrupts are disabled, just acquire the lock
+ */
+ spin_lock(&client->buffer_lock);
++ wake_lock_timeout(&client->wake_lock, 5 * HZ);
+ client->buffer[client->head++] = *event;
+ client->head &= EVDEV_BUFFER_SIZE - 1;
+ spin_unlock(&client->buffer_lock);
+@@ -233,6 +236,7 @@ static int evdev_release(struct inode *i
+ mutex_unlock(&evdev->mutex);
+
+ evdev_detach_client(evdev, client);
++ wake_lock_destroy(&client->wake_lock);
+ kfree(client);
+
+ evdev_close_device(evdev);
+@@ -269,6 +273,7 @@ static int evdev_open(struct inode *inod
+ }
+
+ spin_lock_init(&client->buffer_lock);
++ wake_lock_init(&client->wake_lock, WAKE_LOCK_SUSPEND, "evdev");
+ client->evdev = evdev;
+ evdev_attach_client(evdev, client);
+
+@@ -332,6 +337,8 @@ static int evdev_fetch_next_event(struct
+ if (have_event) {
+ *event = client->buffer[client->tail++];
+ client->tail &= EVDEV_BUFFER_SIZE - 1;
++ if (client->head == client->tail)
++ wake_unlock(&client->wake_lock);
+ }
+
+ spin_unlock_irq(&client->buffer_lock);
--- /dev/null
+From 474db0e1425f8da03a7d49ebba1602efa503c73f Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Fri, 17 Oct 2008 15:28:08 -0700
+Subject: [PATCH 088/134] Input: Use monotonic time for event time stamps.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Since wall time can jump backwards, it cannot be used to determine if one
+event occured before another or for how long a key was pressed.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ drivers/input/evdev.c | 5 ++++-
+ 1 files changed, 4 insertions(+), 1 deletions(-)
+
+--- a/drivers/input/evdev.c
++++ b/drivers/input/evdev.c
+@@ -74,8 +74,11 @@ static void evdev_event(struct input_han
+ struct evdev *evdev = handle->private;
+ struct evdev_client *client;
+ struct input_event event;
++ struct timespec ts;
+
+- do_gettimeofday(&event.time);
++ ktime_get_ts(&ts);
++ event.time.tv_sec = ts.tv_sec;
++ event.time.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
+ event.type = type;
+ event.code = code;
+ event.value = value;
--- /dev/null
+From eb92150c047e76960ecf8989b9037fd34b43a4af Mon Sep 17 00:00:00 2001
+From: =?utf-8?q?Arve=20Hj=C3=B8nnev=C3=A5g?= <arve@android.com>
+Date: Fri, 21 Nov 2008 21:47:23 -0800
+Subject: [PATCH 090/134] input: Add keyreset driver.
+MIME-Version: 1.0
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+Add a platform device in the board file to specify a reset key-combo.
+The first time the key-combo is detected a work function that syncs
+the filesystems is scheduled. If all the keys are released and then
+pressed again, it calls panic. Reboot on panic should be set for
+this to work.
+
+Signed-off-by: Arve Hjønnevåg <arve@android.com>
+---
+ drivers/input/Kconfig | 9 ++
+ drivers/input/Makefile | 1 +
+ drivers/input/keyreset.c | 229 ++++++++++++++++++++++++++++++++++++++++++++++
+ include/linux/keyreset.h | 27 ++++++
+ 4 files changed, 266 insertions(+), 0 deletions(-)
+ create mode 100644 drivers/input/keyreset.c
+ create mode 100644 include/linux/keyreset.h
+
+--- a/drivers/input/Kconfig
++++ b/drivers/input/Kconfig
+@@ -149,6 +149,15 @@ config INPUT_APMPOWER
+ To compile this driver as a module, choose M here: the
+ module will be called apm-power.
+
++config INPUT_KEYRESET
++ tristate "Reset key"
++ depends on INPUT
++ ---help---
++ Say Y here if you want to reboot when some keys are pressed;
++
++ To compile this driver as a module, choose M here: the
++ module will be called keyreset.
++
+ config XEN_KBDDEV_FRONTEND
+ tristate "Xen virtual keyboard and mouse support"
+ depends on XEN_FBDEV_FRONTEND
+--- a/drivers/input/Makefile
++++ b/drivers/input/Makefile
+@@ -23,5 +23,6 @@ obj-$(CONFIG_INPUT_TOUCHSCREEN) += touch
+ obj-$(CONFIG_INPUT_MISC) += misc/
+
+ obj-$(CONFIG_INPUT_APMPOWER) += apm-power.o
++obj-$(CONFIG_INPUT_KEYRESET) += keyreset.o
+
+ obj-$(CONFIG_XEN_KBDDEV_FRONTEND) += xen-kbdfront.o
+--- /dev/null
++++ b/drivers/input/keyreset.c
+@@ -0,0 +1,229 @@
++/* drivers/input/keyreset.c
++ *
++ * Copyright (C) 2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#include <linux/input.h>
++#include <linux/keyreset.h>
++#include <linux/module.h>
++#include <linux/platform_device.h>
++#include <linux/reboot.h>
++#include <linux/sched.h>
++#include <linux/syscalls.h>
++
++
++struct keyreset_state {
++ struct input_handler input_handler;
++ unsigned long keybit[BITS_TO_LONGS(KEY_CNT)];
++ unsigned long upbit[BITS_TO_LONGS(KEY_CNT)];
++ unsigned long key[BITS_TO_LONGS(KEY_CNT)];
++ spinlock_t lock;
++ int key_down_target;
++ int key_down;
++ int key_up;
++ int restart_disabled;
++};
++
++int restart_requested;
++static void deferred_restart(struct work_struct *dummy)
++{
++ restart_requested = 2;
++ sys_sync();
++ restart_requested = 3;
++ kernel_restart(NULL);
++}
++static DECLARE_WORK(restart_work, deferred_restart);
++
++static void keyreset_event(struct input_handle *handle, unsigned int type,
++ unsigned int code, int value)
++{
++ unsigned long flags;
++ struct keyreset_state *state = handle->private;
++
++ if (type != EV_KEY)
++ return;
++
++ if (code >= KEY_MAX)
++ return;
++
++ if (!test_bit(code, state->keybit))
++ return;
++
++ spin_lock_irqsave(&state->lock, flags);
++ if (!test_bit(code, state->key) == !value)
++ goto done;
++ __change_bit(code, state->key);
++ if (test_bit(code, state->upbit)) {
++ if (value) {
++ state->restart_disabled = 1;
++ state->key_up++;
++ } else
++ state->key_up--;
++ } else {
++ if (value)
++ state->key_down++;
++ else
++ state->key_down--;
++ }
++ if (state->key_down == 0 && state->key_up == 0)
++ state->restart_disabled = 0;
++
++ pr_debug("reset key changed %d %d new state %d-%d-%d\n", code, value,
++ state->key_down, state->key_up, state->restart_disabled);
++
++ if (value && !state->restart_disabled &&
++ state->key_down == state->key_down_target) {
++ state->restart_disabled = 1;
++ if (restart_requested)
++ panic("keyboard reset failed, %d", restart_requested);
++ pr_info("keyboard reset\n");
++ schedule_work(&restart_work);
++ restart_requested = 1;
++ }
++done:
++ spin_unlock_irqrestore(&state->lock, flags);
++}
++
++static int keyreset_connect(struct input_handler *handler,
++ struct input_dev *dev,
++ const struct input_device_id *id)
++{
++ int i;
++ int ret;
++ struct input_handle *handle;
++ struct keyreset_state *state =
++ container_of(handler, struct keyreset_state, input_handler);
++
++ for (i = 0; i < KEY_MAX; i++) {
++ if (test_bit(i, state->keybit) && test_bit(i, dev->keybit))
++ break;
++ }
++ if (i == KEY_MAX)
++ return -ENODEV;
++
++ handle = kzalloc(sizeof(*handle), GFP_KERNEL);
++ if (!handle)
++ return -ENOMEM;
++
++ handle->dev = dev;
++ handle->handler = handler;
++ handle->name = "keyreset";
++ handle->private = state;
++
++ ret = input_register_handle(handle);
++ if (ret)
++ goto err_input_register_handle;
++
++ ret = input_open_device(handle);
++ if (ret)
++ goto err_input_open_device;
++
++ pr_info("using input dev %s for key reset\n", dev->name);
++
++ return 0;
++
++err_input_open_device:
++ input_unregister_handle(handle);
++err_input_register_handle:
++ kfree(handle);
++ return ret;
++}
++
++static void keyreset_disconnect(struct input_handle *handle)
++{
++ input_close_device(handle);
++ input_unregister_handle(handle);
++ kfree(handle);
++}
++
++static const struct input_device_id keyreset_ids[] = {
++ {
++ .flags = INPUT_DEVICE_ID_MATCH_EVBIT,
++ .evbit = { BIT_MASK(EV_KEY) },
++ },
++ { },
++};
++MODULE_DEVICE_TABLE(input, keyreset_ids);
++
++static int keyreset_probe(struct platform_device *pdev)
++{
++ int ret;
++ int key, *keyp;
++ struct keyreset_state *state;
++ struct keyreset_platform_data *pdata = pdev->dev.platform_data;
++
++ if (!pdata)
++ return -EINVAL;
++
++ state = kzalloc(sizeof(*state), GFP_KERNEL);
++ if (!state)
++ return -ENOMEM;
++
++ spin_lock_init(&state->lock);
++ keyp = pdata->keys_down;
++ while ((key = *keyp++)) {
++ if (key >= KEY_MAX)
++ continue;
++ state->key_down_target++;
++ __set_bit(key, state->keybit);
++ }
++ if (pdata->keys_up) {
++ keyp = pdata->keys_up;
++ while ((key = *keyp++)) {
++ if (key >= KEY_MAX)
++ continue;
++ __set_bit(key, state->keybit);
++ __set_bit(key, state->upbit);
++ }
++ }
++ state->input_handler.event = keyreset_event;
++ state->input_handler.connect = keyreset_connect;
++ state->input_handler.disconnect = keyreset_disconnect;
++ state->input_handler.name = KEYRESET_NAME;
++ state->input_handler.id_table = keyreset_ids;
++ ret = input_register_handler(&state->input_handler);
++ if (ret) {
++ kfree(state);
++ return ret;
++ }
++ platform_set_drvdata(pdev, state);
++ return 0;
++}
++
++int keyreset_remove(struct platform_device *pdev)
++{
++ struct keyreset_state *state = platform_get_drvdata(pdev);
++ input_unregister_handler(&state->input_handler);
++ kfree(state);
++ return 0;
++}
++
++
++struct platform_driver keyreset_driver = {
++ .driver.name = KEYRESET_NAME,
++ .probe = keyreset_probe,
++ .remove = keyreset_remove,
++};
++
++static int __init keyreset_init(void)
++{
++ return platform_driver_register(&keyreset_driver);
++}
++
++static void __exit keyreset_exit(void)
++{
++ return platform_driver_unregister(&keyreset_driver);
++}
++
++module_init(keyreset_init);
++module_exit(keyreset_exit);
+--- /dev/null
++++ b/include/linux/keyreset.h
+@@ -0,0 +1,27 @@
++/*
++ * include/linux/keyreset.h - platform data structure for resetkeys driver
++ *
++ * Copyright (C) 2008 Google, Inc.
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#ifndef _LINUX_KEYRESET_H
++#define _LINUX_KEYRESET_H
++
++#define KEYRESET_NAME "keyreset"
++
++struct keyreset_platform_data {
++ int *keys_up;
++ int keys_down[]; /* 0 terminated */
++};
++
++#endif /* _LINUX_KEYRESET_H */
--- /dev/null
+From 2cae40a6a76e9e440f146ce0402aed40a7c127ca Mon Sep 17 00:00:00 2001
+From: San Mehat <san@google.com>
+Date: Mon, 10 Nov 2008 16:29:50 -0800
+Subject: [PATCH 093/134] mmc: Add status IRQ and status callback function to mmc platform data
+
+Signed-off-by: San Mehat <san@google.com>
+---
+ arch/arm/include/asm/mach/mmc.h | 2 ++
+ 1 files changed, 2 insertions(+), 0 deletions(-)
+
+--- a/arch/arm/include/asm/mach/mmc.h
++++ b/arch/arm/include/asm/mach/mmc.h
+@@ -10,6 +10,8 @@ struct mmc_platform_data {
+ unsigned int ocr_mask; /* available voltages */
+ u32 (*translate_vdd)(struct device *, unsigned int);
+ unsigned int (*status)(struct device *);
++ unsigned int status_irq;
++ int (*register_status_notify)(void (*callback)(int card_present, void *dev_id), void *dev_id);
+ };
+
+ #endif
--- /dev/null
+From 66983857a54479d76ce6dbd8399e1276698bd3c5 Mon Sep 17 00:00:00 2001
+From: San Mehat <san@google.com>
+Date: Tue, 11 Nov 2008 09:35:36 -0800
+Subject: [PATCH 094/134] mmc: sd: Add new CONFIG_MMC_PARANOID_SD_INIT for enabling retries during SD detection
+
+Signed-off-by: San Mehat <san@google.com>
+---
+ drivers/mmc/core/Kconfig | 8 ++++++++
+ drivers/mmc/core/sd.c | 24 ++++++++++++++++++++++--
+ 2 files changed, 30 insertions(+), 2 deletions(-)
+
+--- a/drivers/mmc/core/Kconfig
++++ b/drivers/mmc/core/Kconfig
+@@ -14,3 +14,11 @@ config MMC_UNSAFE_RESUME
+ This option is usually just for embedded systems which use
+ a MMC/SD card for rootfs. Most people should say N here.
+
++config MMC_PARANOID_SD_INIT
++ bool "Enable paranoid SD card initialization (EXPERIMENTAL)"
++ help
++ If you say Y here, the MMC layer will be extra paranoid
++ about re-trying SD init requests. This can be a useful
++ work-around for buggy controllers and hardware. Enable
++ if you are experiencing issues with SD detection.
++
+--- a/drivers/mmc/core/sd.c
++++ b/drivers/mmc/core/sd.c
+@@ -336,7 +336,9 @@ static int mmc_sd_init_card(struct mmc_h
+ int err;
+ u32 cid[4];
+ unsigned int max_dtr;
+-
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ int retries;
++#endif
+ BUG_ON(!host);
+ WARN_ON(!host->claimed);
+
+@@ -439,11 +441,29 @@ static int mmc_sd_init_card(struct mmc_h
+ err = mmc_decode_scr(card);
+ if (err < 0)
+ goto free_card;
+-
+ /*
+ * Fetch switch information from card.
+ */
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ for (retries = 1; retries <= 3; retries++) {
++ err = mmc_read_switch(card);
++ if (!err) {
++ if (retries > 1) {
++ printk(KERN_WARNING
++ "%s: recovered\n",
++ mmc_hostname(host));
++ }
++ break;
++ } else {
++ printk(KERN_WARNING
++ "%s: read switch failed (attempt %d)\n",
++ mmc_hostname(host), retries);
++ }
++ }
++#else
+ err = mmc_read_switch(card);
++#endif
++
+ if (err)
+ goto free_card;
+ }
--- /dev/null
+From 62d51f0d0d0b3c758b4505c3855b61288b8e90aa Mon Sep 17 00:00:00 2001
+From: San Mehat <san@android.com>
+Date: Mon, 14 Apr 2008 15:22:49 -0700
+Subject: [PATCH 095/134] mmc: Add concept of an 'embedded' SDIO device.
+
+This is required to support chips which use SDIO for signaling/
+communication but do not implement the various card enumeration registers
+as required for full SD / SDIO cards.
+
+mmc: sdio: Fix bug where we're freeing the CIS tables we never allocated when using EMBEDDED_SDIO
+mmc: Add max_blksize to embedded SDIO data
+
+Signed-off-by: San Mehat <san@google.com>
+---
+ arch/arm/include/asm/mach/mmc.h | 10 ++++++
+ drivers/mmc/core/Kconfig | 10 +++++-
+ drivers/mmc/core/core.c | 16 +++++++++
+ drivers/mmc/core/sdio.c | 67 ++++++++++++++++++++++++++++++++-------
+ drivers/mmc/core/sdio_bus.c | 13 +++++++-
+ include/linux/mmc/host.h | 17 ++++++++++
+ include/linux/mmc/sdio_func.h | 8 +++++
+ 7 files changed, 127 insertions(+), 14 deletions(-)
+
+--- a/arch/arm/include/asm/mach/mmc.h
++++ b/arch/arm/include/asm/mach/mmc.h
+@@ -5,12 +5,22 @@
+ #define ASMARM_MACH_MMC_H
+
+ #include <linux/mmc/host.h>
++#include <linux/mmc/card.h>
++#include <linux/mmc/sdio_func.h>
++
++struct embedded_sdio_data {
++ struct sdio_cis cis;
++ struct sdio_cccr cccr;
++ struct sdio_embedded_func *funcs;
++ int num_funcs;
++};
+
+ struct mmc_platform_data {
+ unsigned int ocr_mask; /* available voltages */
+ u32 (*translate_vdd)(struct device *, unsigned int);
+ unsigned int (*status)(struct device *);
+ unsigned int status_irq;
++ struct embedded_sdio_data *embedded_sdio;
+ int (*register_status_notify)(void (*callback)(int card_present, void *dev_id), void *dev_id);
+ };
+
+--- a/drivers/mmc/core/Kconfig
++++ b/drivers/mmc/core/Kconfig
+@@ -14,11 +14,19 @@ config MMC_UNSAFE_RESUME
+ This option is usually just for embedded systems which use
+ a MMC/SD card for rootfs. Most people should say N here.
+
++config MMC_EMBEDDED_SDIO
++ boolean "MMC embedded SDIO device support (EXPERIMENTAL)"
++ depends on EXPERIMENTAL
++ help
++ If you say Y here, support will be added for embedded SDIO
++ devices which do not contain the necessary enumeration
++ support in hardware to be properly detected.
++
+ config MMC_PARANOID_SD_INIT
+ bool "Enable paranoid SD card initialization (EXPERIMENTAL)"
++ depends on EXPERIMENTAL
+ help
+ If you say Y here, the MMC layer will be extra paranoid
+ about re-trying SD init requests. This can be a useful
+ work-around for buggy controllers and hardware. Enable
+ if you are experiencing issues with SD detection.
+-
+--- a/drivers/mmc/core/core.c
++++ b/drivers/mmc/core/core.c
+@@ -1011,6 +1011,22 @@ EXPORT_SYMBOL(mmc_resume_host);
+
+ #endif
+
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++void mmc_set_embedded_sdio_data(struct mmc_host *host,
++ struct sdio_cis *cis,
++ struct sdio_cccr *cccr,
++ struct sdio_embedded_func *funcs,
++ int num_funcs)
++{
++ host->embedded_sdio_data.cis = cis;
++ host->embedded_sdio_data.cccr = cccr;
++ host->embedded_sdio_data.funcs = funcs;
++ host->embedded_sdio_data.num_funcs = num_funcs;
++}
++
++EXPORT_SYMBOL(mmc_set_embedded_sdio_data);
++#endif
++
+ static int __init mmc_init(void)
+ {
+ int ret;
+--- a/drivers/mmc/core/sdio.c
++++ b/drivers/mmc/core/sdio.c
+@@ -24,6 +24,10 @@
+ #include "sdio_ops.h"
+ #include "sdio_cis.h"
+
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++#include <linux/mmc/sdio_ids.h>
++#endif
++
+ static int sdio_read_fbr(struct sdio_func *func)
+ {
+ int ret;
+@@ -314,6 +318,11 @@ int mmc_attach_sdio(struct mmc_host *hos
+ */
+ funcs = (ocr & 0x70000000) >> 28;
+
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ if (host->embedded_sdio_data.funcs)
++ funcs = host->embedded_sdio_data.num_funcs;
++#endif
++
+ /*
+ * Allocate card structure.
+ */
+@@ -351,17 +360,33 @@ int mmc_attach_sdio(struct mmc_host *hos
+ /*
+ * Read the common registers.
+ */
+- err = sdio_read_cccr(card);
+- if (err)
+- goto remove;
+
+- /*
+- * Read the common CIS tuples.
+- */
+- err = sdio_read_common_cis(card);
+- if (err)
+- goto remove;
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ if (host->embedded_sdio_data.cccr)
++ memcpy(&card->cccr, host->embedded_sdio_data.cccr, sizeof(struct sdio_cccr));
++ else {
++#endif
++ err = sdio_read_cccr(card);
++ if (err)
++ goto remove;
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ }
++#endif
+
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ if (host->embedded_sdio_data.cis)
++ memcpy(&card->cis, host->embedded_sdio_data.cis, sizeof(struct sdio_cis));
++ else {
++#endif
++ /*
++ * Read the common CIS tuples.
++ */
++ err = sdio_read_common_cis(card);
++ if (err)
++ goto remove;
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ }
++#endif
+ /*
+ * Switch to high-speed (if supported).
+ */
+@@ -395,9 +420,27 @@ int mmc_attach_sdio(struct mmc_host *hos
+ * Initialize (but don't add) all present functions.
+ */
+ for (i = 0;i < funcs;i++) {
+- err = sdio_init_func(host->card, i + 1);
+- if (err)
+- goto remove;
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ if (host->embedded_sdio_data.funcs) {
++ struct sdio_func *tmp;
++
++ tmp = sdio_alloc_func(host->card);
++ if (IS_ERR(tmp))
++ goto remove;
++ tmp->num = (i + 1);
++ card->sdio_func[i] = tmp;
++ tmp->class = host->embedded_sdio_data.funcs[i].f_class;
++ tmp->max_blksize = host->embedded_sdio_data.funcs[i].f_maxblksize;
++ tmp->vendor = card->cis.vendor;
++ tmp->device = card->cis.device;
++ } else {
++#endif
++ err = sdio_init_func(host->card, i + 1);
++ if (err)
++ goto remove;
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ }
++#endif
+ }
+
+ mmc_release_host(host);
+--- a/drivers/mmc/core/sdio_bus.c
++++ b/drivers/mmc/core/sdio_bus.c
+@@ -20,6 +20,10 @@
+ #include "sdio_cis.h"
+ #include "sdio_bus.h"
+
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++#include <linux/mmc/host.h>
++#endif
++
+ #define dev_to_sdio_func(d) container_of(d, struct sdio_func, dev)
+ #define to_sdio_driver(d) container_of(d, struct sdio_driver, drv)
+
+@@ -202,7 +206,14 @@ static void sdio_release_func(struct dev
+ {
+ struct sdio_func *func = dev_to_sdio_func(dev);
+
+- sdio_free_func_cis(func);
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ /*
++ * If this device is embedded then we never allocated
++ * cis tables for this func
++ */
++ if (!func->card->host->embedded_sdio_data.funcs)
++#endif
++ sdio_free_func_cis(func);
+
+ if (func->info)
+ kfree(func->info);
+--- a/include/linux/mmc/host.h
++++ b/include/linux/mmc/host.h
+@@ -161,6 +161,15 @@ struct mmc_host {
+
+ struct dentry *debugfs_root;
+
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++ struct {
++ struct sdio_cis *cis;
++ struct sdio_cccr *cccr;
++ struct sdio_embedded_func *funcs;
++ int num_funcs;
++ } embedded_sdio_data;
++#endif
++
+ unsigned long private[0] ____cacheline_aligned;
+ };
+
+@@ -169,6 +178,14 @@ extern int mmc_add_host(struct mmc_host
+ extern void mmc_remove_host(struct mmc_host *);
+ extern void mmc_free_host(struct mmc_host *);
+
++#ifdef CONFIG_MMC_EMBEDDED_SDIO
++extern void mmc_set_embedded_sdio_data(struct mmc_host *host,
++ struct sdio_cis *cis,
++ struct sdio_cccr *cccr,
++ struct sdio_embedded_func *funcs,
++ int num_funcs);
++#endif
++
+ static inline void *mmc_priv(struct mmc_host *host)
+ {
+ return (void *)host->private;
+--- a/include/linux/mmc/sdio_func.h
++++ b/include/linux/mmc/sdio_func.h
+@@ -21,6 +21,14 @@ struct sdio_func;
+ typedef void (sdio_irq_handler_t)(struct sdio_func *);
+
+ /*
++ * Structure used to hold embedded SDIO device data from platform layer
++ */
++struct sdio_embedded_func {
++ uint8_t f_class;
++ uint32_t f_maxblksize;
++};
++
++/*
+ * SDIO function CIS tuple (unknown to the core)
+ */
+ struct sdio_func_tuple {
--- /dev/null
+From 0b9879757f15d4ac99e032647cb3ee26393031b0 Mon Sep 17 00:00:00 2001
+From: San Mehat <san@android.com>
+Date: Thu, 15 May 2008 09:15:37 -0700
+Subject: [PATCH 097/134] mmc: Add new API call 'sdio_reset_comm' for resetting communication with an SDIO device
+
+Signed-off-by: San Mehat <san@android.com>
+---
+ drivers/mmc/core/sdio.c | 58 +++++++++++++++++++++++++++++++++++++++++++++++
+ 1 files changed, 58 insertions(+), 0 deletions(-)
+
+--- a/drivers/mmc/core/sdio.c
++++ b/drivers/mmc/core/sdio.c
+@@ -482,3 +482,61 @@ err:
+ return err;
+ }
+
++int sdio_reset_comm(struct mmc_card *card)
++{
++ struct mmc_host *host = card->host;
++ u32 ocr;
++ int err;
++
++ printk("%s():\n", __func__);
++ mmc_go_idle(host);
++
++ mmc_set_clock(host, host->f_min);
++
++ err = mmc_send_io_op_cond(host, 0, &ocr);
++ if (err)
++ goto err;
++
++ host->ocr = mmc_select_voltage(host, ocr);
++ if (!host->ocr) {
++ err = -EINVAL;
++ goto err;
++ }
++
++ err = mmc_send_io_op_cond(host, host->ocr, &ocr);
++ if (err)
++ goto err;
++
++ if (mmc_host_is_spi(host)) {
++ err = mmc_spi_set_crc(host, use_spi_crc);
++ if (err)
++ goto err;
++ }
++
++ if (!mmc_host_is_spi(host)) {
++ err = mmc_send_relative_addr(host, &card->rca);
++ if (err)
++ goto err;
++ mmc_set_bus_mode(host, MMC_BUSMODE_PUSHPULL);
++ }
++ if (!mmc_host_is_spi(host)) {
++ err = mmc_select_card(card);
++ if (err)
++ goto err;
++ }
++
++ mmc_set_clock(host, card->cis.max_dtr);
++ err = sdio_enable_wide(card);
++ if (err)
++ goto err;
++
++ return 0;
++ err:
++ printk("%s: Error resetting SDIO communications (%d)\n",
++ mmc_hostname(host), err);
++ mmc_release_host(host);
++ return err;
++}
++EXPORT_SYMBOL(sdio_reset_comm);
++
++
--- /dev/null
+From bd8df907ee8e95143d1bb7ec01ee0e4b6f7e1b79 Mon Sep 17 00:00:00 2001
+From: San Mehat <san@android.com>
+Date: Mon, 1 Dec 2008 08:52:34 -0800
+Subject: [PATCH 098/134] mmc: sd: When resuming, try a little harder to init the card
+
+Signed-off-by: San Mehat <san@android.com>
+---
+ drivers/mmc/core/sd.c | 19 +++++++++++++++++++
+ 1 files changed, 19 insertions(+), 0 deletions(-)
+
+--- a/drivers/mmc/core/sd.c
++++ b/drivers/mmc/core/sd.c
+@@ -607,12 +607,31 @@ static void mmc_sd_suspend(struct mmc_ho
+ static void mmc_sd_resume(struct mmc_host *host)
+ {
+ int err;
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ int retries;
++#endif
+
+ BUG_ON(!host);
+ BUG_ON(!host->card);
+
+ mmc_claim_host(host);
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ retries = 5;
++ while (retries) {
++ err = mmc_sd_init_card(host, host->ocr, host->card);
++
++ if (err) {
++ printk(KERN_ERR "%s: Re-init card rc = %d (retries = %d)\n",
++ mmc_hostname(host), err, retries);
++ mdelay(5);
++ retries--;
++ continue;
++ }
++ break;
++ }
++#else
+ err = mmc_sd_init_card(host, host->ocr, host->card);
++#endif
+ mmc_release_host(host);
+
+ if (err) {
--- /dev/null
+From 5ca694dfd981a371e9b18cdd4a89c002ffaccbc5 Mon Sep 17 00:00:00 2001
+From: San Mehat <san@android.com>
+Date: Wed, 3 Dec 2008 10:22:59 -0800
+Subject: [PATCH 099/134] mmc: mmcblk: Add new feature 'CONFIG_MMC_BLOCK_PARANOID_RESUME'
+
+ With this feature enabled, mmcblk will check the card-status before issuing
+a transaction *only* after being resumed. This protectes us from issuing
+transactions before the sdcard is ready (which can occur if the host driver
+deferrs mmc_resume_host() to reduce resume latency)
+
+Signed-off-by: San Mehat <san@android.com>
+---
+ drivers/mmc/card/Kconfig | 7 +++++++
+ drivers/mmc/card/block.c | 3 +++
+ drivers/mmc/card/queue.c | 28 ++++++++++++++++++++++++++++
+ drivers/mmc/card/queue.h | 3 +++
+ 4 files changed, 41 insertions(+), 0 deletions(-)
+
+--- a/drivers/mmc/card/Kconfig
++++ b/drivers/mmc/card/Kconfig
+@@ -32,6 +32,13 @@ config MMC_BLOCK_BOUNCE
+
+ If unsure, say Y here.
+
++config MMC_BLOCK_PARANOID_RESUME
++ bool "Check card status on resume"
++ depends on MMC_BLOCK
++ default y
++ help
++ Nohelp
++
+ config SDIO_UART
+ tristate "SDIO UART/GPS class support"
+ help
+--- a/drivers/mmc/card/block.c
++++ b/drivers/mmc/card/block.c
+@@ -643,6 +643,9 @@ static int mmc_blk_resume(struct mmc_car
+
+ if (md) {
+ mmc_blk_set_blksize(md, card);
++#ifdef CONFIG_MMC_BLOCK_PARANOID_RESUME
++ md->queue.check_status = 1;
++#endif
+ mmc_queue_resume(&md->queue);
+ }
+ return 0;
+--- a/drivers/mmc/card/queue.c
++++ b/drivers/mmc/card/queue.c
+@@ -14,7 +14,9 @@
+ #include <linux/freezer.h>
+ #include <linux/kthread.h>
+ #include <linux/scatterlist.h>
++#include <linux/delay.h>
+
++#include <linux/mmc/mmc.h>
+ #include <linux/mmc/card.h>
+ #include <linux/mmc/host.h>
+ #include "queue.h"
+@@ -70,7 +72,33 @@ static int mmc_queue_thread(void *d)
+ continue;
+ }
+ set_current_state(TASK_RUNNING);
++#ifdef CONFIG_MMC_BLOCK_PARANOID_RESUME
++ if (mq->check_status) {
++ struct mmc_command cmd;
+
++ do {
++ int err;
++
++ cmd.opcode = MMC_SEND_STATUS;
++ cmd.arg = mq->card->rca << 16;
++ cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
++
++ mmc_claim_host(mq->card->host);
++ err = mmc_wait_for_cmd(mq->card->host, &cmd, 5);
++ mmc_release_host(mq->card->host);
++
++ if (err) {
++ printk(KERN_ERR "%s: failed to get status (%d)\n",
++ __func__, err);
++ msleep(5);
++ continue;
++ }
++ printk(KERN_DEBUG "%s: status 0x%.8x\n", __func__, cmd.resp[0]);
++ } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
++ (R1_CURRENT_STATE(cmd.resp[0]) == 7));
++ mq->check_status = 0;
++ }
++#endif
+ mq->issue_fn(mq, req);
+ } while (1);
+ up(&mq->thread_sem);
+--- a/drivers/mmc/card/queue.h
++++ b/drivers/mmc/card/queue.h
+@@ -17,6 +17,9 @@ struct mmc_queue {
+ char *bounce_buf;
+ struct scatterlist *bounce_sg;
+ unsigned int bounce_sg_len;
++#ifdef CONFIG_MMC_BLOCK_PARANOID_RESUME
++ int check_status;
++#endif
+ };
+
+ extern int mmc_init_queue(struct mmc_queue *, struct mmc_card *, spinlock_t *);
--- /dev/null
+From 39e3d37b1f7194277b8a3ea3536a67ec2d24491e Mon Sep 17 00:00:00 2001
+From: San Mehat <san@android.com>
+Date: Thu, 4 Dec 2008 11:18:00 -0800
+Subject: [PATCH 100/134] mmc: sd: Add retries in re-detection
+
+Signed-off-by: San Mehat <san@android.com>
+---
+ drivers/mmc/core/sd.c | 46 +++++++++++++++++++++++++++++++++++++++++++---
+ 1 files changed, 43 insertions(+), 3 deletions(-)
+
+--- a/drivers/mmc/core/sd.c
++++ b/drivers/mmc/core/sd.c
+@@ -558,18 +558,37 @@ static void mmc_sd_remove(struct mmc_hos
+ */
+ static void mmc_sd_detect(struct mmc_host *host)
+ {
+- int err;
++ int err = 0;
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ int retries = 5;
++#endif
+
+ BUG_ON(!host);
+ BUG_ON(!host->card);
+-
++
+ mmc_claim_host(host);
+
+ /*
+ * Just check if our card has been removed.
+ */
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ while(retries) {
++ err = mmc_send_status(host->card, NULL);
++ printk("%s(%s): err = %d\n", __func__, mmc_hostname(host), err);
++ if (err) {
++ retries--;
++ udelay(5);
++ continue;
++ }
++ break;
++ }
++ if (!retries) {
++ printk(KERN_ERR "%s(%s): Unable to re-detect card (%d)\n",
++ __func__, mmc_hostname(host), err);
++ }
++#else
+ err = mmc_send_status(host->card, NULL);
+-
++#endif
+ mmc_release_host(host);
+
+ if (err) {
+@@ -664,6 +683,9 @@ static const struct mmc_bus_ops mmc_sd_o
+ int mmc_attach_sd(struct mmc_host *host, u32 ocr)
+ {
+ int err;
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ int retries;
++#endif
+
+ BUG_ON(!host);
+ WARN_ON(!host->claimed);
+@@ -712,9 +734,27 @@ int mmc_attach_sd(struct mmc_host *host,
+ /*
+ * Detect and init the card.
+ */
++#ifdef CONFIG_MMC_PARANOID_SD_INIT
++ retries = 5;
++ while (retries) {
++ err = mmc_sd_init_card(host, host->ocr, NULL);
++ if (err) {
++ retries--;
++ continue;
++ }
++ break;
++ }
++
++ if (!retries) {
++ printk(KERN_ERR "%s: mmc_sd_init_card() failure (err = %d)\n",
++ mmc_hostname(host), err);
++ goto err;
++ }
++#else
+ err = mmc_sd_init_card(host, host->ocr, NULL);
+ if (err)
+ goto err;
++#endif
+
+ mmc_release_host(host);
+
--- /dev/null
+From 03e39e8f663c896dac11e87d96e8cb0292520e36 Mon Sep 17 00:00:00 2001
+From: Mike Lockwood <lockwood@android.com>
+Date: Tue, 2 Dec 2008 22:01:33 -0500
+Subject: [PATCH 101/134] android_usb: Composite USB gadget driver for android.
+
+Signed-off-by: Mike Lockwood <lockwood@android.com>
+
+USB: android gadget: add remote wakeup attribute to android function
+
+Add remote wakeup attribute to configuration descriptor of android
+function to advertise remote wakeup capability to host
+
+Acked-by: Allam, Suresh Reddy <sallam@qualcomm.com>
+
+Signed-off-by: Mike Lockwood <lockwood@android.com>
+
+usb gadget: link fixes for android composite gadget
+
+Signed-off-by: Mike Lockwood <lockwood@android.com>
+
+usb gadget: Fix null pointer errors in android composite driver
+
+Signed-off-by: Mike Lockwood <lockwood@android.com>
+---
+ drivers/usb/gadget/Kconfig | 8 +
+ drivers/usb/gadget/Makefile | 2 +
+ drivers/usb/gadget/android.c | 345 +++++
+ drivers/usb/gadget/f_adb.c | 668 ++++++++
+ drivers/usb/gadget/f_adb.h | 25 +
+ drivers/usb/gadget/f_mass_storage.c | 2906 +++++++++++++++++++++++++++++++++++
+ drivers/usb/gadget/f_mass_storage.h | 52 +
+ include/linux/usb/android.h | 40 +
+ 8 files changed, 4046 insertions(+), 0 deletions(-)
+ create mode 100644 drivers/usb/gadget/android.c
+ create mode 100644 drivers/usb/gadget/f_adb.c
+ create mode 100644 drivers/usb/gadget/f_adb.h
+ create mode 100644 drivers/usb/gadget/f_mass_storage.c
+ create mode 100644 drivers/usb/gadget/f_mass_storage.h
+ create mode 100644 include/linux/usb/android.h
+
+--- a/drivers/usb/gadget/Kconfig
++++ b/drivers/usb/gadget/Kconfig
+@@ -700,6 +700,14 @@ config USB_G_PRINTER
+ For more information, see Documentation/usb/gadget_printer.txt
+ which includes sample code for accessing the device file.
+
++config USB_ANDROID
++ tristate "Android Gadget"
++ help
++ The Android gadget provides mass storage and adb transport.
++
++ Say "y" to link the driver statically, or "m" to build a
++ dynamically linked module called "g_android".
++
+ config USB_CDC_COMPOSITE
+ tristate "CDC Composite Device (Ethernet and ACM)"
+ depends on NET
+--- a/drivers/usb/gadget/Makefile
++++ b/drivers/usb/gadget/Makefile
+@@ -33,6 +33,7 @@ gadgetfs-objs := inode.o
+ g_file_storage-objs := file_storage.o
+ g_printer-objs := printer.o
+ g_cdc-objs := cdc2.o
++g_android-objs := android.o f_adb.o f_mass_storage.o
+
+ obj-$(CONFIG_USB_ZERO) += g_zero.o
+ obj-$(CONFIG_USB_ETH) += g_ether.o
+@@ -42,4 +43,5 @@ obj-$(CONFIG_USB_G_SERIAL) += g_serial.o
+ obj-$(CONFIG_USB_G_PRINTER) += g_printer.o
+ obj-$(CONFIG_USB_MIDI_GADGET) += g_midi.o
+ obj-$(CONFIG_USB_CDC_COMPOSITE) += g_cdc.o
++obj-$(CONFIG_USB_ANDROID) += g_android.o
+
+--- /dev/null
++++ b/drivers/usb/gadget/android.c
+@@ -0,0 +1,345 @@
++/*
++ * Gadget Driver for Android
++ *
++ * Copyright (C) 2008 Google, Inc.
++ * Author: Mike Lockwood <lockwood@android.com>
++ *
++ * 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.
++ *
++ */
++
++/* #define DEBUG */
++/* #define VERBOSE_DEBUG */
++
++#include <linux/init.h>
++#include <linux/module.h>
++#include <linux/fs.h>
++
++#include <linux/delay.h>
++#include <linux/kernel.h>
++#include <linux/utsname.h>
++#include <linux/miscdevice.h>
++#include <linux/platform_device.h>
++
++#include <linux/usb/android.h>
++#include <linux/usb/ch9.h>
++#include <linux/usb/composite.h>
++#include <linux/usb/gadget.h>
++
++#include "f_mass_storage.h"
++#include "f_adb.h"
++
++#include "gadget_chips.h"
++
++/*
++ * Kbuild is not very cooperative with respect to linking separately
++ * compiled library objects into one module. So for now we won't use
++ * separate compilation ... ensuring init/exit sections work to shrink
++ * the runtime footprint, and giving us at least some parts of what
++ * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
++ */
++#include "usbstring.c"
++#include "config.c"
++#include "epautoconf.c"
++#include "composite.c"
++
++MODULE_AUTHOR("Mike Lockwood");
++MODULE_DESCRIPTION("Android Composite USB Driver");
++MODULE_LICENSE("GPL");
++MODULE_VERSION("1.0");
++
++static const char longname[] = "Gadget Android";
++
++/* Default vendor and product IDs, overridden by platform data */
++#define VENDOR_ID 0x18D1
++#define PRODUCT_ID 0x0001
++#define ADB_PRODUCT_ID 0x0002
++
++struct android_dev {
++ struct usb_gadget *gadget;
++ struct usb_composite_dev *cdev;
++
++ int product_id;
++ int adb_product_id;
++ int version;
++
++ int adb_enabled;
++ int nluns;
++};
++
++static atomic_t adb_enable_excl;
++static struct android_dev *_android_dev;
++
++/* string IDs are assigned dynamically */
++
++#define STRING_MANUFACTURER_IDX 0
++#define STRING_PRODUCT_IDX 1
++#define STRING_SERIAL_IDX 2
++
++/* String Table */
++static struct usb_string strings_dev[] = {
++ /* These dummy values should be overridden by platform data */
++ [STRING_MANUFACTURER_IDX].s = "Android",
++ [STRING_PRODUCT_IDX].s = "Android",
++ [STRING_SERIAL_IDX].s = "0123456789ABCDEF",
++ { } /* end of list */
++};
++
++static struct usb_gadget_strings stringtab_dev = {
++ .language = 0x0409, /* en-us */
++ .strings = strings_dev,
++};
++
++static struct usb_gadget_strings *dev_strings[] = {
++ &stringtab_dev,
++ NULL,
++};
++
++static struct usb_device_descriptor device_desc = {
++ .bLength = sizeof(device_desc),
++ .bDescriptorType = USB_DT_DEVICE,
++ .bcdUSB = __constant_cpu_to_le16(0x0200),
++ .bDeviceClass = USB_CLASS_PER_INTERFACE,
++ .idVendor = __constant_cpu_to_le16(VENDOR_ID),
++ .idProduct = __constant_cpu_to_le16(PRODUCT_ID),
++ .bcdDevice = __constant_cpu_to_le16(0xffff),
++ .bNumConfigurations = 1,
++};
++
++static int __init android_bind_config(struct usb_configuration *c)
++{
++ struct android_dev *dev = _android_dev;
++ int ret;
++ printk(KERN_DEBUG "android_bind_config\n");
++
++ ret = mass_storage_function_add(dev->cdev, c, dev->nluns);
++ if (ret)
++ return ret;
++ return adb_function_add(dev->cdev, c);
++}
++
++static struct usb_configuration android_config_driver = {
++ .label = "android",
++ .bind = android_bind_config,
++ .bConfigurationValue = 1,
++ .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
++ .bMaxPower = 0x80, /* 250ma */
++};
++
++static int __init android_bind(struct usb_composite_dev *cdev)
++{
++ struct android_dev *dev = _android_dev;
++ struct usb_gadget *gadget = cdev->gadget;
++ int gcnum;
++ int id;
++ int ret;
++
++ printk(KERN_INFO "android_bind\n");
++
++ /* Allocate string descriptor numbers ... note that string
++ * contents can be overridden by the composite_dev glue.
++ */
++ id = usb_string_id(cdev);
++ if (id < 0)
++ return id;
++ strings_dev[STRING_MANUFACTURER_IDX].id = id;
++ device_desc.iManufacturer = id;
++
++ id = usb_string_id(cdev);
++ if (id < 0)
++ return id;
++ strings_dev[STRING_PRODUCT_IDX].id = id;
++ device_desc.iProduct = id;
++
++ id = usb_string_id(cdev);
++ if (id < 0)
++ return id;
++ strings_dev[STRING_SERIAL_IDX].id = id;
++ device_desc.iSerialNumber = id;
++
++ if (gadget->ops->wakeup)
++ android_config_driver.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
++
++ /* register our configuration */
++ ret = usb_add_config(cdev, &android_config_driver);
++ if (ret) {
++ printk(KERN_ERR "usb_add_config failed\n");
++ return ret;
++ }
++
++ gcnum = usb_gadget_controller_number(gadget);
++ if (gcnum >= 0)
++ device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum);
++ else {
++ /* gadget zero is so simple (for now, no altsettings) that
++ * it SHOULD NOT have problems with bulk-capable hardware.
++ * so just warn about unrcognized controllers -- don't panic.
++ *
++ * things like configuration and altsetting numbering
++ * can need hardware-specific attention though.
++ */
++ pr_warning("%s: controller '%s' not recognized\n",
++ longname, gadget->name);
++ device_desc.bcdDevice = __constant_cpu_to_le16(0x9999);
++ }
++
++ usb_gadget_set_selfpowered(gadget);
++ dev->cdev = cdev;
++
++ return 0;
++}
++
++static struct usb_composite_driver android_usb_driver = {
++ .name = "android_usb",
++ .dev = &device_desc,
++ .strings = dev_strings,
++ .bind = android_bind,
++};
++
++static void enable_adb(struct android_dev *dev, int enable)
++{
++ if (enable != dev->adb_enabled) {
++ dev->adb_enabled = enable;
++ adb_function_enable(enable);
++
++ /* set product ID to the appropriate value */
++ if (enable)
++ device_desc.idProduct =
++ __constant_cpu_to_le16(dev->adb_product_id);
++ else
++ device_desc.idProduct =
++ __constant_cpu_to_le16(dev->product_id);
++ if (dev->cdev)
++ dev->cdev->desc.idProduct = device_desc.idProduct;
++
++ /* force reenumeration */
++ if (dev->cdev && dev->cdev->gadget &&
++ dev->cdev->gadget->speed != USB_SPEED_UNKNOWN) {
++ usb_gadget_disconnect(dev->cdev->gadget);
++ msleep(10);
++ usb_gadget_connect(dev->cdev->gadget);
++ }
++ }
++}
++
++static int adb_enable_open(struct inode *ip, struct file *fp)
++{
++ if (atomic_inc_return(&adb_enable_excl) != 1) {
++ atomic_dec(&adb_enable_excl);
++ return -EBUSY;
++ }
++
++ printk(KERN_INFO "enabling adb\n");
++ enable_adb(_android_dev, 1);
++
++ return 0;
++}
++
++static int adb_enable_release(struct inode *ip, struct file *fp)
++{
++ printk(KERN_INFO "disabling adb\n");
++ enable_adb(_android_dev, 0);
++ atomic_dec(&adb_enable_excl);
++ return 0;
++}
++
++static struct file_operations adb_enable_fops = {
++ .owner = THIS_MODULE,
++ .open = adb_enable_open,
++ .release = adb_enable_release,
++};
++
++static struct miscdevice adb_enable_device = {
++ .minor = MISC_DYNAMIC_MINOR,
++ .name = "android_adb_enable",
++ .fops = &adb_enable_fops,
++};
++
++static int __init android_probe(struct platform_device *pdev)
++{
++ struct android_usb_platform_data *pdata = pdev->dev.platform_data;
++ struct android_dev *dev = _android_dev;
++
++ printk(KERN_INFO "android_probe pdata: %p\n", pdata);
++
++ if (pdata) {
++ if (pdata->vendor_id)
++ device_desc.idVendor =
++ __constant_cpu_to_le16(pdata->vendor_id);
++ if (pdata->product_id) {
++ dev->product_id = pdata->product_id;
++ device_desc.idProduct =
++ __constant_cpu_to_le16(pdata->product_id);
++ }
++ if (pdata->adb_product_id)
++ dev->adb_product_id = pdata->adb_product_id;
++ if (pdata->version)
++ dev->version = pdata->version;
++
++ if (pdata->product_name)
++ strings_dev[STRING_PRODUCT_IDX].s = pdata->product_name;
++ if (pdata->manufacturer_name)
++ strings_dev[STRING_MANUFACTURER_IDX].s =
++ pdata->manufacturer_name;
++ if (pdata->serial_number)
++ strings_dev[STRING_SERIAL_IDX].s = pdata->serial_number;
++ dev->nluns = pdata->nluns;
++ }
++
++ return 0;
++}
++
++static struct platform_driver android_platform_driver = {
++ .driver = { .name = "android_usb", },
++ .probe = android_probe,
++};
++
++static int __init init(void)
++{
++ struct android_dev *dev;
++ int ret;
++
++ printk(KERN_INFO "android init\n");
++
++ dev = kzalloc(sizeof(*dev), GFP_KERNEL);
++ if (!dev)
++ return -ENOMEM;
++
++ /* set default values, which should be overridden by platform data */
++ dev->product_id = PRODUCT_ID;
++ dev->adb_product_id = ADB_PRODUCT_ID;
++ _android_dev = dev;
++
++ ret = platform_driver_register(&android_platform_driver);
++ if (ret)
++ return ret;
++ ret = misc_register(&adb_enable_device);
++ if (ret) {
++ platform_driver_unregister(&android_platform_driver);
++ return ret;
++ }
++ ret = usb_composite_register(&android_usb_driver);
++ if (ret) {
++ misc_deregister(&adb_enable_device);
++ platform_driver_unregister(&android_platform_driver);
++ }
++ return ret;
++}
++module_init(init);
++
++static void __exit cleanup(void)
++{
++ usb_composite_unregister(&android_usb_driver);
++ misc_deregister(&adb_enable_device);
++ platform_driver_unregister(&android_platform_driver);
++ kfree(_android_dev);
++ _android_dev = NULL;
++}
++module_exit(cleanup);
+--- /dev/null
++++ b/drivers/usb/gadget/f_adb.c
+@@ -0,0 +1,668 @@
++/*
++ * Gadget Driver for Android ADB
++ *
++ * Copyright (C) 2008 Google, Inc.
++ * Author: Mike Lockwood <lockwood@android.com>
++ *
++ * 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.
++ *
++ */
++
++/* #define DEBUG */
++/* #define VERBOSE_DEBUG */
++
++#include <linux/module.h>
++#include <linux/init.h>
++#include <linux/poll.h>
++#include <linux/delay.h>
++#include <linux/wait.h>
++#include <linux/err.h>
++#include <linux/interrupt.h>
++
++#include <linux/types.h>
++#include <linux/device.h>
++#include <linux/miscdevice.h>
++
++#include <linux/usb/ch9.h>
++#include <linux/usb/composite.h>
++#include <linux/usb/gadget.h>
++
++#include "f_adb.h"
++
++#define BULK_BUFFER_SIZE 4096
++
++/* number of rx and tx requests to allocate */
++#define RX_REQ_MAX 4
++#define TX_REQ_MAX 4
++
++static const char shortname[] = "android_adb";
++
++struct adb_dev {
++ struct usb_function function;
++ struct usb_composite_dev *cdev;
++ spinlock_t lock;
++
++ struct usb_ep *ep_in;
++ struct usb_ep *ep_out;
++
++ int online;
++ int error;
++
++ atomic_t read_excl;
++ atomic_t write_excl;
++ atomic_t open_excl;
++
++ struct list_head tx_idle;
++ struct list_head rx_idle;
++ struct list_head rx_done;
++
++ wait_queue_head_t read_wq;
++ wait_queue_head_t write_wq;
++
++ /* the request we're currently reading from */
++ struct usb_request *read_req;
++ unsigned char *read_buf;
++ unsigned read_count;
++};
++
++static struct usb_interface_descriptor adb_interface_desc = {
++ .bLength = USB_DT_INTERFACE_SIZE,
++ .bDescriptorType = USB_DT_INTERFACE,
++ .bInterfaceNumber = 0,
++ .bNumEndpoints = 2,
++ .bInterfaceClass = 0xFF,
++ .bInterfaceSubClass = 0x42,
++ .bInterfaceProtocol = 1,
++};
++
++static struct usb_endpoint_descriptor adb_highspeed_in_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++ .bEndpointAddress = USB_DIR_IN,
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++ .wMaxPacketSize = __constant_cpu_to_le16(512),
++};
++
++static struct usb_endpoint_descriptor adb_highspeed_out_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++ .bEndpointAddress = USB_DIR_OUT,
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++ .wMaxPacketSize = __constant_cpu_to_le16(512),
++};
++
++static struct usb_endpoint_descriptor adb_fullspeed_in_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++ .bEndpointAddress = USB_DIR_IN,
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++};
++
++static struct usb_endpoint_descriptor adb_fullspeed_out_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++ .bEndpointAddress = USB_DIR_OUT,
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++};
++
++static struct usb_descriptor_header *fs_adb_descs[] = {
++ (struct usb_descriptor_header *) &adb_interface_desc,
++ (struct usb_descriptor_header *) &adb_fullspeed_in_desc,
++ (struct usb_descriptor_header *) &adb_fullspeed_out_desc,
++ NULL,
++};
++
++static struct usb_descriptor_header *hs_adb_descs[] = {
++ (struct usb_descriptor_header *) &adb_interface_desc,
++ (struct usb_descriptor_header *) &adb_highspeed_in_desc,
++ (struct usb_descriptor_header *) &adb_highspeed_out_desc,
++ NULL,
++};
++
++/* used when adb function is disabled */
++static struct usb_descriptor_header *null_adb_descs[] = {
++ NULL,
++};
++
++
++/* temporary variable used between adb_open() and adb_gadget_bind() */
++static struct adb_dev *_adb_dev;
++
++static inline struct adb_dev *func_to_dev(struct usb_function *f)
++{
++ return container_of(f, struct adb_dev, function);
++}
++
++
++static struct usb_request *adb_request_new(struct usb_ep *ep, int buffer_size)
++{
++ struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
++ if (!req)
++ return NULL;
++
++ /* now allocate buffers for the requests */
++ req->buf = kmalloc(buffer_size, GFP_KERNEL);
++ if (!req->buf) {
++ usb_ep_free_request(ep, req);
++ return NULL;
++ }
++
++ return req;
++}
++
++static void adb_request_free(struct usb_request *req, struct usb_ep *ep)
++{
++ if (req) {
++ kfree(req->buf);
++ usb_ep_free_request(ep, req);
++ }
++}
++
++static inline int _lock(atomic_t *excl)
++{
++ if (atomic_inc_return(excl) == 1) {
++ return 0;
++ } else {
++ atomic_dec(excl);
++ return -1;
++ }
++}
++
++static inline void _unlock(atomic_t *excl)
++{
++ atomic_dec(excl);
++}
++
++/* add a request to the tail of a list */
++void req_put(struct adb_dev *dev, struct list_head *head,
++ struct usb_request *req)
++{
++ unsigned long flags;
++
++ spin_lock_irqsave(&dev->lock, flags);
++ list_add_tail(&req->list, head);
++ spin_unlock_irqrestore(&dev->lock, flags);
++}
++
++/* remove a request from the head of a list */
++struct usb_request *req_get(struct adb_dev *dev, struct list_head *head)
++{
++ unsigned long flags;
++ struct usb_request *req;
++
++ spin_lock_irqsave(&dev->lock, flags);
++ if (list_empty(head)) {
++ req = 0;
++ } else {
++ req = list_first_entry(head, struct usb_request, list);
++ list_del(&req->list);
++ }
++ spin_unlock_irqrestore(&dev->lock, flags);
++ return req;
++}
++
++static void adb_complete_in(struct usb_ep *ep, struct usb_request *req)
++{
++ struct adb_dev *dev = _adb_dev;
++
++ if (req->status != 0)
++ dev->error = 1;
++
++ req_put(dev, &dev->tx_idle, req);
++
++ wake_up(&dev->write_wq);
++}
++
++static void adb_complete_out(struct usb_ep *ep, struct usb_request *req)
++{
++ struct adb_dev *dev = _adb_dev;
++
++ if (req->status != 0) {
++ dev->error = 1;
++ req_put(dev, &dev->rx_idle, req);
++ } else {
++ req_put(dev, &dev->rx_done, req);
++ }
++
++ wake_up(&dev->read_wq);
++}
++
++static int __init create_bulk_endpoints(struct adb_dev *dev,
++ struct usb_endpoint_descriptor *in_desc,
++ struct usb_endpoint_descriptor *out_desc)
++{
++ struct usb_composite_dev *cdev = dev->cdev;
++ struct usb_request *req;
++ struct usb_ep *ep;
++ int i;
++
++ DBG(cdev, "create_bulk_endpoints dev: %p\n", dev);
++
++ ep = usb_ep_autoconfig(cdev->gadget, in_desc);
++ if (!ep) {
++ DBG(cdev, "usb_ep_autoconfig for ep_in failed\n");
++ return -ENODEV;
++ }
++ DBG(cdev, "usb_ep_autoconfig for ep_in got %s\n", ep->name);
++ dev->ep_in = ep;
++
++ ep = usb_ep_autoconfig(cdev->gadget, out_desc);
++ if (!ep) {
++ DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
++ return -ENODEV;
++ }
++ DBG(cdev, "usb_ep_autoconfig for adb ep_out got %s\n", ep->name);
++ dev->ep_out = ep;
++
++ /* now allocate requests for our endpoints */
++ for (i = 0; i < RX_REQ_MAX; i++) {
++ req = adb_request_new(dev->ep_out, BULK_BUFFER_SIZE);
++ if (!req)
++ goto fail;
++ req->complete = adb_complete_out;
++ req_put(dev, &dev->rx_idle, req);
++ }
++
++ for (i = 0; i < TX_REQ_MAX; i++) {
++ req = adb_request_new(dev->ep_in, BULK_BUFFER_SIZE);
++ if (!req)
++ goto fail;
++ req->complete = adb_complete_in;
++ req_put(dev, &dev->tx_idle, req);
++ }
++
++ return 0;
++
++fail:
++ printk(KERN_ERR "adb_bind() could not allocate requests\n");
++ return -1;
++}
++
++static ssize_t adb_read(struct file *fp, char __user *buf,
++ size_t count, loff_t *pos)
++{
++ struct adb_dev *dev = fp->private_data;
++ struct usb_composite_dev *cdev = dev->cdev;
++ struct usb_request *req;
++ int r = count, xfer;
++ int ret;
++
++ DBG(cdev, "adb_read(%d)\n", count);
++
++ if (_lock(&dev->read_excl))
++ return -EBUSY;
++
++ /* we will block until we're online */
++ while (!(dev->online || dev->error)) {
++ DBG(cdev, "adb_read: waiting for online state\n");
++ ret = wait_event_interruptible(dev->read_wq,
++ (dev->online || dev->error));
++ if (ret < 0) {
++ _unlock(&dev->read_excl);
++ return ret;
++ }
++ }
++
++ while (count > 0) {
++ if (dev->error) {
++ DBG(cdev, "adb_read dev->error\n");
++ r = -EIO;
++ break;
++ }
++
++ /* if we have idle read requests, get them queued */
++ while ((req = req_get(dev, &dev->rx_idle))) {
++requeue_req:
++ req->length = BULK_BUFFER_SIZE;
++ ret = usb_ep_queue(dev->ep_out, req, GFP_ATOMIC);
++
++ if (ret < 0) {
++ r = -EIO;
++ dev->error = 1;
++ req_put(dev, &dev->rx_idle, req);
++ goto fail;
++ } else {
++ DBG(cdev, "rx %p queue\n", req);
++ }
++ }
++
++ /* if we have data pending, give it to userspace */
++ if (dev->read_count > 0) {
++ if (dev->read_count < count)
++ xfer = dev->read_count;
++ else
++ xfer = count;
++
++ if (copy_to_user(buf, dev->read_buf, xfer)) {
++ r = -EFAULT;
++ break;
++ }
++ dev->read_buf += xfer;
++ dev->read_count -= xfer;
++ buf += xfer;
++ count -= xfer;
++
++ /* if we've emptied the buffer, release the request */
++ if (dev->read_count == 0) {
++ req_put(dev, &dev->rx_idle, dev->read_req);
++ dev->read_req = 0;
++ }
++ continue;
++ }
++
++ /* wait for a request to complete */
++ req = 0;
++ ret = wait_event_interruptible(dev->read_wq,
++ ((req = req_get(dev, &dev->rx_done)) || dev->error));
++ if (req != 0) {
++ /* if we got a 0-len one we need to put it back into
++ ** service. if we made it the current read req we'd
++ ** be stuck forever
++ */
++ if (req->actual == 0)
++ goto requeue_req;
++
++ dev->read_req = req;
++ dev->read_count = req->actual;
++ dev->read_buf = req->buf;
++ DBG(cdev, "rx %p %d\n", req, req->actual);
++ }
++
++ if (ret < 0) {
++ r = ret;
++ break;
++ }
++ }
++
++fail:
++ _unlock(&dev->read_excl);
++ DBG(cdev, "adb_read returning %d\n", r);
++ return r;
++}
++
++static ssize_t adb_write(struct file *fp, const char __user *buf,
++ size_t count, loff_t *pos)
++{
++ struct adb_dev *dev = fp->private_data;
++ struct usb_composite_dev *cdev = dev->cdev;
++ struct usb_request *req = 0;
++ int r = count, xfer;
++ int ret;
++
++ DBG(cdev, "adb_write(%d)\n", count);
++
++ if (_lock(&dev->write_excl))
++ return -EBUSY;
++
++ while (count > 0) {
++ if (dev->error) {
++ DBG(cdev, "adb_write dev->error\n");
++ r = -EIO;
++ break;
++ }
++
++ /* get an idle tx request to use */
++ req = 0;
++ ret = wait_event_interruptible(dev->write_wq,
++ ((req = req_get(dev, &dev->tx_idle)) || dev->error));
++
++ if (ret < 0) {
++ r = ret;
++ break;
++ }
++
++ if (req != 0) {
++ if (count > BULK_BUFFER_SIZE)
++ xfer = BULK_BUFFER_SIZE;
++ else
++ xfer = count;
++ if (copy_from_user(req->buf, buf, xfer)) {
++ r = -EFAULT;
++ break;
++ }
++
++ req->length = xfer;
++ ret = usb_ep_queue(dev->ep_in, req, GFP_ATOMIC);
++ if (ret < 0) {
++ DBG(cdev, "adb_write: xfer error %d\n", ret);
++ dev->error = 1;
++ r = -EIO;
++ break;
++ }
++
++ buf += xfer;
++ count -= xfer;
++
++ /* zero this so we don't try to free it on error exit */
++ req = 0;
++ }
++ }
++
++ if (req)
++ req_put(dev, &dev->tx_idle, req);
++
++ _unlock(&dev->write_excl);
++ DBG(cdev, "adb_write returning %d\n", r);
++ return r;
++}
++
++static int adb_open(struct inode *ip, struct file *fp)
++{
++ printk(KERN_INFO "adb_open\n");
++ if (_lock(&_adb_dev->open_excl))
++ return -EBUSY;
++
++ fp->private_data = _adb_dev;
++
++ /* clear the error latch */
++ _adb_dev->error = 0;
++
++ return 0;
++}
++
++static int adb_release(struct inode *ip, struct file *fp)
++{
++ printk(KERN_INFO "adb_release\n");
++ _unlock(&_adb_dev->open_excl);
++ return 0;
++}
++
++/* file operations for ADB device /dev/android_adb */
++static struct file_operations adb_fops = {
++ .owner = THIS_MODULE,
++ .read = adb_read,
++ .write = adb_write,
++ .open = adb_open,
++ .release = adb_release,
++};
++
++static struct miscdevice adb_device = {
++ .minor = MISC_DYNAMIC_MINOR,
++ .name = shortname,
++ .fops = &adb_fops,
++};
++
++static int __init
++adb_function_bind(struct usb_configuration *c, struct usb_function *f)
++{
++ struct usb_composite_dev *cdev = c->cdev;
++ struct adb_dev *dev = func_to_dev(f);
++ int id;
++ int ret;
++
++ dev->cdev = cdev;
++ DBG(cdev, "adb_function_bind dev: %p\n", dev);
++
++ /* allocate interface ID(s) */
++ id = usb_interface_id(c, f);
++ if (id < 0)
++ return id;
++ adb_interface_desc.bInterfaceNumber = id;
++
++ /* allocate endpoints */
++ ret = create_bulk_endpoints(dev, &adb_fullspeed_in_desc,
++ &adb_fullspeed_out_desc);
++ if (ret)
++ return ret;
++
++ /* support high speed hardware */
++ if (gadget_is_dualspeed(c->cdev->gadget)) {
++ adb_highspeed_in_desc.bEndpointAddress =
++ adb_fullspeed_in_desc.bEndpointAddress;
++ adb_highspeed_out_desc.bEndpointAddress =
++ adb_fullspeed_out_desc.bEndpointAddress;
++ }
++
++ DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
++ gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
++ f->name, dev->ep_in->name, dev->ep_out->name);
++ return 0;
++}
++
++static void
++adb_function_unbind(struct usb_configuration *c, struct usb_function *f)
++{
++ struct adb_dev *dev = func_to_dev(f);
++ struct usb_request *req;
++
++ spin_lock_irq(&dev->lock);
++
++ while ((req = req_get(dev, &dev->rx_idle)))
++ adb_request_free(req, dev->ep_out);
++ while ((req = req_get(dev, &dev->tx_idle)))
++ adb_request_free(req, dev->ep_in);
++
++ dev->online = 0;
++ dev->error = 1;
++ spin_unlock_irq(&dev->lock);
++
++ misc_deregister(&adb_device);
++ kfree(_adb_dev);
++ _adb_dev = NULL;
++}
++
++static int adb_function_set_alt(struct usb_function *f,
++ unsigned intf, unsigned alt)
++{
++ struct adb_dev *dev = func_to_dev(f);
++ struct usb_composite_dev *cdev = f->config->cdev;
++ int ret;
++
++ DBG(cdev, "adb_function_set_alt intf: %d alt: %d\n", intf, alt);
++ ret = usb_ep_enable(dev->ep_in,
++ ep_choose(cdev->gadget,
++ &adb_highspeed_in_desc,
++ &adb_fullspeed_in_desc));
++ if (ret)
++ return ret;
++ ret = usb_ep_enable(dev->ep_out,
++ ep_choose(cdev->gadget,
++ &adb_highspeed_out_desc,
++ &adb_fullspeed_out_desc));
++ if (ret) {
++ usb_ep_disable(dev->ep_in);
++ return ret;
++ }
++ dev->online = 1;
++
++ /* readers may be blocked waiting for us to go online */
++ wake_up(&dev->read_wq);
++ return 0;
++}
++
++static void adb_function_disable(struct usb_function *f)
++{
++ struct adb_dev *dev = func_to_dev(f);
++ struct usb_composite_dev *cdev = dev->cdev;
++
++ DBG(cdev, "adb_function_disable\n");
++ dev->online = 0;
++ dev->error = 1;
++ usb_ep_disable(dev->ep_in);
++ usb_ep_disable(dev->ep_out);
++
++ /* readers may be blocked waiting for us to go online */
++ wake_up(&dev->read_wq);
++
++ VDBG(cdev, "%s disabled\n", dev->function.name);
++}
++
++int __init adb_function_add(struct usb_composite_dev *cdev,
++ struct usb_configuration *c)
++{
++ struct adb_dev *dev;
++ int ret;
++
++ printk(KERN_INFO "adb_function_add\n");
++
++ dev = kzalloc(sizeof(*dev), GFP_KERNEL);
++ if (!dev)
++ return -ENOMEM;
++
++ spin_lock_init(&dev->lock);
++
++ init_waitqueue_head(&dev->read_wq);
++ init_waitqueue_head(&dev->write_wq);
++
++ atomic_set(&dev->open_excl, 0);
++ atomic_set(&dev->read_excl, 0);
++ atomic_set(&dev->write_excl, 0);
++
++ INIT_LIST_HEAD(&dev->rx_idle);
++ INIT_LIST_HEAD(&dev->rx_done);
++ INIT_LIST_HEAD(&dev->tx_idle);
++
++ dev->cdev = cdev;
++ dev->function.name = "adb";
++ dev->function.descriptors = null_adb_descs;
++ dev->function.hs_descriptors = null_adb_descs;
++ dev->function.bind = adb_function_bind;
++ dev->function.unbind = adb_function_unbind;
++ dev->function.set_alt = adb_function_set_alt;
++ dev->function.disable = adb_function_disable;
++
++ /* _adb_dev must be set before calling usb_gadget_register_driver */
++ _adb_dev = dev;
++
++ ret = misc_register(&adb_device);
++ if (ret)
++ goto err1;
++ ret = usb_add_function(c, &dev->function);
++ if (ret)
++ goto err2;
++
++ return 0;
++
++err2:
++ misc_deregister(&adb_device);
++err1:
++ kfree(dev);
++ printk(KERN_ERR "adb gadget driver failed to initialize\n");
++ return ret;
++}
++
++void adb_function_enable(int enable)
++{
++ struct adb_dev *dev = _adb_dev;
++
++ if (dev) {
++ DBG(dev->cdev, "adb_function_enable(%s)\n",
++ enable ? "true" : "false");
++
++ if (enable) {
++ dev->function.descriptors = fs_adb_descs;
++ dev->function.hs_descriptors = hs_adb_descs;
++ } else {
++ dev->function.descriptors = null_adb_descs;
++ dev->function.hs_descriptors = null_adb_descs;
++ }
++ }
++}
++
+--- /dev/null
++++ b/drivers/usb/gadget/f_adb.h
+@@ -0,0 +1,25 @@
++/*
++ * Gadget Driver for Android ADB
++ *
++ * Copyright (C) 2008 Google, Inc.
++ * Author: Mike Lockwood <lockwood@android.com>
++ *
++ * This software is licensed under the terms of the GNU General Public
++ * License version 2, as published by the Free Software Foundation, and
++ * may be copied, distributed, and modified under those terms.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
++ * GNU General Public License for more details.
++ *
++ */
++
++#ifndef __F_ADB_H
++#define __F_ADB_H
++
++int adb_function_add(struct usb_composite_dev *cdev,
++ struct usb_configuration *c);
++void adb_function_enable(int enable);
++
++#endif /* __F_ADB_H */
+--- /dev/null
++++ b/drivers/usb/gadget/f_mass_storage.c
+@@ -0,0 +1,2906 @@
++/*
++ * drivers/usb/gadget/f_mass_storage.c
++ *
++ * Function Driver for USB Mass Storage
++ *
++ * Copyright (C) 2008 Google, Inc.
++ * Author: Mike Lockwood <lockwood@android.com>
++ *
++ * Based heavily on the file_storage gadget driver in
++ * drivers/usb/gadget/file_storage.c and licensed under the same terms:
++ *
++ * Copyright (C) 2003-2007 Alan Stern
++ * 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,
++ * without modification.
++ * 2. Redistributions in binary form must reproduce the above copyright
++ * notice, this list of conditions and the following disclaimer in the
++ * documentation and/or other materials provided with the distribution.
++ * 3. The names of the above-listed copyright holders may not be used
++ * to endorse or promote products derived from this software without
++ * specific prior written permission.
++ *
++ * ALTERNATIVELY, this software may be distributed under the terms of the
++ * GNU General Public License ("GPL") as published by the Free Software
++ * Foundation, either version 2 of that License or (at your option) any
++ * later version.
++ *
++ * 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 DEBUG */
++/* #define VERBOSE_DEBUG */
++/* #define DUMP_MSGS */
++
++
++#include <linux/blkdev.h>
++#include <linux/completion.h>
++#include <linux/dcache.h>
++#include <linux/delay.h>
++#include <linux/device.h>
++#include <linux/fcntl.h>
++#include <linux/file.h>
++#include <linux/fs.h>
++#include <linux/kref.h>
++#include <linux/kthread.h>
++#include <linux/limits.h>
++#include <linux/rwsem.h>
++#include <linux/slab.h>
++#include <linux/spinlock.h>
++#include <linux/string.h>
++#include <linux/switch.h>
++#include <linux/freezer.h>
++#include <linux/utsname.h>
++#include <linux/wakelock.h>
++
++#include <linux/usb_usual.h>
++#include <linux/usb/ch9.h>
++#include <linux/usb/composite.h>
++#include <linux/usb/gadget.h>
++
++#include "f_mass_storage.h"
++#include "gadget_chips.h"
++
++
++#define BULK_BUFFER_SIZE 4096
++
++/*-------------------------------------------------------------------------*/
++
++#define DRIVER_NAME "usb_mass_storage"
++#define MAX_LUNS 8
++
++static const char shortname[] = DRIVER_NAME;
++
++#ifdef DEBUG
++#define LDBG(lun, fmt, args...) \
++ dev_dbg(&(lun)->dev , fmt , ## args)
++#define MDBG(fmt,args...) \
++ printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
++#else
++#define LDBG(lun, fmt, args...) \
++ do { } while (0)
++#define MDBG(fmt,args...) \
++ do { } while (0)
++#undef VERBOSE_DEBUG
++#undef DUMP_MSGS
++#endif /* DEBUG */
++
++#ifdef VERBOSE_DEBUG
++#define VLDBG LDBG
++#else
++#define VLDBG(lun, fmt, args...) \
++ do { } while (0)
++#endif /* VERBOSE_DEBUG */
++
++#define LERROR(lun, fmt, args...) \
++ dev_err(&(lun)->dev , fmt , ## args)
++#define LWARN(lun, fmt, args...) \
++ dev_warn(&(lun)->dev , fmt , ## args)
++#define LINFO(lun, fmt, args...) \
++ dev_info(&(lun)->dev , fmt , ## args)
++
++#define MINFO(fmt,args...) \
++ printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
++
++#undef DBG
++#undef VDBG
++#undef ERROR
++#undef WARNING
++#undef INFO
++#define DBG(d, fmt, args...) \
++ dev_dbg(&(d)->cdev->gadget->dev , fmt , ## args)
++#define VDBG(d, fmt, args...) \
++ dev_vdbg(&(d)->cdev->gadget->dev , fmt , ## args)
++#define ERROR(d, fmt, args...) \
++ dev_err(&(d)->cdev->gadget->dev , fmt , ## args)
++#define WARNING(d, fmt, args...) \
++ dev_warn(&(d)->cdev->gadget->dev , fmt , ## args)
++#define INFO(d, fmt, args...) \
++ dev_info(&(d)->cdev->gadget->dev , fmt , ## args)
++
++
++/*-------------------------------------------------------------------------*/
++
++/* Bulk-only data structures */
++
++/* Command Block Wrapper */
++struct bulk_cb_wrap {
++ __le32 Signature; /* Contains 'USBC' */
++ u32 Tag; /* Unique per command id */
++ __le32 DataTransferLength; /* Size of the data */
++ u8 Flags; /* Direction in bit 7 */
++ u8 Lun; /* LUN (normally 0) */
++ u8 Length; /* Of the CDB, <= MAX_COMMAND_SIZE */
++ u8 CDB[16]; /* Command Data Block */
++};
++
++#define USB_BULK_CB_WRAP_LEN 31
++#define USB_BULK_CB_SIG 0x43425355 /* Spells out USBC */
++#define USB_BULK_IN_FLAG 0x80
++
++/* Command Status Wrapper */
++struct bulk_cs_wrap {
++ __le32 Signature; /* Should = 'USBS' */
++ u32 Tag; /* Same as original command */
++ __le32 Residue; /* Amount not transferred */
++ u8 Status; /* See below */
++};
++
++#define USB_BULK_CS_WRAP_LEN 13
++#define USB_BULK_CS_SIG 0x53425355 /* Spells out 'USBS' */
++#define USB_STATUS_PASS 0
++#define USB_STATUS_FAIL 1
++#define USB_STATUS_PHASE_ERROR 2
++
++/* Bulk-only class specific requests */
++#define USB_BULK_RESET_REQUEST 0xff
++#define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
++
++/* Length of a SCSI Command Data Block */
++#define MAX_COMMAND_SIZE 16
++
++/* SCSI commands that we recognize */
++#define SC_FORMAT_UNIT 0x04
++#define SC_INQUIRY 0x12
++#define SC_MODE_SELECT_6 0x15
++#define SC_MODE_SELECT_10 0x55
++#define SC_MODE_SENSE_6 0x1a
++#define SC_MODE_SENSE_10 0x5a
++#define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
++#define SC_READ_6 0x08
++#define SC_READ_10 0x28
++#define SC_READ_12 0xa8
++#define SC_READ_CAPACITY 0x25
++#define SC_READ_FORMAT_CAPACITIES 0x23
++#define SC_RELEASE 0x17
++#define SC_REQUEST_SENSE 0x03
++#define SC_RESERVE 0x16
++#define SC_SEND_DIAGNOSTIC 0x1d
++#define SC_START_STOP_UNIT 0x1b
++#define SC_SYNCHRONIZE_CACHE 0x35
++#define SC_TEST_UNIT_READY 0x00
++#define SC_VERIFY 0x2f
++#define SC_WRITE_6 0x0a
++#define SC_WRITE_10 0x2a
++#define SC_WRITE_12 0xaa
++
++/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
++#define SS_NO_SENSE 0
++#define SS_COMMUNICATION_FAILURE 0x040800
++#define SS_INVALID_COMMAND 0x052000
++#define SS_INVALID_FIELD_IN_CDB 0x052400
++#define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
++#define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
++#define SS_MEDIUM_NOT_PRESENT 0x023a00
++#define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
++#define SS_NOT_READY_TO_READY_TRANSITION 0x062800
++#define SS_RESET_OCCURRED 0x062900
++#define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
++#define SS_UNRECOVERED_READ_ERROR 0x031100
++#define SS_WRITE_ERROR 0x030c02
++#define SS_WRITE_PROTECTED 0x072700
++
++#define SK(x) ((u8) ((x) >> 16)) /* Sense Key byte, etc. */
++#define ASC(x) ((u8) ((x) >> 8))
++#define ASCQ(x) ((u8) (x))
++
++
++/*-------------------------------------------------------------------------*/
++
++struct lun {
++ struct file *filp;
++ loff_t file_length;
++ loff_t num_sectors;
++
++ unsigned int ro : 1;
++ unsigned int prevent_medium_removal : 1;
++ unsigned int registered : 1;
++ unsigned int info_valid : 1;
++
++ u32 sense_data;
++ u32 sense_data_info;
++ u32 unit_attention_data;
++
++ struct device dev;
++};
++
++#define backing_file_is_open(curlun) ((curlun)->filp != NULL)
++
++
++static struct lun *dev_to_lun(struct device *dev)
++{
++ return container_of(dev, struct lun, dev);
++}
++
++/* Big enough to hold our biggest descriptor */
++#define EP0_BUFSIZE 256
++#define DELAYED_STATUS (EP0_BUFSIZE + 999) /* An impossibly large value */
++
++/* Number of buffers we will use. 2 is enough for double-buffering */
++#define NUM_BUFFERS 2
++
++enum fsg_buffer_state {
++ BUF_STATE_EMPTY = 0,
++ BUF_STATE_FULL,
++ BUF_STATE_BUSY
++};
++
++struct fsg_buffhd {
++ void *buf;
++ enum fsg_buffer_state state;
++ struct fsg_buffhd *next;
++
++ /* The NetChip 2280 is faster, and handles some protocol faults
++ * better, if we don't submit any short bulk-out read requests.
++ * So we will record the intended request length here. */
++ unsigned int bulk_out_intended_length;
++
++ struct usb_request *inreq;
++ int inreq_busy;
++ struct usb_request *outreq;
++ int outreq_busy;
++};
++
++enum fsg_state {
++ /* This one isn't used anywhere */
++ FSG_STATE_COMMAND_PHASE = -10,
++
++ FSG_STATE_DATA_PHASE,
++ FSG_STATE_STATUS_PHASE,
++
++ FSG_STATE_IDLE = 0,
++ FSG_STATE_ABORT_BULK_OUT,
++ FSG_STATE_RESET,
++ FSG_STATE_CONFIG_CHANGE,
++ FSG_STATE_EXIT,
++ FSG_STATE_TERMINATED
++};
++
++enum data_direction {
++ DATA_DIR_UNKNOWN = 0,
++ DATA_DIR_FROM_HOST,
++ DATA_DIR_TO_HOST,
++ DATA_DIR_NONE
++};
++
++struct fsg_dev {
++ struct usb_function function;
++ struct usb_composite_dev *cdev;
++
++ /* lock protects: state and all the req_busy's */
++ spinlock_t lock;
++
++ /* filesem protects: backing files in use */
++ struct rw_semaphore filesem;
++
++ /* reference counting: wait until all LUNs are released */
++ struct kref ref;
++
++ unsigned int bulk_out_maxpacket;
++ enum fsg_state state; /* For exception handling */
++
++ u8 config, new_config;
++
++ unsigned int running : 1;
++ unsigned int bulk_in_enabled : 1;
++ unsigned int bulk_out_enabled : 1;
++ unsigned int phase_error : 1;
++ unsigned int short_packet_received : 1;
++ unsigned int bad_lun_okay : 1;
++
++ unsigned long atomic_bitflags;
++#define REGISTERED 0
++#define CLEAR_BULK_HALTS 1
++#define SUSPENDED 2
++
++ struct usb_ep *bulk_in;
++ struct usb_ep *bulk_out;
++
++ struct fsg_buffhd *next_buffhd_to_fill;
++ struct fsg_buffhd *next_buffhd_to_drain;
++ struct fsg_buffhd buffhds[NUM_BUFFERS];
++
++ int thread_wakeup_needed;
++ struct completion thread_notifier;
++ struct task_struct *thread_task;
++
++ int cmnd_size;
++ u8 cmnd[MAX_COMMAND_SIZE];
++ enum data_direction data_dir;
++ u32 data_size;
++ u32 data_size_from_cmnd;
++ u32 tag;
++ unsigned int lun;
++ u32 residue;
++ u32 usb_amount_left;
++
++ unsigned int nluns;
++ struct lun *luns;
++ struct lun *curlun;
++
++ u32 buf_size;
++ const char *vendor;
++ const char *product;
++ int release;
++
++ struct switch_dev sdev;
++
++ struct wake_lock wake_lock;
++};
++
++static inline struct fsg_dev *func_to_dev(struct usb_function *f)
++{
++ return container_of(f, struct fsg_dev, function);
++}
++
++static int exception_in_progress(struct fsg_dev *fsg)
++{
++ return (fsg->state > FSG_STATE_IDLE);
++}
++
++/* Make bulk-out requests be divisible by the maxpacket size */
++static void set_bulk_out_req_length(struct fsg_dev *fsg,
++ struct fsg_buffhd *bh, unsigned int length)
++{
++ unsigned int rem;
++
++ bh->bulk_out_intended_length = length;
++ rem = length % fsg->bulk_out_maxpacket;
++ if (rem > 0)
++ length += fsg->bulk_out_maxpacket - rem;
++ bh->outreq->length = length;
++}
++
++static struct fsg_dev *the_fsg;
++
++static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun);
++static void close_all_backing_files(struct fsg_dev *fsg);
++
++
++/*-------------------------------------------------------------------------*/
++
++#ifdef DUMP_MSGS
++
++static void dump_msg(struct fsg_dev *fsg, const char *label,
++ const u8 *buf, unsigned int length)
++{
++ if (length < 512) {
++ DBG(fsg, "%s, length %u:\n", label, length);
++ print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
++ 16, 1, buf, length, 0);
++ }
++}
++
++static void dump_cdb(struct fsg_dev *fsg)
++{}
++
++#else
++
++static void dump_msg(struct fsg_dev *fsg, const char *label,
++ const u8 *buf, unsigned int length)
++{}
++
++#ifdef VERBOSE_DEBUG
++
++static void dump_cdb(struct fsg_dev *fsg)
++{
++ print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,
++ 16, 1, fsg->cmnd, fsg->cmnd_size, 0);
++}
++
++#else
++
++static void dump_cdb(struct fsg_dev *fsg)
++{}
++
++#endif /* VERBOSE_DEBUG */
++#endif /* DUMP_MSGS */
++
++
++/*-------------------------------------------------------------------------*/
++
++/* Routines for unaligned data access */
++
++static u16 get_be16(u8 *buf)
++{
++ return ((u16) buf[0] << 8) | ((u16) buf[1]);
++}
++
++static u32 get_be32(u8 *buf)
++{
++ return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
++ ((u32) buf[2] << 8) | ((u32) buf[3]);
++}
++
++static void put_be16(u8 *buf, u16 val)
++{
++ buf[0] = val >> 8;
++ buf[1] = val;
++}
++
++static void put_be32(u8 *buf, u32 val)
++{
++ buf[0] = val >> 24;
++ buf[1] = val >> 16;
++ buf[2] = val >> 8;
++ buf[3] = val & 0xff;
++}
++
++/*-------------------------------------------------------------------------*/
++
++/*
++ * DESCRIPTORS ... most are static, but strings and (full) configuration
++ * descriptors are built on demand. Also the (static) config and interface
++ * descriptors are adjusted during fsg_bind().
++ */
++
++/* There is only one interface. */
++
++static struct usb_interface_descriptor
++intf_desc = {
++ .bLength = sizeof intf_desc,
++ .bDescriptorType = USB_DT_INTERFACE,
++
++ .bNumEndpoints = 2, /* Adjusted during fsg_bind() */
++ .bInterfaceClass = USB_CLASS_MASS_STORAGE,
++ .bInterfaceSubClass = US_SC_SCSI,
++ .bInterfaceProtocol = US_PR_BULK,
++};
++
++/* Three full-speed endpoint descriptors: bulk-in, bulk-out,
++ * and interrupt-in. */
++
++static struct usb_endpoint_descriptor
++fs_bulk_in_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++
++ .bEndpointAddress = USB_DIR_IN,
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++ /* wMaxPacketSize set by autoconfiguration */
++};
++
++static struct usb_endpoint_descriptor
++fs_bulk_out_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++
++ .bEndpointAddress = USB_DIR_OUT,
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++ /* wMaxPacketSize set by autoconfiguration */
++};
++
++static struct usb_descriptor_header *fs_function[] = {
++ (struct usb_descriptor_header *) &intf_desc,
++ (struct usb_descriptor_header *) &fs_bulk_in_desc,
++ (struct usb_descriptor_header *) &fs_bulk_out_desc,
++ NULL,
++};
++#define FS_FUNCTION_PRE_EP_ENTRIES 2
++
++
++static struct usb_endpoint_descriptor
++hs_bulk_in_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++
++ /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++ .wMaxPacketSize = __constant_cpu_to_le16(512),
++};
++
++static struct usb_endpoint_descriptor
++hs_bulk_out_desc = {
++ .bLength = USB_DT_ENDPOINT_SIZE,
++ .bDescriptorType = USB_DT_ENDPOINT,
++
++ /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
++ .bmAttributes = USB_ENDPOINT_XFER_BULK,
++ .wMaxPacketSize = __constant_cpu_to_le16(512),
++ .bInterval = 1, /* NAK every 1 uframe */
++};
++
++
++static struct usb_descriptor_header *hs_function[] = {
++ (struct usb_descriptor_header *) &intf_desc,
++ (struct usb_descriptor_header *) &hs_bulk_in_desc,
++ (struct usb_descriptor_header *) &hs_bulk_out_desc,
++ NULL,
++};
++
++/* Maxpacket and other transfer characteristics vary by speed. */
++static struct usb_endpoint_descriptor *
++ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
++ struct usb_endpoint_descriptor *hs)
++{
++ if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
++ return hs;
++ return fs;
++}
++
++/*-------------------------------------------------------------------------*/
++
++/* These routines may be called in process context or in_irq */
++
++/* Caller must hold fsg->lock */
++static void wakeup_thread(struct fsg_dev *fsg)
++{
++ /* Tell the main thread that something has happened */
++ fsg->thread_wakeup_needed = 1;
++ if (fsg->thread_task)
++ wake_up_process(fsg->thread_task);
++}
++
++
++static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
++{
++ unsigned long flags;
++
++ DBG(fsg, "raise_exception %d\n", (int)new_state);
++ /* Do nothing if a higher-priority exception is already in progress.
++ * If a lower-or-equal priority exception is in progress, preempt it
++ * and notify the main thread by sending it a signal. */
++ spin_lock_irqsave(&fsg->lock, flags);
++ if (fsg->state <= new_state) {
++ fsg->state = new_state;
++ if (fsg->thread_task)
++ send_sig_info(SIGUSR1, SEND_SIG_FORCED,
++ fsg->thread_task);
++ }
++ spin_unlock_irqrestore(&fsg->lock, flags);
++}
++
++
++/*-------------------------------------------------------------------------*/
++
++/* Bulk and interrupt endpoint completion handlers.
++ * These always run in_irq. */
++
++static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
++{
++ struct fsg_dev *fsg = ep->driver_data;
++ struct fsg_buffhd *bh = req->context;
++
++ if (req->status || req->actual != req->length)
++ DBG(fsg, "%s --> %d, %u/%u\n", __func__,
++ req->status, req->actual, req->length);
++
++ /* Hold the lock while we update the request and buffer states */
++ smp_wmb();
++ spin_lock(&fsg->lock);
++ bh->inreq_busy = 0;
++ bh->state = BUF_STATE_EMPTY;
++ wakeup_thread(fsg);
++ spin_unlock(&fsg->lock);
++}
++
++static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
++{
++ struct fsg_dev *fsg = ep->driver_data;
++ struct fsg_buffhd *bh = req->context;
++
++ dump_msg(fsg, "bulk-out", req->buf, req->actual);
++ if (req->status || req->actual != bh->bulk_out_intended_length)
++ DBG(fsg, "%s --> %d, %u/%u\n", __func__,
++ req->status, req->actual,
++ bh->bulk_out_intended_length);
++
++ /* Hold the lock while we update the request and buffer states */
++ smp_wmb();
++ spin_lock(&fsg->lock);
++ bh->outreq_busy = 0;
++ bh->state = BUF_STATE_FULL;
++ wakeup_thread(fsg);
++ spin_unlock(&fsg->lock);
++}
++
++static int fsg_function_setup(struct usb_function *f,
++ const struct usb_ctrlrequest *ctrl)
++{
++ struct fsg_dev *fsg = func_to_dev(f);
++ struct usb_composite_dev *cdev = fsg->cdev;
++ int value = -EOPNOTSUPP;
++ u16 w_index = le16_to_cpu(ctrl->wIndex);
++ u16 w_value = le16_to_cpu(ctrl->wValue);
++ u16 w_length = le16_to_cpu(ctrl->wLength);
++
++ DBG(fsg, "fsg_function_setup\n");
++ /* Handle Bulk-only class-specific requests */
++ if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
++ DBG(fsg, "USB_TYPE_CLASS\n");
++ switch (ctrl->bRequest) {
++ case USB_BULK_RESET_REQUEST:
++ if (ctrl->bRequestType != (USB_DIR_OUT |
++ USB_TYPE_CLASS | USB_RECIP_INTERFACE))
++ break;
++ if (w_index != 0 || w_value != 0) {
++ value = -EDOM;
++ break;
++ }
++
++ /* Raise an exception to stop the current operation
++ * and reinitialize our state. */
++ DBG(fsg, "bulk reset request\n");
++ raise_exception(fsg, FSG_STATE_RESET);
++ value = DELAYED_STATUS;
++ break;
++
++ case USB_BULK_GET_MAX_LUN_REQUEST:
++ if (ctrl->bRequestType != (USB_DIR_IN |
++ USB_TYPE_CLASS | USB_RECIP_INTERFACE))
++ break;
++ if (w_index != 0 || w_value != 0) {
++ value = -EDOM;
++ break;
++ }
++ VDBG(fsg, "get max LUN\n");
++ *(u8 *)cdev->req->buf = fsg->nluns - 1;
++ value = 1;
++ break;
++ }
++ }
++
++ if (value == -EOPNOTSUPP)
++ VDBG(fsg,
++ "unknown class-specific control req "
++ "%02x.%02x v%04x i%04x l%u\n",
++ ctrl->bRequestType, ctrl->bRequest,
++ le16_to_cpu(ctrl->wValue), w_index, w_length);
++ return value;
++}
++
++/*-------------------------------------------------------------------------*/
++
++/* All the following routines run in process context */
++
++
++/* Use this for bulk or interrupt transfers, not ep0 */
++static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
++ struct usb_request *req, int *pbusy,
++ enum fsg_buffer_state *state)
++{
++ int rc;
++
++ DBG(fsg, "start_transfer req: %p, req->buf: %p\n", req, req->buf);
++ if (ep == fsg->bulk_in)
++ dump_msg(fsg, "bulk-in", req->buf, req->length);
++
++ spin_lock_irq(&fsg->lock);
++ *pbusy = 1;
++ *state = BUF_STATE_BUSY;
++ spin_unlock_irq(&fsg->lock);
++ rc = usb_ep_queue(ep, req, GFP_KERNEL);
++ if (rc != 0) {
++ *pbusy = 0;
++ *state = BUF_STATE_EMPTY;
++
++ /* We can't do much more than wait for a reset */
++
++ /* Note: currently the net2280 driver fails zero-length
++ * submissions if DMA is enabled. */
++ if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
++ req->length == 0))
++ WARN(fsg, "error in submission: %s --> %d\n",
++ (ep == fsg->bulk_in ? "bulk-in" : "bulk-out"),
++ rc);
++ }
++}
++
++
++static int sleep_thread(struct fsg_dev *fsg)
++{
++ int rc = 0;
++
++ /* Wait until a signal arrives or we are woken up */
++ for (;;) {
++ try_to_freeze();
++ set_current_state(TASK_INTERRUPTIBLE);
++ if (signal_pending(current)) {
++ rc = -EINTR;
++ break;
++ }
++ if (fsg->thread_wakeup_needed)
++ break;
++ schedule();
++ }
++ __set_current_state(TASK_RUNNING);
++ fsg->thread_wakeup_needed = 0;
++ return rc;
++}
++
++
++/*-------------------------------------------------------------------------*/
++
++static int do_read(struct fsg_dev *fsg)
++{
++ struct lun *curlun = fsg->curlun;
++ u32 lba;
++ struct fsg_buffhd *bh;
++ int rc;
++ u32 amount_left;
++ loff_t file_offset, file_offset_tmp;
++ unsigned int amount;
++ unsigned int partial_page;
++ ssize_t nread;
++
++ /* Get the starting Logical Block Address and check that it's
++ * not too big */
++ if (fsg->cmnd[0] == SC_READ_6)
++ lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
++ else {
++ lba = get_be32(&fsg->cmnd[2]);
++
++ /* We allow DPO (Disable Page Out = don't save data in the
++ * cache) and FUA (Force Unit Access = don't read from the
++ * cache), but we don't implement them. */
++ if ((fsg->cmnd[1] & ~0x18) != 0) {
++ curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
++ return -EINVAL;
++ }
++ }
++ if (lba >= curlun->num_sectors) {
++ curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
++ return -EINVAL;
++ }
++ file_offset = ((loff_t) lba) << 9;
++
++ /* Carry out the file reads */
++ amount_left = fsg->data_size_from_cmnd;
++ if (unlikely(amount_left == 0))
++ return -EIO; /* No default reply */
++
++ for (;;) {
++
++ /* Figure out how much we need to read:
++ * Try to read the remaining amount.
++ * But don't read more than the buffer size.
++ * And don't try to read past the end of the file.
++ * Finally, if we're not at a page boundary, don't read past
++ * the next page.
++ * If this means reading 0 then we were asked to read past
++ * the end of file. */
++ amount = min((unsigned int) amount_left,
++ (unsigned int)fsg->buf_size);
++ amount = min((loff_t) amount,
++ curlun->file_length - file_offset);
++ partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
++ if (partial_page > 0)
++ amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
++ partial_page);
++
++ /* Wait for the next buffer to become available */
++ bh = fsg->next_buffhd_to_fill;
++ while (bh->state != BUF_STATE_EMPTY) {
++ rc = sleep_thread(fsg);
++ if (rc)
++ return rc;
++ }
++
++ /* If we were asked to read past the end of file,
++ * end with an empty buffer. */
++ if (amount == 0) {
++ curlun->sense_data =
++ SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
++ curlun->sense_data_info = file_offset >> 9;
++ curlun->info_valid = 1;
++ bh->inreq->length = 0;
++ bh->state = BUF_STATE_FULL;
++ break;
++ }
++
++ /* Perform the read */
++ file_offset_tmp = file_offset;
++ nread = vfs_read(curlun->filp,
++ (char __user *) bh->buf,
++ amount, &file_offset_tmp);
++ VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
++ (unsigned long long) file_offset,
++ (int) nread);
++ if (signal_pending(current))
++ return -EINTR;
++
++ if (nread < 0) {
++ LDBG(curlun, "error in file read: %d\n",
++ (int) nread);
++ nread = 0;
++ } else if (nread < amount) {
++ LDBG(curlun, "partial file read: %d/%u\n",
++ (int) nread, amount);
++ nread -= (nread & 511); /* Round down to a block */
++ }
++ file_offset += nread;
++ amount_left -= nread;
++ fsg->residue -= nread;
++ bh->inreq->length = nread;
++ bh->state = BUF_STATE_FULL;
++
++ /* If an error occurred, report it and its position */
++ if (nread < amount) {
++ curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
++ curlun->sense_data_info = file_offset >> 9;
++ curlun->info_valid = 1;
++ break;
++ }
++
++ if (amount_left == 0)
++ break; /* No more left to read */
++
++ /* Send this buffer and go read some more */
++ start_transfer(fsg, fsg->bulk_in, bh->inreq,
++ &bh->inreq_busy, &bh->state);
++ fsg->next_buffhd_to_fill = bh->next;
++ }
++
++ return -EIO; /* No default reply */
++}
++
++
++/*-------------------------------------------------------------------------*/
++
++static int do_write(struct fsg_dev *fsg)
++{
++ struct lun *curlun = fsg->curlun;
++ u32 lba;
++ struct fsg_buffhd *bh;
++ int get_some_more;
++ u32 amount_left_to_req, amount_left_to_write;
++ loff_t usb_offset, file_offset, file_offset_tmp;
++ unsigned int amount;
++ unsigned int partial_page;
++ ssize_t nwritten;
++ int rc;
++
++ if (curlun->ro) {
++ curlun->sense_data = SS_WRITE_PROTECTED;
++ return -EINVAL;
++ }
++ curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
++
++ /* Get the starting Logical Block Address and check that it's
++ * not too big */
++ if (fsg->cmnd[0] == SC_WRITE_6)
++ lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
++ else {
++ lba = get_be32(&fsg->cmnd[2]);
++
++ /* We allow DPO (Disable Page Out = don't save data in the
++ * cache) and FUA (Force Unit Access = write directly to the
++ * medium). We don't implement DPO; we implement FUA by
++ * performing synchronous output. */
++ if ((fsg->cmnd[1] & ~0x18) != 0) {
++ curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
++ return -EINVAL;
++ }
++ if (fsg->cmnd[1] & 0x08) /* FUA */
++ curlun->filp->f_flags |= O_SYNC;
++ }
++ if (lba >= curlun->num_sectors) {
++ curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
++ return -EINVAL;
++ }
++
++ /* Carry out the file writes */
++ get_some_more = 1;
++ file_offset = usb_offset = ((loff_t) lba) << 9;
++ amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
++
++ while (amount_left_to_write > 0) {
++
++ /* Queue a request for more data from the host */
++ bh = fsg->next_buffhd_to_fill;
++ if (bh->state == BUF_STATE_EMPTY && get_some_more) {
++
++ /* Figure out how much we want to get:
++ * Try to get the remaining amount.
++ * But don't get more than the buffer size.
++ * And don't try to go past the end of the file.
++ * If we're not at a page boundary,
++ * don't go past the next page.
++ * If this means getting 0, then we were asked
++ * to write past the end of file.
++ * Finally, round down to a block boundary. */
++ amount = min(amount_left_to_req, (u32)fsg->buf_size);
++ amount = min((loff_t) amount, curlun->file_length -
++ usb_offset);
++ partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
++ if (partial_page > 0)
++ amount = min(amount,
++ (unsigned int) PAGE_CACHE_SIZE - partial_page);
++
++ if (amount == 0) {
++ get_some_more = 0;
++ curlun->sense_data =
++ SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
++ curlun->sense_data_info = usb_offset >> 9;
++ curlun->info_valid = 1;
++ continue;
++ }
++ amount -= (amount & 511);
++ if (amount == 0) {
++
++ /* Why were we were asked to transfer a
++ * partial block? */
++ get_some_more = 0;
++ continue;
++ }
++
++ /* Get the next buffer */
++ usb_offset += amount;
++ fsg->usb_amount_left -= amount;
++ amount_left_to_req -= amount;
++ if (amount_left_to_req == 0)
++ get_some_more = 0;
++
++ /* amount is always divisible by 512, hence by
++ * the bulk-out maxpacket size */
++ bh->outreq->length = bh->bulk_out_intended_length =
++ amount;
++ start_transfer(fsg, fsg->bulk_out, bh->outreq,
++ &bh->outreq_busy, &bh->state);
++ fsg->next_buffhd_to_fill = bh->next;
++ continue;
++ }
++
++ /* Write the received data to the backing file */
++ bh = fsg->next_buffhd_to_drain;
++ if (bh->state == BUF_STATE_EMPTY && !get_some_more)
++ break; /* We stopped early */
++ if (bh->state == BUF_STATE_FULL) {
++ smp_rmb();
++ fsg->next_buffhd_to_drain = bh->next;
++ bh->state = BUF_STATE_EMPTY;
++
++ /* Did something go wrong with the transfer? */
++ if (bh->outreq->status != 0) {
++ curlun->sense_data = SS_COMMUNICATION_FAILURE;
++ curlun->sense_data_info = file_offset >> 9;
++ curlun->info_valid = 1;
++ break;
++ }
++
++ amount = bh->outreq->actual;
++ if (curlun->file_length - file_offset < amount) {
++ LERROR(curlun,
++ "write %u @ %llu beyond end %llu\n",
++ amount, (unsigned long long) file_offset,
++ (unsigned long long) curlun->file_length);
++ amount = curlun->file_length - file_offset;
++ }
++
++ /* Perform the write */
++ file_offset_tmp = file_offset;
++ nwritten = vfs_write(curlun->filp,
++ (char __user *) bh->buf,
++ amount, &file_offset_tmp);
++ VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
++ (unsigned long long) file_offset,
++ (int) nwritten);
++ if (signal_pending(current))
++ return -EINTR; /* Interrupted! */
++
++ if (nwritten < 0) {
++ LDBG(curlun, "error in file write: %d\n",
++ (int) nwritten);
++ nwritten = 0;
++ } else if (nwritten < amount) {
++ LDBG(curlun, "partial file write: %d/%u\n",
++ (int) nwritten, amount);
++ nwritten -= (nwritten & 511);
++ /* Round down to a block */
++ }
++ file_offset += nwritten;
++ amount_left_to_write -= nwritten;
++ fsg->residue -= nwritten;
++
++ /* If an error occurred, report it and its position */
++ if (nwritten < amount) {
++ curlun->sense_data = SS_WRITE_ERROR;
++ curlun->sense_data_info = file_offset >> 9;
++ curlun->info_valid = 1;
++ break;
++ }
++
++ /* Did the host decide to stop early? */
++ if (bh->outreq->actual != bh->outreq->length) {
++ fsg->short_packet_received = 1;
++ break;
++ }
++ continue;
++ }
++
++ /* Wait for something to happen */
++ rc = sleep_thread(fsg);
++ if (rc)
++ return rc;
++ }
++
++ return -EIO; /* No default reply */
++}
++
++
++/*-------------------------------------------------------------------------*/
++
++/* Sync the file data, don't bother with the metadata.
++ * The caller must own fsg->filesem.
++ * This code was copied from fs/buffer.c:sys_fdatasync(). */
++static int fsync_sub(struct lun *curlun)
++{
++ struct file *filp = curlun->filp;
++ struct inode *inode;
++ int rc, err;
++
++ if (curlun->ro || !filp)
++ return 0;
++ if (!filp->f_op->fsync)
++ return -EINVAL;
++
++ inode = filp->f_path.dentry->d_inode;
++ mutex_lock(&inode->i_mutex);
++ rc = filemap_fdatawrite(inode->i_mapping);
++ err = filp->f_op->fsync(filp, filp->f_path.dentry, 1);
++ if (!rc)
++ rc = err;
++ err = filemap_fdatawait(inode->i_mapping);
++ if (!rc)
++ rc = err;
++ mutex_unlock(&inode->i_mutex);
++ VLDBG(curlun, "fdatasync -> %d\n", rc);
++ return rc;
++}
++
++static void fsync_all(struct fsg_dev *fsg)
++{
++ int i;
++
++ for (i = 0; i < fsg->nluns; ++i)
++ fsync_sub(&fsg->luns[i]);
++}
++
++static int do_synchronize_cache(struct fsg_dev *fsg)
++{
++ struct lun *curlun = fsg->curlun;
++ int rc;
++
++ /* We ignore the requested LBA and write out all file's
++ * dirty data buffers. */
++ rc = fsync_sub(curlun);
++ if (rc)
++ curlun->sense_data = SS_WRITE_ERROR;
++ return 0;
++}
++
++
++/*-------------------------------------------------------------------------*/
++