History log of /linux-master/drivers/usb/gadget/function/f_fs.c
Revision Date Author Comments
# 862b4165 02-Apr-2024 Paul Cercueil <paul@crapouillou.net>

usb: gadget: functionfs: Wait for fences before enqueueing DMABUF

Instead of bailing when fences have already been installed on the
DMABUF, wait for them (with a timeout) when doing a blocking operation.

This fixes the issue where userspace would submit a DMABUF with fences
already installed, with the (correct) expectation that it would just
work.

Fixes: 7b07a2a7ca02 ("usb: gadget: functionfs: Add DMABUF import interface")
Signed-off-by: Paul Cercueil <paul@crapouillou.net>
Link: https://lore.kernel.org/r/20240402110951.16376-3-paul@crapouillou.net
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 1500a7b2 02-Apr-2024 Paul Cercueil <paul@crapouillou.net>

usb: gadget: functionfs: Fix inverted DMA fence direction

A "read" fence was installed when the DMABUF was to be written to,
and a "write" fence was installed when the DMABUF was to be read from.

Besides, dma_resv_usage_rw() should only be used when waiting for
fences.

Fixes: 7b07a2a7ca02 ("usb: gadget: functionfs: Add DMABUF import interface")
Signed-off-by: Paul Cercueil <paul@crapouillou.net>
Link: https://lore.kernel.org/r/20240402110951.16376-2-paul@crapouillou.net
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 7b07a2a7 30-Jan-2024 Paul Cercueil <paul@crapouillou.net>

usb: gadget: functionfs: Add DMABUF import interface

This patch introduces three new ioctls. They all should be called on a
data endpoint (ie. not ep0). They are:

- FUNCTIONFS_DMABUF_ATTACH, which takes the file descriptor of a DMABUF
object to attach to the endpoint.

- FUNCTIONFS_DMABUF_DETACH, which takes the file descriptor of the
DMABUF to detach from the endpoint. Note that closing the endpoint's
file descriptor will automatically detach all attached DMABUFs.

- FUNCTIONFS_DMABUF_TRANSFER, which requests a data transfer from / to
the given DMABUF. Its argument is a structure that packs the DMABUF's
file descriptor, the size in bytes to transfer (which should generally
be set to the size of the DMABUF), and a 'flags' field which is unused
for now.
Before this ioctl can be used, the related DMABUF must be attached
with FUNCTIONFS_DMABUF_ATTACH.

These three ioctls enable the FunctionFS code to transfer data between
the USB stack and a DMABUF object, which can be provided by a driver
from a completely different subsystem, in a zero-copy fashion.

Signed-off-by: Paul Cercueil <paul@crapouillou.net>
Acked-by: Daniel Vetter <daniel.vetter@ffwll.ch>
Acked-by: Christian König <christian.koenig@amd.com>
Link: https://lore.kernel.org/r/20240130122340.54813-4-paul@crapouillou.net
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 799970a5 30-Jan-2024 Paul Cercueil <paul@crapouillou.net>

usb: gadget: functionfs: Factorize wait-for-endpoint code

This exact same code was duplicated in two different places.

Signed-off-by: Paul Cercueil <paul@crapouillou.net>
Link: https://lore.kernel.org/r/20240130122340.54813-3-paul@crapouillou.net
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 43a02972 26-Jan-2024 Peter Korsgaard <peter@korsgaard.com>

usb: gadget: f_fs: expose ready state in configfs

When a USB gadget is configured through configfs with 1 or more f_fs
functions, then the logic setting up the gadget configuration has to wait
until the user space code (typically separate applications) responsible for
those functions have written their descriptors before the gadget can be
activated.

The f_fs instance already knows if this has been done, so expose it through
a "ready" attribute in configfs for easier synchronization.

Signed-off-by: Peter Korsgaard <peter@korsgaard.com>
Link: https://lore.kernel.org/r/20240126203208.2482573-1-peter@korsgaard.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 61fbf203 13-Dec-2023 Dmitry Antipov <dmantipov@yandex.ru>

usb: gadget: f_fs: fix fortify warning

When compiling with gcc version 14.0.0 20231206 (experimental)
and CONFIG_FORTIFY_SOURCE=y, I've noticed the following warning:

...
In function 'fortify_memcpy_chk',
inlined from '__ffs_func_bind_do_os_desc' at drivers/usb/gadget/function/f_fs.c:2934:3:
./include/linux/fortify-string.h:588:25: warning: call to '__read_overflow2_field'
declared with attribute warning: detected read beyond size of field (2nd parameter);
maybe use struct_group()? [-Wattribute-warning]
588 | __read_overflow2_field(q_size_field, size);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This call to 'memcpy()' is interpreted as an attempt to copy both
'CompatibleID' and 'SubCompatibleID' of 'struct usb_ext_compat_desc'
from an address of the first one, which causes an overread warning.
Since we actually want to copy both of them at once, use the
convenient 'struct_group()' and 'sizeof_field()' here.

Signed-off-by: Dmitry Antipov <dmantipov@yandex.ru>
Link: https://lore.kernel.org/r/20231214090428.27292-1-dmantipov@yandex.ru
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 3652117f 22-Nov-2023 Christian Brauner <brauner@kernel.org>

eventfd: simplify eventfd_signal()

Ever since the eventfd type was introduced back in 2007 in commit
e1ad7468c77d ("signal/timer/event: eventfd core") the eventfd_signal()
function only ever passed 1 as a value for @n. There's no point in
keeping that additional argument.

Link: https://lore.kernel.org/r/20231122-vfs-eventfd-signal-v2-2-bd549b14ce0c@kernel.org
Acked-by: Xu Yilun <yilun.xu@intel.com>
Acked-by: Andrew Donnellan <ajd@linux.ibm.com> # ocxl
Acked-by: Eric Farman <farman@linux.ibm.com> # s390
Reviewed-by: Jan Kara <jack@suse.cz>
Reviewed-by: Jens Axboe <axboe@kernel.dk>
Signed-off-by: Christian Brauner <brauner@kernel.org>


# 9a0518de 04-Oct-2023 Jeff Layton <jlayton@kernel.org>

function: convert to new timestamp accessors

Convert to using the new inode timestamp accessor functions.

Signed-off-by: Jeff Layton <jlayton@kernel.org>
Link: https://lore.kernel.org/r/20231004185347.80880-10-jlayton@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>


# c7c4ac7f 15-Sep-2023 Kees Cook <keescook@chromium.org>

usb: gadget: f_fs: Annotate struct ffs_buffer with __counted_by

Prepare for the coming implementation by GCC and Clang of the __counted_by
attribute. Flexible array members annotated with __counted_by can have
their accesses bounds-checked at run-time checking via CONFIG_UBSAN_BOUNDS
(for array indexing) and CONFIG_FORTIFY_SOURCE (for strcpy/memcpy-family
functions).

As found with Coccinelle[1], add __counted_by for struct ffs_buffer.

[1] https://github.com/kees/kernel-tools/blob/trunk/coccinelle/examples/counted_by.cocci

Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: John Keeping <john@keeping.me.uk>
Cc: Udipto Goswami <quic_ugoswami@quicinc.com>
Cc: Linyu Yuan <quic_linyyuan@quicinc.com>
Cc: linux-usb@vger.kernel.org
Reviewed-by: "Gustavo A. R. Silva" <gustavoars@kernel.org>
Link: https://lore.kernel.org/r/20230915195849.never.275-kees@kernel.org
Signed-off-by: Kees Cook <keescook@chromium.org>


# c7603adc 05-Jul-2023 Jeff Layton <jlayton@kernel.org>

usb: convert to ctime accessor functions

In later patches, we're going to change how the inode's ctime field is
used. Switch to using accessor functions instead of raw accesses of
inode->i_ctime.

Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Jan Kara <jack@suse.cz>
Signed-off-by: Jeff Layton <jlayton@kernel.org>
Message-Id: <20230705190309.579783-18-jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>


# efb6b535 25-May-2023 Uttkarsh Aggarwal <quic_uaggarwa@quicinc.com>

usb: gadget: f_fs: Add unbind event before functionfs_unbind

While exercising the unbind path, with the current implementation
the functionfs_unbind would be calling which waits for the ffs->mutex
to be available, however within the same time ffs_ep0_read is invoked
& if no setup packets are pending, it will invoke function
wait_event_interruptible_exclusive_locked_irq which by definition waits
for the ev.count to be increased inside the same mutex for which
functionfs_unbind is waiting.
This creates deadlock situation because the functionfs_unbind won't
get the lock until ev.count is increased which can only happen if
the caller ffs_func_unbind can proceed further.

Following is the illustration:

CPU1 CPU2

ffs_func_unbind() ffs_ep0_read()
mutex_lock(ffs->mutex)
wait_event(ffs->ev.count)
functionfs_unbind()
mutex_lock(ffs->mutex)
mutex_unlock(ffs->mutex)

ffs_event_add()

<deadlock>

Fix this by moving the event unbind before functionfs_unbind
to ensure the ev.count is incrased properly.

Fixes: 6a19da111057 ("usb: gadget: f_fs: Prevent race during ffs_ep0_queue_wait")
Cc: stable <stable@kernel.org>
Signed-off-by: Uttkarsh Aggarwal <quic_uaggarwa@quicinc.com>
Link: https://lore.kernel.org/r/20230525092854.7992-1-quic_uaggarwa@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# f54134b3 27-Mar-2023 Linyu Yuan <quic_linyyuan@quicinc.com>

usb: gadget: ffs: remove ENTER() macro

ENTER() used to show function name which called during runtime, ftrace can
be used to get same information, let's remove it.

Signed-off-by: Linyu Yuan <quic_linyyuan@quicinc.com>
Link: https://lore.kernel.org/r/1679911940-4727-1-git-send-email-quic_linyyuan@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 180bb831 28-Feb-2023 Yuta Hayama <hayama@lineo.co.jp>

usb: gadget: f_fs: Fix incorrect version checking of OS descs

Currently, the USB gadget framework supports only version 1.0 of the MS OS
descriptor. OS desc has a field bcdVersion indicating its version, with
v1.0 represented by the value 0x100. However, __ffs_do_os_desc_header()
was expecting the incorrect value 0x1, so allow the correct value 0x100.

The bcdVersion field of the descriptor that is actually sent to the host
is set by composite_setup() (in composite.c) to the fixed value 0x100.
Therefore, it can be understood that __ffs_do_os_desc_header() is only
performing a format check of the OS desc passed to functionfs. If a value
other than 0x100 is accepted, there is no effect on communication over
the USB bus. Indeed, until now __ffs_do_os_desc_header() has only accepted
the incorrect value 0x1, but there was no problem with the communication
over the USB bus.

However, this can be confusing for functionfs userspace drivers. Since
bcdVersion=0x100 is used in actual communication, functionfs should accept
the value 0x100.

Note that the correct value for bcdVersion in OS desc v1.0 is 0x100, but
to avoid breaking old userspace drivers, the value 0x1 is also accepted as
an exception. At this time, a message is output to notify the user to fix
the userspace driver.

Signed-off-by: Yuta Hayama <hayama@lineo.co.jp>
Reviewed-by: Andrzej Pietrasiewicz <andrzej.p@collabora.com>
Link: https://lore.kernel.org/r/290f96db-1877-5137-373a-318e7b4f2dde@lineo.co.jp
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# d356b3cd 01-Apr-2023 Sandeep Dhavale <dhavale@google.com>

usb: gadget: f_fs: Fix ffs_epfile_read_iter to handle ITER_UBUF

iov_iter for ffs_epfile_read_iter can be ITER_UBUF with io_uring.
In that case dup_iter() does not have to allocate anything and it
can return NULL. ffs_epfile_read_iter treats this as a failure and
returns -ENOMEM. Fix it by checking if iter_is_ubuf().

Fixes: 1e23db450cff ("io_uring: use iter_ubuf for single range imports")
Signed-off-by: Sandeep Dhavale <dhavale@google.com>
Acked-by: Jens Axboe <axboe@kernel.dk>
Link: https://lore.kernel.org/r/20230401060509.3608259-2-dhavale@google.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# b566d388 24-Nov-2022 John Keeping <john@metanate.com>

usb: gadget: f_fs: use io_data->status consistently

