More patches (squashed commit)

cifs: fix bad buffer length check in coalesce_t2

The current check looks to see if the RFC1002 length is larger than
CIFSMaxBufSize, and fails if it is. The buffer is actually larger than
that by MAX_CIFS_HDR_SIZE.

This bug has been around for a long time, but the fact that we used to
cap the clients MaxBufferSize at the same level as the server tended
to paper over it. Commit c974befa changed that however and caused this
bug to bite in more cases.

Change-Id: Idff7c9b476f3171a59bb5bcba8376dbf391ebf23
Reported-and-Tested-by: Konstantinos Skarlatos <k.skarlatos@gmail.com>
Signed-off-by: Jeff Layton <jlayton@redhat.com>

Proportional Rate Reduction for TCP.

This patch implements Proportional Rate Reduction (PRR) for TCP.
PRR is an algorithm that determines TCP's sending rate in fast
recovery. PRR avoids excessive window reductions and aims for
the actual congestion window size at the end of recovery to be as
close as possible to the window determined by the congestion control
algorithm. PRR also improves accuracy of the amount of data sent
during loss recovery.

The patch implements the recommended flavor of PRR called PRR-SSRB
(Proportional rate reduction with slow start reduction bound) and
replaces the existing rate halving algorithm. PRR improves upon the
existing Linux fast recovery under a number of conditions including:
  1) burst losses where the losses implicitly reduce the amount of
outstanding data (pipe) below the ssthresh value selected by the
congestion control algorithm and,
  2) losses near the end of short flows where application runs out of
data to send.

As an example, with the existing rate halving implementation a single
loss event can cause a connection carrying short Web transactions to
go into the slow start mode after the recovery. This is because during
recovery Linux pulls the congestion window down to packets_in_flight+1
on every ACK. A short Web response often runs out of new data to send
and its pipe reduces to zero by the end of recovery when all its packets
are drained from the network. Subsequent HTTP responses using the same
connection will have to slow start to raise cwnd to ssthresh. PRR on
the other hand aims for the cwnd to be as close as possible to ssthresh
by the end of recovery.

A description of PRR and a discussion of its performance can be found at
the following links:
- IETF Draft:
    http://tools.ietf.org/html/draft-mathis-tcpm-proportional-rate-reduction-01
- IETF Slides:
    http://www.ietf.org/proceedings/80/slides/tcpm-6.pdf
    http://tools.ietf.org/agenda/81/slides/tcpm-2.pdf
- Paper to appear in Internet Measurements Conference (IMC) 2011:
    Improving TCP Loss Recovery
    Nandita Dukkipati, Matt Mathis, Yuchung Cheng

Change-Id: I6f5638d033ccb41fd13836d79567bae03f8f4f93
Signed-off-by: Nandita Dukkipati <nanditad@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>

ksm: check and skip page, if it is already scanned

From: Pradeep Sawlani <sawlani@amazon.com>

On system like Android where most of the process are forked
from parent w/o execve, KSM can scan same page multiple times
in one scan cycle. There is no advantage in scanning same page
multiple times for merging. During testing with Android, it was
observed around 60% pages are skipped for each scan cycle.

Change-Id: I0cf01802f0b4d61fcab92558beb9e1c660dc9a77
Link: http://lkml.kernel.org/r/CAMrOTPgBtANS_ryRjan0-dTL97U7eRvtf3dCsss=Kn+Uk89fuA@mail.gmail.com
Signed-off-by: Pradeep Sawlani <sawlani@amazon.com>

CPU hotplug, writeback: Don't call writeback_set_ratelimit() too often during hotplug

The CPU hotplug callback related to writeback calls writeback_set_ratelimit()
during every state change in the hotplug sequence. This is unnecessary
since num_online_cpus() changes only once during the entire hotplug operation.

So invoke the function only once per hotplug, thereby avoiding the
unnecessary repetition of those costly calculations.

Change-Id: Ic180239f846e6ea381a6f6a1ff1122b1a1fecd68
Signed-off-by: Srivatsa S. Bhat <srivatsa.bhat@linux.vnet.ibm.com>

Enable KSM_CHECK_PAGE

Optimise apply_slack() for size and speed

Change-Id: I7e330491dfcfd22cf05bee234298a93c9d346e5b

lib/memcopy: use glibc version

the kernel's memcpy and memmove is very inefficient. But the glibc version is
quite fast, in some cases it is 10 times faster than the kernel version. So I
introduce some memory copy macros and functions of the glibc to improve the
kernel version's performance.

The strategy of the memory functions is:
1. Copy bytes until the destination pointer is aligned.
2. Copy words in unrolled loops.  If the source and destination are not
   aligned in the same way, use word memory operations, but shift and merge
   two read words before writing.
3. Copy the few remaining bytes.

Change-Id: I82a84a951c182ef4370b33cb6786b4a5f5f3efac

Conflicts:

	lib/Makefile

lib/string: use glibc version

the performance of memcpy and memmove of the general version is very
inefficient, this patch improved them.

Change-Id: I8dc171a0326af57ed4ff77b1f7826c9ff91921f8

MFD: twl6040-codec: Add test registers definitions

Add definitions for test registers.

Change-Id: Ic046f4639781981ca2421f5b75c0c5408a3dc976
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>

MFD: twl6040-codec: Add uEvent based event notification

Add initial support for a kobject event based notification mechanism
to inform userspace about TWL6040 events like handsfree overcurrent,
vibrator overcurrent, thermal event.

Since the events can be handled in other drivers apart from the MFD,
a new API (twl6040_report_event) is created so that MFD clients can
notify their events using a single kobject.

Change-Id: I07f71d1693a6eb189ca07fffeb3ebc12e539d4ae
Signed-off-by: Chris Kelly <c-kelly@ti.com>

MFD: twl6040-codec: Add register cache

Add register cache and define register operations (read, write,
set_bits, clear_bits) on cache only. So register operations
performed on I2C registers are now differentiated.

Register operations APIs exported by TWL6040 MFD are a wrapper
to its I2C counterparts at the moment.

Change-Id: I76137099e6264de9ac3213c596f662a50299aa82
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>
Signed-off-by: Gabriel M. Beddingfield <gabrbedd@ti.com>
Signed-off-by: Chris Kelly <c-kelly@ti.com>

MFD: twl6040-codec: Add register supply query APIs

Add a new set of APIs to TWL6040 MFD to query the supply of its
registers: twl6040_get_reg_supply(), twl6040_reg_is_vdd() and
twl6040_reg_is_vio().

Change-Id: Ic320ad7759c66d705f6025361cd6a296ac695dd9
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>
Signed-off-by: Chris Kelly <c-kelly@ti.com>
Signed-off-by: Gabriel M. Beddingfield <gabrbedd@ti.com>

MFD: twl6040-codec: Add register context restore

Add register context restore per supply.

Change-Id: I4918efee4fcc83f4998f59f3d376b798822ca3ce
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>
Signed-off-by: Chris Kelly <c-kelly@ti.com>
Signed-off-by: Gabriel M. Beddingfield <gabrbedd@ti.com>

MFD: twl6040-codec: Handle thermal interrupt

When the TWL6040 temperature increases above a threshold that could
damage the device, a thermal interrupt and shutdown are started
automatically by the hardware.

The thermal event handling involves the following steps:
1. Forcefully deassert AUDPWRON to avoid keeping TWL6040 is
   Power-On state any longer
2. The event is notified to Android userspace through the switch
   class based mechanism so that further actions can be taken
3. While the device is in thermal shutdown, accesses to VDD/VSS
   registers will affect only register cache
4. Once the device has recovered from the thermal event, it will
   be put back to Power-On state regardless of the state requested
   by MFD clients:
   4.1. If clients have requested Power-On state, then the context
        of VDD/VSS registers is restored
   4.2. If clients have requested Sleep state, then the request will
        be honored. The additional Power-On -> Sleep transition is
        required to ensure that reference system is disabled after
        thermal shutdown
5. An additional notification is sent to Android userspace to inform
   about thermal shutdown recovery.

Change-Id: I38afa98fea03210312fc01ab0d2c6ab2a10c447d
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>
Signed-off-by: Chris Kelly <c-kelly@ti.com>

ASoC: twl6040: VDDHF as SUPPLY widget

VDDHF external boost supply was being enabled after and disabled before
handsfree driver as a strategy for pop noise reduction. This strategy
makes handsfree driver very susceptible to overcurrent events, so the
boost supply is converted to a SUPPLY widget to enable it before and
disable it after handsfree path.

Change-Id: I608b4b0f5cb3301053869ccd2732434efe276b81
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>

Conflicts:

	sound/soc/codecs/twl6040.c

OMAP4: SDP44xx: Fix twl604x GPO used for tsp6130x NRESET

TPS6130x NRESET line is controlled by TWL604x GPO, but TWL604x's GPO
capabilities have changed and only a single GPO is supported in TWL6041.
This affects how TPS6130x reset is controlled:
- Processor boards using TWL6040 use GPO2
- Processor boards using TWL6041 use GPO (single GPO available)

Change-Id: I6a65be069aaf4f0dbe0f5c7da1660579c8956057
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>

OMAP4: Tablet: Fix twl604x GPO used for tsp6130x NRESET

TPS6130x NRESET line is controlled by TWL604x GPO, but TWL604x's GPO
capabilities have changed and only a single GPO is supported in TWL6041.
This affects how TPS6130x reset is controlled:
- Processor boards using TWL6040 use GPO2
- Processor boards using TWL6041 use GPO (single GPO available)

Change-Id: I92d41f84dfad003dac66ab3e51b842944bcc16a0
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>

ASoC: TWL6040: Adding Aux audio output

Adding switch controls to enable/disable audio output
throught Aux pins in codec.

Change-Id: I329c44fe95a9157d56017ac47cb4e091e87d8710
Signed-off-by: Israel Cepeda <icepeda@ti.com>

MFD: twl6040-codec: Refactor power-on verification

Refactor power-on verification which consists of checking NCPCTL,
LDOCTL and LPPLLCTL registers against expected values of successful
automatic power-up sequences.

Change-Id: I20c0693922baa6700a117881c47cbf400716446b
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>

MFD: twl6040-codec: Change power-up verification policy

Automatic power-up completion result can be affected by race
conditions between the completion task itself and the READYINT
handler, leading to false power-up failures as the completion
timeout may expire before READYINT handler gets executed and
marks completion.

Instead, the first verification for a successful power-up sequence
is the expected state of NCPCTL, LDOCTL and LPPLLCTL registers.
These registers will have specific values after automatic power-up
sequence has completed.

False power-up success is still checked, this is the case where
the READYINT is received but the hardware state is not consistent
with what is known/expected after a successful sequence. Under these
circumstances, we retry automatic power-up.

Change-Id: I9f85d67a10e84564a38f7d97a78345be06ac3b16
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>

module.h: split out the EXPORT_SYMBOL into export.h

A lot of files pull in module.h when all they are really
looking for is the basic EXPORT_SYMBOL functionality. The
recent data from Ingo[1] shows that this is one of several
instances that has a significant impact on compile times,
and it should be targeted for factoring out (as done here).

