printk: fix buffer overflow when calling log_prefix function from call_console_drivers

This patch corrects a buffer overflow in kernels from 3.0 to 3.4 when calling
log_prefix() function from call_console_drivers().

This bug existed in previous releases but has been revealed with commit
162a7e7500f9664636e649ba59defe541b7c2c60 (2.6.39 => 3.0) that made changes
about how to allocate memory for early printk buffer (use of memblock_alloc).
It disappears with commit 7ff9554bb578ba02166071d2d487b7fc7d860d62 (3.4 => 3.5)
that does a refactoring of printk buffer management.

In log_prefix(), the access to "p[0]", "p[1]", "p[2]" or
"simple_strtoul(&p[1], &endp, 10)" may cause a buffer overflow as this
function is called from call_console_drivers by passing "&LOG_BUF(cur_index)"
where the index must be masked to do not exceed the buffer's boundary.

The trick is to prepare in call_console_drivers() a buffer with the necessary
data (PRI field of syslog message) to be safely evaluated in log_prefix().

This patch can be applied to stable kernel branches 3.0.y, 3.2.y and 3.4.y.

Without this patch, one can freeze a server running this loop from shell :
  $ export DUMMY=`cat /dev/urandom | tr -dc '12345AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn' | head -c255`
  $ while true do ; echo $DUMMY > /dev/kmsg ; done

The "server freeze" depends on where memblock_alloc does allocate printk buffer :
if the buffer overflow is inside another kernel allocation the problem may not
be revealed, else the server may hangs up.

Signed-off-by: Alexandre SIMON <Alexandre.Simon@univ-lorraine.fr>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
switch: Reset device's drvdata before destroying it

dev_set_drvdata() sets the device specific driver data at
dev->p->driver_data.  However, dev is destroyed and has it's
context memory freed in device_destroy().  As a result, calling
dev_set_drvdata() causes a fault when accessing dev->p.

Change-Id: I4b1e6d17db52d0e31caf9b52e59979ff9cbb0c12
Signed-off-by: Deva Ramasubramanian <dramasub@codeaurora.org>
ext4: fix potential deadlock in ext4_nonda_switch()

In ext4_nonda_switch(), if the file system is getting full we used to
call writeback_inodes_sb_if_idle().  The problem is that we can be
holding i_mutex already, and this causes a potential deadlock when
writeback_inodes_sb_if_idle() when it tries to take s_umount.  (See
lockdep output below).

As it turns out we don't need need to hold s_umount; the fact that we
are in the middle of the write(2) system call will keep the superblock
pinned.  Unfortunately writeback_inodes_sb() checks to make sure
s_umount is taken, and the VFS uses a different mechanism for making
sure the file system doesn't get unmounted out from under us.  The
simplest way of dealing with this is to just simply grab s_umount
using a trylock, and skip kicking the writeback flusher thread in the
very unlikely case that we can't take a read lock on s_umount without
blocking.