Commit fb1f16d74e26 ("usb: gadget: f_fs: change ep->status safe in
ffs_epfile_io()") added a new ffs_io_data::status field to fix lifetime
issues in synchronous requests.

While there are no similar lifetime issues for asynchronous requests
(the separate ep member in ffs_io_data avoids them) using the status
field means the USB request can be freed earlier and that there is more
consistency between the synchronous and asynchronous I/O paths.

Cc: Linyu Yuan <quic_linyyuan@quicinc.com>
Signed-off-by: John Keeping <john@metanate.com>
Reviewed-by: Linyu Yuan <quic_linyyuan@quicinc.com>
Link: https://lore.kernel.org/r/20221124170430.3998755-1-john@metanate.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 921deb9d 24-Jan-2023 Udipto Goswami <quic_ugoswami@quicinc.com>

usb: gadget: f_fs: Fix unbalanced spinlock in __ffs_ep0_queue_wait

__ffs_ep0_queue_wait executes holding the spinlock of &ffs->ev.waitq.lock
and unlocks it after the assignments to usb_request are done.
However in the code if the request is already NULL we bail out returning
-EINVAL but never unlocked the spinlock.

Fix this by adding spin_unlock_irq &ffs->ev.waitq.lock before returning.

Fixes: 6a19da111057 ("usb: gadget: f_fs: Prevent race during ffs_ep0_queue_wait")
Reviewed-by: John Keeping <john@metanate.com>
Signed-off-by: Udipto Goswami <quic_ugoswami@quicinc.com>
Link: https://lore.kernel.org/r/20230124091149.18647-1-quic_ugoswami@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# ce405d56 14-Dec-2022 Udipto Goswami <quic_ugoswami@quicinc.com>

usb: gadget: f_fs: Ensure ep0req is dequeued before free_request

As per the documentation, function usb_ep_free_request guarantees
the request will not be queued or no longer be re-queued (or
otherwise used). However, with the current implementation it
doesn't make sure that the request in ep0 isn't reused.

Fix this by dequeuing the ep0req on functionfs_unbind before
freeing the request to align with the definition.

Fixes: ddf8abd25994 ("USB: f_fs: the FunctionFS driver")
Signed-off-by: Udipto Goswami <quic_ugoswami@quicinc.com>
Tested-by: Krishna Kurapati <quic_kriskura@quicinc.com>
Link: https://lore.kernel.org/r/20221215052906.8993-3-quic_ugoswami@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 6a19da11 14-Dec-2022 Udipto Goswami <quic_ugoswami@quicinc.com>

usb: gadget: f_fs: Prevent race during ffs_ep0_queue_wait

While performing fast composition switch, there is a possibility that the
process of ffs_ep0_write/ffs_ep0_read get into a race condition
due to ep0req being freed up from functionfs_unbind.

Consider the scenario that the ffs_ep0_write calls the ffs_ep0_queue_wait
by taking a lock &ffs->ev.waitq.lock. However, the functionfs_unbind isn't
bounded so it can go ahead and mark the ep0req to NULL, and since there
is no NULL check in ffs_ep0_queue_wait we will end up in use-after-free.

Fix this by making a serialized execution between the two functions using
a mutex_lock(ffs->mutex).

Fixes: ddf8abd25994 ("USB: f_fs: the FunctionFS driver")
Signed-off-by: Udipto Goswami <quic_ugoswami@quicinc.com>
Tested-by: Krishna Kurapati <quic_kriskura@quicinc.com>
Link: https://lore.kernel.org/r/20221215052906.8993-2-quic_ugoswami@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# f57004b9 01-Sep-2022 Dan Carpenter <dan.carpenter@oracle.com>

usb: gadget: f_fs: stricter integer overflow checks

This from static analysis. The vla_item() takes a size and adds it to
the total. It has a built in integer overflow check so if it encounters
an integer overflow anywhere then it records the total as SIZE_MAX.

However there is an issue here because the "lang_count*(needed_count+1)"
multiplication can overflow. Technically the "lang_count + 1" addition
could overflow too, but that would be detected and is harmless. Fix
both using the new size_add() and size_mul() functions.

Fixes: e6f3862fa1ec ("usb: gadget: FunctionFS: Remove VLAIS usage from gadget code")
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Link: https://lore.kernel.org/r/YxDI3lMYomE7WCjn@kili
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# b7db5733 18-Aug-2022 Wolfram Sang <wsa+renesas@sang-engineering.com>

usb: move from strlcpy with unused retval to strscpy

Follow the advice of the below link and prefer 'strscpy' in this
subsystem. Conversion is 1:1 because the return value is not used.
Generated by a coccinelle script.

Link: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw@mail.gmail.com/
Reviewed-by: Richard Leitner <richard.leitner@skidata.com>
Reviewed-by: Laurent Pinchart <laurent.pinchart+renesas@ideasonboard.com>
Acked-by: Shuah Khan <skhan@linuxfoundation.org>
Signed-off-by: Wolfram Sang <wsa+renesas@sang-engineering.com>
Link: https://lore.kernel.org/r/20220818210116.7517-1-wsa+renesas@sang-engineering.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 0698f020 10-Jun-2022 Linyu Yuan <quic_linyyuan@quicinc.com>

usb: gadget: f_fs: change ep->ep safe in ffs_epfile_io()

In ffs_epfile_io(), when read/write data in blocking mode, it will wait
the completion in interruptible mode, if task receive a signal, it will
terminate the wait, at same time, if function unbind occurs,
ffs_func_unbind() will kfree all eps, ffs_epfile_io() still try to
dequeue request by dereferencing ep which may become invalid.

Fix it by add ep spinlock and will not dereference ep if it is not valid.

Cc: <stable@vger.kernel.org> # 5.15
Reported-by: Michael Wu <michael@allwinnertech.com>
Tested-by: Michael Wu <michael@allwinnertech.com>
Reviewed-by: John Keeping <john@metanate.com>
Signed-off-by: Linyu Yuan <quic_linyyuan@quicinc.com>
Link: https://lore.kernel.org/r/1654863478-26228-3-git-send-email-quic_linyyuan@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# fb1f16d7 10-Jun-2022 Linyu Yuan <quic_linyyuan@quicinc.com>

usb: gadget: f_fs: change ep->status safe in ffs_epfile_io()

If a task read/write data in blocking mode, it will wait the completion
in ffs_epfile_io(), if function unbind occurs, ffs_func_unbind() will
kfree ffs ep, once the task wake up, it still dereference the ffs ep to
obtain the request status.

Fix it by moving the request status to io_data which is stack-safe.

Cc: <stable@vger.kernel.org> # 5.15
Reported-by: Michael Wu <michael@allwinnertech.com>
Tested-by: Michael Wu <michael@allwinnertech.com>
Reviewed-by: John Keeping <john@metanate.com>
Signed-off-by: Linyu Yuan <quic_linyyuan@quicinc.com>
Link: https://lore.kernel.org/r/1654863478-26228-2-git-send-email-quic_linyyuan@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 4213e92e 20-Jan-2022 Gustavo A. R. Silva <gustavoars@kernel.org>

usb: gadget: f_fs: Use struct_size() and flex_array_size() helpers

Make use of the struct_size() and flex_array_size() helpers instead of
an open-coded version, in order to avoid any potential type mistakes
or integer overflows that, in the worst scenario, could lead to heap
overflows.

Also, address the following sparse warnings:
drivers/usb/gadget/function/f_fs.c:922:23: warning: using sizeof on a flexible structure

Link: https://github.com/KSPP/linux/issues/174
Reviewed-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Gustavo A. R. Silva <gustavoars@kernel.org>
Link: https://lore.kernel.org/r/20220120222933.GA35155@embeddedor
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# ebe2b1ad 26-Jan-2022 Udipto Goswami <quic_ugoswami@quicinc.com>

usb: f_fs: Fix use-after-free for epfile

Consider a case where ffs_func_eps_disable is called from
ffs_func_disable as part of composition switch and at the
same time ffs_epfile_release get called from userspace.
ffs_epfile_release will free up the read buffer and call
ffs_data_closed which in turn destroys ffs->epfiles and
mark it as NULL. While this was happening the driver has
already initialized the local epfile in ffs_func_eps_disable
which is now freed and waiting to acquire the spinlock. Once
spinlock is acquired the driver proceeds with the stale value
of epfile and tries to free the already freed read buffer
causing use-after-free.

Following is the illustration of the race:

CPU1 CPU2

ffs_func_eps_disable
epfiles (local copy)
ffs_epfile_release
ffs_data_closed
if (last file closed)
ffs_data_reset
ffs_data_clear
ffs_epfiles_destroy
spin_lock
dereference epfiles

Fix this races by taking epfiles local copy & assigning it under
spinlock and if epfiles(local) is null then update it in ffs->epfiles
then finally destroy it.
Extending the scope further from the race, protecting the ep related
structures, and concurrent accesses.

Fixes: a9e6f83c2df1 ("usb: gadget: f_fs: stop sleeping in ffs_func_eps_disable")
Co-developed-by: Udipto Goswami <quic_ugoswami@quicinc.com>
Reviewed-by: John Keeping <john@metanate.com>
Signed-off-by: Pratham Pratap <quic_ppratap@quicinc.com>
Signed-off-by: Udipto Goswami <quic_ugoswami@quicinc.com>
Link: https://lore.kernel.org/r/1643256595-10797-1-git-send-email-quic_ugoswami@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# c76ef96f 12-Nov-2021 Pavankumar Kondeti <quic_pkondeti@quicinc.com>

usb: gadget: f_fs: Use stream_open() for endpoint files

Function fs endpoint file operations are synchronized via an interruptible
mutex wait. However we see threads that do ep file operations concurrently
are getting blocked for the mutex lock in __fdget_pos(). This is an
uninterruptible wait and we see hung task warnings and kernel panic
if hung_task_panic systcl is enabled if host does not send/receive
the data for long time.

The reason for threads getting blocked in __fdget_pos() is due to
the file position protection introduced by the commit 9c225f2655e3
("vfs: atomic f_pos accesses as per POSIX"). Since function fs
endpoint files does not have the notion of the file position, switch
to the stream mode. This will bypass the file position mutex and
threads will be blocked in interruptible state for the function fs
mutex.

It should not affects user space as we are only changing the task state
changes the task state from UNINTERRUPTIBLE to INTERRUPTIBLE while waiting
for the USB transfers to be finished. However there is a slight change to
the O_NONBLOCK behavior. Earlier threads that are using O_NONBLOCK are also
getting blocked inside fdget_pos(). Now they reach to function fs and error
code is returned. The non blocking behavior is actually honoured now.

Reviewed-by: John Keeping <john@metanate.com>
Signed-off-by: Pavankumar Kondeti <quic_pkondeti@quicinc.com>
Link: https://lore.kernel.org/r/1636712682-1226-1-git-send-email-quic_pkondeti@quicinc.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# b1e088737 17-Dec-2021 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: f_fs: Clear ffs_eventfd in ffs_data_clear.

ffs_data_clear is indirectly called from both ffs_fs_kill_sb and
ffs_ep0_release, so it ends up being called twice when userland closes ep0
and then unmounts f_fs.
If userland provided an eventfd along with function's USB descriptors, it
ends up calling eventfd_ctx_put as many times, causing a refcount
underflow.
NULL-ify ffs_eventfd to prevent these extraneous eventfd_ctx_put calls.

Also, set epfiles to NULL right after de-allocating it, for readability.

For completeness, ffs_data_clear actually ends up being called thrice, the
last call being before the whole ffs structure gets freed, so when this
specific sequence happens there is a second underflow happening (but not
being reported):

/sys/kernel/debug/tracing# modprobe usb_f_fs
/sys/kernel/debug/tracing# echo ffs_data_clear > set_ftrace_filter
/sys/kernel/debug/tracing# echo function > current_tracer
/sys/kernel/debug/tracing# echo 1 > tracing_on
(setup gadget, run and kill function userland process, teardown gadget)
/sys/kernel/debug/tracing# echo 0 > tracing_on
/sys/kernel/debug/tracing# cat trace
smartcard-openp-436 [000] ..... 1946.208786: ffs_data_clear <-ffs_data_closed
smartcard-openp-431 [000] ..... 1946.279147: ffs_data_clear <-ffs_data_closed
smartcard-openp-431 [000] .n... 1946.905512: ffs_data_clear <-ffs_data_put

Warning output corresponding to above trace:
[ 1946.284139] WARNING: CPU: 0 PID: 431 at lib/refcount.c:28 refcount_warn_saturate+0x110/0x15c
[ 1946.293094] refcount_t: underflow; use-after-free.
[ 1946.298164] Modules linked in: usb_f_ncm(E) u_ether(E) usb_f_fs(E) hci_uart(E) btqca(E) btrtl(E) btbcm(E) btintel(E) bluetooth(E) nls_ascii(E) nls_cp437(E) vfat(E) fat(E) bcm2835_v4l2(CE) bcm2835_mmal_vchiq(CE) videobuf2_vmalloc(E) videobuf2_memops(E) sha512_generic(E) videobuf2_v4l2(E) sha512_arm(E) videobuf2_common(E) videodev(E) cpufreq_dt(E) snd_bcm2835(CE) brcmfmac(E) mc(E) vc4(E) ctr(E) brcmutil(E) snd_soc_core(E) snd_pcm_dmaengine(E) drbg(E) snd_pcm(E) snd_timer(E) snd(E) soundcore(E) drm_kms_helper(E) cec(E) ansi_cprng(E) rc_core(E) syscopyarea(E) raspberrypi_cpufreq(E) sysfillrect(E) sysimgblt(E) cfg80211(E) max17040_battery(OE) raspberrypi_hwmon(E) fb_sys_fops(E) regmap_i2c(E) ecdh_generic(E) rfkill(E) ecc(E) bcm2835_rng(E) rng_core(E) vchiq(CE) leds_gpio(E) libcomposite(E) fuse(E) configfs(E) ip_tables(E) x_tables(E) autofs4(E) ext4(E) crc16(E) mbcache(E) jbd2(E) crc32c_generic(E) sdhci_iproc(E) sdhci_pltfm(E) sdhci(E)
[ 1946.399633] CPU: 0 PID: 431 Comm: smartcard-openp Tainted: G C OE 5.15.0-1-rpi #1 Debian 5.15.3-1
[ 1946.417950] Hardware name: BCM2835
[ 1946.425442] Backtrace:
[ 1946.432048] [<c08d60a0>] (dump_backtrace) from [<c08d62ec>] (show_stack+0x20/0x24)
[ 1946.448226] r7:00000009 r6:0000001c r5:c04a948c r4:c0a64e2c
[ 1946.458412] [<c08d62cc>] (show_stack) from [<c08d9ae0>] (dump_stack+0x28/0x30)
[ 1946.470380] [<c08d9ab8>] (dump_stack) from [<c0123500>] (__warn+0xe8/0x154)
[ 1946.482067] r5:c04a948c r4:c0a71dc8
[ 1946.490184] [<c0123418>] (__warn) from [<c08d6948>] (warn_slowpath_fmt+0xa0/0xe4)
[ 1946.506758] r7:00000009 r6:0000001c r5:c0a71dc8 r4:c0a71e04
[ 1946.517070] [<c08d68ac>] (warn_slowpath_fmt) from [<c04a948c>] (refcount_warn_saturate+0x110/0x15c)
[ 1946.535309] r8:c0100224 r7:c0dfcb84 r6:ffffffff r5:c3b84c00 r4:c24a17c0
[ 1946.546708] [<c04a937c>] (refcount_warn_saturate) from [<c0380134>] (eventfd_ctx_put+0x48/0x74)
[ 1946.564476] [<c03800ec>] (eventfd_ctx_put) from [<bf5464e8>] (ffs_data_clear+0xd0/0x118 [usb_f_fs])
[ 1946.582664] r5:c3b84c00 r4:c2695b00
[ 1946.590668] [<bf546418>] (ffs_data_clear [usb_f_fs]) from [<bf547cc0>] (ffs_data_closed+0x9c/0x150 [usb_f_fs])
[ 1946.609608] r5:bf54d014 r4:c2695b00
[ 1946.617522] [<bf547c24>] (ffs_data_closed [usb_f_fs]) from [<bf547da0>] (ffs_fs_kill_sb+0x2c/0x30 [usb_f_fs])
[ 1946.636217] r7:c0dfcb84 r6:c3a12260 r5:bf54d014 r4:c229f000
[ 1946.646273] [<bf547d74>] (ffs_fs_kill_sb [usb_f_fs]) from [<c0326d50>] (deactivate_locked_super+0x54/0x9c)
[ 1946.664893] r5:bf54d014 r4:c229f000
[ 1946.672921] [<c0326cfc>] (deactivate_locked_super) from [<c0326df8>] (deactivate_super+0x60/0x64)
[ 1946.690722] r5:c2a09000 r4:c229f000
[ 1946.698706] [<c0326d98>] (deactivate_super) from [<c0349a28>] (cleanup_mnt+0xe4/0x14c)
[ 1946.715553] r5:c2a09000 r4:00000000
[ 1946.723528] [<c0349944>] (cleanup_mnt) from [<c0349b08>] (__cleanup_mnt+0x1c/0x20)
[ 1946.739922] r7:c0dfcb84 r6:c3a12260 r5:c3a126fc r4:00000000
[ 1946.750088] [<c0349aec>] (__cleanup_mnt) from [<c0143d10>] (task_work_run+0x84/0xb8)
[ 1946.766602] [<c0143c8c>] (task_work_run) from [<c010bdc8>] (do_work_pending+0x470/0x56c)
[ 1946.783540] r7:5ac3c35a r6:c0d0424c r5:c200bfb0 r4:c200a000
[ 1946.793614] [<c010b958>] (do_work_pending) from [<c01000c0>] (slow_work_pending+0xc/0x20)
[ 1946.810553] Exception stack(0xc200bfb0 to 0xc200bff8)
[ 1946.820129] bfa0: 00000000 00000000 000000aa b5e21430
[ 1946.837104] bfc0: bef867a0 00000001 bef86840 00000034 bef86838 bef86790 bef86794 bef867a0
[ 1946.854125] bfe0: 00000000 bef86798 b67b7a1c b6d626a4 60000010 b5a23760
[ 1946.865335] r10:00000000 r9:c200a000 r8:c0100224 r7:00000034 r6:bef86840 r5:00000001
[ 1946.881914] r4:bef867a0
[ 1946.888793] ---[ end trace 7387f2a9725b28d0 ]---

Fixes: 5e33f6fdf735 ("usb: gadget: ffs: add eventfd notification about ffs events")
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Link: https://lore.kernel.org/r/f79eeea29f3f98de6782a064ec0f7351ad2f598f.1639793920.git.plr.vincent@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 6b19b766 21-Oct-2021 Jens Axboe <axboe@kernel.dk>

fs: get rid of the res2 iocb->ki_complete argument

The second argument was only used by the USB gadget code, yet everyone
pays the overhead of passing a zero to be passed into aio, where it
ends up being part of the aio res2 value.

Now that everybody is passing in zero, kill off the extra argument.

Reviewed-by: Darrick J. Wong <djwong@kernel.org>
Signed-off-by: Jens Axboe <axboe@kernel.dk>


# 4c3d8acc 23-Oct-2021 Jens Axboe <axboe@kernel.dk>

usb: remove res2 argument from gadget code completions

The USB gadget code is the only code that every tried to utilize the
2nd argument of the aio completions, but there are strong suspicions
that it was never actually used by anything on the userspace side.

Out of the 3 cases that touch it, two of them just pass in the same
as res, and the last one passes in error/transfer in res like any
other normal use case.

Remove the 2nd argument, pass 0 like the rest of the in-kernel users
of kiocb based IO.

Link: https://lore.kernel.org/linux-block/20211021174021.273c82b1.john@metanate.com/
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Jens Axboe <axboe@kernel.dk>


# 90059e93 31-Jul-2021 Salah Triki <salah.triki@gmail.com>

usb: gadget: remove useless cast

Remove the cast done by ERR_PTR() and PTR_ERR() since data is of type char
* and fss_prepare_buffer() should returns a value of this type.

Acked-by: Felipe Balbi <balbi@kernel.org>
Signed-off-by: Salah Triki <salah.triki@gmail.com>
Link: https://lore.kernel.org/r/20210731171838.GA912463@pc
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 9311a531 31-Jul-2021 Wei Ming Chen <jj251510319013@gmail.com>

usb: gadget: Fix inconsistent indent

Remove whitespace and use tab as indent

Acked-by: Felipe Balbi <balbi@kernel.org>
Signed-off-by: Wei Ming Chen <jj251510319013@gmail.com>
Link: https://lore.kernel.org/r/20210801055454.53015-1-jj251510319013@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# ecfbd7b9 02-Jun-2021 Andrew Gabbasov <andrew_gabbasov@mentor.com>

usb: gadget: f_fs: Fix setting of device and driver data cross-references

FunctionFS device structure 'struct ffs_dev' and driver data structure
'struct ffs_data' are bound to each other with cross-reference pointers
'ffs_data->private_data' and 'ffs_dev->ffs_data'. While the first one
is supposed to be valid through the whole life of 'struct ffs_data'
(and while 'struct ffs_dev' exists non-freed), the second one is cleared
in 'ffs_closed()' (called from 'ffs_data_reset()' or the last
'ffs_data_put()'). This can be called several times, alternating in
different order with 'ffs_free_inst()', that, if possible, clears
the other cross-reference.

As a result, different cases of these calls order may leave stale
cross-reference pointers, used when the pointed structure is already
freed. Even if it occasionally doesn't cause kernel crash, this error
is reported by KASAN-enabled kernel configuration.

For example, the case [last 'ffs_data_put()' - 'ffs_free_inst()'] was
fixed by commit cdafb6d8b8da ("usb: gadget: f_fs: Fix use-after-free in
ffs_free_inst").

The other case ['ffs_data_reset()' - 'ffs_free_inst()' - 'ffs_data_put()']
now causes KASAN reported error [1], when 'ffs_data_reset()' clears
'ffs_dev->ffs_data', then 'ffs_free_inst()' frees the 'struct ffs_dev',
but can't clear 'ffs_data->private_data', which is then accessed
in 'ffs_closed()' called from 'ffs_data_put()'. This happens since
'ffs_dev->ffs_data' reference is cleared too early.

Moreover, one more use case, when 'ffs_free_inst()' is called immediately
after mounting FunctionFS device (that is before the descriptors are
written and 'ffs_ready()' is called), and then 'ffs_data_reset()'
or 'ffs_data_put()' is called from accessing "ep0" file or unmounting
the device. This causes KASAN error report like [2], since
'ffs_dev->ffs_data' is not yet set when 'ffs_free_inst()' can't properly
clear 'ffs_data->private_data', that is later accessed to freed structure.

Fix these (and may be other) cases of stale pointers access by moving
setting and clearing of the mentioned cross-references to the single
places, setting both of them when 'struct ffs_data' is created and
bound to 'struct ffs_dev', and clearing both of them when one of the
structures is destroyed. It seems convenient to make this pointer
initialization and structures binding in 'ffs_acquire_dev()' and
make pointers clearing in 'ffs_release_dev()'. This required some
changes in these functions parameters and return types.

Also, 'ffs_release_dev()' calling requires some cleanup, fixing minor
issues, like (1) 'ffs_release_dev()' is not called if 'ffs_free_inst()'
is called without unmounting the device, and "release_dev" callback
is not called at all, or (2) "release_dev" callback is called before
"ffs_closed" callback on unmounting, which seems to be not correctly
nested with "acquire_dev" and "ffs_ready" callbacks.
Make this cleanup togther with other mentioned 'ffs_release_dev()' changes.

[1]
==================================================================
root@rcar-gen3:~# mkdir /dev/cfs
root@rcar-gen3:~# mkdir /dev/ffs
root@rcar-gen3:~# modprobe libcomposite
root@rcar-gen3:~# mount -t configfs none /dev/cfs
root@rcar-gen3:~# mkdir /dev/cfs/usb_gadget/g1
root@rcar-gen3:~# mkdir /dev/cfs/usb_gadget/g1/functions/ffs.ffs
[ 64.340664] file system registered
root@rcar-gen3:~# mount -t functionfs ffs /dev/ffs
root@rcar-gen3:~# cd /dev/ffs
root@rcar-gen3:/dev/ffs# /home/root/ffs-test
ffs-test: info: ep0: writing descriptors (in v2 format)
[ 83.181442] read descriptors
[ 83.186085] read strings
ffs-test: info: ep0: writing strings
ffs-test: dbg: ep1: starting
ffs-test: dbg: ep2: starting
ffs-test: info: ep1: starts
ffs-test: info: ep2: starts
ffs-test: info: ep0: starts

^C
root@rcar-gen3:/dev/ffs# cd /home/root/
root@rcar-gen3:~# rmdir /dev/cfs/usb_gadget/g1/functions/ffs.ffs
[ 98.935061] unloading
root@rcar-gen3:~# umount /dev/ffs
[ 102.734301] ==================================================================
[ 102.742059] BUG: KASAN: use-after-free in ffs_release_dev+0x64/0xa8 [usb_f_fs]
[ 102.749683] Write of size 1 at addr ffff0004d46ff549 by task umount/2997
[ 102.756709]
[ 102.758311] CPU: 0 PID: 2997 Comm: umount Not tainted 5.13.0-rc4+ #8
[ 102.764971] Hardware name: Renesas Salvator-X board based on r8a77951 (DT)
[ 102.772179] Call trace:
[ 102.774779] dump_backtrace+0x0/0x330
[ 102.778653] show_stack+0x20/0x2c
[ 102.782152] dump_stack+0x11c/0x1ac
[ 102.785833] print_address_description.constprop.0+0x30/0x274
[ 102.791862] kasan_report+0x14c/0x1c8
[ 102.795719] __asan_report_store1_noabort+0x34/0x58
[ 102.800840] ffs_release_dev+0x64/0xa8 [usb_f_fs]
[ 102.805801] ffs_fs_kill_sb+0x50/0x84 [usb_f_fs]
[ 102.810663] deactivate_locked_super+0xa0/0xf0
[ 102.815339] deactivate_super+0x98/0xac
[ 102.819378] cleanup_mnt+0xd0/0x1b0
[ 102.823057] __cleanup_mnt+0x1c/0x28
[ 102.826823] task_work_run+0x104/0x180
[ 102.830774] do_notify_resume+0x458/0x14e0
[ 102.835083] work_pending+0xc/0x5f8
[ 102.838762]
[ 102.840357] Allocated by task 2988:
[ 102.844032] kasan_save_stack+0x28/0x58
[ 102.848071] kasan_set_track+0x28/0x3c
[ 102.852016] ____kasan_kmalloc+0x84/0x9c
[ 102.856142] __kasan_kmalloc+0x10/0x1c
[ 102.860088] __kmalloc+0x214/0x2f8
[ 102.863678] kzalloc.constprop.0+0x14/0x20 [usb_f_fs]
[ 102.868990] ffs_alloc_inst+0x8c/0x208 [usb_f_fs]
[ 102.873942] try_get_usb_function_instance+0xf0/0x164 [libcomposite]
[ 102.880629] usb_get_function_instance+0x64/0x68 [libcomposite]
[ 102.886858] function_make+0x128/0x1ec [libcomposite]
[ 102.892185] configfs_mkdir+0x330/0x590 [configfs]
[ 102.897245] vfs_mkdir+0x12c/0x1bc
[ 102.900835] do_mkdirat+0x180/0x1d0
[ 102.904513] __arm64_sys_mkdirat+0x80/0x94
[ 102.908822] invoke_syscall+0xf8/0x25c
[ 102.912772] el0_svc_common.constprop.0+0x150/0x1a0
[ 102.917891] do_el0_svc+0xa0/0xd4
[ 102.921386] el0_svc+0x24/0x34
[ 102.924613] el0_sync_handler+0xcc/0x154
[ 102.928743] el0_sync+0x198/0x1c0
[ 102.932238]
[ 102.933832] Freed by task 2996:
[ 102.937144] kasan_save_stack+0x28/0x58
[ 102.941181] kasan_set_track+0x28/0x3c
[ 102.945128] kasan_set_free_info+0x28/0x4c
[ 102.949435] ____kasan_slab_free+0x104/0x118
[ 102.953921] __kasan_slab_free+0x18/0x24
[ 102.958047] slab_free_freelist_hook+0x148/0x1f0
[ 102.962897] kfree+0x318/0x440
[ 102.966123] ffs_free_inst+0x164/0x2d8 [usb_f_fs]
[ 102.971075] usb_put_function_instance+0x84/0xa4 [libcomposite]
[ 102.977302] ffs_attr_release+0x18/0x24 [usb_f_fs]
[ 102.982344] config_item_put+0x140/0x1a4 [configfs]
[ 102.987486] configfs_rmdir+0x3fc/0x518 [configfs]
[ 102.992535] vfs_rmdir+0x114/0x234
[ 102.996122] do_rmdir+0x274/0x2b0
[ 102.999617] __arm64_sys_unlinkat+0x94/0xc8
[ 103.004015] invoke_syscall+0xf8/0x25c
[ 103.007961] el0_svc_common.constprop.0+0x150/0x1a0
[ 103.013080] do_el0_svc+0xa0/0xd4
[ 103.016575] el0_svc+0x24/0x34
[ 103.019801] el0_sync_handler+0xcc/0x154
[ 103.023930] el0_sync+0x198/0x1c0
[ 103.027426]
[ 103.029020] The buggy address belongs to the object at ffff0004d46ff500
[ 103.029020] which belongs to the cache kmalloc-128 of size 128
[ 103.042079] The buggy address is located 73 bytes inside of
[ 103.042079] 128-byte region [ffff0004d46ff500, ffff0004d46ff580)
[ 103.054236] The buggy address belongs to the page:
[ 103.059262] page:0000000021aa849b refcount:1 mapcount:0 mapping:0000000000000000 index:0xffff0004d46fee00 pfn:0x5146fe
[ 103.070437] head:0000000021aa849b order:1 compound_mapcount:0
[ 103.076456] flags: 0x8000000000010200(slab|head|zone=2)
[ 103.081948] raw: 8000000000010200 fffffc0013521a80 0000000d0000000d ffff0004c0002300
[ 103.090052] raw: ffff0004d46fee00 000000008020001e 00000001ffffffff 0000000000000000
[ 103.098150] page dumped because: kasan: bad access detected
[ 103.103985]
[ 103.105578] Memory state around the buggy address:
[ 103.110602] ffff0004d46ff400: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 103.118161] ffff0004d46ff480: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 103.125726] >ffff0004d46ff500: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 103.133284] ^
[ 103.139120] ffff0004d46ff580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 103.146679] ffff0004d46ff600: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 103.154238] ==================================================================
[ 103.161792] Disabling lock debugging due to kernel taint
[ 103.167319] Unable to handle kernel paging request at virtual address 0037801d6000018e
[ 103.175406] Mem abort info:
[ 103.178457] ESR = 0x96000004
[ 103.181609] EC = 0x25: DABT (current EL), IL = 32 bits
[ 103.187020] SET = 0, FnV = 0
[ 103.190185] EA = 0, S1PTW = 0
[ 103.193417] Data abort info:
[ 103.196385] ISV = 0, ISS = 0x00000004
[ 103.200315] CM = 0, WnR = 0
[ 103.203366] [0037801d6000018e] address between user and kernel address ranges
[ 103.210611] Internal error: Oops: 96000004 [#1] PREEMPT SMP
[ 103.216231] Modules linked in: usb_f_fs libcomposite configfs ath9k_htc led_class mac80211 libarc4 ath9k_common ath9k_hw ath cfg80211 aes_ce_blk sata_rc4
[ 103.259233] CPU: 0 PID: 2997 Comm: umount Tainted: G B 5.13.0-rc4+ #8
[ 103.267031] Hardware name: Renesas Salvator-X board based on r8a77951 (DT)
[ 103.273951] pstate: 00000005 (nzcv daif -PAN -UAO -TCO BTYPE=--)
[ 103.280001] pc : ffs_data_clear+0x138/0x370 [usb_f_fs]
[ 103.285197] lr : ffs_data_clear+0x124/0x370 [usb_f_fs]
[ 103.290385] sp : ffff800014777a80
[ 103.293725] x29: ffff800014777a80 x28: ffff0004d7649c80 x27: 0000000000000000
[ 103.300931] x26: ffff800014777fb0 x25: ffff60009aec9394 x24: ffff0004d7649ca4
[ 103.308136] x23: 1fffe0009a3d063a x22: dfff800000000000 x21: ffff0004d1e831d0
[ 103.315340] x20: e1c000eb00000bb4 x19: ffff0004d1e83000 x18: 0000000000000000
[ 103.322545] x17: 0000000000000000 x16: 0000000000000000 x15: 0000000000000000
[ 103.329748] x14: 0720072007200720 x13: 0720072007200720 x12: 1ffff000012ef658
[ 103.336952] x11: ffff7000012ef658 x10: 0720072007200720 x9 : ffff800011322648
[ 103.344157] x8 : ffff800014777818 x7 : ffff80000977b2c7 x6 : 0000000000000000
[ 103.351359] x5 : 0000000000000001 x4 : ffff7000012ef659 x3 : 0000000000000001
[ 103.358562] x2 : 0000000000000000 x1 : 1c38001d6000018e x0 : e1c000eb00000c70
[ 103.365766] Call trace:
[ 103.368235] ffs_data_clear+0x138/0x370 [usb_f_fs]
[ 103.373076] ffs_data_reset+0x20/0x304 [usb_f_fs]
[ 103.377829] ffs_data_closed+0x1ec/0x244 [usb_f_fs]
[ 103.382755] ffs_fs_kill_sb+0x70/0x84 [usb_f_fs]
[ 103.387420] deactivate_locked_super+0xa0/0xf0
[ 103.391905] deactivate_super+0x98/0xac
[ 103.395776] cleanup_mnt+0xd0/0x1b0
[ 103.399299] __cleanup_mnt+0x1c/0x28
[ 103.402906] task_work_run+0x104/0x180
[ 103.406691] do_notify_resume+0x458/0x14e0
[ 103.410823] work_pending+0xc/0x5f8
[ 103.414351] Code: b4000a54 9102f280 12000802 d343fc01 (38f66821)
[ 103.420490] ---[ end trace 57b43a50e8244f57 ]---
Segmentation fault
root@rcar-gen3:~#
==================================================================

[2]
==================================================================
root@rcar-gen3:~# mkdir /dev/ffs
root@rcar-gen3:~# modprobe libcomposite
root@rcar-gen3:~#
root@rcar-gen3:~# mount -t configfs none /dev/cfs
root@rcar-gen3:~# mkdir /dev/cfs/usb_gadget/g1
root@rcar-gen3:~# mkdir /dev/cfs/usb_gadget/g1/functions/ffs.ffs
[ 54.766480] file system registered
root@rcar-gen3:~# mount -t functionfs ffs /dev/ffs
root@rcar-gen3:~# rmdir /dev/cfs/usb_gadget/g1/functions/ffs.ffs
[ 63.197597] unloading
root@rcar-gen3:~# cat /dev/ffs/ep0
cat: read error:[ 67.213506] ==================================================================
[ 67.222095] BUG: KASAN: use-after-free in ffs_data_clear+0x70/0x370 [usb_f_fs]
[ 67.229699] Write of size 1 at addr ffff0004c26e974a by task cat/2994
[ 67.236446]
[ 67.238045] CPU: 0 PID: 2994 Comm: cat Not tainted 5.13.0-rc4+ #8
[ 67.244431] Hardware name: Renesas Salvator-X board based on r8a77951 (DT)
[ 67.251624] Call trace:
[ 67.254212] dump_backtrace+0x0/0x330
[ 67.258081] show_stack+0x20/0x2c
[ 67.261579] dump_stack+0x11c/0x1ac
[ 67.265260] print_address_description.constprop.0+0x30/0x274
[ 67.271286] kasan_report+0x14c/0x1c8
[ 67.275143] __asan_report_store1_noabort+0x34/0x58
[ 67.280265] ffs_data_clear+0x70/0x370 [usb_f_fs]
[ 67.285220] ffs_data_reset+0x20/0x304 [usb_f_fs]
[ 67.290172] ffs_data_closed+0x240/0x244 [usb_f_fs]
[ 67.295305] ffs_ep0_release+0x40/0x54 [usb_f_fs]
[ 67.300256] __fput+0x304/0x580
[ 67.303576] ____fput+0x18/0x24
[ 67.306893] task_work_run+0x104/0x180
[ 67.310846] do_notify_resume+0x458/0x14e0
[ 67.315154] work_pending+0xc/0x5f8
[ 67.318834]
[ 67.320429] Allocated by task 2988:
[ 67.324105] kasan_save_stack+0x28/0x58
[ 67.328144] kasan_set_track+0x28/0x3c
[ 67.332090] ____kasan_kmalloc+0x84/0x9c
[ 67.336217] __kasan_kmalloc+0x10/0x1c
[ 67.340163] __kmalloc+0x214/0x2f8
[ 67.343754] kzalloc.constprop.0+0x14/0x20 [usb_f_fs]
[ 67.349066] ffs_alloc_inst+0x8c/0x208 [usb_f_fs]
[ 67.354017] try_get_usb_function_instance+0xf0/0x164 [libcomposite]
[ 67.360705] usb_get_function_instance+0x64/0x68 [libcomposite]
[ 67.366934] function_make+0x128/0x1ec [libcomposite]
[ 67.372260] configfs_mkdir+0x330/0x590 [configfs]
[ 67.377320] vfs_mkdir+0x12c/0x1bc
[ 67.380911] do_mkdirat+0x180/0x1d0
[ 67.384589] __arm64_sys_mkdirat+0x80/0x94
[ 67.388899] invoke_syscall+0xf8/0x25c
[ 67.392850] el0_svc_common.constprop.0+0x150/0x1a0
[ 67.397969] do_el0_svc+0xa0/0xd4
[ 67.401464] el0_svc+0x24/0x34
[ 67.404691] el0_sync_handler+0xcc/0x154
[ 67.408819] el0_sync+0x198/0x1c0
[ 67.412315]
[ 67.413909] Freed by task 2993:
[ 67.417220] kasan_save_stack+0x28/0x58
[ 67.421257] kasan_set_track+0x28/0x3c
[ 67.425204] kasan_set_free_info+0x28/0x4c
[ 67.429513] ____kasan_slab_free+0x104/0x118
[ 67.434001] __kasan_slab_free+0x18/0x24
[ 67.438128] slab_free_freelist_hook+0x148/0x1f0
[ 67.442978] kfree+0x318/0x440
[ 67.446205] ffs_free_inst+0x164/0x2d8 [usb_f_fs]
[ 67.451156] usb_put_function_instance+0x84/0xa4 [libcomposite]
[ 67.457385] ffs_attr_release+0x18/0x24 [usb_f_fs]
[ 67.462428] config_item_put+0x140/0x1a4 [configfs]
[ 67.467570] configfs_rmdir+0x3fc/0x518 [configfs]
[ 67.472626] vfs_rmdir+0x114/0x234
[ 67.476215] do_rmdir+0x274/0x2b0
[ 67.479710] __arm64_sys_unlinkat+0x94/0xc8
[ 67.484108] invoke_syscall+0xf8/0x25c
[ 67.488055] el0_svc_common.constprop.0+0x150/0x1a0
[ 67.493175] do_el0_svc+0xa0/0xd4
[ 67.496671] el0_svc+0x24/0x34
[ 67.499896] el0_sync_handler+0xcc/0x154
[ 67.504024] el0_sync+0x198/0x1c0
[ 67.507520]
[ 67.509114] The buggy address belongs to the object at ffff0004c26e9700
[ 67.509114] which belongs to the cache kmalloc-128 of size 128
[ 67.522171] The buggy address is located 74 bytes inside of
[ 67.522171] 128-byte region [ffff0004c26e9700, ffff0004c26e9780)
[ 67.534328] The buggy address belongs to the page:
[ 67.539355] page:000000003177a217 refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x5026e8
[ 67.549175] head:000000003177a217 order:1 compound_mapcount:0
[ 67.555195] flags: 0x8000000000010200(slab|head|zone=2)
[ 67.560687] raw: 8000000000010200 fffffc0013037100 0000000c00000002 ffff0004c0002300
[ 67.568791] raw: 0000000000000000 0000000080200020 00000001ffffffff 0000000000000000
[ 67.576890] page dumped because: kasan: bad access detected
[ 67.582725]
[ 67.584318] Memory state around the buggy address:
[ 67.589343] ffff0004c26e9600: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 67.596903] ffff0004c26e9680: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 67.604463] >ffff0004c26e9700: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 67.612022] ^
[ 67.617860] ffff0004c26e9780: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 67.625421] ffff0004c26e9800: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 67.632981] ==================================================================
[ 67.640535] Disabling lock debugging due to kernel taint
File descriptor[ 67.646100] Unable to handle kernel paging request at virtual address fabb801d4000018d
in bad state
[ 67.655456] Mem abort info:
[ 67.659619] ESR = 0x96000004
[ 67.662801] EC = 0x25: DABT (current EL), IL = 32 bits
[ 67.668225] SET = 0, FnV = 0
[ 67.671375] EA = 0, S1PTW = 0
[ 67.674613] Data abort info:
[ 67.677587] ISV = 0, ISS = 0x00000004
[ 67.681522] CM = 0, WnR = 0
[ 67.684588] [fabb801d4000018d] address between user and kernel address ranges
[ 67.691849] Internal error: Oops: 96000004 [#1] PREEMPT SMP
[ 67.697470] Modules linked in: usb_f_fs libcomposite configfs ath9k_htc led_class mac80211 libarc4 ath9k_common ath9k_hw ath cfg80211 aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce gf128mul sha2_ce sha1_ce evdev sata_rcar libata xhci_plat_hcd scsi_mod xhci_hcd rene4
[ 67.740467] CPU: 0 PID: 2994 Comm: cat Tainted: G B 5.13.0-rc4+ #8
[ 67.748005] Hardware name: Renesas Salvator-X board based on r8a77951 (DT)
[ 67.754924] pstate: 00000005 (nzcv daif -PAN -UAO -TCO BTYPE=--)
[ 67.760974] pc : ffs_data_clear+0x138/0x370 [usb_f_fs]
[ 67.766178] lr : ffs_data_clear+0x124/0x370 [usb_f_fs]
[ 67.771365] sp : ffff800014767ad0
[ 67.774706] x29: ffff800014767ad0 x28: ffff800009cf91c0 x27: ffff0004c54861a0
[ 67.781913] x26: ffff0004dc90b288 x25: 1fffe00099ec10f5 x24: 00000000000a801d
[ 67.789118] x23: 1fffe00099f6953a x22: dfff800000000000 x21: ffff0004cfb4a9d0
[ 67.796322] x20: d5e000ea00000bb1 x19: ffff0004cfb4a800 x18: 0000000000000000
[ 67.803526] x17: 0000000000000000 x16: 0000000000000000 x15: 0000000000000000
[ 67.810730] x14: 0720072007200720 x13: 0720072007200720 x12: 1ffff000028ecefa
[ 67.817934] x11: ffff7000028ecefa x10: 0720072007200720 x9 : ffff80001132c014
[ 67.825137] x8 : ffff8000147677d8 x7 : ffff8000147677d7 x6 : 0000000000000000
[ 67.832341] x5 : 0000000000000001 x4 : ffff7000028ecefb x3 : 0000000000000001
[ 67.839544] x2 : 0000000000000005 x1 : 1abc001d4000018d x0 : d5e000ea00000c6d
[ 67.846748] Call trace:
[ 67.849218] ffs_data_clear+0x138/0x370 [usb_f_fs]
[ 67.854058] ffs_data_reset+0x20/0x304 [usb_f_fs]
[ 67.858810] ffs_data_closed+0x240/0x244 [usb_f_fs]
[ 67.863736] ffs_ep0_release+0x40/0x54 [usb_f_fs]
[ 67.868488] __fput+0x304/0x580
[ 67.871665] ____fput+0x18/0x24
[ 67.874837] task_work_run+0x104/0x180
[ 67.878622] do_notify_resume+0x458/0x14e0
[ 67.882754] work_pending+0xc/0x5f8
[ 67.886282] Code: b4000a54 9102f280 12000802 d343fc01 (38f66821)
[ 67.892422] ---[ end trace 6d7cedf53d7abbea ]---
Segmentation fault
root@rcar-gen3:~#
==================================================================

Fixes: 4b187fceec3c ("usb: gadget: FunctionFS: add devices management code")
Fixes: 3262ad824307 ("usb: gadget: f_fs: Stop ffs_closed NULL pointer dereference")
Fixes: cdafb6d8b8da ("usb: gadget: f_fs: Fix use-after-free in ffs_free_inst")
Reported-by: Bhuvanesh Surachari <bhuvanesh_surachari@mentor.com>
Tested-by: Eugeniu Rosca <erosca@de.adit-jv.com>
Reviewed-by: Eugeniu Rosca <erosca@de.adit-jv.com>
Signed-off-by: Andrew Gabbasov <andrew_gabbasov@mentor.com>
Link: https://lore.kernel.org/r/20210603171507.22514-1-andrew_gabbasov@mentor.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 6fc1db5e 21-May-2021 Wesley Cheng <wcheng@codeaurora.org>

usb: gadget: f_fs: Ensure io_completion_wq is idle during unbind

During unbind, ffs_func_eps_disable() will be executed, resulting in
completion callbacks for any pending USB requests. When using AIO,
irrespective of the completion status, io_data work is queued to
io_completion_wq to evaluate and handle the completed requests. Since
work runs asynchronously to the unbind() routine, there can be a
scenario where the work runs after the USB gadget has been fully
removed, resulting in accessing of a resource which has been already
freed. (i.e. usb_ep_free_request() accessing the USB ep structure)

Explicitly drain the io_completion_wq, instead of relying on the
destroy_workqueue() (in ffs_data_put()) to make sure no pending
completion work items are running.

Signed-off-by: Wesley Cheng <wcheng@codeaurora.org>
Cc: stable <stable@vger.kernel.org>
Link: https://lore.kernel.org/r/1621644261-1236-1-git-send-email-wcheng@codeaurora.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 42343207 08-Mar-2021 kernel test robot <lkp@intel.com>

USB: gadget: f_fs: fix memdup_user.cocci warnings

drivers/usb/gadget/function/f_fs.c:3829:8-15: WARNING opportunity for memdup_user

Use memdup_user rather than duplicating its implementation
This is a little bit restricted to reduce false positives

Generated by: scripts/coccinelle/api/memdup_user.cocci

Fixes: 8704fd73bf56 ("USB: gadget: f_fs: remove likely/unlikely")
Reported-by: kernel test robot <lkp@intel.com>
Signed-off-by: kernel test robot <lkp@intel.com>
Link: https://lore.kernel.org/r/20210308070951.GA83949@8a16bdd473dc
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 55b74ce7 17-Mar-2021 Dean Anderson <dean@sensoray.com>

usb: gadget/function/f_fs string table fix for multiple languages

Fixes bug with the handling of more than one language in
the string table in f_fs.c.
str_count was not reset for subsequent language codes.
str_count-- "rolls under" and processes u32 max strings on
the processing of the second language entry.
The existing bug can be reproduced by adding a second language table
to the structure "strings" in tools/usb/ffs-test.c.

Signed-off-by: Dean Anderson <dean@sensoray.com>
Link: https://lore.kernel.org/r/20210317224109.21534-1-dean@sensoray.com
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 8704fd73 27-Nov-2020 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

USB: gadget: f_fs: remove likely/unlikely

They are used way too often in this file, in some ways that are actually
wrong. Almost all of these are already known by the compiler and CPU so
just remove them all as none of these should be on any "hot paths" where
it actually matters.

Cc: Felipe Balbi <balbi@kernel.org>
Reported-by: Peter Chen <peter.chen@nxp.com>
Reviewed-by: Peter Chen <peter.chen@nxp.com>
Link: https://lore.kernel.org/r/20201127140559.381351-6-gregkh@linuxfoundation.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# a353397b 27-Oct-2020 Jack Pham <jackp@codeaurora.org>

usb: gadget: f_fs: Re-use SS descriptors for SuperSpeedPlus

In many cases a function that supports SuperSpeed can very well
operate in SuperSpeedPlus, if a gadget controller supports it,
as the endpoint descriptors (and companion descriptors) are
generally identical and can be re-used. This is true for two
commonly used functions: Android's ADB and MTP. So we can simply
assign the usb_function's ssp_descriptors array to point to its
ss_descriptors, if available. Similarly, we need to allow an
epfile's ioctl for FUNCTIONFS_ENDPOINT_DESC to correctly
return the corresponding SuperSpeed endpoint descriptor in case
the connected speed is SuperSpeedPlus as well.

The only exception is if a function wants to implement an
Isochronous endpoint capable of transferring more than 48KB per
service interval when operating at greater than USB 3.1 Gen1
speed, in which case it would require an additional SuperSpeedPlus
Isochronous Endpoint Companion descriptor to be returned as part
of the Configuration Descriptor. Support for that would need
to be separately added to the userspace-facing FunctionFS API
which may not be a trivial task--likely a new descriptor format
(v3?) may need to be devised to allow for separate SS and SSP
descriptors to be supplied.

Signed-off-by: Jack Pham <jackp@codeaurora.org>
Cc: stable <stable@vger.kernel.org>
Link: https://lore.kernel.org/r/20201027230731.9073-1-jackp@codeaurora.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# a4b98a75 30-Nov-2020 Vamsi Krishna Samavedam <vskrishn@codeaurora.org>

usb: gadget: f_fs: Use local copy of descriptors for userspace copy

The function may be unbound causing the ffs_ep and its descriptors
to be freed while userspace is in the middle of an ioctl requesting
the same descriptors. Avoid dangling pointer reference by first
making a local copy of desctiptors before releasing the spinlock.

Fixes: c559a3534109 ("usb: gadget: f_fs: add ioctl returning ep descriptor")
Reviewed-by: Peter Chen <peter.chen@nxp.com>
Signed-off-by: Vamsi Krishna Samavedam <vskrishn@codeaurora.org>
Signed-off-by: Jack Pham <jackp@codeaurora.org>
Cc: stable <stable@vger.kernel.org>
Link: https://lore.kernel.org/r/20201130203453.28154-1-jackp@codeaurora.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 93c747ed 19-Nov-2020 Gustavo A. R. Silva <gustavoars@kernel.org>

usb: Fix fall-through warnings for Clang

In preparation to enable -Wimplicit-fallthrough for Clang, fix multiple
warnings by explicitly adding multiple break/return/fallthrough
statements instead of letting the code fall through to the next
case.

Link: https://github.com/KSPP/linux/issues/115
Signed-off-by: Gustavo A. R. Silva <gustavoars@kernel.org>
Link: https://lore.kernel.org/r/a76da7ca5b4f41c13d27b298accb8222d0b04e61.1605896060.git.gustavoars@kernel.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# a74005ab 06-Jul-2020 Gustavo A. R. Silva <gustavoars@kernel.org>

usb: gadget: Use fallthrough pseudo-keyword

Replace the existing /* fall through */ comments and its variants with
the new pseudo-keyword macro fallthrough[1]. Also, remove unnecessary
fall-through markings when it is the case.

[1] https://www.kernel.org/doc/html/latest/process/deprecated.html?highlight=fallthrough#implicit-switch-case-fall-through

Signed-off-by: Gustavo A. R. Silva <gustavoars@kernel.org>
Link: https://lore.kernel.org/r/20200707171500.GA13620@embeddedor
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 8f9a0e10 06-Jul-2020 Lee Jones <lee.jones@linaro.org>

usb: gadget: function: f_fs: Demote function header which is clearly not kerneldoc

No attempt has been made to document the demoted function here.

Fixes the following W=1 kernel build warning(s):

drivers/usb/gadget/function/f_fs.c:2361: warning: Function parameter or member 'type' not described in '__ffs_data_do_os_desc'
drivers/usb/gadget/function/f_fs.c:2361: warning: Function parameter or member 'h' not described in '__ffs_data_do_os_desc'
drivers/usb/gadget/function/f_fs.c:2361: warning: Function parameter or member 'data' not described in '__ffs_data_do_os_desc'
drivers/usb/gadget/function/f_fs.c:2361: warning: Function parameter or member 'len' not described in '__ffs_data_do_os_desc'
drivers/usb/gadget/function/f_fs.c:2361: warning: Function parameter or member 'priv' not described in '__ffs_data_do_os_desc'

Cc: Felipe Balbi <balbi@kernel.org>
Cc: David Howells <dhowells@redhat.com>
Cc: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Lee Jones <lee.jones@linaro.org>
Link: https://lore.kernel.org/r/20200706133341.476881-12-lee.jones@linaro.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 37c54f9b 10-Jun-2020 Christoph Hellwig <hch@lst.de>

kernel: set USER_DS in kthread_use_mm

Some architectures like arm64 and s390 require USER_DS to be set for
kernel threads to access user address space, which is the whole purpose of
kthread_use_mm, but other like x86 don't. That has lead to a huge mess
where some callers are fixed up once they are tested on said
architectures, while others linger around and yet other like io_uring try
to do "clever" optimizations for what usually is just a trivial asignment
to a member in the thread_struct for most architectures.

Make kthread_use_mm set USER_DS, and kthread_unuse_mm restore to the
previous value instead.

Signed-off-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Tested-by: Jens Axboe <axboe@kernel.dk>
Reviewed-by: Jens Axboe <axboe@kernel.dk>
Acked-by: Michael S. Tsirkin <mst@redhat.com>
Cc: Alex Deucher <alexander.deucher@amd.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Felipe Balbi <balbi@kernel.org>
Cc: Felix Kuehling <Felix.Kuehling@amd.com>
Cc: Jason Wang <jasowang@redhat.com>
Cc: Zhenyu Wang <zhenyuw@linux.intel.com>
Cc: Zhi Wang <zhi.a.wang@intel.com>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: http://lkml.kernel.org/r/20200404094101.672954-7-hch@lst.de
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# f5678e7f 10-Jun-2020 Christoph Hellwig <hch@lst.de>

kernel: better document the use_mm/unuse_mm API contract

Switch the function documentation to kerneldoc comments, and add
WARN_ON_ONCE asserts that the calling thread is a kernel thread and does
not have ->mm set (or has ->mm set in the case of unuse_mm).

Also give the functions a kthread_ prefix to better document the use case.

[hch@lst.de: fix a comment typo, cover the newly merged use_mm/unuse_mm caller in vfio]
Link: http://lkml.kernel.org/r/20200416053158.586887-3-hch@lst.de
[sfr@canb.auug.org.au: powerpc/vas: fix up for {un}use_mm() rename]
Link: http://lkml.kernel.org/r/20200422163935.5aa93ba5@canb.auug.org.au

Signed-off-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Stephen Rothwell <sfr@canb.auug.org.au>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Tested-by: Jens Axboe <axboe@kernel.dk>
Reviewed-by: Jens Axboe <axboe@kernel.dk>
Acked-by: Felix Kuehling <Felix.Kuehling@amd.com>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> [usb]
Acked-by: Haren Myneni <haren@linux.ibm.com>
Cc: Alex Deucher <alexander.deucher@amd.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Felipe Balbi <balbi@kernel.org>
Cc: Jason Wang <jasowang@redhat.com>
Cc: "Michael S. Tsirkin" <mst@redhat.com>
Cc: Zhenyu Wang <zhenyuw@linux.intel.com>
Cc: Zhi Wang <zhi.a.wang@intel.com>
Link: http://lkml.kernel.org/r/20200404094101.672954-6-hch@lst.de
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 9bf5b9eb 10-Jun-2020 Christoph Hellwig <hch@lst.de>

kernel: move use_mm/unuse_mm to kthread.c

Patch series "improve use_mm / unuse_mm", v2.

This series improves the use_mm / unuse_mm interface by better documenting
the assumptions, and my taking the set_fs manipulations spread over the
callers into the core API.

This patch (of 3):

Use the proper API instead.

Link: http://lkml.kernel.org/r/20200404094101.672954-1-hch@lst.de

These helpers are only for use with kernel threads, and I will tie them
more into the kthread infrastructure going forward. Also move the
prototypes to kthread.h - mmu_context.h was a little weird to start with
as it otherwise contains very low-level MM bits.

Signed-off-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Tested-by: Jens Axboe <axboe@kernel.dk>
Reviewed-by: Jens Axboe <axboe@kernel.dk>
Acked-by: Felix Kuehling <Felix.Kuehling@amd.com>
Cc: Alex Deucher <alexander.deucher@amd.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Felipe Balbi <balbi@kernel.org>
Cc: Jason Wang <jasowang@redhat.com>
Cc: "Michael S. Tsirkin" <mst@redhat.com>
Cc: Zhenyu Wang <zhenyuw@linux.intel.com>
Cc: Zhi Wang <zhi.a.wang@intel.com>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: http://lkml.kernel.org/r/20200404094101.672954-1-hch@lst.de
Link: http://lkml.kernel.org/r/20200416053158.586887-1-hch@lst.de
Link: http://lkml.kernel.org/r/20200404094101.672954-5-hch@lst.de
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# a54177d2 18-Apr-2020 Jason Yan <yanaijie@huawei.com>

usb: gadget: f_fs: remove unneeded semicolon in __ffs_data_got_descs()

Fix the following coccicheck warning:

drivers/usb/gadget/function/f_fs.c:2507:2-3: Unneeded semicolon

Reported-by: Hulk Robot <hulkci@huawei.com>
Signed-off-by: Jason Yan <yanaijie@huawei.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>


# 1c2e54fb 01-Apr-2020 Udipto Goswami <ugoswami@codeaurora.org>

usb: f_fs: Clear OS Extended descriptor counts to zero in ffs_data_reset()

For userspace functions using OS Descriptors, if a function also supplies
Extended Property descriptors currently the counts and lengths stored in
the ms_os_descs_ext_prop_{count,name_len,data_len} variables are not
getting reset to 0 during an unbind or when the epfiles are closed. If
the same function is re-bound and the descriptors are re-written, this
results in those count/length variables to monotonically increase
causing the VLA allocation in _ffs_func_bind() to grow larger and larger
at each bind/unbind cycle and eventually fail to allocate.

Fix this by clearing the ms_os_descs_ext_prop count & lengths to 0 in
ffs_data_reset().

Fixes: f0175ab51993 ("usb: gadget: f_fs: OS descriptors support")
Cc: stable@vger.kernel.org
Signed-off-by: Udipto Goswami <ugoswami@codeaurora.org>
Signed-off-by: Sriharsha Allenki <sallenki@codeaurora.org>
Reviewed-by: Manu Gautam <mgautam@codeaurora.org>
Link: https://lore.kernel.org/r/20200402044521.9312-1-sallenki@codeaurora.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# f63ec55f 26-Mar-2020 Sriharsha Allenki <sallenki@codeaurora.org>

usb: gadget: f_fs: Fix use after free issue as part of queue failure

In AIO case, the request is freed up if ep_queue fails.
However, io_data->req still has the reference to this freed
request. In the case of this failure if there is aio_cancel
call on this io_data it will lead to an invalid dequeue
operation and a potential use after free issue.
Fix this by setting the io_data->req to NULL when the request
is freed as part of queue failure.

Fixes: 2e4c7553cd6f ("usb: gadget: f_fs: add aio support")
Signed-off-by: Sriharsha Allenki <sallenki@codeaurora.org>
CC: stable <stable@vger.kernel.org>
Reviewed-by: Peter Chen <peter.chen@nxp.com>
Link: https://lore.kernel.org/r/20200326115620.12571-1-sallenki@codeaurora.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# a5c6234e 20-Mar-2020 Thomas Gleixner <tglx@linutronix.de>

completion: Use simple wait queues

completion uses a wait_queue_head_t to enqueue waiters.

wait_queue_head_t contains a spinlock_t to protect the list of waiters
which excludes it from being used in truly atomic context on a PREEMPT_RT
enabled kernel.

The spinlock in the wait queue head cannot be replaced by a raw_spinlock
because:

- wait queues can have custom wakeup callbacks, which acquire other
spinlock_t locks and have potentially long execution times

- wake_up() walks an unbounded number of list entries during the wake up
and may wake an unbounded number of waiters.

For simplicity and performance reasons complete() should be usable on
PREEMPT_RT enabled kernels.

completions do not use custom wakeup callbacks and are usually single
waiter, except for a few corner cases.

Replace the wait queue in the completion with a simple wait queue (swait),
which uses a raw_spinlock_t for protecting the waiter list and therefore is
safe to use inside truly atomic regions on PREEMPT_RT.

There is no semantical or functional change:

- completions use the exclusive wait mode which is what swait provides

- complete() wakes one exclusive waiter

- complete_all() wakes all waiters while holding the lock which protects
the wait queue against newly incoming waiters. The conversion to swait
preserves this behaviour.

complete_all() might cause unbound latencies with a large number of waiters
being woken at once, but most complete_all() usage sites are either in
testing or initialization code or have only a really small number of
concurrent waiters which for now does not cause a latency problem. Keep it
simple for now.

The fixup of the warning check in the USB gadget driver is just a straight
forward conversion of the lockless waiter check from one waitqueue type to
the other.

Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Davidlohr Bueso <dbueso@suse.de>
Reviewed-by: Joel Fernandes (Google) <joel@joelfernandes.org>
Acked-by: Linus Torvalds <torvalds@linux-foundation.org>
Link: https://lkml.kernel.org/r/20200321113242.317954042@linutronix.de


# 43d56572 16-Jan-2020 Lars-Peter Clausen <lars@metafoo.de>

usb: gadget: ffs: ffs_aio_cancel(): Save/restore IRQ flags

ffs_aio_cancel() can be called from both interrupt and thread context. Make
sure that the current IRQ state is saved and restored by using
spin_{un,}lock_irq{save,restore}().

Otherwise undefined behavior might occur.

Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>


# d7167b14 07-Sep-2019 Al Viro <viro@zeniv.linux.org.uk>

fs_parse: fold fs_parameter_desc/fs_parameter_spec

The former contains nothing but a pointer to an array of the latter...

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 96cafb9c 06-Dec-2019 Eric Sandeen <sandeen@sandeen.net>

fs_parser: remove fs_parameter_description name field

Unused now.

Signed-off-by: Eric Sandeen <sandeen@redhat.com>
Acked-by: David Howells <dhowells@redhat.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# d2450c69 12-Dec-2019 Peter Chen <peter.chen@nxp.com>

usb: gadget: f_fs: set req->num_sgs as 0 for non-sg transfer

The UDC core uses req->num_sgs to judge if scatter buffer list is used.
Eg: usb_gadget_map_request_by_dev. For f_fs sync io mode, the request
is re-used for each request, so if the 1st request->length > PAGE_SIZE,
and the 2nd request->length is <= PAGE_SIZE, the f_fs uses the 1st
req->num_sgs for the 2nd request, it causes the UDC core get the wrong
req->num_sgs value (The 2nd request doesn't use sg). For f_fs async
io mode, it is not harm to initialize req->num_sgs as 0 either, in case,
the UDC driver doesn't zeroed request structure.

Cc: Jun Li <jun.li@nxp.com>
Cc: stable <stable@vger.kernel.org>
Fixes: 772a7a724f69 ("usb: gadget: f_fs: Allow scatter-gather buffers")
Signed-off-by: Peter Chen <peter.chen@nxp.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# c593642c 09-Dec-2019 Pankaj Bharadiya <pankaj.laxminarayan.bharadiya@intel.com>

treewide: Use sizeof_field() macro

Replace all the occurrences of FIELD_SIZEOF() with sizeof_field() except
at places where these are defined. Later patches will remove the unused
definition of FIELD_SIZEOF().

This patch is generated using following script:

EXCLUDE_FILES="include/linux/stddef.h|include/linux/kernel.h"

git grep -l -e "\bFIELD_SIZEOF\b" | while read file;
do

if [[ "$file" =~ $EXCLUDE_FILES ]]; then
continue
fi
sed -i -e 's/\bFIELD_SIZEOF\b/sizeof_field/g' $file;
done

Signed-off-by: Pankaj Bharadiya <pankaj.laxminarayan.bharadiya@intel.com>
Link: https://lore.kernel.org/r/20190924105839.110713-3-pankaj.laxminarayan.bharadiya@intel.com
Co-developed-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Kees Cook <keescook@chromium.org>
Acked-by: David Miller <davem@davemloft.net> # for net


# 01b8bca8 11-Sep-2018 Arnd Bergmann <arnd@arndb.de>

compat_ioctl: use correct compat_ptr() translation in drivers

A handful of drivers all have a trivial wrapper around their ioctl
handler, but don't call the compat_ptr() conversion function at the
moment. In practice this does not matter, since none of them are used
on the s390 architecture and for all other architectures, compat_ptr()
does not do anything, but using the new compat_ptr_ioctl()
helper makes it more correct in theory, and simplifies the code.

I checked that all ioctl handlers in these files are compatible
and take either pointer arguments or no argument.

Acked-by: Al Viro <viro@zeniv.linux.org.uk>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: Andrew Donnellan <andrew.donnellan@au1.ibm.com>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Signed-off-by: Arnd Bergmann <arnd@arndb.de>


# dec90f61 20-Mar-2019 David Howells <dhowells@redhat.com>

vfs: Convert functionfs to use the new mount API

Convert the functionfs filesystem to the new internal mount API as the old
one will be obsoleted and removed. This allows greater flexibility in
communication of mount parameters between userspace, the VFS and the
filesystem.

See Documentation/filesystems/mount_api.txt for more information.

Signed-off-by: David Howells <dhowells@redhat.com>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
cc: linux-usb@vger.kernel.org
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 50859551 03-Jun-2019 Andrzej Pietrasiewicz <andrzej.p@collabora.com>

usb: gadget: Zero ffs_io_data

In some cases the "Allocate & copy" block in ffs_epfile_io() is not
executed. Consequently, in such a case ffs_alloc_buffer() is never called
and struct ffs_io_data is not initialized properly. This in turn leads to
problems when ffs_free_buffer() is called at the end of ffs_epfile_io().

This patch uses kzalloc() instead of kmalloc() in the aio case and memset()
in non-aio case to properly initialize struct ffs_io_data.

Signed-off-by: Andrzej Pietrasiewicz <andrzej.p@collabora.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 4833a94e 12-Jun-2019 Fei Yang <fei.yang@intel.com>

usb: gadget: f_fs: data_len used before properly set

The following line of code in function ffs_epfile_io is trying to set
flag io_data->use_sg in case buffer required is larger than one page.

io_data->use_sg = gadget->sg_supported && data_len > PAGE_SIZE;

However at this point of time the variable data_len has not been set
to the proper buffer size yet. The consequence is that io_data->use_sg
is always set regardless what buffer size really is, because the condition
(data_len > PAGE_SIZE) is effectively an unsigned comparison between
-EINVAL and PAGE_SIZE which would always result in TRUE.

Fixes: 772a7a724f69 ("usb: gadget: f_fs: Allow scatter-gather buffers")
Signed-off-by: Fei Yang <fei.yang@intel.com>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 73103c7f 19-Mar-2019 Fei Yang <fei.yang@intel.com>

usb: gadget: f_fs: don't free buffer prematurely

The following kernel panic happens due to the io_data buffer gets deallocated
before the async io is completed. Add a check for the case where io_data buffer
should be deallocated by ffs_user_copy_worker.

[ 41.663334] BUG: unable to handle kernel NULL pointer dereference at 0000000000000048
[ 41.672099] #PF error: [normal kernel read fault]
[ 41.677356] PGD 20c974067 P4D 20c974067 PUD 20c973067 PMD 0
[ 41.683687] Oops: 0000 [#1] PREEMPT SMP
[ 41.687976] CPU: 1 PID: 7 Comm: kworker/u8:0 Tainted: G U 5.0.0-quilt-2e5dc0ac-00790-gd8c79f2-dirty #2
[ 41.705309] Workqueue: adb ffs_user_copy_worker
[ 41.705316] RIP: 0010:__vunmap+0x2a/0xc0
[ 41.705318] Code: 0f 1f 44 00 00 48 85 ff 0f 84 87 00 00 00 55 f7 c7 ff 0f 00 00 48 89 e5 41 55 41 89 f5 41 54 53 48 89 fb 75 71 e8 56 d7 ff ff <4c> 8b 60 48 4d 85 e4 74 76 48 89 df e8 25 ff ff ff 45 85 ed 74 46
[ 41.705320] RSP: 0018:ffffbc3a40053df0 EFLAGS: 00010286
[ 41.705322] RAX: 0000000000000000 RBX: ffffbc3a406f1000 RCX: 0000000000000000
[ 41.705323] RDX: 0000000000000001 RSI: 0000000000000001 RDI: 00000000ffffffff
[ 41.705324] RBP: ffffbc3a40053e08 R08: 000000000001fb79 R09: 0000000000000037
[ 41.705325] R10: ffffbc3a40053b68 R11: ffffbc3a40053cad R12: fffffffffffffff2
[ 41.705326] R13: 0000000000000001 R14: 0000000000000000 R15: ffffffffffffffff
[ 41.705328] FS: 0000000000000000(0000) GS:ffff9e2977a80000(0000) knlGS:0000000000000000
[ 41.705329] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 41.705330] CR2: 0000000000000048 CR3: 000000020c994000 CR4: 00000000003406e0
[ 41.705331] Call Trace:
[ 41.705338] vfree+0x50/0xb0
[ 41.705341] ffs_user_copy_worker+0xe9/0x1c0
[ 41.705344] process_one_work+0x19f/0x3e0
[ 41.705348] worker_thread+0x3f/0x3b0
[ 41.829766] kthread+0x12b/0x150
[ 41.833371] ? process_one_work+0x3e0/0x3e0
[ 41.838045] ? kthread_create_worker_on_cpu+0x70/0x70
[ 41.843695] ret_from_fork+0x3a/0x50
[ 41.847689] Modules linked in: hci_uart bluetooth ecdh_generic rfkill_gpio dwc3_pci dwc3 snd_usb_audio mei_me tpm_crb snd_usbmidi_lib xhci_pci xhci_hcd mei tpm snd_hwdep cfg80211 snd_soc_skl snd_soc_skl_ipc snd_soc_sst_ipc snd_soc_sst_dsp snd_hda_ext_core snd_hda_core videobuf2_dma_sg crlmodule
[ 41.876880] CR2: 0000000000000048
[ 41.880584] ---[ end trace 2bc4addff0f2e673 ]---
[ 41.891346] RIP: 0010:__vunmap+0x2a/0xc0
[ 41.895734] Code: 0f 1f 44 00 00 48 85 ff 0f 84 87 00 00 00 55 f7 c7 ff 0f 00 00 48 89 e5 41 55 41 89 f5 41 54 53 48 89 fb 75 71 e8 56 d7 ff ff <4c> 8b 60 48 4d 85 e4 74 76 48 89 df e8 25 ff ff ff 45 85 ed 74 46
[ 41.916740] RSP: 0018:ffffbc3a40053df0 EFLAGS: 00010286
[ 41.922583] RAX: 0000000000000000 RBX: ffffbc3a406f1000 RCX: 0000000000000000
[ 41.930563] RDX: 0000000000000001 RSI: 0000000000000001 RDI: 00000000ffffffff
[ 41.938540] RBP: ffffbc3a40053e08 R08: 000000000001fb79 R09: 0000000000000037
[ 41.946520] R10: ffffbc3a40053b68 R11: ffffbc3a40053cad R12: fffffffffffffff2
[ 41.954502] R13: 0000000000000001 R14: 0000000000000000 R15: ffffffffffffffff
[ 41.962482] FS: 0000000000000000(0000) GS:ffff9e2977a80000(0000) knlGS:0000000000000000
[ 41.971536] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 41.977960] CR2: 0000000000000048 CR3: 000000020c994000 CR4: 00000000003406e0
[ 41.985930] Kernel panic - not syncing: Fatal exception
[ 41.991817] Kernel Offset: 0x16000000 from 0xffffffff81000000 (relocation range: 0xffffffff80000000-0xffffffffbfffffff)
[ 42.009525] Rebooting in 10 seconds..
[ 52.014376] ACPI MEMORY or I/O RESET_REG.

Fixes: 772a7a724f69 ("usb: gadget: f_fs: Allow scatter-gather buffers")
Signed-off-by: Fei Yang <fei.yang@intel.com>
Reviewed-by: Manu Gautam <mgautam@codeaurora.org>
Tested-by: John Stultz <john.stultz@linaro.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 54f64d5c 05-Feb-2019 John Stultz <john.stultz@linaro.org>

usb: f_fs: Avoid crash due to out-of-scope stack ptr access

Since the 5.0 merge window opened, I've been seeing frequent
crashes on suspend and reboot with the trace:

[ 36.911170] Unable to handle kernel paging request at virtual address ffffff801153d660
[ 36.912769] Unable to handle kernel paging request at virtual address ffffff800004b564
...
[ 36.950666] Call trace:
[ 36.950670] queued_spin_lock_slowpath+0x1cc/0x2c8
[ 36.950681] _raw_spin_lock_irqsave+0x64/0x78
[ 36.950692] complete+0x28/0x70
[ 36.950703] ffs_epfile_io_complete+0x3c/0x50
[ 36.950713] usb_gadget_giveback_request+0x34/0x108
[ 36.950721] dwc3_gadget_giveback+0x50/0x68
[ 36.950723] dwc3_thread_interrupt+0x358/0x1488
[ 36.950731] irq_thread_fn+0x30/0x88
[ 36.950734] irq_thread+0x114/0x1b0
[ 36.950739] kthread+0x104/0x130
[ 36.950747] ret_from_fork+0x10/0x1c

I isolated this down to in ffs_epfile_io():
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/usb/gadget/function/f_fs.c#n1065

Where the completion done is setup on the stack:
DECLARE_COMPLETION_ONSTACK(done);

Then later we setup a request and queue it, and wait for it:
if (unlikely(wait_for_completion_interruptible(&done))) {
/*
* To avoid race condition with ffs_epfile_io_complete,
* dequeue the request first then check
* status. usb_ep_dequeue API should guarantee no race
* condition with req->complete callback.
*/
usb_ep_dequeue(ep->ep, req);
interrupted = ep->status < 0;
}

The problem is, that we end up being interrupted, dequeue the
request, and exit.

But then the irq triggers and we try calling complete() on the
context pointer which points to now random stack space, which
results in the panic.

Alan Stern pointed out there is a bug here, in that the snippet
above "assumes that usb_ep_dequeue() waits until the request has
been completed." And that:

wait_for_completion(&done);

Is needed right after the usb_ep_dequeue().

Thus this patch implements that change. With it I no longer see
the crashes on suspend or reboot.

This issue seems to have been uncovered by behavioral changes in
the dwc3 driver in commit fec9095bdef4e ("usb: dwc3: gadget:
remove wait_end_transfer").

Cc: Alan Stern <stern@rowland.harvard.edu>
Cc: Felipe Balbi <balbi@kernel.org>
Cc: Zeng Tao <prime.zeng@hisilicon.com>
Cc: Jack Pham <jackp@codeaurora.org>
Cc: Thinh Nguyen <thinh.nguyen@synopsys.com>
Cc: Chen Yu <chenyu56@huawei.com>
Cc: Jerry Zhang <zhangjerry@google.com>
Cc: Lars-Peter Clausen <lars@metafoo.de>
Cc: Vincent Pelletier <plr.vincent@gmail.com>
Cc: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Linux USB List <linux-usb@vger.kernel.org>
Suggested-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: John Stultz <john.stultz@linaro.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# bdcc03ce 31-Jan-2019 Andrzej Pietrasiewicz <andrzej.p@collabora.com>

usb: gadget: f_fs: preserve wMaxPacketSize across usb_ep_autoconfig() call

usb_ep_autoconfig() treats the passed descriptor as if it were an fs
descriptor. In particular, for bulk endpoints, it clips wMaxPacketSize
to 64. This patch preserves the original value.

Signed-off-by: Andrzej Pietrasiewicz <andrzej.p@collabora.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 772a7a72 14-Nov-2018 Andrzej Pietrasiewicz <andrzej.p@samsung.com>

usb: gadget: f_fs: Allow scatter-gather buffers

Some protocols implemented in userspace with FunctionFS might require large
buffers, e.g. 64kB or more. Currently the said memory is allocated with
kmalloc, which might fail should system memory be highly fragmented.

On the other hand, some UDC hardware allows scatter-gather operation and
this patch takes advantage of this capability: if the requested buffer
is larger than PAGE_SIZE and the UDC allows scatter-gather operation, then
the buffer is allocated with vmalloc and a scatterlist describing it is
created and passed to usb request.

Signed-off-by: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 7f7c548c 09-Oct-2018 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: f_fs: Add support for CCID descriptors.

Nothing to remap, only check length.
Define a minimal structure for CCID descriptor only used to check length.
As this descriptor shares the same value as HID descriptors, keep track and
compare current interface's class to expected HID and CCID standard values.

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# a9c85903 01-Nov-2018 Shen Jing <jingx.shen@intel.com>

Revert "usb: gadget: ffs: Fix BUG when userland exits with submitted AIO transfers"

This reverts commit b4194da3f9087dd38d91b40f9bec42d59ce589a8
since it causes list corruption followed by kernel panic:

Workqueue: adb ffs_aio_cancel_worker
RIP: 0010:__list_add_valid+0x4d/0x70
Call Trace:
insert_work+0x47/0xb0
__queue_work+0xf6/0x400
queue_work_on+0x65/0x70
dwc3_gadget_giveback+0x44/0x50 [dwc3]
dwc3_gadget_ep_dequeue+0x83/0x2d0 [dwc3]
? finish_wait+0x80/0x80
usb_ep_dequeue+0x1e/0x90
process_one_work+0x18c/0x3b0
worker_thread+0x3c/0x390
? process_one_work+0x3b0/0x3b0
kthread+0x11e/0x140
? kthread_create_worker_on_cpu+0x70/0x70
ret_from_fork+0x3a/0x50

This issue is seen with warm reboot stability testing.

Signed-off-by: Shen Jing <jingx.shen@intel.com>
Signed-off-by: Saranya Gopal <saranya.gopal@intel.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# e610257e 16-Apr-2018 Jerry Zhang <zhangjerry@google.com>

usb: gadget: f_fs: Only return delayed status when len is 0

Commit 1b9ba000 ("Allow function drivers to pause control
transfers") states that USB_GADGET_DELAYED_STATUS is only
supported if data phase is 0 bytes.

It seems that when the length is not 0 bytes, there is no
need to explicitly delay the data stage since the transfer
is not completed until the user responds. However, when the
length is 0, there is no data stage and the transfer is
finished once setup() returns, hence there is a need to
explicitly delay completion.

This manifests as the following bugs:

Prior to 946ef68ad4e4 ('Let setup() return
USB_GADGET_DELAYED_STATUS'), when setup is 0 bytes, ffs
would require user to queue a 0 byte request in order to
clear setup state. However, that 0 byte request was actually
not needed and would hang and cause errors in other setup
requests.

After the above commit, 0 byte setups work since the gadget
now accepts empty queues to ep0 to clear the delay, but all
other setups hang.

Fixes: 946ef68ad4e4 ("Let setup() return USB_GADGET_DELAYED_STATUS")
Signed-off-by: Jerry Zhang <zhangjerry@google.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 4d644abf 02-Jul-2018 Jerry Zhang <zhangjerry@google.com>

usb: gadget: f_fs: Only return delayed status when len is 0

Commit 1b9ba000 ("Allow function drivers to pause control
transfers") states that USB_GADGET_DELAYED_STATUS is only
supported if data phase is 0 bytes.

It seems that when the length is not 0 bytes, there is no
need to explicitly delay the data stage since the transfer
is not completed until the user responds. However, when the
length is 0, there is no data stage and the transfer is
finished once setup() returns, hence there is a need to
explicitly delay completion.

This manifests as the following bugs:

Prior to 946ef68ad4e4 ('Let setup() return
USB_GADGET_DELAYED_STATUS'), when setup is 0 bytes, ffs
would require user to queue a 0 byte request in order to
clear setup state. However, that 0 byte request was actually
not needed and would hang and cause errors in other setup
requests.

After the above commit, 0 byte setups work since the gadget
now accepts empty queues to ep0 to clear the delay, but all
other setups hang.

Fixes: 946ef68ad4e4 ("Let setup() return USB_GADGET_DELAYED_STATUS")
Signed-off-by: Jerry Zhang <zhangjerry@google.com>
Cc: stable <stable@vger.kernel.org>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# d52e4d0c 13-Jun-2018 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: ffs: Fix BUG when userland exits with submitted AIO transfers

This bug happens only when the UDC needs to sleep during usb_ep_dequeue,
as is the case for (at least) dwc3.

[ 382.200896] BUG: scheduling while atomic: screen/1808/0x00000100
[ 382.207124] 4 locks held by screen/1808:
[ 382.211266] #0: (rcu_callback){....}, at: [<c10b4ff0>] rcu_process_callbacks+0x260/0x440
[ 382.219949] #1: (rcu_read_lock_sched){....}, at: [<c1358ba0>] percpu_ref_switch_to_atomic_rcu+0xb0/0x130
[ 382.230034] #2: (&(&ctx->ctx_lock)->rlock){....}, at: [<c11f0c73>] free_ioctx_users+0x23/0xd0
[ 382.230096] #3: (&(&ffs->eps_lock)->rlock){....}, at: [<f81e7710>] ffs_aio_cancel+0x20/0x60 [usb_f_fs]
[ 382.230160] Modules linked in: usb_f_fs libcomposite configfs bnep btsdio bluetooth ecdh_generic brcmfmac brcmutil intel_powerclamp coretemp dwc3 kvm_intel ulpi udc_core kvm irqbypass crc32_pclmul crc32c_intel pcbc dwc3_pci aesni_intel aes_i586 crypto_simd cryptd ehci_pci ehci_hcd gpio_keys usbcore basincove_gpadc industrialio usb_common
[ 382.230407] CPU: 1 PID: 1808 Comm: screen Not tainted 4.14.0-edison+ #117
[ 382.230416] Hardware name: Intel Corporation Merrifield/BODEGA BAY, BIOS 542 2015.01.21:18.19.48
[ 382.230425] Call Trace:
[ 382.230438] <SOFTIRQ>
[ 382.230466] dump_stack+0x47/0x62
[ 382.230498] __schedule_bug+0x61/0x80
[ 382.230522] __schedule+0x43/0x7a0
[ 382.230587] schedule+0x5f/0x70
[ 382.230625] dwc3_gadget_ep_dequeue+0x14c/0x270 [dwc3]
[ 382.230669] ? do_wait_intr_irq+0x70/0x70
[ 382.230724] usb_ep_dequeue+0x19/0x90 [udc_core]
[ 382.230770] ffs_aio_cancel+0x37/0x60 [usb_f_fs]
[ 382.230798] kiocb_cancel+0x31/0x40
[ 382.230822] free_ioctx_users+0x4d/0xd0
[ 382.230858] percpu_ref_switch_to_atomic_rcu+0x10a/0x130
[ 382.230881] ? percpu_ref_exit+0x40/0x40
[ 382.230904] rcu_process_callbacks+0x2b3/0x440
[ 382.230965] __do_softirq+0xf8/0x26b
[ 382.231011] ? __softirqentry_text_start+0x8/0x8
[ 382.231033] do_softirq_own_stack+0x22/0x30
[ 382.231042] </SOFTIRQ>
[ 382.231071] irq_exit+0x45/0xc0
[ 382.231089] smp_apic_timer_interrupt+0x13c/0x150
[ 382.231118] apic_timer_interrupt+0x35/0x3c
[ 382.231132] EIP: __copy_user_ll+0xe2/0xf0
[ 382.231142] EFLAGS: 00210293 CPU: 1
[ 382.231154] EAX: bfd4508c EBX: 00000004 ECX: 00000003 EDX: f3d8fe50
[ 382.231165] ESI: f3d8fe51 EDI: bfd4508d EBP: f3d8fe14 ESP: f3d8fe08
[ 382.231176] DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
[ 382.231265] core_sys_select+0x25f/0x320
[ 382.231346] ? __wake_up_common_lock+0x62/0x80
[ 382.231399] ? tty_ldisc_deref+0x13/0x20
[ 382.231438] ? ldsem_up_read+0x1b/0x40
[ 382.231459] ? tty_ldisc_deref+0x13/0x20
[ 382.231479] ? tty_write+0x29f/0x2e0
[ 382.231514] ? n_tty_ioctl+0xe0/0xe0
[ 382.231541] ? tty_write_unlock+0x30/0x30
[ 382.231566] ? __vfs_write+0x22/0x110
[ 382.231604] ? security_file_permission+0x2f/0xd0
[ 382.231635] ? rw_verify_area+0xac/0x120
[ 382.231677] ? vfs_write+0x103/0x180
[ 382.231711] SyS_select+0x87/0xc0
[ 382.231739] ? SyS_write+0x42/0x90
[ 382.231781] do_fast_syscall_32+0xd6/0x1a0
[ 382.231836] entry_SYSENTER_32+0x47/0x71
[ 382.231848] EIP: 0xb7f75b05
[ 382.231857] EFLAGS: 00000246 CPU: 1
[ 382.231868] EAX: ffffffda EBX: 00000400 ECX: bfd4508c EDX: bfd4510c
[ 382.231878] ESI: 00000000 EDI: 00000000 EBP: 00000000 ESP: bfd45020
[ 382.231889] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 007b
[ 382.232281] softirq: huh, entered softirq 9 RCU c10b4d90 with preempt_count 00000100, exited with 00000000?

Tested-by: Sam Protsenko <semen.protsenko@linaro.org>
Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 95582b00 08-May-2018 Deepa Dinamani <deepa.kernel@gmail.com>

vfs: change inode times to use struct timespec64

struct timespec is not y2038 safe. Transition vfs to use
y2038 safe struct timespec64 instead.

The change was made with the help of the following cocinelle
script. This catches about 80% of the changes.
All the header file and logic changes are included in the
first 5 rules. The rest are trivial substitutions.
I avoid changing any of the function signatures or any other
filesystem specific data structures to keep the patch simple
for review.

The script can be a little shorter by combining different cases.
But, this version was sufficient for my usecase.

virtual patch

@ depends on patch @
identifier now;
@@
- struct timespec
+ struct timespec64
current_time ( ... )
{
- struct timespec now = current_kernel_time();
+ struct timespec64 now = current_kernel_time64();
...
- return timespec_trunc(
+ return timespec64_trunc(
... );
}

@ depends on patch @
identifier xtime;
@@
struct \( iattr \| inode \| kstat \) {
...
- struct timespec xtime;
+ struct timespec64 xtime;
...
}

@ depends on patch @
identifier t;
@@
struct inode_operations {
...
int (*update_time) (...,
- struct timespec t,
+ struct timespec64 t,
...);
...
}

@ depends on patch @
identifier t;
identifier fn_update_time =~ "update_time$";
@@
fn_update_time (...,
- struct timespec *t,
+ struct timespec64 *t,
...) { ... }

@ depends on patch @
identifier t;
@@
lease_get_mtime( ... ,
- struct timespec *t
+ struct timespec64 *t
) { ... }

@te depends on patch forall@
identifier ts;
local idexpression struct inode *inode_node;
identifier i_xtime =~ "^i_[acm]time$";
identifier ia_xtime =~ "^ia_[acm]time$";
identifier fn_update_time =~ "update_time$";
identifier fn;
expression e, E3;
local idexpression struct inode *node1;
local idexpression struct inode *node2;
local idexpression struct iattr *attr1;
local idexpression struct iattr *attr2;
local idexpression struct iattr attr;
identifier i_xtime1 =~ "^i_[acm]time$";
identifier i_xtime2 =~ "^i_[acm]time$";
identifier ia_xtime1 =~ "^ia_[acm]time$";
identifier ia_xtime2 =~ "^ia_[acm]time$";
@@
(
(
- struct timespec ts;
+ struct timespec64 ts;
|
- struct timespec ts = current_time(inode_node);
+ struct timespec64 ts = current_time(inode_node);
)

<+... when != ts
(
- timespec_equal(&inode_node->i_xtime, &ts)
+ timespec64_equal(&inode_node->i_xtime, &ts)
|
- timespec_equal(&ts, &inode_node->i_xtime)
+ timespec64_equal(&ts, &inode_node->i_xtime)
|
- timespec_compare(&inode_node->i_xtime, &ts)
+ timespec64_compare(&inode_node->i_xtime, &ts)
|
- timespec_compare(&ts, &inode_node->i_xtime)
+ timespec64_compare(&ts, &inode_node->i_xtime)
|
ts = current_time(e)
|
fn_update_time(..., &ts,...)
|
inode_node->i_xtime = ts
|
node1->i_xtime = ts
|
ts = inode_node->i_xtime
|
<+... attr1->ia_xtime ...+> = ts
|
ts = attr1->ia_xtime
|
ts.tv_sec
|
ts.tv_nsec
|
btrfs_set_stack_timespec_sec(..., ts.tv_sec)
|
btrfs_set_stack_timespec_nsec(..., ts.tv_nsec)
|
- ts = timespec64_to_timespec(
+ ts =
...
-)
|
- ts = ktime_to_timespec(
+ ts = ktime_to_timespec64(
...)
|
- ts = E3
+ ts = timespec_to_timespec64(E3)
|
- ktime_get_real_ts(&ts)
+ ktime_get_real_ts64(&ts)
|
fn(...,
- ts
+ timespec64_to_timespec(ts)
,...)
)
...+>
(
<... when != ts
- return ts;
+ return timespec64_to_timespec(ts);
...>
)
|
- timespec_equal(&node1->i_xtime1, &node2->i_xtime2)
+ timespec64_equal(&node1->i_xtime2, &node2->i_xtime2)
|
- timespec_equal(&node1->i_xtime1, &attr2->ia_xtime2)
+ timespec64_equal(&node1->i_xtime2, &attr2->ia_xtime2)
|
- timespec_compare(&node1->i_xtime1, &node2->i_xtime2)
+ timespec64_compare(&node1->i_xtime1, &node2->i_xtime2)
|
node1->i_xtime1 =
- timespec_trunc(attr1->ia_xtime1,
+ timespec64_trunc(attr1->ia_xtime1,
...)
|
- attr1->ia_xtime1 = timespec_trunc(attr2->ia_xtime2,
+ attr1->ia_xtime1 = timespec64_trunc(attr2->ia_xtime2,
...)
|
- ktime_get_real_ts(&attr1->ia_xtime1)
+ ktime_get_real_ts64(&attr1->ia_xtime1)
|
- ktime_get_real_ts(&attr.ia_xtime1)
+ ktime_get_real_ts64(&attr.ia_xtime1)
)

@ depends on patch @
struct inode *node;
struct iattr *attr;
identifier fn;
identifier i_xtime =~ "^i_[acm]time$";
identifier ia_xtime =~ "^ia_[acm]time$";
expression e;
@@
(
- fn(node->i_xtime);
+ fn(timespec64_to_timespec(node->i_xtime));
|
fn(...,
- node->i_xtime);
+ timespec64_to_timespec(node->i_xtime));
|
- e = fn(attr->ia_xtime);
+ e = fn(timespec64_to_timespec(attr->ia_xtime));
)

@ depends on patch forall @
struct inode *node;
struct iattr *attr;
identifier i_xtime =~ "^i_[acm]time$";
identifier ia_xtime =~ "^ia_[acm]time$";
identifier fn;
@@
{
+ struct timespec ts;
<+...
(
+ ts = timespec64_to_timespec(node->i_xtime);
fn (...,
- &node->i_xtime,
+ &ts,
...);
|
+ ts = timespec64_to_timespec(attr->ia_xtime);
fn (...,
- &attr->ia_xtime,
+ &ts,
...);
)
...+>
}

@ depends on patch forall @
struct inode *node;
struct iattr *attr;
struct kstat *stat;
identifier ia_xtime =~ "^ia_[acm]time$";
identifier i_xtime =~ "^i_[acm]time$";
identifier xtime =~ "^[acm]time$";
identifier fn, ret;
@@
{
+ struct timespec ts;
<+...
(
+ ts = timespec64_to_timespec(node->i_xtime);
ret = fn (...,
- &node->i_xtime,
+ &ts,
...);
|
+ ts = timespec64_to_timespec(node->i_xtime);
ret = fn (...,
- &node->i_xtime);
+ &ts);
|
+ ts = timespec64_to_timespec(attr->ia_xtime);
ret = fn (...,
- &attr->ia_xtime,
+ &ts,
...);
|
+ ts = timespec64_to_timespec(attr->ia_xtime);
ret = fn (...,
- &attr->ia_xtime);
+ &ts);
|
+ ts = timespec64_to_timespec(stat->xtime);
ret = fn (...,
- &stat->xtime);
+ &ts);
)
...+>
}

@ depends on patch @
struct inode *node;
struct inode *node2;
identifier i_xtime1 =~ "^i_[acm]time$";
identifier i_xtime2 =~ "^i_[acm]time$";
identifier i_xtime3 =~ "^i_[acm]time$";
struct iattr *attrp;
struct iattr *attrp2;
struct iattr attr ;
identifier ia_xtime1 =~ "^ia_[acm]time$";
identifier ia_xtime2 =~ "^ia_[acm]time$";
struct kstat *stat;
struct kstat stat1;
struct timespec64 ts;
identifier xtime =~ "^[acmb]time$";
expression e;
@@
(
( node->i_xtime2 \| attrp->ia_xtime2 \| attr.ia_xtime2 \) = node->i_xtime1 ;
|
node->i_xtime2 = \( node2->i_xtime1 \| timespec64_trunc(...) \);
|
node->i_xtime2 = node->i_xtime1 = node->i_xtime3 = \(ts \| current_time(...) \);
|
node->i_xtime1 = node->i_xtime3 = \(ts \| current_time(...) \);
|
stat->xtime = node2->i_xtime1;
|
stat1.xtime = node2->i_xtime1;
|
( node->i_xtime2 \| attrp->ia_xtime2 \) = attrp->ia_xtime1 ;
|
( attrp->ia_xtime1 \| attr.ia_xtime1 \) = attrp2->ia_xtime2;
|
- e = node->i_xtime1;
+ e = timespec64_to_timespec( node->i_xtime1 );
|
- e = attrp->ia_xtime1;
+ e = timespec64_to_timespec( attrp->ia_xtime1 );
|
node->i_xtime1 = current_time(...);
|
node->i_xtime2 = node->i_xtime1 = node->i_xtime3 =
- e;
+ timespec_to_timespec64(e);
|
node->i_xtime1 = node->i_xtime3 =
- e;
+ timespec_to_timespec64(e);
|
- node->i_xtime1 = e;
+ node->i_xtime1 = timespec_to_timespec64(e);
)

Signed-off-by: Deepa Dinamani <deepa.kernel@gmail.com>
Cc: <anton@tuxera.com>
Cc: <balbi@kernel.org>
Cc: <bfields@fieldses.org>
Cc: <darrick.wong@oracle.com>
Cc: <dhowells@redhat.com>
Cc: <dsterba@suse.com>
Cc: <dwmw2@infradead.org>
Cc: <hch@lst.de>
Cc: <hirofumi@mail.parknet.co.jp>
Cc: <hubcap@omnibond.com>
Cc: <jack@suse.com>
Cc: <jaegeuk@kernel.org>
Cc: <jaharkes@cs.cmu.edu>
Cc: <jslaby@suse.com>
Cc: <keescook@chromium.org>
Cc: <mark@fasheh.com>
Cc: <miklos@szeredi.hu>
Cc: <nico@linaro.org>
Cc: <reiserfs-devel@vger.kernel.org>
Cc: <richard@nod.at>
Cc: <sage@redhat.com>
Cc: <sfrench@samba.org>
Cc: <swhiteho@redhat.com>
Cc: <tj@kernel.org>
Cc: <trond.myklebust@primarydata.com>
Cc: <tytso@mit.edu>
Cc: <viro@zeniv.linux.org.uk>


# 6819e323 30-Mar-2018 Jerry Zhang <zhangjerry@google.com>

usb: gadget: f_fs: Add compat_ioctl to epfiles

This allows 32 bit owners of ffs endpoints to
make ioctls into a 64 bit kernel.

All of the current epfile ioctls can be handled
with the same struct definitions as regular
ioctl.

Acked-by: Michał Nazarewicz <mina86@mina86.com>
Signed-off-by: Jerry Zhang <zhangjerry@google.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 946ef68a 12-Jan-2018 Lars-Peter Clausen <lars@metafoo.de>

usb: gadget: ffs: Let setup() return USB_GADGET_DELAYED_STATUS

Some UDC drivers (like the DWC3) expect that the response to a setup()
request is queued from within the setup function itself so that it is
available as soon as setup() has completed.

Upon receiving a setup request the function fs driver creates an event that
is made available to userspace. And only once userspace has acknowledged
that event the response to the setup request is queued.

So it violates the requirement of those UDC drivers and random failures can
be observed. This is basically a race condition and if userspace is able to
read the event and queue the response fast enough all is good. But if it is
not, for example because other processes are currently scheduled to run,
the USB host that sent the setup request will observe an error.

To avoid this the gadget framework provides the USB_GADGET_DELAYED_STATUS
return code. If a setup() callback returns this value the UDC driver is
aware that response is not yet available and can uses the appropriate
methods to handle this case.

Since in the case of function fs the response will never be available when
the setup() function returns make sure that this status code is used.

This fixed random occasional failures that were previously observed on a
DWC3 based system under high system load.

Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 4058ebf3 12-Jan-2018 Lars-Peter Clausen <lars@metafoo.de>

usb: gadget: ffs: Execute copy_to_user() with USER_DS set

When using a AIO read() operation on the function FS gadget driver a URB is
submitted asynchronously and on URB completion the received data is copied
to the userspace buffer associated with the read operation.

This is done from a kernel worker thread invoking copy_to_user() (through
copy_to_iter()). And while the user space process memory is made available
to the kernel thread using use_mm(), some architecture require in addition
to this that the operation runs with USER_DS set. Otherwise the userspace
memory access will fail.

For example on ARM64 with Privileged Access Never (PAN) and User Access
Override (UAO) enabled the following crash occurs.

Internal error: Accessing user space memory with fs=KERNEL_DS: 9600004f [#1] SMP
Modules linked in:
CPU: 2 PID: 1636 Comm: kworker/2:1 Not tainted 4.9.0-04081-g8ab2dfb-dirty #487
Hardware name: ZynqMP ZCU102 Rev1.0 (DT)
Workqueue: events ffs_user_copy_worker
task: ffffffc87afc8080 task.stack: ffffffc87a00c000
PC is at __arch_copy_to_user+0x190/0x220
LR is at copy_to_iter+0x78/0x3c8
[...]
[<ffffff800847b790>] __arch_copy_to_user+0x190/0x220
[<ffffff80086f25d8>] ffs_user_copy_worker+0x70/0x130
[<ffffff80080b8c64>] process_one_work+0x1dc/0x460
[<ffffff80080b8f38>] worker_thread+0x50/0x4b0
[<ffffff80080bf5a0>] kthread+0xd8/0xf0
[<ffffff8008083680>] ret_from_fork+0x10/0x50

Address this by placing a set_fs(USER_DS) before of the copy operation
and revert it again once the copy operation has finished.

This patch is analogous to commit d7ffde35e31a ("vhost: use USER_DS in
vhost_worker thread") which addresses the same underlying issue.

Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 1a087f03 02-Mar-2018 Xinyong <xinyong.fang@linux.alibaba.com>

usb: gadget: f_fs: Fix use-after-free in ffs_fs_kill_sb()

When I debug a kernel crash issue in funcitonfs, found ffs_data.ref
overflowed, While functionfs is unmounting, ffs_data is put twice.

Commit 43938613c6fd ("drivers, usb: convert ffs_data.ref from atomic_t to
refcount_t") can avoid refcount overflow, but that is risk some situations.
So no need put ffs data in ffs_fs_kill_sb, already put in ffs_data_closed.

The issue can be reproduced in Mediatek mt6763 SoC, ffs for ADB device.
KASAN enabled configuration reports use-after-free errro.

BUG: KASAN: use-after-free in refcount_dec_and_test+0x14/0xe0 at addr ffffffc0579386a0
Read of size 4 by task umount/4650
====================================================
BUG kmalloc-512 (Tainted: P W O ): kasan: bad access detected
-----------------------------------------------------------------------------

INFO: Allocated in ffs_fs_mount+0x194/0x844 age=22856 cpu=2 pid=566
alloc_debug_processing+0x1ac/0x1e8
___slab_alloc.constprop.63+0x640/0x648
__slab_alloc.isra.57.constprop.62+0x24/0x34
kmem_cache_alloc_trace+0x1a8/0x2bc
ffs_fs_mount+0x194/0x844
mount_fs+0x6c/0x1d0
vfs_kern_mount+0x50/0x1b4
do_mount+0x258/0x1034
INFO: Freed in ffs_data_put+0x25c/0x320 age=0 cpu=3 pid=4650
free_debug_processing+0x22c/0x434
__slab_free+0x2d8/0x3a0
kfree+0x254/0x264
ffs_data_put+0x25c/0x320
ffs_data_closed+0x124/0x15c
ffs_fs_kill_sb+0xb8/0x110
deactivate_locked_super+0x6c/0x98
deactivate_super+0xb0/0xbc
INFO: Object 0xffffffc057938600 @offset=1536 fp=0x (null)
......
Call trace:
[<ffffff900808cf5c>] dump_backtrace+0x0/0x250
[<ffffff900808d3a0>] show_stack+0x14/0x1c
[<ffffff90084a8c04>] dump_stack+0xa0/0xc8
[<ffffff900826c2b4>] print_trailer+0x158/0x260
[<ffffff900826d9d8>] object_err+0x3c/0x40
[<ffffff90082745f0>] kasan_report_error+0x2a8/0x754
[<ffffff9008274f84>] kasan_report+0x5c/0x60
[<ffffff9008273208>] __asan_load4+0x70/0x88
[<ffffff90084cd81c>] refcount_dec_and_test+0x14/0xe0
[<ffffff9008d98f9c>] ffs_data_put+0x80/0x320
[<ffffff9008d9d904>] ffs_fs_kill_sb+0xc8/0x110
[<ffffff90082852a0>] deactivate_locked_super+0x6c/0x98
[<ffffff900828537c>] deactivate_super+0xb0/0xbc
[<ffffff90082af0c0>] cleanup_mnt+0x64/0xec
[<ffffff90082af1b0>] __cleanup_mnt+0x10/0x18
[<ffffff90080d9e68>] task_work_run+0xcc/0x124
[<ffffff900808c8c0>] do_notify_resume+0x60/0x70
[<ffffff90080866e4>] work_pending+0x10/0x14

Cc: stable@vger.kernel.org
Signed-off-by: Xinyong <xinyong.fang@linux.alibaba.com>

Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 675272d0 25-Jan-2018 Jack Pham <jackp@codeaurora.org>

usb: gadget: f_fs: Use config_ep_by_speed()

In commit 2bfa0719ac2a ("usb: gadget: function: f_fs: pass
companion descriptor along") there is a pointer arithmetic
bug where the comp_desc is obtained as follows:

comp_desc = (struct usb_ss_ep_comp_descriptor *)(ds +
USB_DT_ENDPOINT_SIZE);

Since ds is a pointer to usb_endpoint_descriptor, adding
7 to it ends up going out of bounds (7 * sizeof(struct
usb_endpoint_descriptor), which is actually 7*9 bytes) past
the SS descriptor. As a result the maxburst value will be
read incorrectly, and the UDC driver will also get a garbage
comp_desc (assuming it uses it).

Since Felipe wrote, "Eventually, f_fs.c should be converted
to use config_ep_by_speed() like all other functions, though",
let's finally do it. This allows the other usb_ep fields to
be properly populated, such as maxpacket and mult. It also
eliminates the awkward speed-based descriptor lookup since
config_ep_by_speed() does that already using the ones found
in struct usb_function.

Fixes: 2bfa0719ac2a ("usb: gadget: function: f_fs: pass companion descriptor along")
Cc: stable@vger.kernel.org
Signed-off-by: Jack Pham <jackp@codeaurora.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 6cf439e0 24-Jan-2018 Jack Pham <jackp@codeaurora.org>

usb: gadget: f_fs: Process all descriptors during bind

During _ffs_func_bind(), the received descriptors are evaluated
to prepare for binding with the gadget in order to allocate
endpoints and optionally set up OS descriptors. However, the
high- and super-speed descriptors are only parsed based on
whether the gadget_is_dualspeed() and gadget_is_superspeed()
calls are true, respectively.

This is a problem in case a userspace program always provides
all of the {full,high,super,OS} descriptors when configuring a
function. Then, for example if a gadget device is not capable
of SuperSpeed, the call to ffs_do_descs() for the SS descriptors
is skipped, resulting in an incorrect offset calculation for
the vla_ptr when moving on to the OS descriptors that follow.
This causes ffs_do_os_descs() to fail as it is now looking at
the SS descriptors' offset within the raw_descs buffer instead.

_ffs_func_bind() should evaluate the descriptors unconditionally,
so remove the checks for gadget speed.

Fixes: f0175ab51993 ("usb: gadget: f_fs: OS descriptors support")
Cc: stable@vger.kernel.org
Co-Developed-by: Mayank Rana <mrana@codeaurora.org>
Signed-off-by: Mayank Rana <mrana@codeaurora.org>
Signed-off-by: Jack Pham <jackp@codeaurora.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# a9a08845 11-Feb-2018 Linus Torvalds <torvalds@linux-foundation.org>

vfs: do bulk POLL* -> EPOLL* replacement

This is the mindless scripted replacement of kernel use of POLL*
variables as described by Al, done by this script:

for V in IN OUT PRI ERR RDNORM RDBAND WRNORM WRBAND HUP RDHUP NVAL MSG; do
L=`git grep -l -w POLL$V | grep -v '^t' | grep -v /um/ | grep -v '^sa' | grep -v '/poll.h$'|grep -v '^D'`
for f in $L; do sed -i "-es/^\([^\"]*\)\(\<POLL$V\>\)/\\1E\\2/" $f; done
done

with de-mangling cleanups yet to come.

NOTE! On almost all architectures, the EPOLL* constants have the same
values as the POLL* constants do. But they keyword here is "almost".
For various bad reasons they aren't the same, and epoll() doesn't
actually work quite correctly in some cases due to this on Sparc et al.

The next patch from Al will sort out the final differences, and we
should be all done.

Scripted-by: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# ce5bf9a5 08-Jan-2018 Hemant Kumar <hemantk@codeaurora.org>

usb: f_fs: Prevent gadget unbind if it is already unbound

Upon usb composition switch there is possibility of ep0 file
release happening after gadget driver bind. In case of composition
switch from adb to a non-adb composition gadget will never gets
bound again resulting into failure of usb device enumeration. Fix
this issue by checking FFS_FL_BOUND flag and avoid extra
gadget driver unbind if it is already done as part of composition
switch.

This fixes adb reconnection error reported on Android running
v4.4 and above kernel versions. Verified on Hikey running vanilla
v4.15-rc7 + few out of tree Mali patches.

Reviewed-at: https://android-review.googlesource.com/#/c/582632/

Cc: Felipe Balbi <balbi@kernel.org>
Cc: Greg KH <gregkh@linux-foundation.org>
Cc: Michal Nazarewicz <mina86@mina86.com>
Cc: John Stultz <john.stultz@linaro.org>
Cc: Dmitry Shmidt <dimitrysh@google.com>
Cc: Badhri <badhri@google.com>
Cc: Android Kernel Team <kernel-team@android.com>
Cc: stable@vger.kernel.org
Signed-off-by: Hemant Kumar <hemantk@codeaurora.org>
[AmitP: Cherry-picked it from android-4.14 and updated the commit log]
Signed-off-by: Amit Pundir <amit.pundir@linaro.org>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# c40619bb 28-Nov-2017 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: ffs: Make sparse happier

Silences the following warnings:
drivers/usb/gadget/function/f_fs.c:1253:37: warning: incorrect type in argument 1 (different address spaces)
drivers/usb/gadget/function/f_fs.c:1253:37: expected void [noderef] <asn:1>*to
drivers/usb/gadget/function/f_fs.c:1253:37: got void *<noident>
drivers/usb/gadget/function/f_fs.c:2322:23: warning: cast to restricted __le32
drivers/usb/gadget/function/f_fs.c:2876:38: warning: cast to restricted __le32
drivers/usb/gadget/function/f_fs.c:272:12: warning: context imbalance in '__ffs_ep0_queue_wait' - unexpected unlock
drivers/usb/gadget/function/f_fs.c:450:17: warning: context imbalance in 'ffs_ep0_write' - different lock contexts for basic block
drivers/usb/gadget/function/f_fs.c:490:24: warning: context imbalance in '__ffs_ep0_read_events' - unexpected unlock
drivers/usb/gadget/function/f_fs.c:496:16: warning: context imbalance in 'ffs_ep0_read' - different lock contexts for basic block

Also, add an "unlocks spinlock" comment for consistency with existing ones.
No behaviour change is intended.

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# afc9a42b 03-Jul-2017 Al Viro <viro@zeniv.linux.org.uk>

the rest of drivers/*: annotate ->poll() instances

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# a3acc696 27-Nov-2017 John Keeping <john@metanate.com>

usb: f_fs: Force Reserved1=1 in OS_DESC_EXT_COMPAT

The specification says that the Reserved1 field in OS_DESC_EXT_COMPAT
must have the value "1", but when this feature was first implemented we
rejected any non-zero values.

This was adjusted to accept all non-zero values (while now rejecting
zero) in commit 53642399aa71 ("usb: gadget: f_fs: Fix wrong check on
reserved1 of OS_DESC_EXT_COMPAT"), but that breaks any userspace
programs that worked previously by returning EINVAL when Reserved1 == 0
which was previously the only value that succeeded!

If we just set the field to "1" ourselves, both old and new userspace
programs continue to work correctly and, as a bonus, old programs are
now compliant with the specification without having to fix anything
themselves.

Fixes: 53642399aa71 ("usb: gadget: f_fs: Fix wrong check on reserved1 of OS_DESC_EXT_COMPAT")
Cc: <stable@vger.kernel.org>
Signed-off-by: John Keeping <john@metanate.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 30bf90cc 25-Nov-2017 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: ffs: Forbid usb_ep_alloc_request from sleeping

Found using DEBUG_ATOMIC_SLEEP while submitting an AIO read operation:

[ 100.853642] BUG: sleeping function called from invalid context at mm/slab.h:421
[ 100.861148] in_atomic(): 1, irqs_disabled(): 1, pid: 1880, name: python
[ 100.867954] 2 locks held by python/1880:
[ 100.867961] #0: (&epfile->mutex){....}, at: [<f8188627>] ffs_mutex_lock+0x27/0x30 [usb_f_fs]
[ 100.868020] #1: (&(&ffs->eps_lock)->rlock){....}, at: [<f818ad4b>] ffs_epfile_io.isra.17+0x24b/0x590 [usb_f_fs]
[ 100.868076] CPU: 1 PID: 1880 Comm: python Not tainted 4.14.0-edison+ #118
[ 100.868085] Hardware name: Intel Corporation Merrifield/BODEGA BAY, BIOS 542 2015.01.21:18.19.48
[ 100.868093] Call Trace:
[ 100.868122] dump_stack+0x47/0x62
[ 100.868156] ___might_sleep+0xfd/0x110
[ 100.868182] __might_sleep+0x68/0x70
[ 100.868217] kmem_cache_alloc_trace+0x4b/0x200
[ 100.868248] ? dwc3_gadget_ep_alloc_request+0x24/0xe0 [dwc3]
[ 100.868302] dwc3_gadget_ep_alloc_request+0x24/0xe0 [dwc3]
[ 100.868343] usb_ep_alloc_request+0x16/0xc0 [udc_core]
[ 100.868386] ffs_epfile_io.isra.17+0x444/0x590 [usb_f_fs]
[ 100.868424] ? _raw_spin_unlock_irqrestore+0x27/0x40
[ 100.868457] ? kiocb_set_cancel_fn+0x57/0x60
[ 100.868477] ? ffs_ep0_poll+0xc0/0xc0 [usb_f_fs]
[ 100.868512] ffs_epfile_read_iter+0xfe/0x157 [usb_f_fs]
[ 100.868551] ? security_file_permission+0x9c/0xd0
[ 100.868587] ? rw_verify_area+0xac/0x120
[ 100.868633] aio_read+0x9d/0x100
[ 100.868692] ? __fget+0xa2/0xd0
[ 100.868727] ? __might_sleep+0x68/0x70
[ 100.868763] SyS_io_submit+0x471/0x680
[ 100.868878] do_int80_syscall_32+0x4e/0xd0
[ 100.868921] entry_INT80_32+0x2a/0x2a
[ 100.868932] EIP: 0xb7fbb676
[ 100.868941] EFLAGS: 00000292 CPU: 1
[ 100.868951] EAX: ffffffda EBX: b7aa2000 ECX: 00000002 EDX: b7af8368
[ 100.868961] ESI: b7fbb660 EDI: b7aab000 EBP: bfb6c658 ESP: bfb6c638
[ 100.868973] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 007b

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# cdafb6d8 08-Nov-2017 Andrew Gabbasov <andrew_gabbasov@mentor.com>

usb: gadget: f_fs: Fix use-after-free in ffs_free_inst

KASAN enabled configuration reports an error

BUG: KASAN: use-after-free in ffs_free_inst+... [usb_f_fs] at addr ...
Write of size 8 by task ...

This is observed after "ffs-test" is run and interrupted. If after that
functionfs is unmounted and g_ffs module is unloaded, that use-after-free
occurs during g_ffs module removal.

Although the report indicates ffs_free_inst() function, the actual
use-after-free condition occurs in _ffs_free_dev() function, which
is probably inlined into ffs_free_inst().

This happens due to keeping the ffs_data reference in device structure
during functionfs unmounting, while ffs_data itself is freed as no longer
needed. The fix is to clear that reference in ffs_closed() function,
which is a counterpart of ffs_ready(), where the reference is stored.

Fixes: 3262ad824307 ("usb: gadget: f_fs: Stop ffs_closed NULL pointer dereference")
Cc: stable@vger.kernel.org
Signed-off-by: Andrew Gabbasov <andrew_gabbasov@mentor.com>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 24ceb9c6 06-Nov-2017 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

USB: gadget: function: Remove redundant license text

Now that the SPDX tag is in all USB files, that identifies the license
in a specific and legally-defined manner. So the extra GPL text wording
can be removed as it is no longer needed at all.

This is done on a quest to remove the 700+ different ways that files in
the kernel describe the GPL license text. And there's unneeded stuff
like the address (sometimes incorrect) for the FSF which is never
needed.

No copyright headers or other non-license-description text was removed.

Cc: Oliver Neukum <oneukum@suse.com>
Cc: Johan Hovold <johan@kernel.org>
Cc: Jerry Zhang <zhangjerry@google.com>
Cc: John Keeping <john@metanate.com>
Cc: Krzysztof Opasiak <k.opasiak@samsung.com>
Cc: Abdulhadi Mohamed <abdulahhadi2@gmail.com>
Cc: Matthew Wilcox <willy@linux.intel.com>
Cc: Janusz Dziedzic <januszx.dziedzic@linux.intel.com>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Acked-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Acked-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 5fd54ace 03-Nov-2017 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

USB: add SPDX identifiers to all remaining files in drivers/usb/

It's good to have SPDX identifiers in all files to make it easier to
audit the kernel tree for correct licenses.

Update the drivers/usb/ and include/linux/usb* files with the correct
SPDX license identifier based on the license text in the file itself.
The SPDX identifier is a legally binding shorthand, which can be used
instead of the full boiler plate text.

This work is based on a script and data from Thomas Gleixner, Philippe
Ombredanne, and Kate Stewart.

Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: Kate Stewart <kstewart@linuxfoundation.org>
Cc: Philippe Ombredanne <pombredanne@nexb.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Acked-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 97363902 16-Oct-2017 Bhumika Goyal <bhumirks@gmail.com>

usb: gadget: make config_item_type structures const

Make these structures const as they are only passed to the const
argument of the functions config_{group/item}_init_type_name.

Signed-off-by: Bhumika Goyal <bhumirks@gmail.com>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Signed-off-by: Christoph Hellwig <hch@lst.de>


# addfc582 12-Sep-2017 John Keeping <john@metanate.com>

usb: gadget: ffs: handle I/O completion in-order

By submitting completed transfers to the system workqueue there is no
guarantee that completion events will be queued up in the correct order,
as in multi-processor systems there is a thread running for each
processor and the work items are not bound to a particular core.

This means that several completions are in the queue at the same time,
they may be processed in parallel and complete out of order, resulting
in data appearing corrupt when read by userspace.

Create a single-threaded workqueue for FunctionFS so that data completed
requests is passed to userspace in the order in which they complete.

Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: John Keeping <john@metanate.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# cdff9f8e 11-Aug-2017 Jerry Zhang <zhangjerry@google.com>

usb: gadget: f_fs: Pass along set_halt errors.

Users can apply i/o in the wrong direction on an
endpoint to stall it. In case there is an error
that does not allow the endpoint to be stalled,
we want the user to know.

An operation to stall the endpoint will return
EBADMSG if successful, EAGAIN if there are still
queued requests, and other errors depending on
the underlying implementation.

Also remove the conditional since it is always true.

Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Jerry Zhang <zhangjerry@google.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# e16828cf 18-Apr-2017 Jerry Zhang <zhangjerry@google.com>

usb: gadget: function: f_fs: Move epfile waitqueue to ffs_data.

There were individual waitqueues for each epfile but eps_enable
would iterate through all of them, resulting in essentially the
same wakeup time.

The waitqueue represents the function being enabled, so a central
waitqueue in ffs_data makes more sense and is less redundant.

Also use wake_up_interruptible to reflect use of
wait_event_interruptible.

Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Jerry Zhang <zhangjerry@google.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 222155de 19-Apr-2017 Jerry Zhang <zhangjerry@google.com>

usb: gadget: function: f_fs: Let ffs_epfile_ioctl wait for enable.

This allows users to make an ioctl call as the first action on a
connection. Ex, some functions might want to get endpoint size
before making any i/os.

Previously, calling ioctls before read/write would depending on the
timing of endpoints being enabled.

ESHUTDOWN is now a possible return value and ENODEV is not, so change
docs accordingly.

Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Jerry Zhang <zhangjerry@google.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# b7f73850 25-Apr-2017 William Wu <william.wu@rock-chips.com>

usb: gadget: f_fs: avoid out of bounds access on comp_desc

Companion descriptor is only used for SuperSpeed endpoints,
if the endpoints are HighSpeed or FullSpeed, the Companion
descriptor will not allocated, so we can only access it if
gadget is SuperSpeed.

I can reproduce this issue on Rockchip platform rk3368 SoC
which supports USB 2.0, and use functionfs for ADB. Kernel
build with CONFIG_KASAN=y and CONFIG_SLUB_DEBUG=y report
the following BUG:

==================================================================
BUG: KASAN: slab-out-of-bounds in ffs_func_set_alt+0x224/0x3a0 at addr ffffffc0601f6509
Read of size 1 by task swapper/0/0
============================================================================
BUG kmalloc-256 (Not tainted): kasan: bad access detected
----------------------------------------------------------------------------

Disabling lock debugging due to kernel taint
INFO: Allocated in ffs_func_bind+0x52c/0x99c age=1275 cpu=0 pid=1
alloc_debug_processing+0x128/0x17c
___slab_alloc.constprop.58+0x50c/0x610
__slab_alloc.isra.55.constprop.57+0x24/0x34
__kmalloc+0xe0/0x250
ffs_func_bind+0x52c/0x99c
usb_add_function+0xd8/0x1d4
configfs_composite_bind+0x48c/0x570
udc_bind_to_driver+0x6c/0x170
usb_udc_attach_driver+0xa4/0xd0
gadget_dev_desc_UDC_store+0xcc/0x118
configfs_write_file+0x1a0/0x1f8
__vfs_write+0x64/0x174
vfs_write+0xe4/0x200
SyS_write+0x68/0xc8
el0_svc_naked+0x24/0x28
INFO: Freed in inode_doinit_with_dentry+0x3f0/0x7c4 age=1275 cpu=7 pid=247
...
Call trace:
[<ffffff900808aab4>] dump_backtrace+0x0/0x230
[<ffffff900808acf8>] show_stack+0x14/0x1c
[<ffffff90084ad420>] dump_stack+0xa0/0xc8
[<ffffff90082157cc>] print_trailer+0x188/0x198
[<ffffff9008215948>] object_err+0x3c/0x4c
[<ffffff900821b5ac>] kasan_report+0x324/0x4dc
[<ffffff900821aa38>] __asan_load1+0x24/0x50
[<ffffff90089eb750>] ffs_func_set_alt+0x224/0x3a0
[<ffffff90089d3760>] composite_setup+0xdcc/0x1ac8
[<ffffff90089d7394>] android_setup+0x124/0x1a0
[<ffffff90089acd18>] _setup+0x54/0x74
[<ffffff90089b6b98>] handle_ep0+0x3288/0x4390
[<ffffff90089b9b44>] dwc_otg_pcd_handle_out_ep_intr+0x14dc/0x2ae4
[<ffffff90089be85c>] dwc_otg_pcd_handle_intr+0x1ec/0x298
[<ffffff90089ad680>] dwc_otg_pcd_irq+0x10/0x20
[<ffffff9008116328>] handle_irq_event_percpu+0x124/0x3ac
[<ffffff9008116610>] handle_irq_event+0x60/0xa0
[<ffffff900811af30>] handle_fasteoi_irq+0x10c/0x1d4
[<ffffff9008115568>] generic_handle_irq+0x30/0x40
[<ffffff90081159b4>] __handle_domain_irq+0xac/0xdc
[<ffffff9008080e9c>] gic_handle_irq+0x64/0xa4
...
Memory state around the buggy address:
ffffffc0601f6400: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
ffffffc0601f6480: 00 00 00 00 00 00 00 00 00 00 06 fc fc fc fc fc
>ffffffc0601f6500: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
^
ffffffc0601f6580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffffffc0601f6600: fc fc fc fc fc fc fc fc 00 00 00 00 00 00 00 00
==================================================================

Signed-off-by: William Wu <william.wu@rock-chips.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# ea920bb4 10-Mar-2017 Michal Nazarewicz <mina86@mina86.com>

usb: gadget: f_fs: simplify ffs_dev name handling

Currently ffs_dev::name can be either allocated by the client of
the ffs_dev structure or by the f_fs.c core itself. The former
is used by g_ffs while the latter happens with configfs.

Historically, g_ffs did not need to allocate separate buffer for
the name so what is now f_fs.c core never cared about freeing
that space. With configfs the name needs to be copied since the
memory is not guaranteed to be availeble after ffs_set_inst_name
finishes.

The complication is therefore here to avoid allocations in the
g_ffs case but it complicates the code inproportinally to
benefits it provides. In particular, g_ffs is considered
‘legacy’ so optimising for its sake is unlikely to be worth the
effort.

With that observation in mind, simplify the code by unifying the
code paths in g_ffs and configfs paths. Furthermore, instead of
allocating a new buffer for the name, simply embed it in the
ffs_dev structure. This further makes the memory management
less convoluted and error-prone.

The configfs interface for functionfs imposed a limit of 40
characters for the name so this results in a 41-byte buffer
added to the structure. (For short names this may lead to
wasted memory but the actual amount is not immediately obvious
and depends on pointer size and which slab buckets the structure
and name would fall into).

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 43938613 06-Mar-2017 Elena Reshetova <elena.reshetova@intel.com>

drivers, usb: convert ffs_data.ref from atomic_t to refcount_t

refcount_t type and corresponding API should be
used instead of atomic_t when the variable is used as
a reference counter. This allows to avoid accidental
refcounter overflows that might lead to use-after-free
situations.

Signed-off-by: Elena Reshetova <elena.reshetova@intel.com>
Signed-off-by: Hans Liljestrand <ishkamiel@gmail.com>
Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: David Windsor <dwindsor@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 3ba534df 16-Feb-2017 Janusz Dziedzic <januszx.dziedzic@linux.intel.com>

Revert "usb: gadget: f_fs: Fix ExtCompat descriptor validation"

This reverts commit ac670a3a650b899fc020b81f63e810d06015b865.

This introduce bug we already fixed in
commit 53642399aa71 ("usb: gadget: f_fs: Fix wrong check on reserved1 wof OS_DESC_EXT_COMPAT")

Next FFS (adb) SS enumeration fail with Windows OS.

Signed-off-by: Janusz Dziedzic <januszx.dziedzic@linux.intel.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 2bfa0719 31-Jan-2017 Felipe Balbi <felipe.balbi@linux.intel.com>

usb: gadget: function: f_fs: pass companion descriptor along

If we're dealing with SuperSpeed endpoints, we need
to make sure to pass along the companion descriptor
and initialize fields needed by the Gadget
API. Eventually, f_fs.c should be converted to use
config_ep_by_speed() like all other functions,
though.

Cc: <stable@vger.kernel.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 174cd4b1 02-Feb-2017 Ingo Molnar <mingo@kernel.org>

sched/headers: Prepare to move signal wakeup & sigpending methods from <linux/sched.h> into <linux/sched/signal.h>

Fix up affected files that include this signal functionality via sched.h.

Acked-by: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Mike Galbraith <efault@gmx.de>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: linux-kernel@vger.kernel.org
Signed-off-by: Ingo Molnar <mingo@kernel.org>


# 83e526f2 17-Jan-2017 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: f_fs: Assorted buffer overflow checks.

OS descriptor head, when flagged as provided, is accessed without
checking if it fits in provided buffer. Verify length before access.
Also, there are other places where buffer length it checked
after accessing offsets which are potentially past the end. Check
buffer length before as well to fail cleanly.

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 41dc9ac1 23-Jan-2017 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: f_fs: Accept up to 30 endpoints.

It is allowed by the USB specification to enabled same-address, opposite-
direction endpoints simultaneously, which means 30 non-zero endpoints
are allowed. So double eps_addrmap length to 30.
The original code only accepted 14 descriptors out of a likely intended 15
(as there are 15 endpoint addresses, ignoring direction), because the first
eps_addrmap entry is unused (it is a placeholder for endpoint zero). So
increase eps_addrmap length by one to 31.

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# f199a80c 17-Jan-2017 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadger: f_fs: Do not copy past descriptor end.

Endpoint descriptors come in 2 sizes, struct usb_endpoint_descriptor being
the largest. Use bLength to stop on endpoint descriptor boundary, and not
2 bytes too far.

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 2c935bc5 14-Nov-2016 Peter Zijlstra <peterz@infradead.org>

locking/atomic, kref: Add kref_read()

Since we need to change the implementation, stop exposing internals.

Provide kref_read() to read the current reference count; typically
used for debug messages.

Kills two anti-patterns:

atomic_read(&kref->refcount)
kref->refcount.counter

Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Paul E. McKenney <paulmck@linux.vnet.ibm.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: linux-kernel@vger.kernel.org
Signed-off-by: Ingo Molnar <mingo@kernel.org>


# 08f37148 09-Jan-2017 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: f_fs: Fix iterations on endpoints.

When zero endpoints are declared for a function, there is no endpoint
to disable, enable or free, so replace do...while loops with while loops.
Change pre-decrement to post-decrement to iterate the same number of times
when there are endpoints to process.

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# b3ce3ce0 08-Dec-2016 Baolin Wang <baolin.wang@linaro.org>

usb: gadget: f_fs: Fix possibe deadlock

When system try to close /dev/usb-ffs/adb/ep0 on one core, at the same
time another core try to attach new UDC, which will cause deadlock as
below scenario. Thus we should release ffs lock before issuing
unregister_gadget_item().

[ 52.642225] c1 ======================================================
[ 52.642228] c1 [ INFO: possible circular locking dependency detected ]
[ 52.642236] c1 4.4.6+ #1 Tainted: G W O
[ 52.642241] c1 -------------------------------------------------------
[ 52.642245] c1 usb ffs open/2808 is trying to acquire lock:
[ 52.642270] c0 (udc_lock){+.+.+.}, at: [<ffffffc00065aeec>]
usb_gadget_unregister_driver+0x3c/0xc8
[ 52.642272] c1 but task is already holding lock:
[ 52.642283] c0 (ffs_lock){+.+.+.}, at: [<ffffffc00066b244>]
ffs_data_clear+0x30/0x140
[ 52.642285] c1 which lock already depends on the new lock.
[ 52.642287] c1
the existing dependency chain (in reverse order) is:
[ 52.642295] c0
-> #1 (ffs_lock){+.+.+.}:
[ 52.642307] c0 [<ffffffc00012340c>] __lock_acquire+0x20f0/0x2238
[ 52.642314] c0 [<ffffffc000123b54>] lock_acquire+0xe4/0x298
[ 52.642322] c0 [<ffffffc000aaf6e8>] mutex_lock_nested+0x7c/0x3cc
[ 52.642328] c0 [<ffffffc00066f7bc>] ffs_func_bind+0x504/0x6e8
[ 52.642334] c0 [<ffffffc000654004>] usb_add_function+0x84/0x184
[ 52.642340] c0 [<ffffffc000658ca4>] configfs_composite_bind+0x264/0x39c
[ 52.642346] c0 [<ffffffc00065b348>] udc_bind_to_driver+0x58/0x11c
[ 52.642352] c0 [<ffffffc00065b49c>] usb_udc_attach_driver+0x90/0xc8
[ 52.642358] c0 [<ffffffc0006598e0>] gadget_dev_desc_UDC_store+0xd4/0x128
[ 52.642369] c0 [<ffffffc0002c14e8>] configfs_write_file+0xd0/0x13c
[ 52.642376] c0 [<ffffffc00023c054>] vfs_write+0xb8/0x214
[ 52.642381] c0 [<ffffffc00023cad4>] SyS_write+0x54/0xb0
[ 52.642388] c0 [<ffffffc000085ff0>] el0_svc_naked+0x24/0x28
[ 52.642395] c0
-> #0 (udc_lock){+.+.+.}:
[ 52.642401] c0 [<ffffffc00011e3d0>] print_circular_bug+0x84/0x2e4
[ 52.642407] c0 [<ffffffc000123454>] __lock_acquire+0x2138/0x2238
[ 52.642412] c0 [<ffffffc000123b54>] lock_acquire+0xe4/0x298
[ 52.642420] c0 [<ffffffc000aaf6e8>] mutex_lock_nested+0x7c/0x3cc
[ 52.642427] c0 [<ffffffc00065aeec>] usb_gadget_unregister_driver+0x3c/0xc8
[ 52.642432] c0 [<ffffffc00065995c>] unregister_gadget_item+0x28/0x44
[ 52.642439] c0 [<ffffffc00066b34c>] ffs_data_clear+0x138/0x140
[ 52.642444] c0 [<ffffffc00066b374>] ffs_data_reset+0x20/0x6c
[ 52.642450] c0 [<ffffffc00066efd0>] ffs_data_closed+0xac/0x12c
[ 52.642454] c0 [<ffffffc00066f070>] ffs_ep0_release+0x20/0x2c
[ 52.642460] c0 [<ffffffc00023dbe4>] __fput+0xb0/0x1f4
[ 52.642466] c0 [<ffffffc00023dd9c>] ____fput+0x20/0x2c
[ 52.642473] c0 [<ffffffc0000ee944>] task_work_run+0xb4/0xe8
[ 52.642482] c0 [<ffffffc0000cd45c>] do_exit+0x360/0xb9c
[ 52.642487] c0 [<ffffffc0000cf228>] do_group_exit+0x4c/0xb0
[ 52.642494] c0 [<ffffffc0000dd3c8>] get_signal+0x380/0x89c
[ 52.642501] c0 [<ffffffc00008a8f0>] do_signal+0x154/0x518
[ 52.642507] c0 [<ffffffc00008af00>] do_notify_resume+0x70/0x78
[ 52.642512] c0 [<ffffffc000085ee8>] work_pending+0x1c/0x20
[ 52.642514] c1
other info that might help us debug this:
[ 52.642517] c1 Possible unsafe locking scenario:
[ 52.642518] c1 CPU0 CPU1
[ 52.642520] c1 ---- ----
[ 52.642525] c0 lock(ffs_lock);
[ 52.642529] c0 lock(udc_lock);
[ 52.642533] c0 lock(ffs_lock);
[ 52.642537] c0 lock(udc_lock);
[ 52.642539] c1
*** DEADLOCK ***
[ 52.642543] c1 1 lock held by usb ffs open/2808:
[ 52.642555] c0 #0: (ffs_lock){+.+.+.}, at: [<ffffffc00066b244>]
ffs_data_clear+0x30/0x140
[ 52.642557] c1 stack backtrace:
[ 52.642563] c1 CPU: 1 PID: 2808 Comm: usb ffs open Tainted: G
[ 52.642565] c1 Hardware name: Spreadtrum SP9860g Board (DT)
[ 52.642568] c1 Call trace:
[ 52.642573] c1 [<ffffffc00008b430>] dump_backtrace+0x0/0x170
[ 52.642577] c1 [<ffffffc00008b5c0>] show_stack+0x20/0x28
[ 52.642583] c1 [<ffffffc000422694>] dump_stack+0xa8/0xe0
[ 52.642587] c1 [<ffffffc00011e548>] print_circular_bug+0x1fc/0x2e4
[ 52.642591] c1 [<ffffffc000123454>] __lock_acquire+0x2138/0x2238
[ 52.642595] c1 [<ffffffc000123b54>] lock_acquire+0xe4/0x298
[ 52.642599] c1 [<ffffffc000aaf6e8>] mutex_lock_nested+0x7c/0x3cc
[ 52.642604] c1 [<ffffffc00065aeec>] usb_gadget_unregister_driver+0x3c/0xc8
[ 52.642608] c1 [<ffffffc00065995c>] unregister_gadget_item+0x28/0x44
[ 52.642613] c1 [<ffffffc00066b34c>] ffs_data_clear+0x138/0x140
[ 52.642618] c1 [<ffffffc00066b374>] ffs_data_reset+0x20/0x6c
[ 52.642621] c1 [<ffffffc00066efd0>] ffs_data_closed+0xac/0x12c
[ 52.642625] c1 [<ffffffc00066f070>] ffs_ep0_release+0x20/0x2c
[ 52.642629] c1 [<ffffffc00023dbe4>] __fput+0xb0/0x1f4
[ 52.642633] c1 [<ffffffc00023dd9c>] ____fput+0x20/0x2c
[ 52.642636] c1 [<ffffffc0000ee944>] task_work_run+0xb4/0xe8
[ 52.642640] c1 [<ffffffc0000cd45c>] do_exit+0x360/0xb9c
[ 52.642644] c1 [<ffffffc0000cf228>] do_group_exit+0x4c/0xb0
[ 52.642647] c1 [<ffffffc0000dd3c8>] get_signal+0x380/0x89c
[ 52.642651] c1 [<ffffffc00008a8f0>] do_signal+0x154/0x518
[ 52.642656] c1 [<ffffffc00008af00>] do_notify_resume+0x70/0x78
[ 52.642659] c1 [<ffffffc000085ee8>] work_pending+0x1c/0x20

Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Baolin Wang <baolin.wang@linaro.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 354bc45b 14-Dec-2016 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: f_fs: Fix ExtCompat descriptor validation

Reserved1 is documented as expected to be set to 0, but this test fails
when it it set to 0. Reverse the condition.

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 96a420d2d3 14-Dec-2016 Vincent Pelletier <plr.vincent@gmail.com>

usb: gadget: f_fs: Document eventfd effect on descriptor format.

When FUNCTIONFS_EVENTFD flag is set, __ffs_data_got_descs reads a 32bits,
little-endian value right after the fixed structure header, and passes it
to eventfd_ctx_fdget. Document this.

Also, rephrase a comment to be affirmative about the role of string
descriptor at index 0. Ref: USB 2.0 spec paragraph "9.6.7 String", and
also checked to still be current in USB 3.0 spec paragraph "9.6.9 String".

Signed-off-by: Vincent Pelletier <plr.vincent@gmail.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# cbbd26b8 01-Nov-2016 Al Viro <viro@zeniv.linux.org.uk>

[iov_iter] new primitives - copy_from_iter_full() and friends

copy_from_iter_full(), copy_from_iter_full_nocache() and
csum_and_copy_from_iter_full() - counterparts of copy_from_iter()
et.al., advancing iterator only in case of successful full copy
and returning whether it had been successful or not.

Convert some obvious users. *NOTE* - do not blindly assume that
something is a good candidate for those unless you are sure that
not advancing iov_iter in failure case is the right thing in
this case. Anything that does short read/short write kind of
stuff (or is in a loop, etc.) is unlikely to be a good one.

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 05e78c69 03-Nov-2016 Felix Hädicke <felixhaedicke@web.de>

usb: gadget: f_fs: fix wrong parenthesis in ffs_func_req_match()

Properly check the return code of ffs_func_revmap_intf() and
ffs_func_revmap_ep() for a non-negative value.

Instead of checking the return code, the comparison was performed for the last
parameter of the function calls, because of wrong parenthesis.

This also fixes the following static checker warning:
drivers/usb/gadget/function/f_fs.c:3152 ffs_func_req_match()
warn: always true condition '(((creq->wIndex)) >= 0) => (0-u16max >= 0)'

Reported-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Felix Hädicke <felixhaedicke@web.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 5bdcde90 22-Sep-2016 Daniel Wagner <daniel.wagner@bmw-carit.de>

usb: gadget: f_fs: use complete() instead complete_all()

There is only one waiter for the completion, therefore there
is no need to use complete_all(). Let's make that clear by
using complete() instead of complete_all().

The usage pattern of the completion is:

waiter context waker context
reinit_completion()
usb_esp_queue()
wait_for_completion_interruptible()

ffs_ep0_complete()
complete()

Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Daniel Wagner <daniel.wagner@bmw-carit.de>
Cc: Felipe Balbi <balbi@kernel.org>
Cc: Michal Nazarewicz <mina86@mina86.com>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: linux-usb@vger.kernel.org
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# a9e6f83c 03-Oct-2016 Michal Nazarewicz <mina86@mina86.com>

usb: gadget: f_fs: stop sleeping in ffs_func_eps_disable

ffs_func_eps_disable is called from atomic context so it cannot sleep
thus cannot grab a mutex. Change the handling of epfile->read_buffer
to use non-sleeping synchronisation method.

Reported-by: Chen Yu <chenyu56@huawei.com>
Signed-off-by: Michał Nazarewicz <mina86@mina86.com>
Fixes: 9353afbbfa7b ("buffer data from ‘oversized’ OUT requests")
Tested-by: John Stultz <john.stultz@linaro.org>
Tested-by: Chen Yu <chenyu56@huawei.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 454915dd 03-Oct-2016 Michal Nazarewicz <mina86@mina86.com>

usb: gadget: f_fs: edit epfile->ep under lock

epfile->ep is protected by ffs->eps_lock (not epfile->mutex) so clear it
while holding the spin lock.

Tested-by: John Stultz <john.stultz@linaro.org>
Tested-by: Chen Yu <chenyu56@huawei.com>
Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 078cd827 14-Sep-2016 Deepa Dinamani <deepa.kernel@gmail.com>

fs: Replace CURRENT_TIME with current_time() for inode timestamps

CURRENT_TIME macro is not appropriate for filesystems as it
doesn't use the right granularity for filesystem timestamps.
Use current_time() instead.

CURRENT_TIME is also not y2038 safe.

This is also in preparation for the patch that transitions
vfs timestamps to use 64 bit time and hence make them
y2038 safe. As part of the effort current_time() will be
extended to do range checks. Hence, it is necessary for all
file system timestamps to use current_time(). Also,
current_time() will be transitioned along with vfs to be
y2038 safe.

Note that whenever a single call to current_time() is used
to change timestamps in different inodes, it is because they
share the same time granularity.

Signed-off-by: Deepa Dinamani <deepa.kernel@gmail.com>
Reviewed-by: Arnd Bergmann <arnd@arndb.de>
Acked-by: Felipe Balbi <balbi@kernel.org>
Acked-by: Steven Whitehouse <swhiteho@redhat.com>
Acked-by: Ryusuke Konishi <konishi.ryusuke@lab.ntt.co.jp>
Acked-by: David Sterba <dsterba@suse.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 3262ad82 08-Sep-2016 Jim Baxter <jim_baxter@mentor.com>

usb: gadget: f_fs: Stop ffs_closed NULL pointer dereference

The struct ffs_data::private_data has a pointer to
ffs_dev stored in it during the ffs_fs_mount() function
however it is not cleared when the ffs_dev is freed
later which causes the ffs_closed function to crash
with "Unable to handle kernel NULL pointer dereference"
error when using the data in ffs_data::private_data.

This clears this pointer during the ffs_free_dev clean
up function.

Signed-off-by: Jim Baxter <jim_baxter@mentor.com>
Signed-off-by: Jiada Wang <jiada_wang@mentor.com>
Signed-off-by: Harish Jenny K N <harish_kandiga@mentor.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 4368c28a 21-Jun-2016 Felix Hädicke <felixhaedicke@web.de>

usb: gadget: f_fs: handle control requests in config 0

Introduces a new FunctionFS descriptor flag named
FUNCTIONFS_CONFIG0_SETUP.

When this flag is enabled, FunctionFS userspace drivers can process
non-standard control requests in configuration 0.

Signed-off-by: Felix Hädicke <felixhaedicke@web.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 1a00b457 21-Jun-2016 Felix Hädicke <felixhaedicke@web.de>

usb: gadget: composite: let USB functions process ctrl reqs in cfg0

It can sometimes be necessary for gadget drivers to process non-standard
control requests, which host devices can send without having sent
USB_REQ_SET_CONFIGURATION.

Therefore, the req_match() usb_function method is enhanced with the new
parameter "config0". When a USB configuration is active, this parameter
is false. When a non-core control request is processed in
composite_setup(), without an active configuration, req_match() of the
USB functions of all available configurations which implement this
function, is called with config0=true. Then the control request gets
processed by the first usb_function instance whose req_match() returns
true.

Signed-off-by: Felix Hädicke <felixhaedicke@web.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 54dfce6d 21-Jun-2016 Felix Hädicke <felixhaedicke@web.de>

usb: gadget: f_fs: handle control requests not directed to interface or endpoint

Introduces a new FunctionFS descriptor flag named
FUNCTIONFS_ALL_CTRL_RECIP. When this flag is enabled, control requests,
which are not explicitly directed to an interface or endpoint, can be
handled.

This allows FunctionFS userspace drivers to process non-standard
control requests.

Signed-off-by: Felix Hädicke <felixhaedicke@web.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 44963d64 24-Jun-2016 Dan Carpenter <dan.carpenter@oracle.com>

usb: gadget: f_fs: check for allocation failure

Return -ENOMEM if kmalloc() fails.

Fixes: 9353afbbfa7b ('usb: gadget: f_fs: buffer data from ‘oversized’ OUT requests')
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 9353afbb 21-May-2016 Michal Nazarewicz <mina86@mina86.com>

usb: gadget: f_fs: buffer data from ‘oversized’ OUT requests

f_fs rounds up read(2) requests to a multiple of a max packet size
which means that host may provide more data than user has space for.
So far, the excess data has been silently ignored.

This introduces a buffer for a tail of such requests so that they are
returned on next read instead of being ignored.

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# c662a31b 21-May-2016 Michal Nazarewicz <mina86@mina86.com>

usb: gadget: f_fs: printk error when excess data is dropped on read

Add a pr_err when host sent more data then the size of the buffer user
space gave us. This may happen on UDCs which require OUT requests to
be aligned to max packet size. The patch includes a description of the
situation.

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 872ce511 31-May-2016 Michal Nazarewicz <mina86@mina86.com>

usb: gadget: fix unused-but-set-variale warnings

Those are enabled with W=1 make option.

The patch leaves of some type-limits warnings which are caused by
generic macros used in a way where they produce always-false
conditions.

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# c6010c8b 13-May-2016 Jim Lin <jilin@nvidia.com>

usb: gadget: f_fs: Fix kernel panic if use_os_string not set

If c->cdev->use_os_string flag is not set,
don't need to invoke ffs_do_os_descs() in _ffs_func_bind.
So uninitialized ext_compat_id pointer won't be accessed by
__ffs_func_bind_do_os_desc to cause kernel panic.

Signed-off-by: Jim Lin <jilin@nvidia.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 53642399 20-May-2016 Jim Lin <jilin@nvidia.com>

usb: gadget: f_fs: Fix wrong check on reserved1 of OS_DESC_EXT_COMPAT

Current __ffs_data_do_os_desc() of f_fs.c will check reserved1 field
of OS_DESC_EXT_COMPAT and return -EINVAL if it's 1.
But MS OS 1.0 Descriptors
http://msdn.microsoft.com/en-us/library/windows/hardware/gg463179.aspx
defines that field to be 1.

Signed-off-by: Jim Lin <jilin@nvidia.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 0015f915 27-May-2016 Dan Carpenter <dan.carpenter@oracle.com>

usb: f_fs: off by one bug in _ffs_func_bind()

This loop is supposed to set all the .num[] values to -1 but it's off by
one so it skips the first element and sets one element past the end of
the array.

I've cleaned up the loop a little as well.

Fixes: ddf8abd25994 ('USB: f_fs: the FunctionFS driver')
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 38740a5b 14-Apr-2016 Lars-Peter Clausen <lars@metafoo.de>

usb: gadget: f_fs: Fix use-after-free

When using asynchronous read or write operations on the USB endpoints the
issuer of the IO request is notified by calling the ki_complete() callback
of the submitted kiocb when the URB has been completed.

Calling this ki_complete() callback will free kiocb. Make sure that the
structure is no longer accessed beyond that point, otherwise undefined
behaviour might occur.

Fixes: 2e4c7553cd6f ("usb: gadget: f_fs: add aio support")
Cc: <stable@vger.kernel.org> # v3.15+
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 332a5b44 30-Mar-2016 Lars-Peter Clausen <lars@metafoo.de>

usb: gadget: f_fs: Fix EFAULT generation for async read operations

In the current implementation functionfs generates a EFAULT for async read
operations if the read buffer size is larger than the URB data size. Since
a application does not necessarily know how much data the host side is
going to send it typically supplies a buffer larger than the actual data,
which will then result in a EFAULT error.

This behaviour was introduced while refactoring the code to use iov_iter
interface in commit c993c39b8639 ("gadget/function/f_fs.c: use put iov_iter
into io_data"). The original code took the minimum over the URB size and
the user buffer size and then attempted to copy that many bytes using
copy_to_user(). If copy_to_user() could not copy all data a EFAULT error
was generated. Restore the original behaviour by only generating a EFAULT
error when the number of bytes copied is not the size of the URB and the
target buffer has not been fully filled.

Commit 342f39a6c8d3 ("usb: gadget: f_fs: fix check in read operation")
already fixed the same problem for the synchronous read path.

Fixes: c993c39b8639 ("gadget/function/f_fs.c: use put iov_iter into io_data")
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>


# 09cbfeaf 01-Apr-2016 Kirill A. Shutemov <kirill.shutemov@linux.intel.com>

mm, fs: get rid of PAGE_CACHE_* and page_cache_{get,release} macros

PAGE_CACHE_{SIZE,SHIFT,MASK,ALIGN} macros were introduced *long* time
ago with promise that one day it will be possible to implement page
cache with bigger chunks than PAGE_SIZE.

This promise never materialized. And unlikely will.

We have many places where PAGE_CACHE_SIZE assumed to be equal to
PAGE_SIZE. And it's constant source of confusion on whether
PAGE_CACHE_* or PAGE_* constant should be used in a particular case,
especially on the border between fs and mm.

Global switching to PAGE_CACHE_SIZE != PAGE_SIZE would cause to much
breakage to be doable.

Let's stop pretending that pages in page cache are special. They are
not.

The changes are pretty straight-forward:

- <foo> << (PAGE_CACHE_SHIFT - PAGE_SHIFT) -> <foo>;

- <foo> >> (PAGE_CACHE_SHIFT - PAGE_SHIFT) -> <foo>;

- PAGE_CACHE_{SIZE,SHIFT,MASK,ALIGN} -> PAGE_{SIZE,SHIFT,MASK,ALIGN};

- page_cache_get() -> get_page();

- page_cache_release() -> put_page();

This patch contains automated changes generated with coccinelle using
script below. For some reason, coccinelle doesn't patch header files.
I've called spatch for them manually.

The only adjustment after coccinelle is revert of changes to
PAGE_CAHCE_ALIGN definition: we are going to drop it later.

There are few places in the code where coccinelle didn't reach. I'll
fix them manually in a separate patch. Comments and documentation also
will be addressed with the separate patch.

virtual patch

@@
expression E;
@@
- E << (PAGE_CACHE_SHIFT - PAGE_SHIFT)
+ E

@@
expression E;
@@
- E >> (PAGE_CACHE_SHIFT - PAGE_SHIFT)
+ E

@@
@@
- PAGE_CACHE_SHIFT
+ PAGE_SHIFT

@@
@@
- PAGE_CACHE_SIZE
+ PAGE_SIZE

@@
@@
- PAGE_CACHE_MASK
+ PAGE_MASK

@@
expression E;
@@
- PAGE_CACHE_ALIGN(E)
+ PAGE_ALIGN(E)

@@
expression E;
@@
- page_cache_get(E)
+ get_page(E)

@@
expression E;
@@
- page_cache_release(E)
+ put_page(E)

Signed-off-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com>
Acked-by: Michal Hocko <mhocko@suse.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# ef150884 28-Dec-2015 Changbin Du <changbin.du@intel.com>

usb: f_fs: avoid race condition with ffs_epfile_io_complete

ffs_epfile_io and ffs_epfile_io_complete runs in different context, but
there is no synchronization between them.

consider the following scenario:
1) ffs_epfile_io interrupted by sigal while
wait_for_completion_interruptible
2) then ffs_epfile_io set ret to -EINTR
3) just before or during usb_ep_dequeue, the request completed
4) ffs_epfile_io return with -EINTR

In this case, ffs_epfile_io tell caller no transfer success but actually
it may has been done. This break the caller's pipe.

Below script can help test it (adbd is the process which lies on f_fs).
while true
do
pkill -19 adbd #SIGSTOP
pkill -18 adbd #SIGCONT
sleep 0.1
done

To avoid this, just dequeue the request first. After usb_ep_dequeue, the
request must be done or canceled.

With this change, we can ensure no race condition in f_fs driver. But
actually I found some of the udc driver has analogical issue in its
dequeue implementation. For example,
1) the dequeue function hold the controller's lock.
2) before driver request controller to stop transfer, a request
completed.
3) the controller trigger a interrupt, but its irq handler need wait
dequeue function to release the lock.
4) dequeue function give back the request with negative status, and
release lock.
5) irq handler get lock but the request has already been given back.

So, the dequeue implementation should take care of this case. IMO, it
can be done as below steps to dequeue a already started request,
1) request controller to stop transfer on the given ep. HW know the
actual transfer status.
2) after hw stop transfer, driver scan if there are any completed one.
3) if found, process it with real status. if no, the request can
canceled.

Signed-off-by: "Du, Changbin" <changbin.du@intel.com>
[mina86@mina86.com: rebased on top of refactoring commits]
Signed-off-by: Michal Nazarewicz <mina86@mina86.com>

Signed-off-by: Felipe Balbi <balbi@kernel.org>


# ae76e134 04-Jan-2016 Michal Nazarewicz <mina86@mina86.com>

usb: f_fs: refactor ffs_epfile_io

Eliminate one of the return paths by using a ‘goto error_mutex’ and
rearrange some if-bodies which results in reduction of the indention level
and thus hopefully makes the function easier to read and reason about.

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>


# b3591f67 04-Jan-2016 Michal Nazarewicz <mina86@mina86.com>

usb: f_fs: replace unnecessary goto with a return

In ffs_epfile_io error label points to a return path which includes
a kfree(data) call. However, at the beginning of the function data is
always NULL so some of the early ‘goto error’ can safely be replaced
with a trivial return statement.

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>


# 3163c79e 04-Jan-2016 Michal Nazarewicz <mina86@mina86.com>

usb: f_fs: fix ffs_epfile_io returning success on req alloc failure

In the AIO path, if allocating of a request failse, the function simply
goes to the error_lock path whose end result is returning value of ret.
However, at this point ret’s value is zero (assigned as return value from
ffs_mutex_lock).

Fix by adding ‘ret = -ENOMEM’ statement.

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>


# 3de4e205 04-Jan-2016 Michal Nazarewicz <mina86@mina86.com>

usb: f_fs: fix memory leak when ep changes during transfer

In the ffs_epfile_io function, data buffer is allocated for non-halt
requests. Later, after grabing a mutex, the function checks that
epfile->ep is still ep and if it’s not, it set ret to -ESHUTDOWN and
follow a path including spin_unlock_irq (just after ‘ret = -ESHUTDOWN’),
mutex_unlock (after if-else-if-else chain) and returns ret. Noticeably,
this does not include freeing of the data buffer.

Fix by introducing a goto which moves control flow to the the end of the
function where spin_unlock_irq, mutex_unlock and kfree are all called.

Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>


# 7fe9a937 18-Nov-2015 Daniel Walter <dwalter@sigma-star.at>

usb: gadget: functionfs: fix missing access_ok checks

use safe copy_*_user instead of unsafe __copy_*_user
functions when accessing userland memory.

Signed-off-by: Daniel Walter <dwalter@sigma-star.at>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 55d81121 13-Jul-2015 Robert Baldyga <r.baldyga@samsung.com>

usb: gadget: ffs: call functionfs_unbind() if _ffs_func_bind() fails

Function ffs_do_functionfs_bind() calls functionfs_bind() which allocates
usb request and increments refcounts. These things needs to be cleaned
up by if further steps of initialization fail by calling functionfs_unbind().

Signed-off-by: Robert Baldyga <r.baldyga@samsung.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 4088acf1 18-May-2015 Rui Miguel Silva <rui.silva@linaro.org>

usb: gadget: f_fs: do not set cancel function on synchronous {read,write}

do not try to set cancel function in synchronous operations in
ffs_epfile_{read,write}_iter.

Cc: <stable@vger.kernel.org> # v4.0+
Acked-by: Al Viro <viro@ZenIV.linux.org.uk>
Signed-off-by: Rui Miguel Silva <rui.silva@linaro.org>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# f14e9ad1 20-May-2015 Rui Miguel Silva <rui.silva@linaro.org>

usb: gadget: f_fs: add extra check before unregister_gadget_item

ffs_closed can race with configfs_rmdir which will call config_item_release, so
add an extra check to avoid calling the unregister_gadget_item with an null
gadget item.

Signed-off-by: Rui Miguel Silva <rui.silva@linaro.org>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 342f39a6 20-May-2015 Rui Miguel Silva <rui.silva@linaro.org>

usb: gadget: f_fs: fix check in read operation

when copying to iter the size can be different then the iov count,
the check for full iov is wrong and make any read on request which
is not the exactly size of iov to return -EFAULT.

So, just check the success of the copy.

Signed-off-by: Rui Miguel Silva <rui.silva@linaro.org>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 49a79d8b 22-May-2015 Krzysztof Opasiak <k.opasiak@samsung.com>

usb: gadget: ffs: fix: Always call ffs_closed() in ffs_data_clear()

Originally FFS_FL_CALL_CLOSED_CALLBACK flag has been used to
indicate if we should call ffs_closed_callback().

Commit 4b187fceec3c ("usb: gadget: FunctionFS: add devices
management code") changed its semantic to indicate if we should
call ffs_closed() function which does a little bit more.

This situation leads to:

[ 122.362269] ------------[ cut here ]------------
[ 122.362287] WARNING: CPU: 2 PID: 2384 at drivers/usb/gadget/function/f_fs.c:3417 ffs_ep0_write+0x730/0x810 [usb_f_fs]()
[ 122.362292] Modules linked in:
[ 122.362555] CPU: 2 PID: 2384 Comm: adbd Tainted: G W 4.1.0-0.rc4.git0.1.1.fc22.i686 #1
[ 122.362561] Hardware name: To be filled by O.E.M. To be filled by O.E.M./Aptio CRB, BIOS 5.6.5 07/25/2014
[ 122.362567] c0d1f947 415badfa 00000000 d1029e64 c0a86e54 00000000 d1029e94 c045b937
[ 122.362584] c0c37f94 00000002 00000950 f9b313d4 00000d59 f9b2ebf0 f9b2ebf0 fffffff0
[ 122.362600] 00000003 deb53d00 d1029ea4 c045ba42 00000009 00000000 d1029f08 f9b2ebf0
[ 122.362617] Call Trace:
[ 122.362633] [<c0a86e54>] dump_stack+0x41/0x52
[ 122.362645] [<c045b937>] warn_slowpath_common+0x87/0xc0
[ 122.362658] [<f9b2ebf0>] ? ffs_ep0_write+0x730/0x810 [usb_f_fs]
[ 122.362668] [<f9b2ebf0>] ? ffs_ep0_write+0x730/0x810 [usb_f_fs]
[ 122.362678] [<c045ba42>] warn_slowpath_null+0x22/0x30
[ 122.362689] [<f9b2ebf0>] ffs_ep0_write+0x730/0x810 [usb_f_fs]
[ 122.362702] [<f9b2e4c0>] ? ffs_ep0_read+0x380/0x380 [usb_f_fs]
[ 122.362712] [<c05a1c1f>] __vfs_write+0x2f/0x100
[ 122.362722] [<c05a42f2>] ? __sb_start_write+0x52/0x110
[ 122.362731] [<c05a2534>] vfs_write+0x94/0x1b0
[ 122.362740] [<c0a8a1c0>] ? mutex_lock+0x10/0x30
[ 122.362749] [<c05a2f41>] SyS_write+0x51/0xb0
[ 122.362759] [<c0a8c71f>] sysenter_do_call+0x12/0x12
[ 122.362766] ---[ end trace 0673d3467cecf8db ]---

in some cases (reproduction path below). This commit get back
semantic of that flag and ensures that ffs_closed() is called
always when needed but ffs_closed_callback() is called only
if this flag is set.

Reproduction path:
Compile kernel without any UDC driver or bound some gadget
to existing one and then:

$ modprobe g_ffs
$ mount none -t functionfs mount_point
$ ffs-example mount_point

This will fail with -ENODEV as there is no udc.

$ ffs-example mount_point

This will fail with -EBUSY because ffs_data has not been
properly cleaned up.

Signed-off-by: Krzysztof Opasiak <k.opasiak@samsung.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 5d5d5689 03-Apr-2015 Al Viro <viro@zeniv.linux.org.uk>

make new_sync_{read,write}() static

All places outside of core VFS that checked ->read and ->write for being NULL or
called the methods directly are gone now, so NULL {read,write} with non-NULL
{read,write}_iter will do the right thing in all cases.

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# e2e40f2c 22-Feb-2015 Christoph Hellwig <hch@lst.de>

fs: move struct kiocb to fs.h

struct kiocb now is a generic I/O container, so move it to fs.h.
Also do a #include diet for aio.h while we're at it.

Signed-off-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 04b2fa9f 02-Feb-2015 Christoph Hellwig <hch@lst.de>

fs: split generic and aio kiocb

Most callers in the kernel want to perform synchronous file I/O, but
still have to bloat the stack with a full struct kiocb. Split out
the parts needed in filesystem code from those in the aio code, and
only allocate those needed to pass down argument on the stack. The
aio code embedds the generic iocb in the one it allocates and can
easily get back to it by using container_of.

Also add a ->ki_complete method to struct kiocb, this is used to call
into the aio code and thus removes the dependency on aio for filesystems
impementing asynchronous operations. It will also allow other callers
to substitute their own completion callback.

We also add a new ->ki_flags field to work around the nasty layering
violation recently introduced in commit 5e33f6 ("usb: gadget: ffs: add
eventfd notification about ffs events").

Signed-off-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 70e60d91 31-Jan-2015 Al Viro <viro@zeniv.linux.org.uk>

gadget/function/f_fs.c: switch to ->{read,write}_iter()

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# c993c39b 31-Jan-2015 Al Viro <viro@zeniv.linux.org.uk>

gadget/function/f_fs.c: use put iov_iter into io_data

both on aio and non-aio sides

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# de2080d4 31-Jan-2015 Al Viro <viro@zeniv.linux.org.uk>

gadget/function/f_fs.c: close leaks

If ffs_epfile_io() fails in AIO case, we end up leaking io_data
(and iovec_copy in case of AIO read).

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 5e33f6fd 23-Jan-2015 Robert Baldyga <r.baldyga@samsung.com>

usb: gadget: ffs: add eventfd notification about ffs events

Add eventfd which notifies userspace about ep0 events and AIO completion
events. It simplifies using of FunctionFS with event loop, because now
we need to poll on single file (instead of polling on ep0 and eventfd's
supplied to AIO layer).

FunctionFS eventfd is not triggered if another eventfd is supplied to
AIO layer (in AIO request). It can be useful, for example, when we want
to handle AIO transations for chosen endpoint in separate thread.

Signed-off-by: Robert Baldyga <r.baldyga@samsung.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# acba23fe 26-Jan-2015 Mario Schuknecht <mario.schuknecht@dresearch-fe.de>

usb: gadget: f_fs: Fix loop variable

Use if-loop variable 'epfile' instead of start variable 'epfiles'. Now the
correct endpoint file name is stored.

Signed-off-by: Mario Schuknecht <mario.schuknecht@dresearch-fe.de>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 18d6b32f 18-Dec-2014 Robert Baldyga <r.baldyga@samsung.com>

usb: gadget: f_fs: add "no_disconnect" mode

Since we can compose gadgets from many functions, there is the problem
related to gadget breakage while FunctionFS daemon being closed. FFS
function is userspace code so there is no way to know when it will close
files (it doesn't matter what is the reason of this situation, it can
be daemon logic, program breakage, process kill or any other). So when
we have another function in gadget which, for example, sends some amount
of data, does some software update or implements some real-time functionality,
we may want to keep the gadget connected despite FFS function is no longer
functional.

We can't just remove one of functions from gadget since it has been
enumerated, so the only way to keep entire gadget working is to make
broken FFS function deactivated but still visible to host. For this
purpose this patch introduces "no_disconnect" mode. It can be enabled
by setting mount option "no_disconnect=1", and results with defering
function disconnect to the moment of reopen ep0 file or filesystem
unmount. After closing all endpoint files, FunctionFS is set to state
FFS_DEACTIVATED.

When ffs->state == FFS_DEACTIVATED:
- function is still bound and visible to host,
- setup requests are automatically stalled,
- transfers on other endpoints are refused,
- epfiles, except ep0, are deleted from the filesystem,
- opening ep0 causes the function to be closed, and then FunctionFS
is ready for descriptors and string write,
- altsetting change causes the function to be closed - we want to keep
function alive until another functions are potentialy used, altsetting
change means that another configuration is being selected or USB cable
was unplugged, which indicates that we don't need to stay longer in
FFS_DEACTIVATED state
- unmounting of the FunctionFS instance causes the function to be closed.

Tested-by: David Cohen <david.a.cohen@linux.intel.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Robert Baldyga <r.baldyga@samsung.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 67913bbd 10-Sep-2014 Michal Nazarewicz <mina86@mina86.com>

usb: gadget: f_fs: refactor and document __ffs_ep0_read_events better

Instead of using variable length array, use a static length equal to
the size of the ffs->ev.types array. This gets rid of a sparse warning:

drivers/usb/gadget/function/f_fs.c:401:44: warning:
Variable length array is used.

and makes it more explicit that the array has a very tight upper size
limit. Also add some more documentation about the ev.types array and
how its size is limited and affects the rest of the code.

Reported-by: Dan Carpenter <dan.carpenter@oracle.com>
Reported-by: Rohith Seelaboyina <rseelaboyina@nvidia.com>
Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# c0d31b3c 13-Oct-2014 David Cohen <david.a.cohen@linux.intel.com>

usb: ffs: fix regression when quirk_ep_out_aligned_size flag is set

The commit '2e4c7553cd usb: gadget: f_fs: add aio support' broke the
quirk implemented to align buffer size to maxpacketsize on out endpoint.
As result, functionfs does not work on Intel platforms using dwc3 driver
(i.e. Bay Trail and Merrifield). This patch fixes the issue.

This code is based on a previous Qiuxu's patch.

Fixes: 2e4c7553cd (usb: gadget: f_fs: add aio support)
Cc: <stable@vger.kernel.org> # v3.16+
Signed-off-by: David Cohen <david.a.cohen@linux.intel.com>
Signed-off-by: Qiuxu Zhuo <qiuxu.zhuo@intel.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# a3058a5d 09-Oct-2014 Robert Baldyga <r.baldyga@samsung.com>

usb: gadget: f_fs: remove redundant ffs_data_get()

During FunctionFS bind, ffs_data_get() function was called twice
(in functionfs_bind() and in ffs_do_functionfs_bind()), while on unbind
ffs_data_put() was called once (in functionfs_unbind() function).
In result refcount never reached value 0, and ffs memory resources has
been never released.

Since ffs_data_get() call in ffs_do_functionfs_bind() is redundant
and not neccessary, we remove it to have equal number of gets ans puts,
and free allocated memory after refcount reach 0.

Fixes: 5920cda (usb: gadget: FunctionFS: convert to new function
interface with backward compatibility)
Cc: <stable@vger.kernel.org> # v3.14+
Signed-off-by: Robert Baldyga <r.baldyga@samsung.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 1bb27cac 03-Sep-2014 Al Viro <viro@zeniv.linux.org.uk>

f_fs: saner API for ffs_sb_create_file()

make it return dentry instead of inode

Acked-by: Felipe Balbi <balbi@ti.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 1b0bf88f 09-Sep-2014 Robert Baldyga <r.baldyga@samsung.com>

usb: gadget: f_fs: virtual endpoint address mapping

This patch introduces virtual endpoint address mapping. It separates
function logic form physical endpoint addresses making it more hardware
independent.

Following modifications changes user space API, so to enable them user
have to switch on the FUNCTIONFS_VIRTUAL_ADDR flag in descriptors.

Endpoints are now refered using virtual endpoint addresses chosen by
user in endpoint descpriptors. This applies to each context when endpoint
address can be used:
- when accessing endpoint files in FunctionFS filesystemi (in file name),
- in setup requests directed to specific endpoint (in wIndex field),
- in descriptors returned by FUNCTIONFS_ENDPOINT_DESC ioctl.

In endpoint file names the endpoint address number is formatted as
double-digit hexadecimal value ("ep%02x") which has few advantages -
it is easy to parse, allows to easly recognize endpoint direction basing
on its name (IN endpoint number starts with digit 8, and OUT with 0)
which can be useful for debugging purpose, and it makes easier to introduce
further features allowing to use each endpoint number in both directions
to have more endpoints available for function if hardware supports this
(for example we could have ep01 which is endpoint 1 with OUT direction,
and ep81 which is endpoint 1 with IN direction).

Physical endpoint address can be still obtained using ioctl named
FUNCTIONFS_ENDPOINT_REVMAP, but now it's not neccesary to handle
USB transactions properly.

Signed-off-by: Robert Baldyga <r.baldyga@samsung.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# fe00bcbf 11-Sep-2014 Michal Nazarewicz <mina86@mina86.com>

usb: f_fs: replace BUG in dead-code with less serious WARN_ON

Even though the BUG() in __ffs_event_add is a dead-code, it is still
better to warn rather then crash the system if that code ever gets
executed.

Reported-by: Felipe Balbi <balbi@ti.com>
Signed-off-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# c559a353 09-Sep-2014 Robert Baldyga <r.baldyga@samsung.com>

usb: gadget: f_fs: add ioctl returning ep descriptor

This patch introduces ioctl named FUNCTIONFS_ENDPOINT_DESC, which
returns endpoint descriptor to userspace. It works only if function
is active.

Signed-off-by: Robert Baldyga <r.baldyga@samsung.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 85b06f5e 09-Sep-2014 Dan Carpenter <dan.carpenter@oracle.com>

usb: gadget: f_fs: signedness bug in __ffs_func_bind_do_descs()

We need "idx" to be signed for the error handling to work.

Fixes: 6d5c1c77bbf9 ('usb: gadget: f_fs: fix the redundant ep files problem')
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 6d5c1c77 25-Aug-2014 Robert Baldyga <r.baldyga@samsung.com>

usb: gadget: f_fs: fix the redundant ep files problem

Up to now, when endpoint addresses in descriptors were non-consecutive,
there were created redundant files, which could cause problems in kernel,
when user tried to read/write to them. It was result of fact that maximum
endpoint address was taken as total number of endpoints in function.

This patch adds endpoint descriptors counting and storing their addresses
in eps_addrmap to verify their cohesion in each speed.

Endpoint address map would be also useful for further features, just like
vitual endpoint address mapping.

Signed-off-by: Robert Baldyga <r.baldyga@samsung.com>
Acked-by: Michal Nazarewicz <mina86@mina86.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>


# 00a2430f 15-Jul-2014 Andrzej Pietrasiewicz <andrzej.p@samsung.com>

usb: gadget: Gadget directory cleanup - group usb functions

The drivers/usb/gadget directory contains many files.
Files which are related can be distributed into separate directories.
This patch moves the USB functions implementations into a separate directory.

Signed-off-by: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
Signed-off-by: Felipe Balbi <balbi@ti.com>