Note that several commonly used header files in include/*
directly include <linux/module.h> themselves (some 34 of them!)
The most commonly used ones of these will have to be made
independent of module.h before the full benefit of this change
can be realized.

We also transition THIS_MODULE from module.h to export.h,
since there are lots of files with subsystem structs that
in turn will have a struct module *owner and only be doing:

	.owner = THIS_MODULE;

and absolutely nothing else modular. So, we also want to have
the THIS_MODULE definition present in the lightweight header.

[1] https://lkml.org/lkml/2011/5/23/76

Change-Id: I52c16cc63f483d7c572cd0ef2475ef642dfa11c1
Signed-off-by: Paul Gortmaker <paul.gortmaker@windriver.com>
Signed-off-by: Hiroshi DOYU <hdoyu@nvidia.com>
[Hiroshi DOYU: Backported from v3.3-rc1 for DMABUF]
Reviewed-on: http://git-master/r/78383
Reviewed-by: Automatic_Commit_Validation_User
Reviewed-by: Varun Wadekar <vwadekar@nvidia.com>

MFD: twl6040-codec: cancel synch all active works on suspend

The TWL6040 vib_update work has to be canceled synchronously
before continue suspending, because of:
- it may sleep while accessing to I2C bus and, as result, WFI may be
reached in the middle of its execution and that may prevent system
from entering to OFF state.
- the device suspend handler may switch TWL6040 device to sleep
state while vib_update work is still active.

Change-Id: I77b681188976378eec9242ea64dc5f001960d279
Signed-off-by: Grygorii Strashko <grygorii.strashko@ti.com>

Add TWL6040 HSKEYS Driver

MFD: twl6040-codec: Store mclk configuration

Store the last used mclk configuration for the PLL.

Signed-off-by: Peter Ujfalusi <peter.ujfalusi@ti.com>
backported to Linux 3.0.x by faux123

MFD: twl6040-codec: Avoid PLL reconfiguration when not needed

Do not reconfigure the PLL in case it has been configured already
with the requested parameters.
In case of different PLL configuration do only the needed changes.
This can save considerable amount of time since we can avoid the
defined protocol (with delays) for the PLL configuration.

Signed-off-by: Peter Ujfalusi <peter.ujfalusi@ti.com>
backported to Linux 3.0.x by faux123

MFD: twl6040-codec: Add register cache

Add register cache and define register operations (read, write,
set_bits, clear_bits) on cache only. So register operations
performed on I2C registers are now differentiated.

Register operations APIs exported by TWL6040 MFD are a wrapper
to its I2C counterparts at the moment.

Change-Id: I76137099e6264de9ac3213c596f662a50299aa82
Signed-off-by: Misael Lopez Cruz <misael.lopez@ti.com>
Signed-off-by: Gabriel M. Beddingfield <gabrbedd@ti.com>
Signed-off-by: Chris Kelly <c-kelly@ti.com>
modified for Tuna from OMAPZOOM reference by faux123

Conflicts:
	drivers/mfd/twl6040-codec.c

MFD: twl6040-codec: Handle thermal interrupt

When the TWL6040 temperature increases above a threshold that could
damage the device, a thermal interrupt and shutdown are started
automatically by the hardware.

The thermal event handling involves the following steps:
1. Forcefully deassert AUDPWRON to avoid keeping TWL6040 is
   Power-On state any longer
2. The event is notified to Android userspace through the switch
   class based mechanism so that further actions can be taken
3. While the device is in thermal shutdown, accesses to VDD/VSS
   registers will affect only register cache
4. Once the device has recovered from the thermal event, it will
   be put back to Power-On state regardless of the state requested
   by MFD clients:
   4.1. If clients have requested Power-On state, then the context
        of VDD/VSS registers is restored
   4.2. If clients have requested Sleep state, then the request will
        be honored. The additional Power-On -> Sleep transition is
        required to ensure that reference system is disabled after
        thermal shutdown
5. An additional notification is sent to Android userspace to inform
   about thermal shutdown recovery.

modified for Tuna from OMAPZOOM reference by faux123

Conflicts:
	drivers/mfd/twl6040-codec.c
	include/linux/mfd/twl6040-codec.h

TWL6030: Fix false GPADC conversion timeout.

When scheduler preempts just started GPADC conversion,
the timeout appears because a time is exhausted
but actual status register value is not updated yet.
Simple scenario:
1. GPADC convertion is started before this function starts to run.
2. reg = twl6030_gpadc_read(gpadc, status_reg);
3.  if (!(reg & TWL6030_GPADC_BUSY) && (reg & TWL6030_GPADC_EOC_SW))
            return 0;
    GPADC is not yet ready, so function does not return.
4.  This moment the context is switched to another thread(s)
      ----------------------------------------------------------------------->
5.                           thread(s) work(s) for    timeout_ms   or more  time.
                             GPADC convertion is finished.
6.    <-----------------------------------------------------------------------
      The context is switched back.
7.  } while (!time_after(jiffies, timeout))
      Next cycle pass does not start, even if GPADC is yet ready.
8.  The Timeout Error is returned.

Additional GPADC status register reading is added for such cases.

	modified:   drivers/mfd/twl6030-gpadc.c

Change-Id: I94b61bb8318c6a03972ad057ab3fd026d1b4c13f
Signed-off-by: x0169938 <vasyl.yushchyshen@ti.com>

TWL6030: relaxing the GPADC busy loop with a sleep.

After GPADC conversion is started, we wait for finish it with
a busy flag polling in twl6030_gpadc_wait_conversion_ready().
Actually the GPADC busy loop finishes immediately, but for the
worst case condition the sleep is added.

      modified:   drivers/mfd/twl6030-gpadc.c

Change-Id: If20a9bfe6943814bcce98e591fd876d66f986e44
Signed-off-by: x0169938 <vasyl.yushchyshen@ti.com>

MFD: twl6030-gpadc update trim information

In the latest iteration of the data sheet the TRIM information was
changed from 2s complement to magnitude + sign. And the codes for
channel 10 were updated. Update code to reflect this change.

Change-Id: Ibaa3cbbe2241e1ce844e1249f0ab6389a1ed9b93
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

MFD: TWL6032_GPADC: Correct calibration parametrs.

This patch corrects GPADC calibration for the TWL6032 due to the
TWL6032 data manual.

Change-Id: I15fb4148bf94a5123467e8b7a316e7edcdb55ebc
Signed-off-by: Oleksandr Dmytryshyn <oleksandr.dmytryshyn@ti.com>

MFD: TWL6030: Introduce errata implementation

This patch adds for the kernel code ability to the errata
implementation for the TWL6030/TWL6032 chips.

Change-Id: Ieb2329ec3cf1e0300decc2908fba28aa471854e5
Signed-off-by: Oleksandr Dmytryshyn <oleksandr.dmytryshyn@ti.com>

Conflicts:

	drivers/mfd/twl-core.c
	include/linux/i2c/twl.h

MFD: TWL6032: Implementation of the ProDB00119490 errata

Residual voltage may be present on VBUS when USB cable is unplugged.
Workaround: Increase the VBUS anticollapse loop threshold to 4.44 V.

This errata affects only TWL6032 ES1.1

Change-Id: I7533fa7e3caa98e9e326f0c30cfb31d813303be8
Signed-off-by: Oleksandr Dmytryshyn <oleksandr.dmytryshyn@ti.com>

Conflicts:

	include/linux/i2c/twl.h

MFD: TWL6030: cancel synch all active works on suspend

The TWL6030 battery works have to be canceled synchronously
before continue suspending, because of:
- they may sleep while accessing to I2C bus and, as result, WFI may be
reached in the middle of its execution and that may prevent system
from entering to OFF state.
- the device suspend handler may switch TWL6030 device to sleep
state while their works are still active.

Change-Id: Ie3ef579e05bded049e39f9186acb01b116283c87
Signed-off-by: Grygorii Strashko <grygorii.strashko@ti.com>

twl6030_bci_battery remove use_eeprom_config

In all sensible use cases use_eeprom_config and use_hw_charger are
actually synonymous so simplify the code and remove the use_eeprom_config.

Change-Id: Ibf473ea8106a72038f646e9163665caa91de9e06
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

twl6030_bci_battery read charger mode from register

For the twl6032 read the charger mode and power path usage from a register
on the chip.

Because of this change these parameters no longer need to be provided by
platform data so move these variable to the private structure.

This change also means that these variables being set also implies
twl6032 is the chip type so simplify the code by removing checks
for this from features at each usage of one of these variables.

Change-Id: If371db6270e40edf2ee315696300cf29bd9e8ea8
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

twl6030_bci_battery correct the current readings.

Correct the current reading functions for current_now and current_avg.
This was done with advice on the correct algorithm from the design team
and application engineers.

Also by default twl6030 and twl6032 use different sense resistors and
according to design team these resistors may be tuned for certain boards.
So allow the resistor value to be passed as platform data but select
sensible defaults if it is not.

Change-Id: Ib60742ec5779708d7156a4c6b4acd16b84cc8f0c
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

twl6030_bci_battery add seperate irq handlers for hw mode

As HW/Auto mode for the charger just wants to read status and convert
this to power supply class statuses. It is easier and cleaner to seperate
the handling of HW mode into seperate IRQ handlers.

Change-Id: Ic80fa0ff6b77a77e8c10b63027876bb8f613e0f8
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

twl6030_bci_battery remove hw handling from sw irq

Now that hardware charging mode has seperate IRQs remove the hardware
mode handling from the software mode IRQs as it is not required here
anymore.

Change-Id: Ib2cd7ae43157014b9111a5bdd5da36e1caeb6602
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

POWER: twl6030_bci_battery fix start/stop for hw mode

In use_hw_charger mode the charger should not be started or stopped
by disabling/enabled the DCDC/Linear charger. It should rather be
paused by setting HZ_MODE. This prevents the charger switching from
HW to SW mode.

Change-Id: I521b094a0fa4835466142219f1a1eef1ef4578b1
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

POWER: twl6030_bci_battery fix boot charge state in hw mode

Change the method to detect the charging state on boot. The
_STS bits used previously did not contain the complete charging
state so in some situations state was incorrectly indicated.

Change-Id: I6e276765d36f41df263ef5588aef4c792c8cbb7e
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

twl6030_bci_battery alter the hw mode start logic

In Active state the omap does not update the CHRG_DET_N signal so to
change the current limits based on the information of USB stack in
HW mode the CINLIMIT register needs to be written. This does not
take the charger out of HW mode.

Because the new logic started to make start fuction messy I have split
into seperate hw/sw start functions.

Change-Id: I647d2934a9b8e39e0d00049444c79ca196e8820b
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

twl6030_bci_battery fix autogate logic

The logic in the autogate function was causing a storm of events causing
I2C transactions as fast as the bus could run. Add an extra check in
the if statement and correctly set the charger source to stop this
happening. This stops the monitor function being scheduled thousands
of times when USB cable is inserted.

Change-Id: Ib783b684c3b3913e2afb9aa6fd607683c9d555ec
Signed-off-by: Graeme Gregory <gg@slimlogic.co.uk>

HACK: POWER: TWL6030_BCI: Remove backup battery sysfs attributes

TWL6030 driver registers two battery type devices,
but there is no way to mark one battery as main for Android.
So Android may use backup battery attibutes instead of main battery.

To workaround this issue /sys/class/power_supply/ should have only one
Battery type device with battery attributes.

Change-Id: I63df13f9847eeeaf8b4efd2fbe2558030caea7c8
Signed-off-by: Taras Kondratiuk <taras@ti.com>

OMAP4 Thermal Framework: Add support for 12-bit GPADC on TWL6032

Changing the the algorithm for temperature calculation using a NTC termistor.
Now the temperature is selected from the table depending on the voltage,
and not from the ADC code. In this implementation, the dependence on the ADC resolution is lost.

Change-Id: I83d7b45d1b0c3b4a60089e3502aaeb91640a4ffd
Signed-off-by: Oleksandr_Tyshchenko <oleksandr.tyshchenko@ti.com>

TWL6032: Fix missing VBUS interrupts after OTG-cable insertion

After OTG-cable is plugged there is no possible to connect PC
to the device (not works adb etc) because VBUS interrupts are
missed. This patch fix it.

Change-Id: Ie045508f05069464e415c4e0dc79c448b696ad98
Signed-off-by: Oleksandr Dmytryshyn <oleksandr.dmytryshyn@ti.com>

MFD: TWL6030: Implementation of the ProDB00112620 errata

This errata affects only TWL6030 ES2.1. The usage of the CIN_LIMIT
codes above 600mA (CHARGERUSB_CINLIMIT Register, codes
650mA/700mA/750mA) may lead to an unlimited input current in
case VBUS < 4.1V.

Workaround: The anti-collapse feature needs to be enabled before
usage of the CIN_LIMIT. All CIN_LIMIT codes will be functional at
all anti-collapse levels.

Change-Id: I4fc0eb64cc96b692f4761a27098df307e1f5cd54
Signed-off-by: Oleksandr Dmytryshyn <oleksandr.dmytryshyn@ti.com>

MFD: TWL6030: Implementation of the ProDB00110684 errata

This errata affects only TWL6030 ES2.1. Each time a charge is
enabled via SW, a THMREG interrupt triggers (Internal USB charger
fault interrupt line).

Workaround: Interrupt (the bit #1 of CHARGERUSB_INT_MASK) has to be
masked before enabling the charge, and unmasked after charge is
enabled.

Change-Id: I14074e384a863c82ba61af9ea9434afe75cc2bc8
Signed-off-by: Oleksandr Dmytryshyn <oleksandr.dmytryshyn@ti.com>

OMAP4: battery: capacity detection.

Capacity could be detected when it is not charging.
If charge status set to POWER_SUPPLY_STATUS_NOT_CHARGING
capacity detection path is omitted.

Add this state to let capacity detection happen.

Change-Id: I34a8295470457423d25cc2ec42e2498682339dcc
Signed-off-by: Oleksandr Kozaruk <oleksandr.kozaruk@ti.com>

twl6030 battery: don't disable gas gauge in suspend

We need the gas gauge to continue measuring power drain in suspend.
Keep it always enabled.

Change-Id: I5b6dd4d8f63e3269dacf8d8dfb814670bfa8937a
Signed-off-by: Sivakumar Pothireddy <sivakumar.pothireddy@ti.com>
Signed-off-by: Anand Gadiyar <gadiyar@ti.com>

twl6030 battery: add lookup table for initial capacity estimation

Add a lookup table for estimating battery capacity at bootup
using the battery voltage measrued at that time.

The table was constructed using actual measured values for Blaze
Tablets. The values don't correspond to the arbitrary values currently
used in the driver.

This table is something that a board file should pass to the
driver. This will be introduced in a later patch - for now, we
keep the values in the driver just like the current design.

Change-Id: I78b35b68c7a41b67d67925dae8015405efb44b0d
Signed-off-by: Sivakumar Pothireddy <sivakumar.pothireddy@ti.com>
Signed-off-by: Anand Gadiyar <gadiyar@ti.com>

twl6030 battery: clear gas gauge at enable time

Otherwise previous register values (from bootloader, or warm reboot)
will distort our calculations.

Change-Id: I302eb3f05cacdc9136c937556dd5a9d5d8baf4d4
Signed-off-by: Sivakumar Pothireddy <sivakumar.pothireddy@ti.com>
Signed-off-by: Anand Gadiyar <gadiyar@ti.com>

twl6030 battery: use gas gauge for capacity estimation

Use the gas gauge in twl6030 to estimate the remaining battery
capacity.

At bootup, we use an estimate of initial capacity using the measured
battery voltage at bootup. From that point on, all future battery
capacity estimations are done by using the gas gauge to measure
all addition/removal of charge from the battery.

Clamp battery value to 99% if the measured value exceeds 99%.
A later patch will add the code to update the initial estimate
once the battery is fully charged.

TODO: Minimum safe battery voltage reporting needs to be worked on

Change-Id: Iab157b559f9de432a93664e8d78c003af3c75b67
Signed-off-by: Sivakumar Pothireddy <sivakumar.pothireddy@ti.com>
Signed-off-by: Anand Gadiyar <gadiyar@ti.com>

twl6030 battery: remove ac_next_refresh

We now update capacity estimates using the gas gauge. No need to
schedule voltage-based estimates except when voltage is critically low.
(This reconciliation based on voltages will be done in a later patch).
So remove this code.

Change-Id: I46706c954e32667a84a4e64c9a0831a706755da8
Signed-off-by: Sivakumar Pothireddy <sivakumar.pothireddy@ti.com>
Signed-off-by: Anand Gadiyar <gadiyar@ti.com>

twl6030 battery: pass nominal capacity from board file

Pass the nominal battery capacity from the board file instead of
hardcoding it in the driver.

TODO: This needs to be done for the blaze as well, although it's
rarely run off the battery

Change-Id: I15cba65f062c70f3b1e26f3c03db59e3af0d6ea9
Signed-off-by: Sivakumar Pothireddy <sivakumar.pothireddy@ti.com>
Signed-off-by: Anand Gadiyar <gadiyar@ti.com>

twl6030 battery: assume default capacity if not specified

If platform data does not pass down the nominal battery capacity,
then assume a sane default value.

Change-Id: Icba698fb0d2f14cc778740734ed8f2c573e67f0d
Signed-off-by: Sivakumar Pothireddy <sivakumar.pothireddy@ti.com>
Signed-off-by: Anand Gadiyar <gadiyar@ti.com>

MFD: TWL6030_GPADC: set conversion sample type in the ioctl function

Sample type of the conversion was not set in the ioctl function
and it was with random value. As result - many attempts to start
GPADC conversion via ioctl function were ended with the EINVAL
error. This patch fixes it.

Change-Id: Id8dc13f9cb7f8b828bc6f74bcac4a47b269bb83c
Signed-off-by: Oleksandr Dmytryshyn <oleksandr.dmytryshyn@ti.com>

MFD: TWL6030: cancel synch all active works on suspend

raw: test against runtime value of max_raw_minors

commit 5bbb2ae3d6f896f8d2082d1eceb6131c2420b7cf upstream.

bind_get() checks the device number it is called with. It uses
MAX_RAW_MINORS for the upper bound. But MAX_RAW_MINORS is set at compile
time while the actual number of raw devices can be set at runtime. This
means the test can either be too strict or too lenient. And if the test
ends up being too lenient bind_get() might try to access memory beyond
what was allocated for "raw_devices".

So check against the runtime value (max_raw_minors) in this function.

Change-Id: I79539a269c0db04f0d04455939014c3f4a000056
Signed-off-by: Paul Bolle <pebolle@tiscali.nl>
Acked-by: Jan Kara <jack@suse.cz>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

Remove excessive debug logging

mmc: tmio_mmc_dma: fix PIO fallback on SDHI

commit f936f9b67b7f8c2eae01dd303a0e90bd777c4679 upstream.

I'm testing SH-Mobile SDHI driver in DMA mode with  a new DMA controller  using
'bonnie++' and getting DMA error after which the tmio_mmc_dma.c code falls back
to PIO but all commands time out after that.  It turned out that the fallback
code calls tmio_mmc_enable_dma() with RX/TX channels already freed and pointers
to them cleared, so that the function bails out early instead  of clearing the
DMA bit in the CTL_DMA_ENABLE register. The regression was introduced by commit
162f43e31c5a376ec16336e5d0ac973373d54c89 (mmc: tmio: fix a deadlock).
Moving tmio_mmc_enable_dma() calls to the top of the PIO fallback code in
tmio_mmc_start_dma_{rx|tx}() helps.

Change-Id: I39fe684debe6e4253279e303e840ac2dba86caee
Signed-off-by: Sergei Shtylyov <sergei.shtylyov@cogentembedded.com>
Acked-by: Guennadi Liakhovetski <g.liakhovetski@gmx.de>
Signed-off-by: Chris Ball <cjb@laptop.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

block: fix race between request completion and timeout handling

commit 4912aa6c11e6a5d910264deedbec2075c6f1bb73 upstream.

crocode i2c_i801 i2c_core iTCO_wdt iTCO_vendor_support shpchp ioatdma dca be2net sg ses enclosure ext4 mbcache jbd2 sd_mod crc_t10dif ahci megaraid_sas(U) dm_mirror dm_region_hash dm_log dm_mod [last unloaded: scsi_wait_scan]

Pid: 491, comm: scsi_eh_0 Tainted: G        W  ----------------   2.6.32-220.13.1.el6.x86_64 #1 IBM  -[8722PAX]-/00D1461
RIP: 0010:[<ffffffff8124e424>]  [<ffffffff8124e424>] blk_requeue_request+0x94/0xa0
RSP: 0018:ffff881057eefd60  EFLAGS: 00010012
RAX: ffff881d99e3e8a8 RBX: ffff881d99e3e780 RCX: ffff881d99e3e8a8
RDX: ffff881d99e3e8a8 RSI: ffff881d99e3e780 RDI: ffff881d99e3e780
RBP: ffff881057eefd80 R08: ffff881057eefe90 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000000 R12: ffff881057f92338
R13: 0000000000000000 R14: ffff881057f92338 R15: ffff883058188000
FS:  0000000000000000(0000) GS:ffff880040200000(0000) knlGS:0000000000000000
CS:  0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 00000000006d3ec0 CR3: 000000302cd7d000 CR4: 00000000000406b0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process scsi_eh_0 (pid: 491, threadinfo ffff881057eee000, task ffff881057e29540)
Stack:
 0000000000001057 0000000000000286 ffff8810275efdc0 ffff881057f16000
<0> ffff881057eefdd0 ffffffff81362323 ffff881057eefe20 ffffffff8135f393
<0> ffff881057e29af8 ffff8810275efdc0 ffff881057eefe78 ffff881057eefe90
Call Trace:
 [<ffffffff81362323>] __scsi_queue_insert+0xa3/0x150
 [<ffffffff8135f393>] ? scsi_eh_ready_devs+0x5e3/0x850
 [<ffffffff81362a23>] scsi_queue_insert+0x13/0x20
 [<ffffffff8135e4d4>] scsi_eh_flush_done_q+0x104/0x160
 [<ffffffff8135fb6b>] scsi_error_handler+0x35b/0x660
 [<ffffffff8135f810>] ? scsi_error_handler+0x0/0x660
 [<ffffffff810908c6>] kthread+0x96/0xa0
 [<ffffffff8100c14a>] child_rip+0xa/0x20
 [<ffffffff81090830>] ? kthread+0x0/0xa0
 [<ffffffff8100c140>] ? child_rip+0x0/0x20
Code: 00 00 eb d1 4c 8b 2d 3c 8f 97 00 4d 85 ed 74 bf 49 8b 45 00 49 83 c5 08 48 89 de 4c 89 e7 ff d0 49 8b 45 00 48 85 c0 75 eb eb a4 <0f> 0b eb fe 0f 1f 84 00 00 00 00 00 55 48 89 e5 0f 1f 44 00 00
RIP  [<ffffffff8124e424>] blk_requeue_request+0x94/0xa0
 RSP <ffff881057eefd60>

The RIP is this line:
        BUG_ON(blk_queued_rq(rq));

After digging through the code, I think there may be a race between the
request completion and the timer handler running.

A timer is started for each request put on the device's queue (see
blk_start_request->blk_add_timer).  If the request does not complete
before the timer expires, the timer handler (blk_rq_timed_out_timer)
will mark the request complete atomically:

static inline int blk_mark_rq_complete(struct request *rq)
{
        return test_and_set_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags);
}

and then call blk_rq_timed_out.  The latter function will call
scsi_times_out, which will return one of BLK_EH_HANDLED,
BLK_EH_RESET_TIMER or BLK_EH_NOT_HANDLED.  If BLK_EH_RESET_TIMER is
returned, blk_clear_rq_complete is called, and blk_add_timer is again
called to simply wait longer for the request to complete.

Now, if the request happens to complete while this is going on, what
happens?  Given that we know the completion handler will bail if it
finds the REQ_ATOM_COMPLETE bit set, we need to focus on the completion
handler running after that bit is cleared.  So, from the above
paragraph, after the call to blk_clear_rq_complete.  If the completion
sets REQ_ATOM_COMPLETE before the BUG_ON in blk_add_timer, we go boom
there (I haven't seen this in the cores).  Next, if we get the
completion before the call to list_add_tail, then the timer will
eventually fire for an old req, which may either be freed or reallocated
(there is evidence that this might be the case).  Finally, if the
completion comes in *after* the addition to the timeout list, I think
it's harmless.  The request will be removed from the timeout list,
req_atom_complete will be set, and all will be well.

This will only actually explain the coredumps *IF* the request
structure was freed, reallocated *and* queued before the error handler
thread had a chance to process it.  That is possible, but it may make
sense to keep digging for another race.  I think that if this is what
was happening, we would see other instances of this problem showing up
as null pointer or garbage pointer dereferences, for example when the
request structure was not re-used.  It looks like we actually do run
into that situation in other reports.

This patch moves the BUG_ON(test_bit(REQ_ATOM_COMPLETE,
&req->atomic_flags)); from blk_add_timer to the only caller that could
trip over it (blk_start_request).  It then inverts the calls to
blk_clear_rq_complete and blk_add_timer in blk_rq_timed_out to address
the race.  I've boot tested this patch, but nothing more.

Change-Id: Ic8af24ef652452786715bc23515e986c0bf138ca
Signed-off-by: Jeff Moyer <jmoyer@redhat.com>
Acked-by: Hannes Reinecke <hare@suse.de>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

block: properly stack underlying max_segment_size to DM device

commit d82ae52e68892338068e7559a0c0657193341ce4 upstream.

Without this patch all DM devices will default to BLK_MAX_SEGMENT_SIZE
(65536) even if the underlying device(s) have a larger value -- this is
due to blk_stack_limits() using min_not_zero() when stacking the
max_segment_size limit.

1073741824

before patch:
65536

after patch:
1073741824

Change-Id: I49315cab0499b79a33f597087c8a8b2fd340e8f1
Reported-by: Lukasz Flis <l.flis@cyfronet.pl>
Signed-off-by: Mike Snitzer <snitzer@redhat.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

elevator: acquire q->sysfs_lock in elevator_change()

commit 7c8a3679e3d8e9d92d58f282161760a0e247df97 upstream.

Add locking of q->sysfs_lock into elevator_change() (an exported function)
to ensure it is held to protect q->elevator from elevator_init(), even if
elevator_change() is called from non-sysfs paths.
sysfs path (elv_iosched_store) uses __elevator_change(), non-locking
version, as the lock is already taken by elv_iosched_store().

Change-Id: I2a7796c1d13fa45218499121a5110ebf78f73d75
Signed-off-by: Tomoki Sekiyama <tomoki.sekiyama@hds.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
Cc: Josh Boyer <jwboyer@fedoraproject.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

block: add cond_resched() to potentially long running ioctl discard loop

commit c8123f8c9cb517403b51aa41c3c46ff5e10b2c17 upstream.

When mkfs issues a full device discard and the device only
supports discards of a smallish size, we can loop in
blkdev_issue_discard() for a long time. If preempt isn't enabled,
this can turn into a softlock situation and the kernel will
start complaining.

Add an explicit cond_resched() at the end of the loop to avoid
that.

Change-Id: Ia683982b894103aa19d937a1a0a379f1160c8df4
Signed-off-by: Jens Axboe <axboe@fb.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

blktrace: fix accounting of partially completed requests

commit af5040da01ef980670b3741b3e10733ee3e33566 upstream.

trace_block_rq_complete does not take into account that request can
be partially completed, so we can get the following incorrect output
of blkparser:

  C   R 232 + 240 [0]
  C   R 240 + 232 [0]
  C   R 248 + 224 [0]
  C   R 256 + 216 [0]

but should be:

  C   R 232 + 8 [0]
  C   R 240 + 8 [0]
  C   R 248 + 8 [0]
  C   R 256 + 8 [0]

Also, the whole output summary statistics of completed requests and
final throughput will be incorrect.

This patch takes into account real completion size of the request and
fixes wrong completion accounting.

Change-Id: I10c78291b2b02d200d778dad247806d701e8c4c1
Signed-off-by: Roman Pen <r.peniaev@gmail.com>
CC: Steven Rostedt <rostedt@goodmis.org>
CC: Frederic Weisbecker <fweisbec@gmail.com>
CC: Ingo Molnar <mingo@redhat.com>
CC: linux-kernel@vger.kernel.org
Signed-off-by: Jens Axboe <axboe@fb.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ext4: improve handling of conflicting mount options

If the user explicitly specifies conflicting mount options for
delalloc or dioread_nolock and data=journal, fail the mount, instead
of printing a warning and continuing (since many user's won't look at
dmesg and notice the warning).

Also, print a single warning that data=journal implies that delayed
allocation is not on by default (since it's not supported), and
furthermore that O_DIRECT is not supported.  Improve the text in
Documentation/filesystems/ext4.txt so this is clear there as well.

Similarly, if the dioread_nolock mount option is specified when the
file system block size != PAGE_SIZE, fail the mount instead of
printing a warning message and ignoring the mount option.

Change-Id: I936c5bbe42d1da494a3c5cee8d2f216848b2a9e7
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>

ext4: fix mount/remount error messages for incompatible mount options

commit 6ae6514b33f941d3386da0dfbe2942766eab1577 upstream.

Commit 5688978 ("ext4: improve handling of conflicting mount options")
introduced incorrect messages shown while choosing wrong mount options.

First of all, both cases of incorrect mount options,
"data=journal,delalloc" and "data=journal,dioread_nolock" result in
the same error message.

Secondly, the problem above isn't solved for remount option: the
mismatched parameter is simply ignored.  Moreover, ext4_msg states
that remount with options "data=journal,delalloc" succeeded, which is
not true.

To fix it up, I added a simple check after parse_options() call to
ensure that data=journal and delalloc/dioread_nolock parameters are
not present at the same time.

Change-Id: I0f37bcb1a42f8ca0f90dc4963fea3f83ad45503e
Signed-off-by: Piotr Sarna <p.sarna@partner.samsung.com>
Acked-by: Bartlomiej Zolnierkiewicz <b.zolnierkie@samsung.com>
Signed-off-by: Kyungmin Park <kyungmin.park@samsung.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

configfs: fix race between dentry put and lookup

commit 76ae281f6307331aa063288edb6422ae99f435f0 upstream.

A race window in configfs, it starts from one dentry is UNHASHED and end
before configfs_d_iput is called.  In this window, if a lookup happen,
since the original dentry was UNHASHED, so a new dentry will be
allocated, and then in configfs_attach_attr(), sd->s_dentry will be
updated to the new dentry.  Then in configfs_d_iput(),
BUG_ON(sd->s_dentry != dentry) will be triggered and system panic.

sys_open:                     sys_close:
 ...                           fput
                                dput
                                 dentry_kill
                                  __d_drop <--- dentry unhashed here,
                                           but sd->dentry still point
                                           to this dentry.

 lookup_real
  configfs_lookup
   configfs_attach_attr---> update sd->s_dentry
                            to new allocated dentry here.

                                   d_kill
                                     configfs_d_iput <--- BUG_ON(sd->s_dentry != dentry)
                                                     triggered here.

To fix it, change configfs_d_iput to not update sd->s_dentry if
sd->s_count > 2, that means there are another dentry is using the sd
beside the one that is going to be put.  Use configfs_dirent_lock in
configfs_attach_attr to sync with configfs_d_iput.

With the following steps, you can reproduce the bug.

1. enable ocfs2, this will mount configfs at /sys/kernel/config and
   fill configure in it.

2. run the following script.
	while [ 1 ]; do cat /sys/kernel/config/cluster/$your_cluster_name/idle_timeout_ms > /dev/null; done &
	while [ 1 ]; do cat /sys/kernel/config/cluster/$your_cluster_name/idle_timeout_ms > /dev/null; done &

Change-Id: Ic3e23d8acccb67695536beca82bca2238806d66a
Signed-off-by: Junxiao Bi <junxiao.bi@oracle.com>
Cc: Joel Becker <jlbec@evilplan.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ext4: avoid bh leak in retry path of ext4_expand_extra_isize_ea()

commit dcb9917ba041866686fe152850364826c4622a36 upstream.

Change-Id: I689816d203f06f61ae30a4102ed6ccb623191e47
Reported-by: Dave Jones <davej@redhat.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

devpts: plug the memory leak in kill_sb

commit 66da0e1f9034140ae2f571ef96e254a25083906c upstream.

When devpts is unmounted, there may be a no-longer-used IDR tree hanging
off the superblock we are about to kill.  This needs to be cleaned up
before destroying the SB.

The leak is usually not a big deal because unmounting devpts is typically
done when shutting down the whole machine.  However, shutting down an LXC
container instead of a physical machine exposes the problem (the garbage
is detectable with kmemleak).

Change-Id: Ia724bff5ccfe7ae9f80866f78ebaf8b608a3533d
Signed-off-by: Ilija Hadzic <ihadzic@research.bell-labs.com>
Cc: Sukadev Bhattiprolu <sukadev@linux.vnet.ibm.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ext4: fix use-after-free in ext4_mb_new_blocks

commit 4e8d2139802ce4f41936a687f06c560b12115247 upstream.

ext4_mb_put_pa should hold pa->pa_lock before accessing pa->pa_count.
While ext4_mb_use_preallocated checks pa->pa_deleted first and then
increments pa->count later, ext4_mb_put_pa decrements pa->pa_count
before holding pa->pa_lock and then sets pa->pa_deleted.

* Free sequence
ext4_mb_put_pa (1):		atomic_dec_and_test pa->pa_count
ext4_mb_put_pa (2):		lock pa->pa_lock
ext4_mb_put_pa (3):			check pa->pa_deleted
ext4_mb_put_pa (4):			set pa->pa_deleted=1
ext4_mb_put_pa (5):		unlock pa->pa_lock
ext4_mb_put_pa (6):		remove pa from a list
ext4_mb_pa_callback:		free pa

* Use sequence
ext4_mb_use_preallocated (1):	iterate over preallocation
ext4_mb_use_preallocated (2):	lock pa->pa_lock
ext4_mb_use_preallocated (3):		check pa->pa_deleted
ext4_mb_use_preallocated (4):		increase pa->pa_count
ext4_mb_use_preallocated (5):	unlock pa->pa_lock
ext4_mb_release_context:	access pa

* Use-after-free sequence
[initial status]		<pa->pa_deleted = 0, pa_count = 1>
ext4_mb_use_preallocated (1):	iterate over preallocation
ext4_mb_use_preallocated (2):	lock pa->pa_lock
ext4_mb_use_preallocated (3):		check pa->pa_deleted
ext4_mb_put_pa (1):		atomic_dec_and_test pa->pa_count
[pa_count decremented]		<pa->pa_deleted = 0, pa_count = 0>
ext4_mb_use_preallocated (4):		increase pa->pa_count
[pa_count incremented]		<pa->pa_deleted = 0, pa_count = 1>
ext4_mb_use_preallocated (5):	unlock pa->pa_lock
ext4_mb_put_pa (2):		lock pa->pa_lock
ext4_mb_put_pa (3):			check pa->pa_deleted
ext4_mb_put_pa (4):			set pa->pa_deleted=1
[race condition!]		<pa->pa_deleted = 1, pa_count = 1>
ext4_mb_put_pa (5):		unlock pa->pa_lock
ext4_mb_put_pa (6):		remove pa from a list
ext4_mb_pa_callback:		free pa
ext4_mb_release_context:	access pa

AddressSanitizer has detected use-after-free in ext4_mb_new_blocks
Bug report: http://goo.gl/rG1On3

Change-Id: Ie963fd6a875712e0397a953c11d59a7a4b7580b9
Signed-off-by: Junho Ryu <jayr@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: __set_page_dirty uses spin_lock_irqsave instead of spin_lock_irq

commit 227d53b397a32a7614667b3ecaf1d89902fb6c12 upstream.

To use spin_{un}lock_irq is dangerous if caller disabled interrupt.
During aio buffer migration, we have a possibility to see the following
call stack.

aio_migratepage  [disable interrupt]
  migrate_page_copy
    clear_page_dirty_for_io
      set_page_dirty
        __set_page_dirty_buffers
          __set_page_dirty
            spin_lock_irq

This mean, current aio migration is a deadlockable.  spin_lock_irqsave
is a safer alternative and we should use it.

Change-Id: I52bb3bc3f4b2de46213d47d11283c7ab096bfdc5
Signed-off-by: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com>
Reported-by: David Rientjes rientjes@google.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

fs/file.c:fdtable: avoid triggering OOMs from alloc_fdmem

commit 96c7a2ff21501691587e1ae969b83cbec8b78e08 upstream.

Recently due to a spike in connections per second memcached on 3
separate boxes triggered the OOM killer from accept.  At the time the
OOM killer was triggered there was 4GB out of 36GB free in zone 1.  The
problem was that alloc_fdtable was allocating an order 3 page (32KiB) to
hold a bitmap, and there was sufficient fragmentation that the largest
page available was 8KiB.

I find the logic that PAGE_ALLOC_COSTLY_ORDER can't fail pretty dubious
but I do agree that order 3 allocations are very likely to succeed.

There are always pathologies where order > 0 allocations can fail when
there are copious amounts of free memory available.  Using the pigeon
hole principle it is easy to show that it requires 1 page more than 50%
of the pages being free to guarantee an order 1 (8KiB) allocation will
succeed, 1 page more than 75% of the pages being free to guarantee an
order 2 (16KiB) allocation will succeed and 1 page more than 87.5% of
the pages being free to guarantee an order 3 allocate will succeed.

A server churning memory with a lot of small requests and replies like
memcached is a common case that if anything can will skew the odds
against large pages being available.

Therefore let's not give external applications a practical way to kill
linux server applications, and specify __GFP_NORETRY to the kmalloc in
alloc_fdmem.  Unless I am misreading the code and by the time the code
reaches should_alloc_retry in __alloc_pages_slowpath (where
__GFP_NORETRY becomes signification).  We have already tried everything
reasonable to allocate a page and the only thing left to do is wait.  So
not waiting and falling back to vmalloc immediately seems like the
reasonable thing to do even if there wasn't a chance of triggering the
OOM killer.

Change-Id: I82991a368b240e3744ece5e82155ad88c7638962
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
Cc: Eric Dumazet <eric.dumazet@gmail.com>
Acked-by: David Rientjes <rientjes@google.com>
Cc: Cong Wang <cwang@twopensource.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ext4: don't try to modify s_flags if the the file system is read-only

commit 23301410972330c0ae9a8afc379ba2005e249cc6 upstream.

If an ext4 file system is created by some tool other than mke2fs
(perhaps by someone who has a pathalogical fear of the GPL) that
doesn't set one or the other of the EXT2_FLAGS_{UN}SIGNED_HASH flags,
and that file system is then mounted read-only, don't try to modify
the s_flags field.  Otherwise, if dm_verity is in use, the superblock
will change, causing an dm_verity failure.

Change-Id: Ie2d6f5d37cfa39a04e3f703464312225af4fd146
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ext4: don't leave i_crtime.tv_sec uninitialized

commit 19ea80603715d473600cd993b9987bc97d042e02 upstream.

If the i_crtime field is not present in the inode, don't leave the
field uninitialized.

Change-Id: I98d789c3cba6e3ea86ef7ccfc6afbcd2a224f435
Fixes: ef7f38359 ("ext4: Add nanosecond timestamps")
Reported-by: Vegard Nossum <vegard.nossum@oracle.com>
Tested-by: Vegard Nossum <vegard.nossum@oracle.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

fuse: readdir: check for slash in names

commit efeb9e60d48f7778fdcad4a0f3ad9ea9b19e5dfd upstream.

Userspace can add names containing a slash character to the directory
listing.  Don't allow this as it could cause all sorts of trouble.

Change-Id: I7836dab7a5fedbf593f201e3a8506a94d93f4051
Signed-off-by: Miklos Szeredi <mszeredi@suse.cz>
[bwh: Backported to 3.2: drop changes to parse_dirplusfile() which we
 don't have]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Rui Xiang <rui.xiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

cifs: don't instantiate new dentries in readdir for inodes that need to be revalidated immediately

commit 757c4f6260febff982276818bb946df89c1105aa upstream.

David reported that commit c2b93e06 (cifs: only set ops for inodes in
I_NEW state) caused a regression with mfsymlinks. Prior to that patch,
if a mfsymlink dentry was instantiated at readdir time, the inode would
get a new set of ops when it was revalidated. After that patch, this
did not occur.

This patch addresses this by simply skipping instantiating dentries in
the readdir codepath when we know that they will need to be immediately
revalidated. The next attempt to use that dentry will cause a new lookup
to occur (which is basically what we want to happen anyway).

Change-Id: If17ca08eee7eadb740d375f3e6d01e5c3a7a3cae
Cc: "Stefan (metze) Metzmacher" <metze@samba.org>
Cc: Sachin Prabhu <sprabhu@redhat.com>
Reported-and-Tested-by: David McBride <dwm37@cam.ac.uk>
Signed-off-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Steve French <smfrench@gmail.com>
[bwh: Backported to 3.2: need to return NULL]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Rui Xiang <rui.xiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

cifs: adjust sequence number downward after signing NT_CANCEL request

commit 31efee60f489c759c341454d755a9fd13de8c03d upstream.

When a call goes out, the signing code adjusts the sequence number
upward by two to account for the request and the response. An NT_CANCEL
however doesn't get a response of its own, it just hurries the server
along to get it to respond to the original request more quickly.
Therefore, we must adjust the sequence number back down by one after
signing a NT_CANCEL request.

Change-Id: Ib4815ef347b793016c82dab2e48427f2b56a77e9
Reported-by: Tim Perry <tdparmor-sambabugs@yahoo.com>
Signed-off-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Steve French <smfrench@gmail.com>
[bwh: Backported to 3.2: adjust filename]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Rui Xiang <rui.xiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ext4: atomically set inode->i_flags in ext4_set_inode_flags()

commit 00a1a053ebe5febcfc2ec498bd894f035ad2aa06 upstream.

Use cmpxchg() to atomically set i_flags instead of clearing out the
S_IMMUTABLE, S_APPEND, etc. flags and then setting them from the
EXT4_IMMUTABLE_FL, EXT4_APPEND_FL flags, since this opens up a race
where an immutable file has the immutable flag cleared for a brief
window of time.

Change-Id: Icabe644691c6dc9246389adc513439f7d67d8a73
Reported-by: John Sullivan <jsrhbz@kanargh.force9.co.uk>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

proc: pid/status: show all supplementary groups

commit 8d238027b87e654be552eabdf492042a34c5c300 upstream.

We display a list of supplementary group for each process in
/proc/<pid>/status.  However, we show only the first 32 groups, not all of
them.

Although this is rare, but sometimes processes do have more than 32
supplementary groups, and this kernel limitation breaks user-space apps
that rely on the group list in /proc/<pid>/status.

Number 32 comes from the internal NGROUPS_SMALL macro which defines the
length for the internal kernel "small" groups buffer.  There is no
apparent reason to limit to this value.

This patch removes the 32 groups printing limit.

The Linux kernel limits the amount of supplementary groups by NGROUPS_MAX,
which is currently set to 65536.  And this is the maximum count of groups
we may possibly print.

Change-Id: Iee760113e5e6d79fba0952b56224d2668236c939
Signed-off-by: Artem Bityutskiy <artem.bityutskiy@linux.intel.com>
Acked-by: Serge E. Hallyn <serge.hallyn@ubuntu.com>
Acked-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
[bwh: Backported to 3.2: adjust context]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Qiang Huang <h.huangqiang@huawei.com>
Cc: Li Zefan <lizefan@huawei.com>
Cc: Jianguo Wu <wujianguo@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ext4: use i_size_read in ext4_unaligned_aio()

commit 6e6358fc3c3c862bfe9a5bc029d3f8ce43dc9765 upstream.

We haven't taken i_mutex yet, so we need to use i_size_read().

Change-Id: Ia7d94d593999484a3d565954417e1dd15c15daad
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

locks: allow __break_lease to sleep even when break_time is 0

commit 4991a628a789dc5954e98e79476d9808812292ec upstream.

A fl->fl_break_time of 0 has a special meaning to the lease break code
that basically means "never break the lease". knfsd uses this to ensure
that leases don't disappear out from under it.

Unfortunately, the code in __break_lease can end up passing this value
to wait_event_interruptible as a timeout, which prevents it from going
to sleep at all. This causes __break_lease to spin in a tight loop and
causes soft lockups.

Fix this by ensuring that we pass a minimum value of 1 as a timeout
instead.

Change-Id: I29302e1861df545fbb85ced19194cce6b6084d30
Cc: J. Bruce Fields <bfields@fieldses.org>
Reported-by: Terry Barnaby <terry1@beam.ltd.uk>
Signed-off-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: J. Bruce Fields <bfields@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

setfacl removes part of ACL when setting POSIX ACLs to Samba

commit b1d93356427be6f050dc55c86eb019d173700af6 upstream.

setfacl over cifs mounts can remove the default ACL when setting the
(non-default part of) the ACL and vice versa (we were leaving at 0
rather than setting to -1 the count field for the unaffected
half of the ACL.  For example notice the setfacl removed
the default ACL in this sequence:

steven@steven-GA-970A-DS3:~/cifs-2.6$ getfacl /mnt/test-dir ; setfacl
-m default:user:test:rwx,user:test:rwx /mnt/test-dir
getfacl: Removing leading '/' from absolute path names
user::rwx
group::r-x
other::r-x
default:user::rwx
default:user:test:rwx
default:group::r-x
default:mask::rwx
default:other::r-x

steven@steven-GA-970A-DS3:~/cifs-2.6$ getfacl /mnt/test-dir
getfacl: Removing leading '/' from absolute path names
user::rwx
user:test:rwx
group::r-x
mask::rwx
other::r-x

Change-Id: I841dc56c52341071bfe96ad1c1a7bd4a790b814c
Signed-off-by: Steve French <smfrench@gmail.com>
Acked-by: Jeremy Allison <jra@samba.org>
[bwh: Backported to 3.2: adjust context]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Rui Xiang <rui.xiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ecryptfs: Fix memory leakage in keystore.c

commit 3edc8376c06133e3386265a824869cad03a4efd4 upstream.

In 'decrypt_pki_encrypted_session_key' function:

Initializes 'payload' pointer and releases it on exit.

Change-Id: I929177a6077dad274dffe704a15858ad48d0c358
Signed-off-by: Geyslan G. Bem <geyslan@gmail.com>
Signed-off-by: Tyler Hicks <tyhicks@canonical.com>
[bwh: Backported to 3.2: adjust context]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Rui Xiang <rui.xiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

fs: cachefiles: add support for large files in filesystem caching

commit 98c350cda2c14a343d34ea01a3d9c24fea5ec66d upstream.

Support the caching of large files.

Addresses https://bugzilla.kernel.org/show_bug.cgi?id=31182

Change-Id: Ic6ed83758a35c10d566cf27b3bcf091812e14843
Signed-off-by: Justin Lecher <jlec@gentoo.org>
Signed-off-by: Suresh Jayaraman <sjayaraman@suse.com>
Tested-by: Suresh Jayaraman <sjayaraman@suse.com>
Acked-by: David Howells <dhowells@redhat.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
[bwh: Backported to 3.2:
 - Adjust context
 - dentry_open() takes dentry and vfsmount pointers, not a path pointer]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Rui Xiang <rui.xiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

tracing: Fix potential out-of-bounds in trace_get_user()

commit 057db8488b53d5e4faa0cedb2f39d4ae75dfbdbb upstream.

Andrey reported the following report:

ERROR: AddressSanitizer: heap-buffer-overflow on address ffff8800359c99f3
ffff8800359c99f3 is located 0 bytes to the right of 243-byte region [ffff8800359c9900, ffff8800359c99f3)
Accessed by thread T13003:
  #0 ffffffff810dd2da (asan_report_error+0x32a/0x440)
  #1 ffffffff810dc6b0 (asan_check_region+0x30/0x40)
  #2 ffffffff810dd4d3 (__tsan_write1+0x13/0x20)
  #3 ffffffff811cd19e (ftrace_regex_release+0x1be/0x260)
  #4 ffffffff812a1065 (__fput+0x155/0x360)
  #5 ffffffff812a12de (____fput+0x1e/0x30)
  #6 ffffffff8111708d (task_work_run+0x10d/0x140)
  #7 ffffffff810ea043 (do_exit+0x433/0x11f0)
  #8 ffffffff810eaee4 (do_group_exit+0x84/0x130)
  #9 ffffffff810eafb1 (SyS_exit_group+0x21/0x30)
  #10 ffffffff81928782 (system_call_fastpath+0x16/0x1b)

Allocated by thread T5167:
  #0 ffffffff810dc778 (asan_slab_alloc+0x48/0xc0)
  #1 ffffffff8128337c (__kmalloc+0xbc/0x500)
  #2 ffffffff811d9d54 (trace_parser_get_init+0x34/0x90)
  #3 ffffffff811cd7b3 (ftrace_regex_open+0x83/0x2e0)
  #4 ffffffff811cda7d (ftrace_filter_open+0x2d/0x40)
  #5 ffffffff8129b4ff (do_dentry_open+0x32f/0x430)
  #6 ffffffff8129b668 (finish_open+0x68/0xa0)
  #7 ffffffff812b66ac (do_last+0xb8c/0x1710)
  #8 ffffffff812b7350 (path_openat+0x120/0xb50)
  #9 ffffffff812b8884 (do_filp_open+0x54/0xb0)
  #10 ffffffff8129d36c (do_sys_open+0x1ac/0x2c0)
  #11 ffffffff8129d4b7 (SyS_open+0x37/0x50)
  #12 ffffffff81928782 (system_call_fastpath+0x16/0x1b)

Shadow bytes around the buggy address:
  ffff8800359c9700: fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd
  ffff8800359c9780: fd fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa
  ffff8800359c9800: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  ffff8800359c9880: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  ffff8800359c9900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>ffff8800359c9980: 00 00 00 00 00 00 00 00 00 00 00 00 00 00[03]fb
  ffff8800359c9a00: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  ffff8800359c9a80: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  ffff8800359c9b00: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  ffff8800359c9b80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ffff8800359c9c00: 00 00 00 00 00 00 00 00 fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap redzone:          fa
  Heap kmalloc redzone:  fb
  Freed heap region:     fd
  Shadow gap:            fe

The out-of-bounds access happens on 'parser->buffer[parser->idx] = 0;'

Although the crash happened in ftrace_regex_open() the real bug
occurred in trace_get_user() where there's an incrementation to
parser->idx without a check against the size. The way it is triggered
is if userspace sends in 128 characters (EVENT_BUF_SIZE + 1), the loop
that reads the last character stores it and then breaks out because
there is no more characters. Then the last character is read to determine
what to do next, and the index is incremented without checking size.

Then the caller of trace_get_user() usually nulls out the last character
with a zero, but since the index is equal to the size, it writes a nul
character after the allocated space, which can corrupt memory.

Luckily, only root user has write access to this file.

Link: http://lkml.kernel.org/r/20131009222323.04fd1a0d@gandalf.local.home

Change-Id: Ie1f6064c5ddac02680e1bf290067df72bb700899
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

clockevents: Sanitize ticks to nsec conversion

commit 97b9410643475d6557d2517c2aff9fd2221141a9 upstream.

Marc Kleine-Budde pointed out, that commit 77cc982 "clocksource: use
clockevents_config_and_register() where possible" caused a regression
for some of the converted subarchs.

The reason is, that the clockevents core code converts the minimal
hardware tick delta to a nanosecond value for core internal
usage. This conversion is affected by integer math rounding loss, so
the backwards conversion to hardware ticks will likely result in a
value which is less than the configured hardware limitation. The
affected subarchs used their own workaround (SIGH!) which got lost in
the conversion.

The solution for the issue at hand is simple: adding evt->mult - 1 to
the shifted value before the integer divison in the core conversion
function takes care of it. But this only works for the case where for
the scaled math mult/shift pair "mult <= 1 << shift" is true. For the
case where "mult > 1 << shift" we can apply the rounding add only for
the minimum delta value to make sure that the backward conversion is
not less than the given hardware limit. For the upper bound we need to
omit the rounding add, because the backwards conversion is always
larger than the original latch value. That would violate the upper
bound of the hardware device.

Though looking closer at the details of that function reveals another
bogosity: The upper bounds check is broken as well. Checking for a
resulting "clc" value greater than KTIME_MAX after the conversion is
pointless. The conversion does:

      u64 clc = (latch << evt->shift) / evt->mult;

So there is no sanity check for (latch << evt->shift) exceeding the
64bit boundary. The latch argument is "unsigned long", so on a 64bit
arch the handed in argument could easily lead to an unnoticed shift
overflow. With the above rounding fix applied the calculation before
the divison is:

       u64 clc = (latch << evt->shift) + evt->mult - 1;

So we need to make sure, that neither the shift nor the rounding add
is overflowing the u64 boundary.

[ukl: move assignment to rnd after eventually changing mult, fix build
 issue and correct comment with the right math]

Change-Id: Ib5c830ce9c4f2f2a3ded4f2f76e8a32a9683daee
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Cc: Russell King - ARM Linux <linux@arm.linux.org.uk>
Cc: Marc Kleine-Budde <mkl@pengutronix.de>
Cc: nicolas.ferre@atmel.com
Cc: Marc Pignat <marc.pignat@hevs.ch>
Cc: john.stultz@linaro.org
Cc: kernel@pengutronix.de
Cc: Ronald Wahl <ronald.wahl@raritan.com>
Cc: LAK <linux-arm-kernel@lists.infradead.org>
Cc: Ludovic Desroches <ludovic.desroches@atmel.com>
Link: http://lkml.kernel.org/r/1380052223-24139-1-git-send-email-u.kleine-koenig@pengutronix.de
Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

audit: printk USER_AVC messages when audit isn't enabled

commit 0868a5e150bc4c47e7a003367cd755811eb41e0b upstream.

When the audit=1 kernel parameter is absent and auditd is not running,
AUDIT_USER_AVC messages are being silently discarded.

AUDIT_USER_AVC messages should be sent to userspace using printk(), as
mentioned in the commit message of 4a4cd633 ("AUDIT: Optimise the
audit-disabled case for discarding user messages").

When audit_enabled is 0, audit_receive_msg() discards all user messages
except for AUDIT_USER_AVC messages. However, audit_log_common_recv_msg()
refuses to allocate an audit_buffer if audit_enabled is 0. The fix is to
special case AUDIT_USER_AVC messages in both functions.

It looks like commit 50397bd1 ("[AUDIT] clean up audit_receive_msg()")
introduced this bug.

Change-Id: I998faaf107fc1b6bcc09ca7a4f079b6ee4b5c549
Signed-off-by: Tyler Hicks <tyhicks@canonical.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Eric Paris <eparis@redhat.com>
Cc: linux-audit@redhat.com
Acked-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Richard Guy Briggs <rgb@redhat.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ftrace: Fix function graph with loading of modules

commit 8a56d7761d2d041ae5e8215d20b4167d8aa93f51 upstream.

Commit 8c4f3c3fa9681 "ftrace: Check module functions being traced on reload"
fixed module loading and unloading with respect to function tracing, but
it missed the function graph tracer. If you perform the following

 # cd /sys/kernel/debug/tracing
 # echo function_graph > current_tracer
 # modprobe nfsd
 # echo nop > current_tracer

You'll get the following oops message:

 ------------[ cut here ]------------
 WARNING: CPU: 2 PID: 2910 at /linux.git/kernel/trace/ftrace.c:1640 __ftrace_hash_rec_update.part.35+0x168/0x1b9()
 Modules linked in: nfsd exportfs nfs_acl lockd ipt_MASQUERADE sunrpc ip6t_REJECT nf_conntrack_ipv6 nf_defrag_ipv6 ip6table_filter ip6_tables uinput snd_hda_codec_idt
 CPU: 2 PID: 2910 Comm: bash Not tainted 3.13.0-rc1-test #7
 Hardware name: To Be Filled By O.E.M. To Be Filled By O.E.M./To be filled by O.E.M., BIOS SDBLI944.86P 05/08/2007
  0000000000000668 ffff8800787efcf8 ffffffff814fe193 ffff88007d500000
  0000000000000000 ffff8800787efd38 ffffffff8103b80a 0000000000000668
  ffffffff810b2b9a ffffffff81a48370 0000000000000001 ffff880037aea000
 Call Trace:
  [<ffffffff814fe193>] dump_stack+0x4f/0x7c
  [<ffffffff8103b80a>] warn_slowpath_common+0x81/0x9b
  [<ffffffff810b2b9a>] ? __ftrace_hash_rec_update.part.35+0x168/0x1b9
  [<ffffffff8103b83e>] warn_slowpath_null+0x1a/0x1c
  [<ffffffff810b2b9a>] __ftrace_hash_rec_update.part.35+0x168/0x1b9
  [<ffffffff81502f89>] ? __mutex_lock_slowpath+0x364/0x364
  [<ffffffff810b2cc2>] ftrace_shutdown+0xd7/0x12b
  [<ffffffff810b47f0>] unregister_ftrace_graph+0x49/0x78
  [<ffffffff810c4b30>] graph_trace_reset+0xe/0x10
  [<ffffffff810bf393>] tracing_set_tracer+0xa7/0x26a
  [<ffffffff810bf5e1>] tracing_set_trace_write+0x8b/0xbd
  [<ffffffff810c501c>] ? ftrace_return_to_handler+0xb2/0xde
  [<ffffffff811240a8>] ? __sb_end_write+0x5e/0x5e
  [<ffffffff81122aed>] vfs_write+0xab/0xf6
  [<ffffffff8150a185>] ftrace_graph_caller+0x85/0x85
  [<ffffffff81122dbd>] SyS_write+0x59/0x82
  [<ffffffff8150a185>] ftrace_graph_caller+0x85/0x85
  [<ffffffff8150a2d2>] system_call_fastpath+0x16/0x1b
 ---[ end trace 940358030751eafb ]---

The above mentioned commit didn't go far enough. Well, it covered the
function tracer by adding checks in __register_ftrace_function(). The
problem is that the function graph tracer circumvents that (for a slight
efficiency gain when function graph trace is running with a function
tracer. The gain was not worth this).

The problem came with ftrace_startup() which should always be called after
__register_ftrace_function(), if you want this bug to be completely fixed.

Anyway, this solution moves __register_ftrace_function() inside of
ftrace_startup() and removes the need to call them both.

Change-Id: I7333fc546109c8e110a96a550979b362b04a5b15
Reported-by: Dave Wysochanski <dwysocha@redhat.com>
Fixes: ed926f9b35cd ("ftrace: Use counters to enable functions to trace")
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

irq: Enable all irqs unconditionally in irq_resume

commit ac01810c9d2814238f08a227062e66a35a0e1ea2 upstream.

When the system enters suspend, it disables all interrupts in
suspend_device_irqs(), including the interrupts marked EARLY_RESUME.

On the resume side things are different. The EARLY_RESUME interrupts
are reenabled in sys_core_ops->resume and the non EARLY_RESUME
interrupts are reenabled in the normal system resume path.

When suspend_noirq() failed or suspend is aborted for any other
reason, we might omit the resume side call to sys_core_ops->resume()
and therefor the interrupts marked EARLY_RESUME are not reenabled and
stay disabled forever.

To solve this, enable all irqs unconditionally in irq_resume()
regardless whether interrupts marked EARLY_RESUMEhave been already
enabled or not.

This might try to reenable already enabled interrupts in the non
failure case, but the only affected platform is XEN and it has been
confirmed that it does not cause any side effects.

[ tglx: Massaged changelog. ]

Change-Id: If00a4529d9010f5b4e7d14ea29074d0be6a2fcb8
Signed-off-by: Laxman Dewangan <ldewangan@nvidia.com>
Acked-by-and-tested-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>
Acked-by: Heiko Stuebner <heiko@sntech.de>
Reviewed-by: Pavel Machek <pavel@ucw.cz>
Cc: <ian.campbell@citrix.com>
Cc: <rjw@rjwysocki.net>
Cc: <len.brown@intel.com>
Cc: <gregkh@linuxfoundation.org>
Link: http://lkml.kernel.org/r/1385388587-16442-1-git-send-email-ldewangan@nvidia.com
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

futex: fix handling of read-only-mapped hugepages

commit f12d5bfceb7e1f9051563381ec047f7f13956c3c upstream.

The hugepage code had the exact same bug that regular pages had in
commit 7485d0d3758e ("futexes: Remove rw parameter from
get_futex_key()").

The regular page case was fixed by commit 9ea71503a8ed ("futex: Fix
regression with read only mappings"), but the transparent hugepage case
(added in a5b338f2b0b1: "thp: update futex compound knowledge") case
remained broken.

Found by Dave Jones and his trinity tool.

Change-Id: I140b382327d83618befb43c6e8296b6911c83e8d
Reported-and-tested-by: Dave Jones <davej@fedoraproject.org>
Acked-by: Thomas Gleixner <tglx@linutronix.de>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Darren Hart <dvhart@linux.intel.com>
Cc: Andrea Arcangeli <aarcange@redhat.com>
Cc: Oleg Nesterov <oleg@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ftrace: Initialize the ftrace profiler for each possible cpu

commit c4602c1c818bd6626178d6d3fcc152d9f2f48ac0 upstream.

Ftrace currently initializes only the online CPUs. This implementation has
two problems:
- If we online a CPU after we enable the function profile, and then run the
  test, we will lose the trace information on that CPU.
  Steps to reproduce:
  # echo 0 > /sys/devices/system/cpu/cpu1/online
  # cd <debugfs>/tracing/
  # echo <some function name> >> set_ftrace_filter
  # echo 1 > function_profile_enabled
  # echo 1 > /sys/devices/system/cpu/cpu1/online
  # run test
- If we offline a CPU before we enable the function profile, we will not clear
  the trace information when we enable the function profile. It will trouble
  the users.
  Steps to reproduce:
  # cd <debugfs>/tracing/
  # echo <some function name> >> set_ftrace_filter
  # echo 1 > function_profile_enabled
  # run test
  # cat trace_stat/function*
  # echo 0 > /sys/devices/system/cpu/cpu1/online
  # echo 0 > function_profile_enabled
  # echo 1 > function_profile_enabled
  # cat trace_stat/function*
  # run test
  # cat trace_stat/function*

So it is better that we initialize the ftrace profiler for each possible cpu
every time we enable the function profile instead of just the online ones.

Link: http://lkml.kernel.org/r/1387178401-10619-1-git-send-email-miaox@cn.fujitsu.com

Change-Id: I2b4f22ccf8554d8d0fd9f2f4524f2c8948683aaa
Signed-off-by: Miao Xie <miaox@cn.fujitsu.com>
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

time: Fix overflow when HZ is smaller than 60

commit 80d767d770fd9c697e434fd080c2db7b5c60c6dd upstream.

When compiling for the IA-64 ski emulator, HZ is set to 32 because the
emulation is slow and we don't want to waste too many cycles processing
timers. Alpha also has an option to set HZ to 32.

This causes integer underflow in
kernel/time/jiffies.c:
kernel/time/jiffies.c:66:2: warning: large integer implicitly truncated to unsigned type [-Woverflow]
  .mult  = NSEC_PER_JIFFY << JIFFIES_SHIFT, /* details above */
  ^

