config: Add ZEN I/O Sched and set it default
cpufreq: interactive: Fix null pointer dereference in interactive governor

For the sync_freq feature currently we check pcpu->policy->cur frequency
for each online cpu.  But for a CPU that isn't using interactive governor
or for an offline CPU, pcpu->policy can be null or an invalid value.
This patch tries to avoid that scenario by using pcpu->target_freq
instead of policy->cur to get the frequency of an online CPU.

Kernel crash without this patch:
[   20.132373] Unable to handle kernel NULL pointer dereference at virtual address 00000028
[   20.132375] pgd = c34f34c0
[   20.132377] pgd = ef6f2440
[   20.132383] [00000028] *pgd=00000000
[   20.132385]
[   20.132388] [00000028] *pgd=2e98f003, *pmd=00000000
[   20.132390] Internal error: Oops: 205 [#1] PREEMPT SMP ARM
[   20.132394] Modules linked in:
[   20.132398] CPU: 0 PID: 1560 Comm: chown Tainted: G        W    3.10.0-perf-gb12057b-00001-ga2c6c16-dirty #7
[   20.132401] task: ef9af300 ti: ee49c000 task.ti: ee49c000
[   20.132411] PC is at cpufreq_interactive_timer+0x10c/0x650
[   20.132415] LR is at cpufreq_interactive_timer+0x128/0x650
<snip>
[   20.133002] [<c07eb204>] (cpufreq_interactive_timer+0x10c/0x650) from [<c02804d8>] (call_timer_fn+0x80/0x198)
[   20.133012] [<c02804d8>] (call_timer_fn+0x80/0x198) from [<c0280acc>] (run_timer_softirq+0x1f8/0x270)
[   20.133019] [<c0280acc>] (run_timer_softirq+0x1f8/0x270) from [<c0279e20>] (__do_softirq+0x12c/0x2d4)
[   20.133025] [<c0279e20>] (__do_softirq+0x12c/0x2d4) from [<c027a2d4>] (irq_exit+0x74/0xc8)
[   20.133034] [<c027a2d4>] (irq_exit+0x74/0xc8) from [<c0206a00>] (handle_IRQ+0x68/0x8c)
[   20.133041] [<c0206a00>] (handle_IRQ+0x68/0x8c) from [<c02004b8>] (gic_handle_irq+0x3c/0x60)
[   20.133051] [<c02004b8>] (gic_handle_irq+0x3c/0x60) from [<c0ac6900>] (__irq_svc+0x40/0x70)
<snip>

Change-Id: Ie834f5d383de4d41e0fe6fbd40c8b0a0c05d82f5
Signed-off-by: Vijay Ganti <viganti@codeaurora.org>
ARM/dt: hammerhead: Reduce minimum panel brightness

Default minimum brightness is a tad too high, this change makes reading
in a dark environment much more enjoyable. A value of 3 is still within
the valid range (see lm3630 blmap).

Change-Id: I40f690e7a06459a06db939c37108bae6fc9c52d6
PM: devfreq: Fix simple_ondemand crashing on startup

simple_ondemands private data must be set to NULL, otherwise we would
run into a NULL pointer in kgsl_devfreq_get_dev_status().

Change-Id: I6cc6a8b11e3b58b8c3e3c26d43ee36949cf62351
ARM/dt: msm8974-gpu: Enable qcom bus-control

Honor DEVFREQ_FLAG_FAST/SLOW_HINT flags in adreno-tz.

Change-Id: I5b995fb29b690946651304ed1607214c63485abc
msm: vidc: Validate session_id in video hardware response

Validate session_id present in video hardware response
packet before processing it. This will avoid system reset
resulting from invalid session_id returned from video hardware.

Change-Id: I37525a3d10b5efe00734c5533931e2700f3c7513
Signed-off-by: Maheshwar Ajja <majja@codeaurora.org>
msm: vidc: Skip session id validation for HFI_EVENT_SYS_ERROR

When SSR is triggered from driver, firmware is responding with session id
as 0X0000dead. Hence, firmware response is being discarded due to such
invalid session id. Skip session id validation for HFI_EVENT_SYS_ERROR
event type.

Change-Id: I750a7332baab4ebeb7702b49ffb744aae9803a36
CRs-Fixed: 539080
Signed-off-by: Srinu Gorle <sgorle@codeaurora.org>
msm: vidc: fix corruption of registered buffer list

The buffer list for output buffers is accessed from
different threads leading to race conditions. Consider
the case of firmware throwing up a fatal error, which gets
propagated to v4l2 client. The v4l2 client closes the
driver fd, which will trigger msm_vidc_release_buffers
to release all output buffers and free node from
the registered buffer list. During this time, if
firmware sends a release reference event, the buffer
node being accessed in msm_vidc_release_buffers could
be freed, triggering kernel panic.

Change-Id: I522edff06a62dbc2ab60d6cca5990babb18d5c6c
Signed-off-by: Arun Menon <avmenon@codeaurora.org>
msm: vidc: Send ABORT in FLUSH command from the Client

When session error is sent to the client, client issues FLUSH
and release buffers commands. But as instance state is INVALID,
these commands are never sent to the firmware, instead FLUSH
DONE and Release buffer done are sent back to client even
though firmware might be working on these buffers which may
result into page faults.
This change fixes the issue by sending ABORT command to the
firmware at the time when driver receives FLUSH command. Then
firmware will release all buffers, clean up session and send
ABORT_DONE back to the driver.

Change-Id: Ie4c79a312d2336c68b858f5f5e2a85331cf55f7b
CRs-fixed: 592920
Signed-off-by: Deepak Verma <dverma@codeaurora.org>
msm: vidc: reduce clk frquency before disable

The change ensures that the clock frequency is reduced to min
before we disable it.
With just clk_disable, rpm still votes for high voltage on CX
as venus vote is not removed.
To unvote, the frequency is set to min.

CRs-Fixed: 574365
Change-Id: I8e0515b9816f8c451d545443573afaba611aafe7
Signed-off-by: Vikash Garodia <vgarodia@codeaurora.org>
msm: vidc: avoid re-initialize of v4l2 spin lock

The fh_lock and fh_list variables are initialized
during probe in video_register_device. This was
re-initialized again when a new video instance was
opened. Since all video instances shared the same
fh_lock and fh_list variable, this gave rise to a race
condition in the v4l2 video driver. Consider the
case of multiple video instances being opened simultaneously.
One video instance has acquired the fh_lock and
calls a v4l2 function which calls v4l2_event_subscribe.
During this time another video instance is opened
and it re-intializes the fh_lock, so the first
instance no longer holds the spin lock and hits
ASSERT in v4l2_event_subscribed. This change
fixes the race condition.

Change-Id: I7af98c8f091cb94e6118c9e2ea1ba5d5d44c6833
Signed-off-by: Arun Menon <avmenon@codeaurora.org>
usb: dwc3-msm: replace wakelock with wakeup source

As the wakelock API is now banned, use the underlying
wakeup_source-based implementation directly.

Change-Id: Id6abe00f77b94b4fe82af19def5138e3286ed456
Signed-off-by: Jack Pham <jackp@codeaurora.org>
USB: dwc3: Clear USB2PHY_SUSP bit during disconnect

Currently GUSB2PHY_SUSP bit is set in GUSB2PHYCFG(0) register
as part of initialization sequence and not clearing that bit
after that. If this bit is set during charger detection, it is
causing issues with VDP_SRC and IDM_SINK like VDP_SRC is not getting
applied within time, IDM_SINK is not large enough, due to which
battery charging complaince tests are failing with complaince test
device. Hence set this bit during peripheral/host start and clear
the bit while stopping peripheral/host role.

Also reduce the debouncing delay which should be in range [0-120]msec
for VBUS. Otherwise seeing battery charging complaince tests fail
due to bigger delay.

CRs-Fixed: 543926
Change-Id: I9ea87a19b43ce7804748dd3735ac436f77cdf933
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>
USB: dwc3: Squashed commit of upstream changes

USB: dwc3: debugfs: Enable logging of control endpoint events by default

Enable logging of EP0 control events, which will be useful for analyzing
the USB issues like crash. Also add more required events wherever required.

Change-Id: I0fd3edfa2cd8711928cd480e99abbf8e6f907774
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3_otg: Move to A_IDLE state if unable to start host

As part of ID clear, OTG driver tries to start host mode. This may
fail if regulator driver is not ready and returns -EPROBE_DEFER
for VBUS regulator_get. Instead of moving to UNDEFINED state, move
OTG state-machine to A_IDLE so that it can retry start_host later
when notified again as part of regulator driver's initialization.

CRs-Fixed: 513074
Change-Id: I1711bfaa0c7ceed01d596f5a10c8d25a8d3931e0
Signed-off-by: Manu Gautam <mgautam@codeaurora.org>

USB: dwc3: msm: add charger detection for floated D+ and D-

Floated charger means "D+/D- floated charger". According batt
charging spec 1.2, during primary detection, the DP voltage
is VDP_SRC, DM voltage may not exceed VDAT_REF, it's same to
standard downstream port(SDP). Introducing data contact
detection(DCD) here to distinguish between SDP and floated
charger. If DCD detected, it's SDP, otherwise floated charger
is detected. Also rename UNSUPPORTED charger as FLOATED charger
as data lines D+/D- are floating.

Change-Id: I0fd307c512f46331e6e1d80759c1585fc1db8a39
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3-msm: Fix LPM related issues with FLOATED charger connected

Currently dwc3-msm driver is putting HSPHY into RETENTION apart from
voting for VDD minimization when FLOATED charger is connected. This
results in spurious MPM interrupt getting triggered during system
suspend.  Due to this, charger detection will be performed endlessly
in case of FLOATED charger. Hence don't put HSPHY into RETENTION with
FLOATED charger connected and also fix bug in incrementing charger
retry count.

CRs-Fixed: 516013
Change-Id: If76fcacf60e880c8752d7461670adb4bab0f4b72
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

usb: dwc3-msm: Add support for controller power collapse

Starting from msm USB core version 1.2.0, if usb cable is
disconnected controller power collapse is allowed. Hence
add support to vote for Global Distributed Switch
Controller (GDSC) when usb cable is connected and remove
the vote when cable is disconnected to shut down the
controller power.

CRs-Fixed: 498960
Change-Id: Ia1d8bb1b8fb5370a335d28fade72485def68f80c
Signed-off-by: Hemant Kumar <hemantk@codeaurora.org>

usb: dwc3-msm: remove use of global context variable (ADC)

Remove usage of the global context variable by retrieving the
instance from the dev pointer passed to the sysfs functions. This
will allow the driver to eventually support multiple instances.

Change-Id: If08ddcab8cdb4753c04add1f2b9efa683bcab474
Signed-off-by: Jack Pham <jackp@codeaurora.org>

usb: dwc3-msm: remove use of global context variable (regulators)

Remove usage of the global context variable in the regulator and
block reset helper functions by passing the dwc3_msm pointer as a
parameter. This will allow the driver to eventually support multiple
instances.

Change-Id: I4e6892ff71a1482c319b6633e7a1ed128c93a3bf
Signed-off-by: Jack Pham <jackp@codeaurora.org>

usb: dwc3-msm: remove use of global context variable (charger)

Remove usage of the global context variable in the charger detection
functions by retrieving the dwc3_msm instance from the dev pointer
passed to the sysfs functions. This will allow the driver to eventually
support multiple instances.

Change-Id: Ia11ec77c04239ae8afacc7dab0b38eaf85024276
Signed-off-by: Jack Pham <jackp@codeaurora.org>

usb: dwc3-msm: remove global context variable

Now that all uses of the global context variable have been removed,
remove the variable itself. This allows the dwc3-msm driver to
support multiple device instances.

Change-Id: Ic1aa6b6a16323cc03870101a157ec35de0c6899b
Signed-off-by: Jack Pham <jackp@codeaurora.org>

usb: dwc3-msm: rename local variables to mdwc

Do 's/msm/mdwc/' throughout the file as 'msm' is a confusing
name to use as a local variable. This makes usage uniform
and consistent with 'mdwc' used in other functions.

Change-Id: I5f94ec518ee4f0dc1324c7e75ee7c077b13cbe91
Signed-off-by: Jack Pham <jackp@codeaurora.org>

USB: dwc3: Dump all relevant core and PHY registers for Erratic error event

DWC3 controller will generate Erratic event if PHY doesn't respond to
PHY command sent by core within stipulated time. In normal case, this
should not happen. Hence dump all relevant core and QSCRATCH registers
to figure out the reason for this Erratic event.

CRs-Fixed: 515005
Change-Id: I02380885a401d9686a542faad16c29e25ac8964f
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

Revert "usb: host: hs_phy_irq wakeup only when host mode and controller lpm"

This reverts commit b0d5ec245d11d557572ece4333f20ca0290a5b0c.

Change-Id: I23fbb115eaefef5be52f3f25da45c6cd4d468e39

USB: dwc3: msm: Implement new initialization sequence

Currently dwc3-msm driver is not following the initialization
sequence as per new hardware programming guide. Hence implement
new initialization sequence. The new sequence does PHY reset
under GCTL reset

This change solves the USB enumeration issue seen with HS/LS devices
connect/disconnect over TI USB3.0 HUB.

CRs-Fixed: 477323
CRs-Fixed: 515048
Change-Id: Ia0500517290c82f6ca6dc9dc32b4cee1e4f44aff
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3: Allocate 3KB FIFO for bulk and isochronous endpoints

Currently dwc3 driver will allocate fifo size of maximum endpoint
packet size for TX endpoints depending on operating speed. Due
to this, double buffering may not work for TX endpoints in both high
speed and superspeed. Hence implement policy that allocates 3KB of
fifo for all bulk and isochronous endpoints irrespective of speed.

Policy is to allocate 3KB for bulk and isochronous endpoints and
allocate maximum packet size for control and interrupt endpoints.
This policy will improve the TX throughput numbers for function
drivers like MTP, mass storage. But side effect is we can't accomodate
more than nine bulk + isochronous endpoints in non QDSS composition
and five bulk + isochronous endpoints in QDSS composition. Otherwise
last interfaces in the USB composition will not work.

CRs-Fixed: 532070
Change-Id: I5e947f21f25fada7829c84eba45980295497cfbc
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

Revert "USB: dwc3: core: Add module parameter for TX fifo resize"

commit "dbe59bf157adf17a39c041ff9379bd5ec751da5c:USB: dwc3: core:
Add module parameter for TX fifo resize" disables dynamic fifo
allocation for TX endpoints by default and provides an option to
enable it for QDSS heavy composition.

Earlier tx fifo resize logic was causing throughput discrepancy
in high speed operation due to double buffering not happening.
With the new policy to allocate 3KB for all bulk and isochronous eps
implemented, this issue will be resolved. Hence revert the change to
always enable dynamic fifo allocation for TX endpoints which will
improve throughput in superspeed mode by having larger fifo to allow
double buffering.

CRs-Fixed: 532070
Change-Id: I9984637d9d3edf8067c4604ed661d3ef8ac426c4
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3-msm: Add recovery mechanism for erratic error event

DWC3 controller will generate Erratic event if PHY doesn't respond to
PHY command sent by core within stipulated time. In normal case, this
should not happen. Due to this, USB functionality will break if not
added recovery mechanism for handling this erratic error event. Hence
add recovery mechanism by doing block reset whenever Erratic error
event is triggered by contoller.

CRs-Fixed: 535976
Change-Id: I5c8cc0c822a26c7fe4b8ac58b651d9a3267626ce
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3: Fix QDSS data integrity issue

Currently RAM12, RAM13 are being used for data fifo and
descriptor fifo allocations in QDSS BAM <-> BAM usecase. Remaining
16KB out of 29KB is being used for allocation of TX FIFO for
USB IN endpoints in the composition. This resulting in data corruption
when captured with host side application. Due to this, QTF host
application is not able to parse the data collected over USB.
Hence reserve RAM11, RAM12, RAM13 for 16KB data fifo allocation and
5KB descritor fifo allocation in QDSS mode and use remaining 8KB for
TX FIFO allocation for IN endpoints.

As available tx fifo size is reduced in QDSS mode, allocate 1KB for
bulk and isochronous endpoints in highspeed mode and also for nonburst
endpoints in superspeed mode. For burst endpoint in superspeed mode,
allocate 3KB for TX FIFO.

CRs-Fixed: 553147
Change-Id: I6d50d2da631a95a921c47bb1fb1139477840a73c
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3-msm: Add support for overriding SSPHY deemphasis setting

TX deemphasis value can be different from platform to platform.
This value has to be set to suitable value to pass USB3 complaince
test. Hence add support for overriding this deemphasis value from
device tree.

CRs-Fixed: 536912
Change-Id: Ic3c2213fc0d090407057525115eae1351ecc4668
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3: clear LANE0_PWR_PRESENT bit after initialization

Currently dwc3-msm driver is setting LANE0_PWR_PRESENT in QSCRATCH
SS_PHY_CTRL register, but not clearing this bit after completion of
initialization. This is affecting data lines behaviour during
charger detection issues when connected wall charger or HVDCP charger.
Hence clear this bit after completion of initialization sequence.

CRs-Fixed: 561316
Change-Id: I05fb75b77c45fc9466a832c83cf2be120dbe3fa2
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3_msm: Disable all events before error recovery for Erratic event

Currently as part of Erratic event handling, dumping all relevant registers
and then scheduling work for block reset. This does lead to erratic event
getting fired continuously and might result in watchdog crash. Hence
disable all events in DEVTEN regiser before doing block reset and reenable
the events once block reset is completed.

Change-Id: Ib2644ea8471cb87792a9524dc5103b61b2d0a74c
Signed-off-by: Wesley Cheng <wcheng@codeaurora.org>
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

usb: dwc3_otg: Turn on VBUS before starting host

Currently the VBUS regulator is enabled only after initializing
the xHCI host stack, which can result in enumeration failures
for certain devices. This is likely due to VBUS having a
finite rise time when it is turned on, especially when a load
is already attached. Mitigate this by enabling VBUS first before
starting the host stack.

CRs-Fixed: 599498
Change-Id: I9785ae4682d0a2dfbcec921b869fc03550e0db82
Signed-off-by: Jack Pham <jackp@codeaurora.org>

USB: dwc3-msm: Fix USB connection issue after DCP charger disconnection

Commit "6e3630b5f28c60c403af8c6b3c87679d3d98d6af: usb: dwc3-msm: Support
external charging detection " has added check not to start charger
detection in case charger detection is done by external circuit. when otg
driver calls charger_detection API to set charger type to invalid as part
of VBUS disconnect handling, this check prevents to do that. This results
next charger detection not happening after DCP charger disconnection.
Hence fix the issue by moving down the check in the charger_detection API.

Change-Id: I5c614a208f22e4cd9f334c80dae6831bcff64ada
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3_otg: Retry if vbus regulator get fail with -EPROBE_DEFER

As part of ID clear, OTG driver tries to start host mode. This might
fail if regulator driver is not ready and returns -EPROBE_DEFER for
VBUS regulator_get. Hence schedule sm_work for one second delay in
case of -EPROBEDEFER so that it can retry start_host again.

CRs-Fixed: 546709
Change-Id: Iab443e7984619d474b15b695fbf5b7639a41ddd0
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

USB: dwc3_otg: Use correct delay for sm_work scheduling in A_IDLE

commit 711b9b117cd983fbf7c29d79596a358a36e288d3: "USB: dwc3_otg:
Retry if vbus regulator get fail with -EPROBE_DEFER" is required
for scheduling sm_work after one sec in case vbus_regulator get
fails when host cable connected during bootup. This introduced a
bug where sm_work is scheduled for delay much greater than one sec.
Hence fix the issue by using correct delay in case vbus_regulator
get fails during bootup.

Change-Id: I5001808962373ff03cf37de04e76ce264d5595e4
Signed-off-by: Vijayavardhan Vennapusa <vvreddy@codeaurora.org>

Conflicts:
	drivers/usb/dwc3/dwc3_otg.c
leds: At disable, set the trigger to default instead of wiping it

Change-Id: Ifb4a3b3034c441d29fd1d9f209ed829adfc76a72
selinux: Fix Kernel panic due to NULL pointer dereference

Below Kernel panic is observed due to race condition, where
sock_has_perm called in a thread and is trying to access sksec->sid
without checking sksec. Just before that, sk->sk_security was set
to NULL by selinux_sk_free_security through sk_free in other thread.

31704.949269:   <3> IPv4: Attempt to release alive inet socket dd81b200
31704.959049:   <1> Unable to handle kernel NULL pointer dereference at \
                        virtual address 00000000
31704.983562:   <1> pgd = c6b74000
31704.985248:   <1> [00000000] *pgd=00000000
31704.996591:   <0> Internal error: Oops: 5 [#1] PREEMPT SMP ARM
31705.001016:   <6> Modules linked in: adsprpc [last unloaded: wlan]
31705.006659:   <6> CPU: 1    Tainted: G           O  \
                        (3.4.0-g837ab9b-00003-g6bcd9c6 #1)
31705.014042:   <6> PC is at sock_has_perm+0x58/0xd4
31705.018292:   <6> LR is at sock_has_perm+0x58/0xd4
31705.022546:   <6> pc : [<c0341e8c>]    lr : [<c0341e8c>]    \
                                                  psr: 60000013
31705.022549:   <6> sp : dda27f00  ip : 00000000  fp : 5f36fc84
31705.034002:   <6> r10: 00004000  r9 : 0000009d  r8 : e8c2b700
31705.039211:   <6> r7 : dda27f24  r6 : dd81b200  r5 : 00000000  \
                                                  r4 : 00000000
31705.045721:   <6> r3 : 00000000  r2 : dda27ef8  r1 : 00000000  \
                                                  r0 : dda27f54
31705.052232:   <6> Flags: nZCv  IRQs on  FIQs on  Mode SVC_32  ISA ARM \
                        Segment user
31705.059349:   <6> Control: 10c5787d  Table: 10d7406a  DAC: 00000015
.
.
.
.
31705.697816:   <6> [<c0341e8c>] (sock_has_perm+0x58/0xd4) from \
                    [<c033ed10>] (security_socket_getsockopt+0x14/0x1c)
31705.707534:   <6> [<c033ed10>] (security_socket_getsockopt+0x14/0x1c) \
                           from [<c0745c18>] (sys_getsockopt+0x34/0xa8)
31705.717343:   <6> [<c0745c18>] (sys_getsockopt+0x34/0xa8) from \
                    [<c0106140>] (ret_fast_syscall+0x0/0x30)
31705.726193:   <0> Code: e59832e8 e5933058 e5939004 ebfac736 (e5953000)
31705.732635:   <4> ---[ end trace 22889004dafd87bd ]---

Change-Id: I79c3fb525f35ea2494d53788788cd71a38a32d6b
Signed-off-by: Satya Durga Srinivasu Prabhala <satyap@codeaurora.org>
Signed-off-by: Osvaldo Banuelos <osvaldob@codeaurora.org>
ipv4: Dump stack on attempt to release alive inet socket

In commit 82e1cecf1 we hide a bug, that will make SELinux
bomb out. Let's dump the stack when it happens to have at
least a chance to find the cause.

Change-Id: I7f9b864d76a48b150c5f248417b47751424449bd
SELinux: Fix possible NULL pointer dereference in selinux_inode_permission()

While running stress tests on adding and deleting ftrace instances I hit
this bug:

  BUG: unable to handle kernel NULL pointer dereference at 0000000000000020
  IP: selinux_inode_permission+0x85/0x160
  PGD 63681067 PUD 7ddbe067 PMD 0
  Oops: 0000 [#1] PREEMPT
  CPU: 0 PID: 5634 Comm: ftrace-test-mki Not tainted 3.13.0-rc4-test-00033-gd2a6dde-dirty #20
  Hardware name:                  /DG965MQ, BIOS MQ96510J.86A.0372.2006.0605.1717 06/05/2006
  task: ffff880078375800 ti: ffff88007ddb0000 task.ti: ffff88007ddb0000
  RIP: 0010:[<ffffffff812d8bc5>]  [<ffffffff812d8bc5>] selinux_inode_permission+0x85/0x160
  RSP: 0018:ffff88007ddb1c48  EFLAGS: 00010246
  RAX: 0000000000000000 RBX: 0000000000800000 RCX: ffff88006dd43840
  RDX: 0000000000000001 RSI: 0000000000000081 RDI: ffff88006ee46000
  RBP: ffff88007ddb1c88 R08: 0000000000000000 R09: ffff88007ddb1c54
  R10: 6e6576652f6f6f66 R11: 0000000000000003 R12: 0000000000000000
  R13: 0000000000000081 R14: ffff88006ee46000 R15: 0000000000000000
  FS:  00007f217b5b6700(0000) GS:ffffffff81e21000(0000) knlGS:0000000000000000
  CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033^M
  CR2: 0000000000000020 CR3: 000000006a0fe000 CR4: 00000000000007f0
  Call Trace:
    security_inode_permission+0x1c/0x30
    __inode_permission+0x41/0xa0
    inode_permission+0x18/0x50
    link_path_walk+0x66/0x920
    path_openat+0xa6/0x6c0
    do_filp_open+0x43/0xa0
    do_sys_open+0x146/0x240
    SyS_open+0x1e/0x20
    system_call_fastpath+0x16/0x1b
  Code: 84 a1 00 00 00 81 e3 00 20 00 00 89 d8 83 c8 02 40 f6 c6 04 0f 45 d8 40 f6 c6 08 74 71 80 cf 02 49 8b 46 38 4c 8d 4d cc 45 31 c0 <0f> b7 50 20 8b 70 1c 48 8b 41 70 89 d9 8b 78 04 e8 36 cf ff ff
  RIP  selinux_inode_permission+0x85/0x160
  CR2: 0000000000000020

Investigating, I found that the inode->i_security was NULL, and the
dereference of it caused the oops.

in selinux_inode_permission():

	isec = inode->i_security;

	rc = avc_has_perm_noaudit(sid, isec->sid, isec->sclass, perms, 0, &avd);

Note, the crash came from stressing the deletion and reading of debugfs
files.  I was not able to recreate this via normal files.  But I'm not
sure they are safe.  It may just be that the race window is much harder
to hit.

What seems to have happened (and what I have traced), is the file is
being opened at the same time the file or directory is being deleted.
As the dentry and inode locks are not held during the path walk, nor is
the inodes ref counts being incremented, there is nothing saving these
structures from being discarded except for an rcu_read_lock().

The rcu_read_lock() protects against freeing of the inode, but it does
not protect freeing of the inode_security_struct.  Now if the freeing of
the i_security happens with a call_rcu(), and the i_security field of
the inode is not changed (it gets freed as the inode gets freed) then
there will be no issue here.  (Linus Torvalds suggested not setting the
field to NULL such that we do not need to check if it is NULL in the
permission check).

Note, this is a hack, but it fixes the problem at hand.  A real fix is
to restructure the destroy_inode() to call all the destructor handlers
from the RCU callback.  But that is a major job to do, and requires a
lot of work.  For now, we just band-aid this bug with this fix (it
works), and work on a more maintainable solution in the future.

Link: http://lkml.kernel.org/r/20140109101932.0508dec7@gandalf.local.home
Link: http://lkml.kernel.org/r/20140109182756.17abaaa8@gandalf.local.home

Cc: stable@vger.kernel.org
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>

Change-Id: Iab1d8871f1dffa499e10ba9d845ac204d0fee32a
SELinux: Fix kernel BUG on empty security contexts.

Setting an empty security context (length=0) on a file will
lead to incorrectly dereferencing the type and other fields
of the security context structure, yielding a kernel BUG.
As a zero-length security context is never valid, just reject
all such security contexts whether coming from userspace
via setxattr or coming from the filesystem upon a getxattr
request by SELinux.

Setting a security context value (empty or otherwise) unknown to
SELinux in the first place is only possible for a root process
(CAP_MAC_ADMIN), and, if running SELinux in enforcing mode, only
if the corresponding SELinux mac_admin permission is also granted
to the domain by policy.  In Fedora policies, this is only allowed for
specific domains such as livecd for setting down security contexts
that are not defined in the build host policy.

[On Android, this can only be set by root/CAP_MAC_ADMIN processes,
and if running SELinux in enforcing mode, only if mac_admin permission
is granted in policy.  In Android 4.4, this would only be allowed for
root/CAP_MAC_ADMIN processes that are also in unconfined domains. In current
AOSP master, mac_admin is not allowed for any domains except the recovery
console which has a legitimate need for it.  The other potential vector
is mounting a maliciously crafted filesystem for which SELinux fetches
xattrs (e.g. an ext4 filesystem on a SDcard).  However, the end result is
only a local denial-of-service (DOS) due to kernel BUG.  This fix is
queued for 3.14.]

Reproducer:
su
setenforce 0
touch foo
setfattr -n security.selinux foo

Caveat:
Relabeling or removing foo after doing the above may not be possible
without booting with SELinux disabled.  Any subsequent access to foo
after doing the above will also trigger the BUG.

BUG output from Matthew Thode:
[  473.893141] ------------[ cut here ]------------
[  473.962110] kernel BUG at security/selinux/ss/services.c:654!
[  473.995314] invalid opcode: 0000 [#6] SMP
[  474.027196] Modules linked in:
[  474.058118] CPU: 0 PID: 8138 Comm: ls Tainted: G      D   I
3.13.0-grsec #1
[  474.116637] Hardware name: Supermicro X8ST3/X8ST3, BIOS 2.0
07/29/10
[  474.149768] task: ffff8805f50cd010 ti: ffff8805f50cd488 task.ti:
ffff8805f50cd488
[  474.183707] RIP: 0010:[<ffffffff814681c7>]  [<ffffffff814681c7>]
context_struct_compute_av+0xce/0x308
[  474.219954] RSP: 0018:ffff8805c0ac3c38  EFLAGS: 00010246
[  474.252253] RAX: 0000000000000000 RBX: ffff8805c0ac3d94 RCX:
0000000000000100
[  474.287018] RDX: ffff8805e8aac000 RSI: 00000000ffffffff RDI:
ffff8805e8aaa000
[  474.321199] RBP: ffff8805c0ac3cb8 R08: 0000000000000010 R09:
0000000000000006
[  474.357446] R10: 0000000000000000 R11: ffff8805c567a000 R12:
0000000000000006
[  474.419191] R13: ffff8805c2b74e88 R14: 00000000000001da R15:
0000000000000000
[  474.453816] FS:  00007f2e75220800(0000) GS:ffff88061fc00000(0000)
knlGS:0000000000000000
[  474.489254] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[  474.522215] CR2: 00007f2e74716090 CR3: 00000005c085e000 CR4:
00000000000207f0
[  474.556058] Stack:
[  474.584325]  ffff8805c0ac3c98 ffffffff811b549b ffff8805c0ac3c98
ffff8805f1190a40
[  474.618913]  ffff8805a6202f08 ffff8805c2b74e88 00068800d0464990
ffff8805e8aac860
[  474.653955]  ffff8805c0ac3cb8 000700068113833a ffff880606c75060
ffff8805c0ac3d94
[  474.690461] Call Trace:
[  474.723779]  [<ffffffff811b549b>] ? lookup_fast+0x1cd/0x22a
[  474.778049]  [<ffffffff81468824>] security_compute_av+0xf4/0x20b
[  474.811398]  [<ffffffff8196f419>] avc_compute_av+0x2a/0x179
[  474.843813]  [<ffffffff8145727b>] avc_has_perm+0x45/0xf4
[  474.875694]  [<ffffffff81457d0e>] inode_has_perm+0x2a/0x31
[  474.907370]  [<ffffffff81457e76>] selinux_inode_getattr+0x3c/0x3e
[  474.938726]  [<ffffffff81455cf6>] security_inode_getattr+0x1b/0x22
[  474.970036]  [<ffffffff811b057d>] vfs_getattr+0x19/0x2d
[  475.000618]  [<ffffffff811b05e5>] vfs_fstatat+0x54/0x91
[  475.030402]  [<ffffffff811b063b>] vfs_lstat+0x19/0x1b
[  475.061097]  [<ffffffff811b077e>] SyS_newlstat+0x15/0x30
[  475.094595]  [<ffffffff8113c5c1>] ? __audit_syscall_entry+0xa1/0xc3
[  475.148405]  [<ffffffff8197791e>] system_call_fastpath+0x16/0x1b
[  475.179201] Code: 00 48 85 c0 48 89 45 b8 75 02 0f 0b 48 8b 45 a0 48
8b 3d 45 d0 b6 00 8b 40 08 89 c6 ff ce e8 d1 b0 06 00 48 85 c0 49 89 c7
75 02 <0f> 0b 48 8b 45 b8 4c 8b 28 eb 1e 49 8d 7d 08 be 80 01 00 00 e8
[  475.255884] RIP  [<ffffffff814681c7>]
context_struct_compute_av+0xce/0x308
[  475.296120]  RSP <ffff8805c0ac3c38>
[  475.328734] ---[ end trace f076482e9d754adc ]---

[sds:  commit message edited to note Android implications and
to generate a unique Change-Id for gerrit]

Change-Id: I4d5389f0cfa72b5f59dada45081fa47e03805413
Reported-by:  Matthew Thode <mthode@mthode.org>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Cc: stable@vger.kernel.org
Signed-off-by: Paul Moore <pmoore@redhat.com>

Change-Id: I815b37117b95e0de10f2f5314c52cd62fd554b1b
SELinux: Fix memory leak upon loading policy

commit 8ed814602876bec9bad2649ca17f34b499357a1c upstream.

Hello.

I got below leak with linux-3.10.0-54.0.1.el7.x86_64 .

[  681.903890] kmemleak: 5538 new suspected memory leaks (see /sys/kernel/debug/kmemleak)

Below is a patch, but I don't know whether we need special handing for undoing
ebitmap_set_bit() call.
----------
>>From fe97527a90fe95e2239dfbaa7558f0ed559c0992 Mon Sep 17 00:00:00 2001
From: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Date: Mon, 6 Jan 2014 16:30:21 +0900
Subject: SELinux: Fix memory leak upon loading policy

Commit 2463c26d "SELinux: put name based create rules in a hashtable" did not
check return value from hashtab_insert() in filename_trans_read(). It leaks
memory if hashtab_insert() returns error.

  unreferenced object 0xffff88005c9160d0 (size 8):
    comm "systemd", pid 1, jiffies 4294688674 (age 235.265s)
    hex dump (first 8 bytes):
      57 0b 00 00 6b 6b 6b a5                          W...kkk.
    backtrace:
      [<ffffffff816604ae>] kmemleak_alloc+0x4e/0xb0
      [<ffffffff811cba5e>] kmem_cache_alloc_trace+0x12e/0x360
      [<ffffffff812aec5d>] policydb_read+0xd1d/0xf70
      [<ffffffff812b345c>] security_load_policy+0x6c/0x500
      [<ffffffff812a623c>] sel_write_load+0xac/0x750
      [<ffffffff811eb680>] vfs_write+0xc0/0x1f0
      [<ffffffff811ec08c>] SyS_write+0x4c/0xa0
      [<ffffffff81690419>] system_call_fastpath+0x16/0x1b
      [<ffffffffffffffff>] 0xffffffffffffffff

However, we should not return EEXIST error to the caller, or the systemd will
show below message and the boot sequence freezes.

  systemd[1]: Failed to load SELinux policy. Freezing.

Signed-off-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Acked-by: Eric Paris <eparis@redhat.com>
Signed-off-by: Paul Moore <pmoore@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

Change-Id: I5204ed79917dc5d0a4a5e7be7dff7a0035ac09b9