Also, we now check the cirteria for kicking the writeback thread
before we decide to whether to fall back to non-delayed writeback, so
if there are any outstanding delayed allocation writes, we try to get
them resolved as soon as possible.

   [ INFO: possible circular locking dependency detected ]
   3.6.0-rc1-00042-gce894ca #367 Not tainted
   -------------------------------------------------------
   dd/8298 is trying to acquire lock:
    (&type->s_umount_key#18){++++..}, at: [<c02277d4>] writeback_inodes_sb_if_idle+0x28/0x46

   but task is already holding lock:
    (&sb->s_type->i_mutex_key#8){+.+...}, at: [<c01ddcce>] generic_file_aio_write+0x5f/0xd3

   which lock already depends on the new lock.

   2 locks held by dd/8298:
    #0:  (sb_writers#2){.+.+.+}, at: [<c01ddcc5>] generic_file_aio_write+0x56/0xd3
    #1:  (&sb->s_type->i_mutex_key#8){+.+...}, at: [<c01ddcce>] generic_file_aio_write+0x5f/0xd3

   stack backtrace:
   Pid: 8298, comm: dd Not tainted 3.6.0-rc1-00042-gce894ca #367
   Call Trace:
    [<c015b79c>] ? console_unlock+0x345/0x372
    [<c06d62a1>] print_circular_bug+0x190/0x19d
    [<c019906c>] __lock_acquire+0x86d/0xb6c
    [<c01999db>] ? mark_held_locks+0x5c/0x7b
    [<c0199724>] lock_acquire+0x66/0xb9
    [<c02277d4>] ? writeback_inodes_sb_if_idle+0x28/0x46
    [<c06db935>] down_read+0x28/0x58
    [<c02277d4>] ? writeback_inodes_sb_if_idle+0x28/0x46
    [<c02277d4>] writeback_inodes_sb_if_idle+0x28/0x46
    [<c026f3b2>] ext4_nonda_switch+0xe1/0xf4
    [<c0271ece>] ext4_da_write_begin+0x27/0x193
    [<c01dcdb0>] generic_file_buffered_write+0xc8/0x1bb
    [<c01ddc47>] __generic_file_aio_write+0x1dd/0x205
    [<c01ddce7>] generic_file_aio_write+0x78/0xd3
    [<c026d336>] ext4_file_write+0x480/0x4a6
    [<c0198c1d>] ? __lock_acquire+0x41e/0xb6c
    [<c0180944>] ? sched_clock_cpu+0x11a/0x13e
    [<c01967e9>] ? trace_hardirqs_off+0xb/0xd
    [<c018099f>] ? local_clock+0x37/0x4e
    [<c0209f2c>] do_sync_write+0x67/0x9d
    [<c0209ec5>] ? wait_on_retry_sync_kiocb+0x44/0x44
    [<c020a7b9>] vfs_write+0x7b/0xe6
    [<c020a9a6>] sys_write+0x3b/0x64
    [<c06dd4bd>] syscall_call+0x7/0xb

Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Cc: stable@vger.kernel.org
block: fix infinite loop in __getblk_slow

Commit 080399aaaf35 ("block: don't mark buffers beyond end of disk as
mapped") exposed a bug in __getblk_slow that causes mount to hang as it
loops infinitely waiting for a buffer that lies beyond the end of the
disk to become uptodate.

The problem was initially reported by Torsten Hilbrich here:

    https://lkml.org/lkml/2012/6/18/54

and also reported independently here:

    http://www.sysresccd.org/forums/viewtopic.php?f=13&t=4511

and then Richard W.M.  Jones and Marcos Mello noted a few separate
bugzillas also associated with the same issue.  This patch has been
confirmed to fix:

    https://bugzilla.redhat.com/show_bug.cgi?id=835019

The main problem is here, in __getblk_slow:

        for (;;) {
                struct buffer_head * bh;
                int ret;

                bh = __find_get_block(bdev, block, size);
                if (bh)
                        return bh;

                ret = grow_buffers(bdev, block, size);
                if (ret < 0)
                        return NULL;
                if (ret == 0)
                        free_more_memory();
        }

__find_get_block does not find the block, since it will not be marked as
mapped, and so grow_buffers is called to fill in the buffers for the
associated page.  I believe the for (;;) loop is there primarily to
retry in the case of memory pressure keeping grow_buffers from
succeeding.  However, we also continue to loop for other cases, like the
block lying beond the end of the disk.  So, the fix I came up with is to
only loop when grow_buffers fails due to memory allocation issues
(return value of 0).

The attached patch was tested by myself, Torsten, and Rich, and was
found to resolve the problem in call cases.

Signed-off-by: Jeff Moyer <jmoyer@redhat.com>
Reported-and-Tested-by: Torsten Hilbrich <torsten.hilbrich@secunet.com>
Tested-by: Richard W.M. Jones <rjones@redhat.com>
Reviewed-by: Josh Boyer <jwboyer@redhat.com>
Cc: Stable <stable@vger.kernel.org>  # 3.0+
[ Jens is on vacation, taking this directly  - Linus ]
--
Stable Notes: this patch requires backport to 3.0, 3.2 and 3.3.
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
ARM: 7467/1: mutex: use generic xchg-based implementation for ARMv6+

The open-coded mutex implementation for ARMv6+ cores suffers from a
severe lack of barriers, so in the uncontended case we don't actually
protect any accesses performed during the critical section.

Furthermore, the code is largely a duplication of the ARMv6+ atomic_dec
code but optimised to remove a branch instruction, as the mutex fastpath
was previously inlined. Now that this is executed out-of-line, we can
reuse the atomic access code for the locking (in fact, we use the xchg
code as this produces shorter critical sections).

This patch uses the generic xchg based implementation for mutexes on
ARMv6+, which introduces barriers to the lock/unlock operations and also
has the benefit of removing a fair amount of inline assembly code.

Cc: <stable@vger.kernel.org>
Acked-by: Arnd Bergmann <arnd@arndb.de>
Acked-by: Nicolas Pitre <nico@linaro.org>
Reported-by: Shan Kang <kangshan0910@gmail.com>
Signed-off-by: Will Deacon <will.deacon@arm.com>
Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk>
ARM: 7495/1: mutex: use generic atomic_dec-based implementation for ARMv6+

Commit a76d7bd96d65 ("ARM: 7467/1: mutex: use generic xchg-based
implementation for ARMv6+") removed the barrier-less, ARM-specific
mutex implementation in favour of the generic xchg-based code.

Since then, a bug was uncovered in the xchg code when running on SMP
platforms, due to interactions between the locking paths and the
MUTEX_SPIN_ON_OWNER code. This was fixed in 0bce9c46bf3b ("mutex: place
lock in contended state after fastpath_lock failure"), however, the
atomic_dec-based mutex algorithm is now marginally more efficient for
ARM (~0.5% improvement in hackbench scores on dual A15).

This patch moves ARMv6+ platforms to the atomic_dec-based mutex code.

Acked-by: Nicolas Pitre <nico@linaro.org>
Signed-off-by: Will Deacon <will.deacon@arm.com>
Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk>
Revert "usb: gadget: rndis: Fix re-binding f_rndis"

This reverts commit 7f141c58da4a6c8920fd6d7051b832e3dec6b877.

This patch should not have been applied in the first place. The USB
string id index is limited to 255.  Function drivers are supposed
to allocate string id for the first time their bind is called.  There
is no API to release string id index.  If string id is reset in unbind,
we will run out of string id after multiple bind/unbind.

CRs-Fixed: 425501
Change-Id: Ia82a528f9e0af192063970a9227c9c739ed77f48
Signed-off-by: Pavankumar Kondeti <pkondeti@codeaurora.org>
USB: android: avoid to set the lock refcount as the native value

If lock refcount is negative, lock will be always failed. To fix this
issue, do not set the lock refcount as negative value.

Change-Id: Ic89f393b60a0ff15313e91566a5055f620752452
usb: gadget: adb: Force OUT(or RX) requests size to be MAX

Synopsys USB3 Controller (DWC3) has a restriction where size
of OUT requests (TRB) queued to the controller must be aligned
with the endpoint's max packet size.
Since, request buffer is already allocated with the size of
ADB_BULK_BUFFER_SIZE, hence, request this much data from the
controller.

Change-Id: Ibba1a627c9e34b92ddcb44ee2260a004a2b78dfc
Signed-off-by: Ido Shayevitz <idos@codeaurora.org>
Signed-off-by: Manu Gautam <mgautam@codeaurora.org>
Revert "USB: ensure parent device is resumed for child's system-resume"

This reverts commit de86e6482897db0006151ae9154f181e75f5ab2c.

Commit 7c8527ce ("PM: Prevent runtime suspend during system resume")
fixes the general issue of a parent device being prematurely
runtime suspended before a child device is resumed. It does so
by moving the pm_runtime_put_sync() call from the device_resume()
stage to device_complete(), which happens to act on the devices
in reverse (children before parent) order.

Thus when usb_resume() is called by device_resume(), we know its
parent will be runtime PM enabled and its usage counter is still
non-zero. This obviates the need to do an additional
pm_runtime_get_sync() before calling usb_resume_both() as the
device and its interfaces now have the opportunity to increment
the parent's power.child_count if necessary without fear of
having a runtime suspended parent.

CRs-fixed: 396041
Change-Id: I793ddfbb9bd88634f45f0c1e570a5d616248e3a8
Signed-off-by: Jack Pham <jackp@codeaurora.org>
PM: Prevent runtime suspend during system resume

This patch (as1591) moves the pm_runtime_get_noresume() and
pm_runtime_put_sync() calls from __device_suspend() and
device_resume() to device_prepare() and device_complete() in the PM
core.

The reason for doing this is to make sure that parent devices remain
at full power (i.e., don't go into runtime suspend) while their
children are being resumed from a system sleep.

The PCI core already contained equivalent code to serve the same
purpose.  The patch removes the duplicated code, since it is no longer
needed.  One of the comments from the PCI core gets moved into the PM
core, and a second comment is added to explain whe the _get_noresume
and _put_sync calls are present.

Signed-off-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: Rafael J. Wysocki <rjw@sisk.pl>
PM: Allow runtime suspend again if prepare is failed

commit 8a5bdaf3 never allow the runtime suspend if prepare is failed.
The complete phase is invoked when calling __device_suspend.
It allows the runtime suspend again. But if prepare is failed,
__device_suspend won't be called and the complete phase won't also
called. Thus this runtime suspend will be blocked forever.

If prepare is failed, you should allow the runtime suspend again.

Change-Id: I57c7c04609299244a042f2524e1c65dbbdd91ae3
slub: fix a possible memory leak

Memory allocated by kstrdup should be freed,
when kmalloc(kmem_size, GFP_KERNEL) is failed.

Acked-by: Christoph Lameter <cl@linux.com>
Acked-by: David Rientjes <rientjes@google.com>
Signed-off-by: Joonsoo Kim <js1304@gmail.com>
Signed-off-by: Pekka Enberg <penberg@kernel.org>
slub: fix a memory leak in get_partial_node()

In the case which is below,

1. acquire slab for cpu partial list
2. free object to it by remote cpu
3. page->freelist = t

then memory leak is occurred.

Change acquire_slab() not to zap freelist when it works for cpu partial list.
I think it is a sufficient solution for fixing a memory leak.

Below is output of 'slabinfo -r kmalloc-256'
when './perf stat -r 30 hackbench 50 process 4000 > /dev/null' is done.

***Vanilla***
Sizes (bytes)     Slabs              Debug                Memory
------------------------------------------------------------------------
Object :     256  Total  :     468   Sanity Checks : Off  Total: 3833856
SlabObj:     256  Full   :     111   Redzoning     : Off  Used : 2004992
SlabSiz:    8192  Partial:     302   Poisoning     : Off  Loss : 1828864
Loss   :       0  CpuSlab:      55   Tracking      : Off  Lalig:       0
Align  :       8  Objects:      32   Tracing       : Off  Lpadd:       0

***Patched***
Sizes (bytes)     Slabs              Debug                Memory
------------------------------------------------------------------------
Object :     256  Total  :     300   Sanity Checks : Off  Total: 2457600
SlabObj:     256  Full   :     204   Redzoning     : Off  Used : 2348800
SlabSiz:    8192  Partial:      33   Poisoning     : Off  Loss :  108800
Loss   :       0  CpuSlab:      63   Tracking      : Off  Lalig:       0
Align  :       8  Objects:      32   Tracing       : Off  Lpadd:       0

Total and loss number is the impact of this patch.

Cc: <stable@vger.kernel.org>
Acked-by: Christoph Lameter <cl@linux.com>
Signed-off-by: Joonsoo Kim <js1304@gmail.com>
Signed-off-by: Pekka Enberg <penberg@kernel.org>
vfs: dcache: fix deadlock in tree traversal

IBM reported a deadlock in select_parent().  This was found to be caused
by taking rename_lock when already locked when restarting the tree
traversal.

There are two cases when the traversal needs to be restarted:

 1) concurrent d_move(); this can only happen when not already locked,
    since taking rename_lock protects against concurrent d_move().

 2) racing with final d_put() on child just at the moment of ascending
    to parent; rename_lock doesn't protect against this rare race, so it
    can happen when already locked.

Because of case 2, we need to be able to handle restarting the traversal
when rename_lock is already held.  This patch fixes all three callers of
try_to_ascend().

IBM reported that the deadlock is gone with this patch.

[ I rewrote the patch to be smaller and just do the "goto again" if the
  lock was already held, but credit goes to Miklos for the real work.
   - Linus ]

Signed-off-by: Miklos Szeredi <mszeredi@suse.cz>
Cc: Al Viro <viro@ZenIV.linux.org.uk>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
USB: Rate limit adb open and release messages

The print messages are helpful in debugging adb stability issues.
However they get flooded if adb daemon is restarted continuously.
If serial console is enabled this is leading to watchdog bark.

CRs-Fixed: 456662
Change-Id: I1381d44b7a5081ee04053c739b9c83111b191125
Signed-off-by: Pavankumar Kondeti <pkondeti@codeaurora.org>
USB: android: Rate limit android enable warning

An error message is printed when user space tries to enable/disable
android configuration when it is already enabled/disabled.  This
message is helpful in debugging USB composition issues.  However
this message is getting flooded in an error condition.  If serial
console is enabled, it is leading to watchdog bark.

CRs-Fixed: 457725
Change-Id: I2d61ac46ba3c8464bada23a64ad0d8027a4adfe9
Signed-off-by: Pavankumar Kondeti <pkondeti@codeaurora.org>
USB gadget: do not include android_composite.h

Signed-off-by: Iliyan Malchev <malchev@google.com>
USB: f_rndis: Check if cdev is NULL before accessing

RNDIS control path completion handlers are getting called after setting
cdev to NULL during disconnect as part of composition switch and this
is leading to a crash. Avoid this crash, by checking, if cdev is NULL
before accessing. Also don't queue request's to DCD, if composition switch
is in progress.

CRs-Fixed: 433534
Change-Id: Ic0790415ec3eaf866af2895370249e45adcbba5d
Signed-off-by: Chiranjeevi Velempati <cvelempa@codeaurora.org>
(cherry picked from commit 46874732be9d6997ff3bceaf97f07911f9f22440)
usb: gadget: u_ether: Fix NULL pointer derefernce crash

port->port_usb can be NULL if USB cable is disconnected when
net device is trying to transfer data which is causing device
to crash. Hence add changes to eliminate need of accessing
port->port_usb to see multi_xfer_pkt value.

CRs-Fixed: 452642
Change-Id: I60bd2302371238707e951c77912b155d75dc8570
Signed-off-by: Mayank Rana <mrana@codeaurora.org>