This patch reduces the JIFFIES_SHIFT value to avoid the overflow.

Change-Id: I46216e6f4312a52d5dd9999f0e434451c6ead781
Signed-off-by: Mikulas Patocka <mikulas@artax.karlin.mff.cuni.cz>
Link: http://lkml.kernel.org/r/alpine.LRH.2.02.1401241639100.23871@file01.intranet.prod.int.rdu2.redhat.com
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ring-buffer: Fix first commit on sub-buffer having non-zero delta

commit d651aa1d68a2f0a7ee65697b04c6a92f8c0a12f2 upstream.

Each sub-buffer (buffer page) has a full 64 bit timestamp. The events on
that page use a 27 bit delta against that timestamp in order to save on
bits written to the ring buffer. If the time between events is larger than
what the 27 bits can hold, a "time extend" event is added to hold the
entire 64 bit timestamp again and the events after that hold a delta from
that timestamp.

As a "time extend" is always paired with an event, it is logical to just
allocate the event with the time extend, to make things a bit more efficient.

Unfortunately, when the pairing code was written, it removed the "delta = 0"
from the first commit on a page, causing the events on the page to be
slightly skewed.

Change-Id: Ifcae3a9bef8ad1ac7a60b634f279f6e464d3aaa1
Fixes: 69d1b839f7ee "ring-buffer: Bind time extend and data events together"
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

genirq: Add missing irq_to_desc export for CONFIG_SPARSE_IRQ=n

commit 2c45aada341121438affc4cb8d5b4cfaa2813d3d upstream.

In allmodconfig builds for sparc and any other arch which does
not set CONFIG_SPARSE_IRQ, the following will be seen at modpost:

  CC [M]  lib/cpu-notifier-error-inject.o
  CC [M]  lib/pm-notifier-error-inject.o
ERROR: "irq_to_desc" [drivers/gpio/gpio-mcp23s08.ko] undefined!
make[2]: *** [__modpost] Error 1

This happens because commit 3911ff30f5 ("genirq: export
handle_edge_irq() and irq_to_desc()") added one export for it, but
there were actually two instances of it, in an if/else clause for
CONFIG_SPARSE_IRQ.  Add the second one.

Change-Id: I4c51787e51343012a0779898bf6b64886ec6b1f0
Signed-off-by: Paul Gortmaker <paul.gortmaker@windriver.com>
Cc: Jiri Kosina <jkosina@suse.cz>
Link: http://lkml.kernel.org/r/1392057610-11514-1-git-send-email-paul.gortmaker@windriver.com
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

workqueue: ensure @task is valid across kthread_stop()

commit 5bdfff96c69a4d5ab9c49e60abf9e070ecd2acbb upstream.

When a kworker should die, the kworkre is notified through WORKER_DIE
flag instead of kthread_should_stop().  This, IIRC, is primarily to
keep the test synchronized inside worker_pool lock.  WORKER_DIE is
first set while holding pool->lock, the lock is dropped and
kthread_stop() is called.

Unfortunately, this means that there's a slight chance that the target
kworker may see WORKER_DIE before kthread_stop() finishes and exits
and frees the target task before or during kthread_stop().

Fix it by pinning the target task before setting WORKER_DIE and
putting it after kthread_stop() is done.

tj: Improved patch description and comment.  Moved pinning above
    WORKER_DIE for better signify what it's protecting.

Change-Id: I9069cd86ea2fac58450824d8282d0f31a711a4ea
Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
Signed-off-by: Tejun Heo <tj@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

perf: Fix hotplug splat

commit e3703f8cdfcf39c25c4338c3ad8e68891cca3731 upstream.

Drew Richardson reported that he could make the kernel go *boom* when hotplugging
while having perf events active.

It turned out that when you have a group event, the code in
__perf_event_exit_context() fails to remove the group siblings from
the context.

We then proceed with destroying and freeing the event, and when you
re-plug the CPU and try and add another event to that CPU, things go
*boom* because you've still got dead entries there.

Change-Id: Ib2f589725e0a43a3533b4131a60d0dad9623ed69
Reported-by: Drew Richardson <drew.richardson@arm.com>
Signed-off-by: Peter Zijlstra <peterz@infradead.org>
Cc: Will Deacon <will.deacon@arm.com>
Link: http://lkml.kernel.org/n/tip-k6v5wundvusvcseqj1si0oz0@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

cpuset: fix a race condition in __cpuset_node_allowed_softwall()

commit 99afb0fd5f05aac467ffa85c36778fec4396209b upstream.

It's not safe to access task's cpuset after releasing task_lock().
Holding callback_mutex won't help.

Change-Id: I544badf8137025bed00ad36e39745e72123252e9
Signed-off-by: Li Zefan <lizefan@huawei.com>
Signed-off-by: Tejun Heo <tj@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

audit: wait_for_auditd() should use TASK_UNINTERRUPTIBLE

commit f000cfdde5de4fc15dead5ccf524359c07eadf2b upstream.

audit_log_start() does wait_for_auditd() in a loop until
audit_backlog_wait_time passes or audit_skb_queue has a room.

If signal_pending() is true this becomes a busy-wait loop, schedule() in
TASK_INTERRUPTIBLE won't block.

Thanks to Guy for fully investigating and explaining the problem.

(akpm: that'll cause the system to lock up on a non-preemptible
uniprocessor kernel)

(Guy: "Our customer was in fact running a uniprocessor machine, and they
reported a system hang.")

Change-Id: I8b801d5001eeb1454f06cb7809fbdefa90575b78
Signed-off-by: Oleg Nesterov <oleg@redhat.com>
Reported-by: Guy Streeter <streeter@redhat.com>
Cc: Eric Paris <eparis@redhat.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
[bwh: Backported to 3.2: adjust context, indentation]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Qiang Huang <h.huangqiang@huawei.com>
Cc: Li Zefan <lizefan@huawei.com>
Cc: Jianguo Wu <wujianguo@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

workqueue: cond_resched() after processing each work item

commit b22ce2785d97423846206cceec4efee0c4afd980 upstream.

If !PREEMPT, a kworker running work items back to back can hog CPU.
This becomes dangerous when a self-requeueing work item which is
waiting for something to happen races against stop_machine.  Such
self-requeueing work item would requeue itself indefinitely hogging
the kworker and CPU it's running on while stop_machine would wait for
that CPU to enter stop_machine while preventing anything else from
happening on all other CPUs.  The two would deadlock.

Jamie Liu reports that this deadlock scenario exists around
scsi_requeue_run_queue() and libata port multiplier support, where one
port may exclude command processing from other ports.  With the right
timing, scsi_requeue_run_queue() can end up requeueing itself trying
to execute an IO which is asked to be retried while another device has
an exclusive access, which in turn can't make forward progress due to
stop_machine.

Fix it by invoking cond_resched() after executing each work item.

Change-Id: I6d4a6bb80363ccce04471bc2e2a5f403284c555e
Signed-off-by: Tejun Heo <tj@kernel.org>
Reported-by: Jamie Liu <jamieliu@google.com>
References: http://thread.gmane.org/gmane.linux.kernel/1552567
[bwh: Backported to 3.2: adjust context]
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Qiang Huang <h.huangqiang@huawei.com>
Cc: Li Zefan <lizefan@huawei.com>
Cc: Jianguo Wu <wujianguo@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

hung_task: check the value of "sysctl_hung_task_timeout_sec"

commit 80df28476505ed4e6701c3448c63c9229a50c655 upstream.

As sysctl_hung_task_timeout_sec is unsigned long, when this value is
larger then LONG_MAX/HZ, the function schedule_timeout_interruptible in
watchdog will return immediately without sleep and with print :

  schedule_timeout: wrong timeout value ffffffffffffff83

and then the funtion watchdog will call schedule_timeout_interruptible
again and again.  The screen will be filled with

	"schedule_timeout: wrong timeout value ffffffffffffff83"

This patch does some check and correction in sysctl, to let the function
schedule_timeout_interruptible allways get the valid parameter.

Change-Id: Ib0265eff85ec774ab3ee1991ba0b4667dcd3f429
Signed-off-by: Liu Hua <sdu.liu@huawei.com>
Tested-by: Satoru Takeuchi <satoru.takeuchi@gmail.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

hrtimer: Prevent all reprogramming if hang detected

commit 6c6c0d5a1c949d2e084706f9e5fb1fccc175b265 upstream.

If the last hrtimer interrupt detected a hang it sets hang_detected=1
and programs the clock event device with a delay to let the system
make progress.

If hang_detected == 1, we prevent reprogramming of the clock event
device in hrtimer_reprogram() but not in hrtimer_force_reprogram().

This can lead to the following situation:

hrtimer_interrupt()
   hang_detected = 1;
   program ce device to Xms from now (hang delay)

We have two timers pending:
   T1 expires 50ms from now
   T2 expires 5s from now

Now T1 gets canceled, which causes hrtimer_force_reprogram() to be
invoked, which in turn programs the clock event device to T2 (5
seconds from now).

Any hrtimer_start after that will not reprogram the hardware due to
hang_detected still being set. So we effectivly block all timers until
the T2 event fires and cleans up the hang situation.

Add a check for hang_detected to hrtimer_force_reprogram() which
prevents the reprogramming of the hang delay in the hardware
timer. The subsequent hrtimer_interrupt will resolve all outstanding
issues.

[ tglx: Rewrote subject and changelog and fixed up the comment in
  	hrtimer_force_reprogram() ]

Change-Id: I878e04f576d98e6f831a8de1f0ac55456aa5437c
Signed-off-by: Stuart Hayes <stuart.w.hayes@gmail.com>
Link: http://lkml.kernel.org/r/53602DC6.2060101@gmail.com
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

hrtimer: Prevent remote enqueue of leftmost timers

commit 012a45e3f4af68e86d85cce060c6c2fed56498b2 upstream.

If a cpu is idle and starts an hrtimer which is not pinned on that
same cpu, the nohz code might target the timer to a different cpu.

In the case that we switch the cpu base of the timer we already have a
sanity check in place, which determines whether the timer is earlier
than the current leftmost timer on the target cpu. In that case we
enqueue the timer on the current cpu because we cannot reprogram the
clock event device on the target.

If the timers base is already the target CPU we do not have this
sanity check in place so we enqueue the timer as the leftmost timer in
the target cpus rb tree, but we cannot reprogram the clock event
device on the target cpu. So the timer expires late and subsequently
prevents the reprogramming of the target cpu clock event device until
the previously programmed event fires or a timer with an earlier
expiry time gets enqueued on the target cpu itself.

Add the same target check as we have for the switch base case and
start the timer on the current cpu if it would become the leftmost
timer on the target.

[ tglx: Rewrote subject and changelog ]

Change-Id: I0af2c438ed0a1d3abc70c8e658b031d88f46734a
Signed-off-by: Leon Ma <xindong.ma@intel.com>
Link: http://lkml.kernel.org/r/1398847391-5994-1-git-send-email-xindong.ma@intel.com
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

hrtimer: Set expiry time before switch_hrtimer_base()

commit 84ea7fe37908254c3bd90910921f6e1045c1747a upstream.

switch_hrtimer_base() calls hrtimer_check_target() which ensures that
we do not migrate a timer to a remote cpu if the timer expires before
the current programmed expiry time on that remote cpu.

But __hrtimer_start_range_ns() calls switch_hrtimer_base() before the
new expiry time is set. So the sanity check in hrtimer_check_target()
is operating on stale or even uninitialized data.

Update expiry time before calling switch_hrtimer_base().

[ tglx: Rewrote changelog once again ]

Change-Id: I990dd5a69cd97fdfb4e6fc4425c9a169ab08ef71
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
Cc: linaro-kernel@lists.linaro.org
Cc: linaro-networking@linaro.org
Cc: fweisbec@gmail.com
Cc: arvind.chauhan@arm.com
Link: http://lkml.kernel.org/r/81999e148745fc51bbcd0615823fbab9b2e87e23.1399882253.git.viresh.kumar@linaro.org
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

perf: Fix error return code

commit c481420248c6730246d2a1b1773d5d7007ae0835 upstream.

Fix to return -ENOMEM in the allocation error case instead of 0
(if pmu_bus_running == 1), as done elsewhere in this function.

Signed-off-by: Wei Yongjun <yongjun_wei@trendmicro.com.cn>
Cc: a.p.zijlstra@chello.nl
Cc: paulus@samba.org
Cc: acme@ghostprotocols.net
Link: http://lkml.kernel.org/r/CAPgLHd8j_fWcgqe%3DKLWjpBj%2B%3Do0Pw6Z-SEq%3DNTPU08c2w1tngQ@mail.gmail.com
[ Tweaked the error code setting placement and the changelog. ]
Signed-off-by: Ingo Molnar <mingo@kernel.org>
Cc: Rui Xiang <rui.xiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

Change-Id: I5824fa3ad1de7001f39ea82c3830215a2edc5935

perf: Prevent false warning in perf_swevent_add

commit 39af6b1678afa5880dda7e375cf3f9d395087f6d upstream.

The perf cpu offline callback takes down all cpu context
events and releases swhash->swevent_hlist.

This could race with task context software event being just
scheduled on this cpu via perf_swevent_add while cpu hotplug
code already cleaned up event's data.

The race happens in the gap between the cpu notifier code
and the cpu being actually taken down. Note that only cpu
ctx events are terminated in the perf cpu hotplug code.

It's easily reproduced with:
  $ perf record -e faults perf bench sched pipe

while putting one of the cpus offline:
  # echo 0 > /sys/devices/system/cpu/cpu1/online

Console emits following warning:
  WARNING: CPU: 1 PID: 2845 at kernel/events/core.c:5672 perf_swevent_add+0x18d/0x1a0()
  Modules linked in:
  CPU: 1 PID: 2845 Comm: sched-pipe Tainted: G        W    3.14.0+ #256
  Hardware name: Intel Corporation Montevina platform/To be filled by O.E.M., BIOS AMVACRB1.86C.0066.B00.0805070703 05/07/2008
   0000000000000009 ffff880077233ab8 ffffffff81665a23 0000000000200005
   0000000000000000 ffff880077233af8 ffffffff8104732c 0000000000000046
   ffff88007467c800 0000000000000002 ffff88007a9cf2a0 0000000000000001
  Call Trace:
   [<ffffffff81665a23>] dump_stack+0x4f/0x7c
   [<ffffffff8104732c>] warn_slowpath_common+0x8c/0xc0
   [<ffffffff8104737a>] warn_slowpath_null+0x1a/0x20
   [<ffffffff8110fb3d>] perf_swevent_add+0x18d/0x1a0
   [<ffffffff811162ae>] event_sched_in.isra.75+0x9e/0x1f0
   [<ffffffff8111646a>] group_sched_in+0x6a/0x1f0
   [<ffffffff81083dd5>] ? sched_clock_local+0x25/0xa0
   [<ffffffff811167e6>] ctx_sched_in+0x1f6/0x450
   [<ffffffff8111757b>] perf_event_sched_in+0x6b/0xa0
   [<ffffffff81117a4b>] perf_event_context_sched_in+0x7b/0xc0
   [<ffffffff81117ece>] __perf_event_task_sched_in+0x43e/0x460
   [<ffffffff81096f1e>] ? put_lock_stats.isra.18+0xe/0x30
   [<ffffffff8107b3c8>] finish_task_switch+0xb8/0x100
   [<ffffffff8166a7de>] __schedule+0x30e/0xad0
   [<ffffffff81172dd2>] ? pipe_read+0x3e2/0x560
   [<ffffffff8166b45e>] ? preempt_schedule_irq+0x3e/0x70
   [<ffffffff8166b45e>] ? preempt_schedule_irq+0x3e/0x70
   [<ffffffff8166b464>] preempt_schedule_irq+0x44/0x70
   [<ffffffff816707f0>] retint_kernel+0x20/0x30
   [<ffffffff8109e60a>] ? lockdep_sys_exit+0x1a/0x90
   [<ffffffff812a4234>] lockdep_sys_exit_thunk+0x35/0x67
   [<ffffffff81679321>] ? sysret_check+0x5/0x56

Fixing this by tracking the cpu hotplug state and displaying
the WARN only if current cpu is initialized properly.

Change-Id: I8b1cccb38a599ce153cea842b796ccbe9bacc5e4
Cc: Corey Ashford <cjashfor@linux.vnet.ibm.com>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Ingo Molnar <mingo@kernel.org>
Cc: Paul Mackerras <paulus@samba.org>
Cc: Arnaldo Carvalho de Melo <acme@redhat.com>
Reported-by: Fengguang Wu <fengguang.wu@intel.com>
Signed-off-by: Jiri Olsa <jolsa@redhat.com>
Signed-off-by: Peter Zijlstra <peterz@infradead.org>
Link: http://lkml.kernel.org/r/1396861448-10097-1-git-send-email-jolsa@redhat.com
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

perf: Limit perf_event_attr::sample_period to 63 bits

commit 0819b2e30ccb93edf04876237b6205eef84ec8d2 upstream.

Vince reported that using a large sample_period (one with bit 63 set)
results in wreckage since while the sample_period is fundamentally
unsigned (negative periods don't make sense) the way we implement
things very much rely on signed logic.

So limit sample_period to 63 bits to avoid tripping over this.

Change-Id: I7f8041517dec6bfd8a80703b1c1ae30bcdcd5793
Reported-by: Vince Weaver <vincent.weaver@maine.edu>
Signed-off-by: Peter Zijlstra <peterz@infradead.org>
Link: http://lkml.kernel.org/n/tip-p25fhunibl4y3qi0zuqmyf4b@git.kernel.org
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm, show_mem: suppress page counts in non-blockable contexts

commit 4b59e6c4730978679b414a8da61514a2518da512 upstream.

On large systems with a lot of memory, walking all RAM to determine page
types may take a half second or even more.

In non-blockable contexts, the page allocator will emit a page allocation
failure warning unless __GFP_NOWARN is specified.  In such contexts, irqs
are typically disabled and such a lengthy delay may even result in NMI
watchdog timeouts.

To fix this, suppress the page walk in such contexts when printing the
page allocation failure warning.

Change-Id: Ib66a32bc4866a98075c4110fd33f0d77475526aa
Signed-off-by: David Rientjes <rientjes@google.com>
Cc: Mel Gorman <mgorman@suse.de>
Acked-by: Michal Hocko <mhocko@suse.cz>
Cc: Dave Hansen <dave@linux.vnet.ibm.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Xishi Qiu <qiuxishi@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

lib/scatterlist.c: don't flush_kernel_dcache_page on slab page

commit 3d77b50c5874b7e923be946ba793644f82336b75 upstream.

Commit b1adaf65ba03 ("[SCSI] block: add sg buffer copy helper
functions") introduces two sg buffer copy helpers, and calls
flush_kernel_dcache_page() on pages in SG list after these pages are
written to.

Unfortunately, the commit may introduce a potential bug:

 - Before sending some SCSI commands, kmalloc() buffer may be passed to
   block layper, so flush_kernel_dcache_page() can see a slab page
   finally

 - According to cachetlb.txt, flush_kernel_dcache_page() is only called
   on "a user page", which surely can't be a slab page.

 - ARCH's implementation of flush_kernel_dcache_page() may use page
   mapping information to do optimization so page_mapping() will see the
   slab page, then VM_BUG_ON() is triggered.

Aaro Koskinen reported the bug on ARM/kirkwood when DEBUG_VM is enabled,
and this patch fixes the bug by adding test of '!PageSlab(miter->page)'
before calling flush_kernel_dcache_page().

Change-Id: I336e2f3133d72f9069f7b0af3751b7571fda0b68
Signed-off-by: Ming Lei <ming.lei@canonical.com>
Reported-by: Aaro Koskinen <aaro.koskinen@iki.fi>
Tested-by: Simon Baatz <gmbnomis@gmail.com>
Cc: Russell King - ARM Linux <linux@arm.linux.org.uk>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Aaro Koskinen <aaro.koskinen@iki.fi>
Acked-by: Catalin Marinas <catalin.marinas@arm.com>
Cc: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Cc: Tejun Heo <tj@kernel.org>
Cc: "James E.J. Bottomley" <JBottomley@parallels.com>
Cc: Jens Axboe <axboe@kernel.dk>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

random32: fix off-by-one in seeding requirement

[ Upstream commit 51c37a70aaa3f95773af560e6db3073520513912 ]

For properly initialising the Tausworthe generator [1], we have
a strict seeding requirement, that is, s1 > 1, s2 > 7, s3 > 15.

Commit 697f8d0348 ("random32: seeding improvement") introduced
a __seed() function that imposes boundary checks proposed by the
errata paper [2] to properly ensure above conditions.

However, we're off by one, as the function is implemented as:
"return (x < m) ? x + m : x;", and called with __seed(X, 1),
__seed(X, 7), __seed(X, 15). Thus, an unwanted seed of 1, 7, 15
would be possible, whereas the lower boundary should actually
be of at least 2, 8, 16, just as GSL does. Fix this, as otherwise
an initialization with an unwanted seed could have the effect
that Tausworthe's PRNG properties cannot not be ensured.

Note that this PRNG is *not* used for cryptography in the kernel.

 [1] http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps
 [2] http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps

Joint work with Hannes Frederic Sowa.

Change-Id: I53ee85d2fd2f8503b09fa2cce623e6e24fbda2c2
Fixes: 697f8d0348a6 ("random32: seeding improvement")
Cc: Stephen Hemminger <stephen@networkplumber.org>
Cc: Florian Weimer <fweimer@redhat.com>
Cc: Theodore Ts'o <tytso@mit.edu>
Signed-off-by: Daniel Borkmann <dborkman@redhat.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

lib/vsprintf.c: kptr_restrict: fix pK-error in SysRq show-all-timers(Q)

commit 3715c5309f6d175c3053672b73fd4f73be16fd07 upstream.

When using ALT+SysRq+Q all the pointers are replaced with "pK-error" like
this:

	[23153.208033]   .base:               pK-error

with echo h > /proc/sysrq-trigger it works:

	[23107.776363]   .base:       ffff88023e60d540

The intent behind this behavior was to return "pK-error" in cases where
the %pK format specifier was used in interrupt context, because the
CAP_SYSLOG check wouldn't be meaningful.  Clearly this should only apply
when kptr_restrict is actually enabled though.

Change-Id: I3c4ae4c589bcaad2a884696ac4b3831d178e0ee8
Reported-by: Stevie Trujillo <stevie.trujillo@gmail.com>
Signed-off-by: Dan Rosenberg <dan.j.rosenberg@gmail.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Li Zefan <lizefan@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

netlink: don't compare the nul-termination in nla_strcmp

[ Upstream commit 8b7b932434f5eee495b91a2804f5b64ebb2bc835 ]

nla_strcmp compares the string length plus one, so it's implicitly
including the nul-termination in the comparison.

 int nla_strcmp(const struct nlattr *nla, const char *str)
 {
        int len = strlen(str) + 1;
        ...
                d = memcmp(nla_data(nla), str, len);

However, if NLA_STRING is used, userspace can send us a string without
the nul-termination. This is a problem since the string
comparison will not match as the last byte may be not the
nul-termination.

Fix this by skipping the comparison of the nul-termination if the
attribute data is nul-terminated. Suggested by Thomas Graf.

Change-Id: I880183f7bf15d1c7aee9acc682f393744ffd399a
Cc: Florian Westphal <fw@strlen.de>
Cc: Thomas Graf <tgraf@suug.ch>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm, memcg: give exiting processes access to memory reserves

commit 465adcf1ea7b2e49b2e0899366624f5532b64012

A memcg may livelock when oom if the process that grabs the hierarchy's
oom lock is never the first process with PF_EXITING set in the memcg's
task iteration.

The oom killer, both global and memcg, will defer if it finds an
eligible process that is in the process of exiting and it is not being
ptraced.  The idea is to allow it to exit without using memory reserves
before needlessly killing another process.

This normally works fine except in the memcg case with a large number of
threads attached to the oom memcg.  In this case, the memcg oom killer
only gets called for the process that grabs the hierarchy's oom lock;
all others end up blocked on the memcg's oom waitqueue.  Thus, if the
process that grabs the hierarchy's oom lock is never the first
PF_EXITING process in the memcg's task iteration, the oom killer is
constantly deferred without anything making progress.

The fix is to give PF_EXITING processes access to memory reserves so
that we've marked them as oom killed without any iteration.  This allows
__mem_cgroup_try_charge() to succeed so that the process may exit.  This
makes the memcg oom killer exemption for TIF_MEMDIE tasks, now
immediately granted for processes with pending SIGKILLs and those in the
exit path, to be equivalent to what is done for the global oom killer.

Change-Id: I89654fb52732351fa09a9098a0f93761f4ab82e5
Signed-off-by: David Rientjes <rientjes@google.com>
Acked-by: Michal Hocko <mhocko@suse.cz>
Acked-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Acked-by: Johannes Weiner <hannes@cmpxchg.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
[Qiang: backported to 3.4:
 - move the changes from memcontrol.c to oom_kill.c]
Signed-off-by: Qiang Huang <h.huangqiang@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm/mmap: check for RLIMIT_AS before unmapping

commit e8420a8ece80b3fe810415ecf061d54ca7fab266 upstream.

Fix a corner case for MAP_FIXED when requested mapping length is larger
than rlimit for virtual memory.  In such case any overlapping mappings
are unmapped before we check for the limit and return ENOMEM.

The check is moved before the loop that unmaps overlapping parts of
existing mappings.  When we are about to hit the limit (currently mapped
pages + len > limit) we scan for overlapping pages and check again
accounting for them.

This fixes situation when userspace program expects that the previous
mappings are preserved after the mmap() syscall has returned with error.
(POSIX clearly states that successfull mapping shall replace any
previous mappings.)

This corner case was found and can be tested with LTP testcase:

testcases/open_posix_testsuite/conformance/interfaces/mmap/24-2.c

In this case the mmap, which is clearly over current limit, unmaps
dynamic libraries and the testcase segfaults right after returning into
userspace.

I've also looked at the second instance of the unmapping loop in the
do_brk().  The do_brk() is called from brk() syscall and from vm_brk().
The brk() syscall checks for overlapping mappings and bails out when
there are any (so it can't be triggered from the brk syscall).  The
vm_brk() is called only from binmft handlers so it shouldn't be
triggered unless binmft handler created overlapping mappings.

Change-Id: Ia867eeffe494e3b7b0457592c0681596c561d779
Signed-off-by: Cyril Hrubis <chrubis@suse.cz>
Reviewed-by: Mel Gorman <mgorman@suse.de>
Reviewed-by: Wanpeng Li <liwanp@linux.vnet.ibm.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Xishi Qiu <qiuxishi@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: fix aio performance regression for database caused by THP

commit 7cb2ef56e6a8b7b368b2e883a0a47d02fed66911 upstream.

I am working with a tool that simulates oracle database I/O workload.
This tool (orion to be specific -
<http://docs.oracle.com/cd/E11882_01/server.112/e16638/iodesign.htm#autoId24>)
allocates hugetlbfs pages using shmget() with SHM_HUGETLB flag.  It then
does aio into these pages from flash disks using various common block
sizes used by database.  I am looking at performance with two of the most
common block sizes - 1M and 64K.  aio performance with these two block
sizes plunged after Transparent HugePages was introduced in the kernel.
Here are performance numbers:

		pre-THP		2.6.39		3.11-rc5
1M read		8384 MB/s	5629 MB/s	6501 MB/s
64K read	7867 MB/s	4576 MB/s	4251 MB/s

I have narrowed the performance impact down to the overheads introduced by
THP in __get_page_tail() and put_compound_page() routines.  perf top shows
>40% of cycles being spent in these two routines.  Every time direct I/O
to hugetlbfs pages starts, kernel calls get_page() to grab a reference to
the pages and calls put_page() when I/O completes to put the reference
away.  THP introduced significant amount of locking overhead to get_page()
and put_page() when dealing with compound pages because hugepages can be
split underneath get_page() and put_page().  It added this overhead
irrespective of whether it is dealing with hugetlbfs pages or transparent
hugepages.  This resulted in 20%-45% drop in aio performance when using
hugetlbfs pages.

Since hugetlbfs pages can not be split, there is no reason to go through
all the locking overhead for these pages from what I can see.  I added
code to __get_page_tail() and put_compound_page() to bypass all the
locking code when working with hugetlbfs pages.  This improved performance
significantly.  Performance numbers with this patch:

		pre-THP		3.11-rc5	3.11-rc5 + Patch
1M read		8384 MB/s	6501 MB/s	8371 MB/s
64K read	7867 MB/s	4251 MB/s	6510 MB/s

Performance with 64K read is still lower than what it was before THP, but
still a 53% improvement.  It does mean there is more work to be done but I
will take a 53% improvement for now.

Please take a look at the following patch and let me know if it looks
reasonable.

[akpm@linux-foundation.org: tweak comments]
Signed-off-by: Khalid Aziz <khalid.aziz@oracle.com>
Cc: Pravin B Shelar <pshelar@nicira.com>
Cc: Christoph Lameter <cl@linux.com>
Cc: Andrea Arcangeli <aarcange@redhat.com>
Cc: Johannes Weiner <hannes@cmpxchg.org>
Cc: Mel Gorman <mel@csn.ul.ie>
Cc: Rik van Riel <riel@redhat.com>
Cc: Minchan Kim <minchan@kernel.org>
Cc: Andi Kleen <andi@firstfloor.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

Change-Id: I7464bfe3b75e191a1f9126aedd02ed361f323ead

mm/hugetlb: check for pte NULL pointer in __page_check_address()

commit 98398c32f6687ee1e1f3ae084effb4b75adb0747 upstream.

In __page_check_address(), if address's pud is not present,
huge_pte_offset() will return NULL, we should check the return value.

Change-Id: Iccdbb94ae45bb5118fd557bf3eea3101e06400e2
Signed-off-by: Jianguo Wu <wujianguo@huawei.com>
Cc: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Cc: Mel Gorman <mgorman@suse.de>
Cc: qiuxishi <qiuxishi@huawei.com>
Cc: Hanjun Guo <guohanjun@huawei.com>
Acked-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm/memory-failure.c: recheck PageHuge() after hugetlb page migrate successfully

commit a49ecbcd7b0d5a1cda7d60e03df402dd0ef76ac8 upstream.

After a successful hugetlb page migration by soft offline, the source
page will either be freed into hugepage_freelists or buddy(over-commit
page).  If page is in buddy, page_hstate(page) will be NULL.  It will
hit a NULL pointer dereference in dequeue_hwpoisoned_huge_page().

  BUG: unable to handle kernel NULL pointer dereference at 0000000000000058
  IP: [<ffffffff81163761>] dequeue_hwpoisoned_huge_page+0x131/0x1d0
  PGD c23762067 PUD c24be2067 PMD 0
  Oops: 0000 [#1] SMP

So check PageHuge(page) after call migrate_pages() successfully.

[wujg: backport to 3.4:
 - adjust context
 - s/num_poisoned_pages/mce_bad_pages/]

Change-Id: Ica3d39b8b37519135a92784caf4ea344b7c1b900
Signed-off-by: Jianguo Wu <wujianguo@huawei.com>
Tested-by: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Reviewed-by: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: __set_page_dirty_nobuffers() uses spin_lock_irqsave() instead of spin_lock_irq()

commit a85d9df1ea1d23682a0ed1e100e6965006595d06 upstream.

During aio stress test, we observed the following lockdep warning.  This
mean AIO+numa_balancing is currently deadlockable.

The problem is, aio_migratepage disable interrupt, but
__set_page_dirty_nobuffers unintentionally enable it again.

Generally, all helper function should use spin_lock_irqsave() instead of
spin_lock_irq() because they don't know caller at all.

   other info that might help us debug this:
    Possible unsafe locking scenario:

          CPU0
          ----
     lock(&(&ctx->completion_lock)->rlock);
     <Interrupt>
       lock(&(&ctx->completion_lock)->rlock);

    *** DEADLOCK ***

      dump_stack+0x19/0x1b
      print_usage_bug+0x1f7/0x208
      mark_lock+0x21d/0x2a0
      mark_held_locks+0xb9/0x140
      trace_hardirqs_on_caller+0x105/0x1d0
      trace_hardirqs_on+0xd/0x10
      _raw_spin_unlock_irq+0x2c/0x50
      __set_page_dirty_nobuffers+0x8c/0xf0
      migrate_page_copy+0x434/0x540
      aio_migratepage+0xb1/0x140
      move_to_new_page+0x7d/0x230
      migrate_pages+0x5e5/0x700
      migrate_misplaced_page+0xbc/0xf0
      do_numa_page+0x102/0x190
      handle_pte_fault+0x241/0x970
      handle_mm_fault+0x265/0x370
      __do_page_fault+0x172/0x5a0
      do_page_fault+0x1a/0x70
      page_fault+0x28/0x30

Change-Id: I558f8127adcfbd3351a209528f129ede66f9317b
Signed-off-by: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com>
Cc: Larry Woodman <lwoodman@redhat.com>
Cc: Rik van Riel <riel@redhat.com>
Cc: Johannes Weiner <jweiner@redhat.com>
Acked-by: David Rientjes <rientjes@google.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: hugetlb: fix softlockup when a large number of hugepages are freed.

commit 55f67141a8927b2be3e51840da37b8a2320143ed upstream.

When I decrease the value of nr_hugepage in procfs a lot, softlockup
happens.  It is because there is no chance of context switch during this
process.

On the other hand, when I allocate a large number of hugepages, there is
some chance of context switch.  Hence softlockup doesn't happen during
this process.  So it's necessary to add the context switch in the
freeing process as same as allocating process to avoid softlockup.

When I freed 12 TB hugapages with kernel-2.6.32-358.el6, the freeing
process occupied a CPU over 150 seconds and following softlockup message
appeared twice or more.

$ echo 6000000 > /proc/sys/vm/nr_hugepages
$ cat /proc/sys/vm/nr_hugepages
6000000
$ grep ^Huge /proc/meminfo
HugePages_Total:   6000000
HugePages_Free:    6000000
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
$ echo 0 > /proc/sys/vm/nr_hugepages

BUG: soft lockup - CPU#16 stuck for 67s! [sh:12883] ...
Pid: 12883, comm: sh Not tainted 2.6.32-358.el6.x86_64 #1
Call Trace:
  free_pool_huge_page+0xb8/0xd0
  set_max_huge_pages+0x128/0x190
  hugetlb_sysctl_handler_common+0x113/0x140
  hugetlb_sysctl_handler+0x1e/0x20
  proc_sys_call_handler+0x97/0xd0
  proc_sys_write+0x14/0x20
  vfs_write+0xb8/0x1a0
  sys_write+0x51/0x90
  __audit_syscall_exit+0x265/0x290
  system_call_fastpath+0x16/0x1b

I have not confirmed this problem with upstream kernels because I am not
able to prepare the machine equipped with 12TB memory now.  However I
confirmed that the amount of decreasing hugepages was directly
proportional to the amount of required time.

I measured required times on a smaller machine.  It showed 130-145
hugepages decreased in a millisecond.

  Amount of decreasing     Required time      Decreasing rate
  hugepages                     (msec)         (pages/msec)
  ------------------------------------------------------------
  10,000 pages == 20GB         70 -  74          135-142
  30,000 pages == 60GB        208 - 229          131-144

It means decrement of 6TB hugepages will trigger softlockup with the
default threshold 20sec, in this decreasing rate.

Change-Id: Ib8ba54649813e9f12e976dfdf85f49ad8a3d78b7
Signed-off-by: Masayoshi Mizuma <m.mizuma@jp.fujitsu.com>
Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com>
Cc: Michal Hocko <mhocko@suse.cz>
Cc: Wanpeng Li <liwanp@linux.vnet.ibm.com>
Cc: Aneesh Kumar <aneesh.kumar@linux.vnet.ibm.com>
Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com>
Cc: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm/hugetlb.c: add cond_resched_lock() in return_unused_surplus_pages()

commit 7848a4bf51b34f41fcc9bd77e837126d99ae84e3 upstream.

soft lockup in freeing gigantic hugepage fixed in commit 55f67141a892 "mm:
hugetlb: fix softlockup when a large number of hugepages are freed." can
happen in return_unused_surplus_pages(), so let's fix it.

Change-Id: Ied9740ef1deae7f3581b173c233a96c47e4b67aa
Signed-off-by: Masayoshi Mizuma <m.mizuma@jp.fujitsu.com>
Signed-off-by: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com>
Cc: Michal Hocko <mhocko@suse.cz>
Cc: Aneesh Kumar <aneesh.kumar@linux.vnet.ibm.com>
Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: make fixup_user_fault() check the vma access rights too

commit 1b17844b29ae042576bea588164f2f1e9590a8bc upstream.

fixup_user_fault() is used by the futex code when the direct user access
fails, and the futex code wants it to either map in the page in a usable
form or return an error.  It relied on handle_mm_fault() to map the
page, and correctly checked the error return from that, but while that
does map the page, it doesn't actually guarantee that the page will be
mapped with sufficient permissions to be then accessed.

So do the appropriate tests of the vma access rights by hand.

[ Side note: arguably handle_mm_fault() could just do that itself, but
  we have traditionally done it in the caller, because some callers -
  notably get_user_pages() - have been able to access pages even when
  they are mapped with PROT_NONE.  Maybe we should re-visit that design
  decision, but in the meantime this is the minimal patch. ]

Found by Dave Jones running his trinity tool.

Change-Id: I5239eec9d326b42838217ae5263b5941f5cb902f
Reported-by: Dave Jones <davej@redhat.com>
Acked-by: Hugh Dickins <hughd@google.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

hwpoison, hugetlb: lock_page/unlock_page does not match for handling a free hugepage

commit b985194c8c0a130ed155b71662e39f7eaea4876f upstream.

For handling a free hugepage in memory failure, the race will happen if
another thread hwpoisoned this hugepage concurrently.  So we need to
check PageHWPoison instead of !PageHWPoison.

If hwpoison_filter(p) returns true or a race happens, then we need to
unlock_page(hpage).

Change-Id: Ida3dfdda08b4bddde0d3b2de6b97447a28f67872
Signed-off-by: Chen Yucong <slaoub@gmail.com>
Reviewed-by: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Tested-by: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Reviewed-by: Andi Kleen <ak@linux.intel.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

percpu: make pcpu_alloc_chunk() use pcpu_mem_free() instead of kfree()

commit 5a838c3b60e3a36ade764cf7751b8f17d7c9c2da upstream.

pcpu_chunk_struct_size = sizeof(struct pcpu_chunk) +
	BITS_TO_LONGS(pcpu_unit_pages) * sizeof(unsigned long)

It hardly could be ever bigger than PAGE_SIZE even for large-scale machine,
but for consistency with its couterpart pcpu_mem_zalloc(),
use pcpu_mem_free() instead.

Commit b4916cb17c26 ("percpu: make pcpu_free_chunk() use
pcpu_mem_free() instead of kfree()") addressed this problem, but
missed this one.

tj: commit message updated

Change-Id: I68eab9b10ca9a7c124e439738f2caa0b9b731d3a
Signed-off-by: Jianyu Zhan <nasa4836@gmail.com>
Signed-off-by: Tejun Heo <tj@kernel.org>
Fixes: 099a19d91ca4 ("percpu: allow limited allocation before slab is online)
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm/memory-failure.c: fix memory leak by race between poison and unpoison

commit 3e030ecc0fc7de10fd0da10c1c19939872a31717 upstream.

When a memory error happens on an in-use page or (free and in-use)
hugepage, the victim page is isolated with its refcount set to one.

When you try to unpoison it later, unpoison_memory() calls put_page()
for it twice in order to bring the page back to free page pool (buddy or
free hugepage list).  However, if another memory error occurs on the
page which we are unpoisoning, memory_failure() returns without
releasing the refcount which was incremented in the same call at first,
which results in memory leak and unconsistent num_poisoned_pages
statistics.  This patch fixes it.

Change-Id: I602bba7baf95fdb434a2583386797153246428c2
Signed-off-by: Naoya Horiguchi <n-horiguchi@ah.jp.nec.com>
Cc: Andi Kleen <andi@firstfloor.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: rmap: fix use-after-free in __put_anon_vma

commit 624483f3ea82598ab0f62f1bdb9177f531ab1892 upstream.

While working address sanitizer for kernel I've discovered
use-after-free bug in __put_anon_vma.

For the last anon_vma, anon_vma->root freed before child anon_vma.
Later in anon_vma_free(anon_vma) we are referencing to already freed
anon_vma->root to check rwsem.

This fixes it by freeing the child anon_vma before freeing
anon_vma->root.

Change-Id: If060d03e163664e8a59ad73179c1e06a779c1477
Signed-off-by: Andrey Ryabinin <a.ryabinin@samsung.com>
Acked-by: Peter Zijlstra <peterz@infradead.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: add kmap_to_page()

commit fcb8996728fb59eddf84678df7cb213b2c9a2e26 upstream.

This is extracted from Mel Gorman's commit 5a178119b0fb ('mm: add
support for direct_IO to highmem pages') upstream.

Required to backport commit b9cdc88df8e6 ('virtio: 9p: correctly pass
physical address to userspace for high pages').

Change-Id: I5bf05e84f7588df4090bf3432488df148b71a484
Cc: Mel Gorman <mgorman@suse.de>
Cc: Rik van Riel <riel@redhat.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Yijing Wang <wangyijing@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: highmem: export kmap_to_page for modules

commit f0263d2d222e9e25f2587e51a9dc58c6fb2a9352 upstream.

Some virtio device drivers (9p) need to translate high virtual addresses
to physical addresses, which are inserted into the virtqueue for
processing by userspace.

This patch exports the kmap_to_page symbol, so that the affected drivers
can be compiled as modules.

Change-Id: Iaf3f951927147dc02d3dd76798052c22a3f2a307
Signed-off-by: Will Deacon <will.deacon@arm.com>
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Cc: Yijing Wang <wangyijing@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

mm: highmem: don't treat PKMAP_ADDR(LAST_PKMAP) as a highmem address

commit 498c2280212327858e521e9d21345d4cc2637f54 upstream.

kmap_to_page returns the corresponding struct page for a virtual address
of an arbitrary mapping.  This works by checking whether the address
falls in the pkmap region and using the pkmap page tables instead of the
linear mapping if appropriate.

Unfortunately, the bounds checking means that PKMAP_ADDR(LAST_PKMAP) is
incorrectly treated as a highmem address and we can end up walking off
the end of pkmap_page_table and subsequently passing junk to pte_page.

This patch fixes the bound check to stay within the pkmap tables.

Change-Id: I4d834b2d26db08801b7584cb6023cd04489e8cdc
Signed-off-by: Will Deacon <will.deacon@arm.com>
Cc: Mel Gorman <mgorman@suse.de>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Yijing Wang <wangyijing@huawei.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

cpufreq: add input-cfboost

Add a module which can be used alongside any cpufreq governor to
temporarily raise CPU frequency upon input events.

Change-Id: Id0c69e5c7194c0e27ec176787cdc076b461d749e
Signed-off-by: Michal Pecio <mpecio@nvidia.com>
Reviewed-on: http://git-master/r/122180
Reviewed-by: Satya Popuri <spopuri@nvidia.com>
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

input-cfboost: improve boost latency

Place a request for one online CPU core to eliminate a 70ms delay before
transition to the G-core on Tegra3.

Change-Id: Ie81f37c0b85a574d9f1432c67818bdd4c3436c9b
Signed-off-by: Michal Pecio <mpecio@nvidia.com>
Reviewed-on: http://git-master/r/122188
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

input-cfboost: monitor keypad & joystick events

Add signatures of keypad & joystick devices to id table so
as to provide cpu boost for events from those devices.

Bug 1229219

Change-Id: If5e9f2669e437808e26a66bb9cd8b4cbfe97c286
Signed-off-by: Yogish Kulkarni <yogishk@nvidia.com>
Reviewed-on: http://git-master/r/197968
Reviewed-by: Automatic_Commit_Validation_User
GVS: Gerrit_Virtual_Submit
Reviewed-by: Bharat Nihalani <bnihalani@nvidia.com>

input: cfboost:Fix for kernel compatibility

Change-Id: I75139e710c6ab8caa6c240483d544cf924a83c92

input-cfboost: add trace points

Add trace points to log time stamp when the input event is received
and time at which boost work is scheduled. This is for detailed
profiling of touch latency.

Bug 1229219

Change-Id: I5f2f4f3d821d93b550fa9f86dc8fd562fa5d460a
Signed-off-by: Yogish Kulkarni <yogishk@nvidia.com>
Reviewed-on: http://git-master/r/197954
Reviewed-by: Riham Haidar <rhaidar@nvidia.com>
Tested-by: Riham Haidar <rhaidar@nvidia.com>

input: cfboost: Add module parameter callback

Cancel PM QoS request upon frequency changing to zero.

Change-Id: I77c0a488e0baa896b9b7382bad46101324dc8491

PM QoS: Simplify PM QoS expansion/merge

- Replace class ID #define with enumeration
- Loop through PM QoS objects during initialization (rather than
  initializing them one-by-one)

Change-Id: I185b700b52c752c62e7550fe739adc498fc989ef
Signed-off-by: Alex Frid <afrid@nvidia.com>
Reviewed-on: http://git-master/r/70603
Reviewed-by: Automatic_Commit_Validation_User
Reviewed-by: Antti Miettinen <amiettinen@nvidia.com>
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>
Reviewed-by: Scott Williams <scwilliams@nvidia.com>
Reviewed-by: Yu-Huan Hsu <yhsu@nvidia.com>

PM QoS: Add max online cpus as PM QoS parameter

Bug 894200

Change-Id: Ieb009a13c6ef9bca2388e234eb973d65a4e3a58b
Signed-off-by: Alex Frid <afrid@nvidia.com>
Reviewed-on: http://git-master/r/71034
Reviewed-by: Rohan Somvanshi <rsomvanshi@nvidia.com>
Tested-by: Rohan Somvanshi <rsomvanshi@nvidia.com>

PM QoS: Add CPU frequency min/max as PM QoS params

Add minimum and maximum CPU frequency as PM QoS parameters.

Bug 888312

Change-Id: I18abddded35a044a6ad8365035e31d1a2213a329
Reviewed-on: http://git-master/r/72206
Signed-off-by: Antti P Miettinen <amiettinen@nvidia.com>
Signed-off-by: Varun Wadekar <vwadekar@nvidia.com>
Reviewed-on: http://git-master/r/75883
Reviewed-by: Automatic_Commit_Validation_User

PM Qos: Add min online cpus as PM QoS parameter

Bug 940061

Change-Id: Ibae842fdc3af3c92ec7e6125c602417110d8b55e
Signed-off-by: Gaurav Sarode <gsarode@nvidia.com>
Reviewed-on: http://git-master/r/84521
Reviewed-by: Sachin Nikam <snikam@nvidia.com>
Tested-by: Aleksandr Frid <afrid@nvidia.com>
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

cpufreq: Enforce PM QoS min/max limits

Observe PM QoS CPU frequency minimum and maximum in addition
to policy settings.

Bug 888312

Change-Id: Ia4f60a1649a9952e02f6847c8add3b2ea5d47524
Reviewed-on: http://git-master/r/72207
Signed-off-by: Antti P Miettinen <amiettinen@nvidia.com>
Signed-off-by: Varun Wadekar <vwadekar@nvidia.com>
Reviewed-on: http://git-master/r/75884
Reviewed-by: Automatic_Commit_Validation_User

Enable input-cfboost

cpufreq: ondemand: Prevent sysfs create race

Protecting sysfs_remove_group() in CPUFREQ_GOV_STOP with dbs_mutex

Bug 946462

Signed-off-by: Peter Boonstoppel <pboonstoppel@nvidia.com>
Reviewed-on: http://git-master/r/86426
(cherry picked from commit d1131158e2ad4d5ccc53b3008743c29385650d86)

Change-Id: Iae810e83eaa6f0f7d970b56238cbcb61118af610
Reviewed-on: http://git-master/r/87392
Reviewed-by: Peter Boonstoppel <pboonstoppel@nvidia.com>
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>
Tested-by: Peter Boonstoppel <pboonstoppel@nvidia.com>

Kill LG debugging chat

Revert "cgroup: Add generic cgroup subsystem permission checks."

This reverts commit 1d38bc7d0523af2233b4280e2aeab34c6a076665.

Change-Id: I2c5066b696cbdd5ca117ed74718bcb7e70e878e7
Signed-off-by: Colin Cross <ccross@android.com>

cpu-hotplug: CPUx should be active before it is marked online

CPU0		CPUn

_cpu_up()
  __cpu_up()

		boostrap()
		  notify_cpu_starting()
		  set_cpu_online()
		  while (!cpu_active())
		    cpu_relax()

<PREEMPT-out>

smp_call_function(.wait=1)
  /* we find cpu_online() is true */
  arch_send_call_function_ipi_mask()
  /* wait-forever-more */
<PREEMPT-in>
		  local_irq_enable()

  cpu_notify(CPU_ONLINE)
    sched_cpu_active()
      set_cpu_active()

Now the purpose of cpu_active is mostly with bringing down a cpu, where
we mark it !active to avoid the load-balancer from moving tasks to it
while we tear down the cpu. This is required because we only update the
sched_domain tree after we brought the cpu-down. And this is needed so
that some tasks can still run while we bring it down, we just don't want
new tasks to appear.

On cpu-up however the sched_domain tree doesn't yet include the new cpu,
so its invisible to the load-balancer, regardless of the active state.
So instead of setting the active state after we boot the new cpu (and
consequently having to wait for it before enabling interrupts) set the
cpu active before we set it online and avoid the whole mess.

Bug 916986

Original Patch: https://lkml.org/lkml/2011/12/15/255

Change-Id: Ia1c07bdc1b3eb07a7cd4d69756fa7bec509c9400
Reported-by: Stepan Moskovchenko <stepanm@codeaurora.org>
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Signed-off-by: Varun Wadekar <vwadekar@nvidia.com>
Reviewed-on: http://git-master/r/72130
Reviewed-by: Automatic_Commit_Validation_User
Reviewed-by: Mayuresh Kulkarni <mkulkarni@nvidia.com>

scheduler: domain: init next_balance in nohz_idle_balancer with jiffies

Bug 878165

The next_balance parameter of nohz_idle_balancer should be initialized
to jiffies since jiffies itself is initialized to 300 seconds shy of
overflow. Otherwise, nohz_idle_balancer does not run for the first 5
mins after bootup.

Change-Id: I18334451f394ead8ddad3b94d725635a31e0173b
Signed-off-by: Diwakar Tundlam <dtundlam@nvidia.com>
Signed-off-by: Varun Wadekar <vwadekar@nvidia.com>
Reviewed-on: http://git-master/r/77300
Reviewed-by: Automatic_Commit_Validation_User

sched: task_times() explosion avoidance for tasks with > 2^32 acrued ticks

Change-Id: I6543c216ccdefb7e75a1cef78c02d1e5d54397a6

sched: Remove rq->avg_load_per_tas.

Change-Id: I435716b938104f32e76d54ed7cfc6c510df2b5cc

 sched: Fix hotplug vs. set_cpus_allowed_ptr()

commit 6acbfb9 upstream.

Lai found that:

  WARNING: CPU: 1 PID: 13 at arch/x86/kernel/smp.c:124 native_smp_send_reschedule+0x2d/0x4b()
  ...
  migration_cpu_stop+0x1d/0x22

was caused by set_cpus_allowed_ptr() assuming that cpu_active_mask is
always a sub-set of cpu_online_mask.

This isn't true since 5fbd036 ("sched: Cleanup cpu_active madness").

So set active and online at the same time to avoid this particular
problem.

Fixes: 5fbd036 ("sched: Cleanup cpu_active madness")
Adapted for p880 3.1.10 kernel by Demetris
Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
Signed-off-by: Peter Zijlstra <peterz@infradead.org>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Gautham R. Shenoy <ego@linux.vnet.ibm.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Michael wang <wangyun@linux.vnet.ibm.com>
Cc: Paul Gortmaker <paul.gortmaker@windriver.com>
Cc: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Cc: Srivatsa S. Bhat <srivatsa.bhat@linux.vnet.ibm.com>
Cc: Toshi Kani <toshi.kani@hp.com>
Link: http://lkml.kernel.org/r/53758B12.8060609@cn.fujitsu.com
Signed-off-by: Ingo Molnar <mingo@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

Change-Id: I39a1c9c679fb7c86710581b8fee3ccf028e3d8bc

cpufreq: expose a cpufreq_quick_get_max routine

This allows drivers and other code to get the max reported CPU frequency.
Initial use is for scaling ring frequency with GPU frequency in the i915
driver.

Signed-off-by: Jesse Barnes <jbarnes@virtuousgeek.org>
Signed-off-by: Keith Packard <keithp@keithp.com>

cpufreq: Export user_policy min/max

Add sysfs nodes for user_policy min and max settings.

Bug 888312

Change-Id: Ife8ec07f8faebc0c04e7ecf6e24976a311bad73b
Reviewed-on: http://git-master/r/72201
Signed-off-by: Antti P Miettinen <amiettinen@nvidia.com>
Signed-off-by: Varun Wadekar <vwadekar@nvidia.com>
Reviewed-on: http://git-master/r/75882
Reviewed-by: Automatic_Commit_Validation_User

Revert "cpufreq: Add Input Boost feature to the cpu-boost driver"

This reverts commit 861d07a939367579259a554d01033277a916a338.

Revert "cpufreq: Add a sync limit to cpu-boost"

This reverts commit 5a55b7bc249638b32f1e1b6c7e97d904c1057457.

Revert "cpufreq: Add cpu-boost driver"

This reverts commit c50d90b78b5dccad192f4d6b333758085026dc04.

Replace interactive governor with older file in preparing for merges

cpufreq interactive governor save/restore IRQs around cpumask spinlocks

Need to use irqsave/restore spin locking for cpumasks since these
are accessed in timers and in thread context.

Change-Id: I4a53eaf0ced7e73b445feddba90ec11482de9126
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq interactive governor: fix crash on CPU shutdown

Don't reference the saved copy of the CPU's cpufreq policy
pointer after the governor has been stopped for the CPU.

When the governor is stopped for a CPU:

* Use del_timer_sync() to wait for a currently-running timer
function to stop.

* Delete the timer when the governor is stopped for the
associated CPU, not when the last CPU is stopped.

* Flush any speed down work ongoing.

* Reset the timestamp that is used to tell if the timer function
has had a chance to run since last idle exit.

Check the governor enabled flag for the CPU before re-arming the
timer from within the timer function and at idle exit (in case
stopping the governor at runtime).

Check the governor enabled flag for the CPU in the worker
function and thread before using the policy pointer.  (There is
still a tiny window in the thread that needs more work to close.)

Change-Id: Ifaddf7a495a8dae15a579a57bdc654f7c47f6ada
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq interactive: support shared CPU scaling

Change-Id: Id5267f04067bf023f6b140b4de2e88ef7287e941
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq: interactive: remove debug trace code

Remove debug trace code in preparation of upstreaming

Change-Id: I0905885e75031f5e9d7cb06878fb68c1fd06d4fe
Signed-off-by: Allen Martin <amartin@nvidia.com>

cpufreq: interactive: use idle notifier

Convert interactive governor to use idle notifier instead of
hooking pm_idle directly.

Change-Id: I47e007f330468ac559240a0ae8a3cb06a89ccb67
Signed-off-by: Allen Martin <amartin@nvidia.com>

cpufreq: interactive: Add error checking on sysfs interfaces

This adds better error checking on tunable parameters on sysfs
interfaces.  Also fixes return value from these functions, previously
on success they would return 0 which would cause a infinite loop.

Change-Id: Ic05038492166f8673d007202092471f98a2f0dfa
Signed-off-by: Allen Martin <amartin@nvidia.com>

cpufreq: interactive: add sysfs control for timer rate

Add a new sysfs control that tunes the rate of the timer used to
increase cpu frequency

Change-Id: I1aa13ae54bb43aff5b3688984d2955f56aae1658
Signed-off-by: Allen Martin <amartin@nvidia.com>

cpufreq: interactive: cleanup checkpatch warnings

Cleanup some style warnings reported by checkpatch

Change-Id: Ie2e6903d52867fb3347e009d7efa3bc4ca755cea
Signed-off-by: Allen Martin <amartin@nvidia.com>

cpufreq: interactive: Fix handling of SMP where CPUs must scale in tandem

The interactive governor relies on quirks of the Tegra 2 cpufreq
implementation for handling SMP systems where the CPUs do not have
separate rate controls.  It needs to determine the maximum rate
for all CPUs covered by the policy and set that speed.

Change-Id: I1ed9fa171e5a9c45a1fa5944e3fa823eb157e81f
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq: interactive: fix possible Division by zero.

The following dump was seen sometimes while resuming,
the only division by zero on this function can happen after
delta_time is reassigned, since at the start of the
function, there is jump that protects against values
less than 1000.

After that, If delta_time and delta_idle == 0,
we will hit a div 0

Division by zero in kernel.
Backtrace:
[<c0057184>] (dump_backtrace+0x0/0x110) from [<c05d5ecc>] (dump_stack+0x18/0x1c)
r6:010f3000 r5:c113dfb0 r4:c004afb0 r3:c6ff0000
[<c05d5eb4>] (dump_stack+0x0/0x1c) from [<c00572cc>] (__div0+0x1c/0x20)
[<c00572b0>] (__div0+0x0/0x20) from [<c02195d4>] (Ldiv0+0x8/0x10)
[<c03dfd64>] (cpufreq_interactive_timer+0x0/0x2c0) from [<c00a7efc>] (run_timer_softirq+0x154/0x260)
[<c00a7da8>] (run_timer_softirq+0x0/0x260) from [<c00a0c8c>] (__do_softirq+0xc8/0x194)
[<c00a0bc4>] (__do_softirq+0x0/0x194) from [<c00a1008>] (irq_exit+0xb4/0xb8)
[<c00a0f54>] (irq_exit+0x0/0xb8) from [<c00584b4>] (ipi_timer+0x44/0x48)
r4:c004a040 r3:00000001
[<c0058470>] (ipi_timer+0x0/0x48) from [<c004c3e4>] (do_local_timer+0x68/0x84)
r5:c004ae2c r4:c07991e8
[<c004c37c>] (do_local_timer+0x0/0x84) from [<c0052948>] (__irq_svc+0x48/0xe0)

Change-Id: I639882db67b8d711c5710778ebc212f0f6a998e3

Acked-by: Nishanth Menon <nm@ti.com>
Signed-off-by: Axel Haslam <axelhaslam@ti.com>

cpufreq: interactive governor: default timer 10ms, maxspeed load 95%

Modify default timer from 30ms to 10ms, sampling 2 jiffies after
idle exit on ARM as in Honeycomb.

Modify default go_maxspeed_load from 85% loaded to 95% loaded, for
use in phones where power savings is more important (tablets may be
best served overriding this).

Change-Id: I3361a6279979bfae1df5262666a2e30ea7a44328
Signed-off-by: Todd Poynor <toddpoynor@google.com>

power: cpufreq interactive governor: use default sample time 20ms

Lower the default time at which a higher speed is allowed to run
before lowering based on lower CPU load from 80ms to 20ms.  Most
Android devices should trade power for performance here,
although tablets and non-battery-powered devices may want to
override this default.

Change-Id: I1a4f7faeca12793c51d5b92db30a63cca8d4f1be
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq: interactive governor: apply intermediate load on current speed

Calculate intermediate speed by applyng CPU load to current speed, not
max speed.

Change-Id: Idecf598b9a203b07c989c5d9e9c6efc67a1afc2e
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq: interactive governor: scale to max only if at min speed

Change-Id: Ieffb2aa56b5290036285c948718be7be0d3af9e8
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq: interactive governor: go to intermediate hi speed before max

* Add attribute hispeed_freq, which defaults to max.

* Rename go_maxspeed_load to go_hispeed_load.

* If hit go_hispeed_load and at min speed, go to hispeed_freq;
  if hit go_hispeed_load and already above min speed go to max
  speed.

Change-Id: I1050dec5f013fc1177387352ba787a7e1c68703e
Signed-off-by: Todd Poynor <toddpoynor@google.com>

cpufreq: interactive governor: default 20ms timer

Change-Id: Ie9952f07b38667f2932474090044195c57976faa
Signed-off-by: Todd Poynor <toddpoynor@google.com>

Revert "cpufreq: interactive governor: go to intermediate hi speed before max"

This reverts commit d7e7e4f15c62464dfa5d2c58d73bc66f131795bc.

Signed-off-by: Dan Willemsen <dwillemsen@nvidia.com>

Rebase-Id: R4a8c8c91c64c2c1d64ecb22dfe8a7c2cd133fd39

Revert "cpufreq: interactive governor: scale to max only if at min speed"

This reverts commit 460145c8b1d2ff8a2488baa10d7421e1d8179b7d.

Signed-off-by: Dan Willemsen <dwillemsen@nvidia.com>

Rebase-Id: Racc6c054ac5c67c38dec7281c7190c6650bfb8bd

Revert "cpufreq: interactive governor: apply intermediate load on current speed"

This reverts commit 6f312490bcf93bf51ad4ba8d4965a952f521cb7d.

Signed-off-by: Dan Willemsen <dwillemsen@nvidia.com>

Rebase-Id: Rf54be39acd2c92decd9e5c4522d2b2e47589d84e

cpufreq interactive governor: Update target frequency calculation

Updated target frequency calculation algorithm to take into account
current rate CPU is running at:

- When CPU is running below go_maxspeed_load threshold, adjust the
target frequency based on current rate to reach tunable sustainable
load (instead of applying cpu load to max possible cpu rate).

Tuned by setting new node ("0" falls back to using max_rate):
/sys/devices/system/cpu/cpufreq/interactive/sustain_load

- When CPU is running at/above go_maxspeed_load threshold, ramp the
target frequency starting from current exponentially with tunable base
(instead of immediate jump to maximum cpu rate).

Tuned by setting new node ("0" falls back to jump to max_rate):
/sys/devices/system/cpu/cpufreq/interactive/boost_factor

Defaults for the new tunning parameters are set to "0" - so no changes
in governor default behavior.

Original-Change-Id: Ie845d747239ba177e6f06b73965c3213649f8135
Reviewed-on: http://git-master/r/34583
Reviewed-by: Aleksandr Frid <afrid@nvidia.com>
Tested-by: Aleksandr Frid <afrid@nvidia.com>
Reviewed-by: Chih-Lung Huang <lhuang@nvidia.com>
Reviewed-by: Scott Williams <scwilliams@nvidia.com>
Reviewed-by: Narendra Damahe <ndamahe@nvidia.com>
Reviewed-by: Yu-Huan Hsu <yhsu@nvidia.com>
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

Rebase-Id: Re898a7b96d3c1b7343e773aab9788e4ff2b1d7f8

cpufreq interactive governor: Init idle times on governor start

When governor starts initialize time_in_idle and idle_exit_time
variables with current data, and restart timer. This is required
to properly start governor on busy CPU that would not enter idle
state for a long time.

(cherry picked from commit 876dc6eddc68054e6abe23f6287cfbf5302a75b9)
(cherry picked from commit d0024f3ad1e4c6d4885355df3fda02435ccc471d)

Change-Id: I992ca9193cb95e64cc9ef8bfb86675b32ad6d43d
Reviewed-on: http://git-master/r/61712
Reviewed-by: Varun Colbert <vcolbert@nvidia.com>
Tested-by: Varun Colbert <vcolbert@nvidia.com>

Rebase-Id: Ra79d9a3ca97b0cfd49fb642ba7cafb98c11c04f1

cpufreq interactive governor: add max_boost sysfs node

Allows you to specify a max increase in frequency, disabled by default.

Cherry-pick from: http://git-master/r/#change,57928
Change-Id: I8174e31faceaa7c27adfe52515e951a4092a39f3
Signed-off-by: Daniel Solomon <daniels@nvidia.com>
Reviewed-on: http://git-master/r/65601
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>
Reviewed-by: Peter Boonstoppel <pboonstoppel@nvidia.com>
Reviewed-by: Yu-Huan Hsu <yhsu@nvidia.com>

cpufreq interactive governor: Fix attribute write bug

Attribute store functions used to return 0 upon success, but should
return count instead.

Change-Id: I2ab15e536d9affbf80bbcb2e557c6d217d5a9dfa
Signed-off-by: Peter Boonstoppel <pboonstoppel@nvidia.com>
Reviewed-on: http://git-master/r/68554
Reviewed-by: Aleksandr Frid <afrid@nvidia.com>
Tested-by: Daniel Solomon <daniels@nvidia.com>
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

cpufreq interactive governor: Made sysfs nodes writable

max_boost and go_maxspeed_load need to be writable for service that
controls balanced power mode

Cherry-picked from: http://git-master/r/#change,57965
Change-Id: I0e3a39ddf317a0f7ba3bb4908afc8a100db1b883
Signed-off-by: Daniel Solomon <daniels@nvidia.com>
Reviewed-on: http://git-master/r/65602
Reviewed-by: Simone Willett <swillett@nvidia.com>
Tested-by: Simone Willett <swillett@nvidia.com>

cpufreq interactive governor: Reduce permissions

Reduce permissions on the max_boost and go_maxspeed_load, the init
scripts will change their owner so the current users continue to work.

Bug 906796

Signed-off-by: Dan Willemsen <dwillemsen@nvidia.com>
Reviewed-on: http://git-master/r/79096
(cherry picked from commit f1d91095baff48e58a04af0062f579f394094b47)

Change-Id: Id9542a202bcf02f886cfee9c0bbe69cc83b8c200
Signed-off-by: Pritesh Raithatha <praithatha@nvidia.com>
Reviewed-on: http://git-master/r/82726
Reviewed-by: Automatic_Commit_Validation_User
Reviewed-by: Varun Wadekar <vwadekar@nvidia.com>
Tested-by: Varun Wadekar <vwadekar@nvidia.com>

cpufreq interactive governor: Unify attribute store functions

Change our added attributes' store functions to Google style

Change-Id: I5dc641112085698918e87b52378fe3a5bfe44360
Signed-off-by: Peter Boonstoppel <pboonstoppel@nvidia.com>
Reviewed-on: http://git-master/r/84452
Reviewed-by: Satya Popuri <spopuri@nvidia.com>
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

Revert "cpufreq: interactive governor: default 20ms timer"

This reverts commit 4714e5222b5a9b11030eda6df7b8159034be0008.

Signed-off-by: Dan Willemsen <dwillemsen@nvidia.com>

Rebase-Id: Rc7c804305f9c37c4b93d5d7eecce0b9b93499e27

cpufreq: change min_sample_time

We prefer a min_sample_time of 30ms. This is tied to our cluster switch
and auto-hotplug artificial delays.

Signed-off-by: satya popuri <spopuri@nvidia.com>

original commit message:

cpufreq: reduce min_sample_time

Reduce the minimum amount of time the interactive governor spends at a
frequency before ramping down. This parameter (min_sample_time) was 80ms
now reduced to 30 ms based on perf and power sweep numbers.

Reviewed-on: http://git-master/r/86900 (cherry picked from commit
581f20a5b7b8c3e4ee2c211b28dbc81510af2ae7).
Signed-off-by: satya popuri <spopuri@nvidia.com>

Change-Id: I24f4cd52737950fd4e78a36b4ee34a84551e0e12
Reviewed-on: http://git-master/r/89217
Reviewed-by: Satya Popuri <spopuri@nvidia.com>
Tested-by: Satya Popuri <spopuri@nvidia.com>
Reviewed-by: Automatic_Commit_Validation_User
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

cpufreq: interactive: fix checkpatch warnings on long lines

Fix up checkpatch warning introduced by long lines in timer_rate
patch.

Change-Id: I22b105dafb1b49390799bb7577464da03f0f8afb
Signed-off-by: Allen Martin <amartin@nvidia.com>

cpufreq: Add a knob to treat IO wait as busy

The new sysfs node io_is_busy enables the interactive governor to
account any time spent by the CPU waiting for IO as non-idle time.
This helps us improve run-time of IO bound tasks by making up for
lost IO time in speeding up the CPU bound parts of the task.

Reviewed on http://git-master/r/#change,86894
cherry picked from 13a15aadc1134b5dae05cdcf9687396644f87411
Signed-off-by: satya popuri <spopuri@nvidia.com>

Change-Id: I4a14ed7fef5fbce00054bb02d52d2d3e0f011f70
Reviewed-on: http://git-master/r/89218
Reviewed-by: Satya Popuri <spopuri@nvidia.com>
Tested-by: Satya Popuri <spopuri@nvidia.com>
Reviewed-by: Automatic_Commit_Validation_User
Reviewed-by: Diwakar Tundlam <dtundlam@nvidia.com>

cpufreq: update target freq always

set determined target freq always

bug 941275

Change-Id: If72936ed145867abd32b43c5c5100290df2fc187
Signed-off-by: Shridhar Rasal <srasal@nvidia.com>
Reviewed-on: http://git-master/r/91010
Reviewed-by: Automatic_Commit_Validation_User
Reviewed-by: Satya Popuri <spopuri@nvidia.com>
Reviewed-by: Peter Boonstoppel <pboonstoppel@nvidia.com>
Reviewed-by: Bharat Nihalani <bnihalani@nvidia.com>

cpufreq interactive: slightly reduce go_maxspeed_load

Tweak entropy

mmc: disable CRC and increase timeout limits when using bad SD cards

cpufreq: report correct min/max frequencies