History log of /linux-master/drivers/spi/spi.c
Revision Date Author Comments
# aa0162dc 11-Mar-2024 Janne Grunau <j@jannau.net>

spi: Restore delays for non-GPIO chip select

SPI controller with integrated chip select handling still need to adhere
to SPI device's CS setup, hold and inactive delays. For controller
without set_cs_timing spi core shall handle the delays to avoid
duplicated delay handling in each controller driver.
Fixes a regression for the out of tree SPI controller and SPI HID
transport on Apple M1/M1 Pro/Max notebooks.

Fixes: 4d8ff6b0991d ("spi: Add multi-cs memories support in SPI core")
Signed-off-by: Janne Grunau <j@jannau.net>
Link: https://msgid.link/r/20240311-spi-cs-delays-regression-v1-1-0075020a90b2@jannau.net
Signed-off-by: Mark Brown <broonie@kernel.org>


# be84be4a 07-Mar-2024 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Introduce SPI_INVALID_CS and is_valid_cs()

The SPI core inconsistently uses the marker value for unused chip select
pin. Define a constant (with appropriate type) and introduce is_valid_cs()
helper function to avoid spreading this inconsistency in the future.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://msgid.link/r/20240307150256.3789138-4-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 1209c556 07-Mar-2024 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Consistently use BIT for cs_index_mask

Some of the parts related to the chip select are using BIT() macro
the rest are using plain numbers. Unify all of them to use BIT().

While at it, make the (repetitive) comment clearer when assigning
cs_index_mask during SPI target device enumeration.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://msgid.link/r/20240307150256.3789138-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9086d0f2 06-Mar-2024 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Exctract spi_dev_check_cs() helper

It seems a few functions implement the similar for-loop to validate
chip select pins for uniqueness. Let's deduplicate that code in order
to have a single place of that for better maintenance.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://msgid.link/r/20240306160114.3471398-3-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5ee91605 06-Mar-2024 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Exctract spi_set_all_cs_unused() helper

It seems a few functions implement the similar for-loop to mark all
chip select pins unused. Let's deduplicate that code in order to have
a single place of that for better maintenance.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://msgid.link/r/20240306160114.3471398-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# fab53fea 19-Feb-2024 David Lechner <dlechner@baylibre.com>

spi: move splitting transfers to spi_optimize_message()

Splitting transfers is an expensive operation so we can potentially
optimize it by doing it only once per optimization of the message
instead of repeating each time the message is transferred.

The transfer splitting functions are currently the only user of
spi_res_alloc() so spi_res_release() can be safely moved at this time
from spi_finalize_current_message() to spi_unoptimize_message().

The doc comments of the public functions for splitting transfers are
also updated so that callers will know when it is safe to call them
to ensure proper resource management.

Reviewed-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>
Signed-off-by: David Lechner <dlechner@baylibre.com>
Link: https://msgid.link/r/20240219-mainline-spi-precook-message-v2-2-4a762c6701b9@baylibre.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7b1d87af 19-Feb-2024 David Lechner <dlechner@baylibre.com>

spi: add spi_optimize_message() APIs

This adds a new spi_optimize_message() function that can be used to
optimize SPI messages that are used more than once. Peripheral drivers
that use the same message multiple times can use this API to perform SPI
message validation and controller-specific optimizations once and then
reuse the message while avoiding the overhead of revalidating the
message on each spi_(a)sync() call.

Internally, the SPI core will also call this function for each message
if the peripheral driver did not explicitly call it. This is done to so
that controller drivers don't have to have multiple code paths for
optimized and non-optimized messages.

A hook is provided for controller drivers to perform controller-specific
optimizations.

Suggested-by: Martin Sperl <kernel@martin.sperl.org>
Link: https://lore.kernel.org/linux-spi/39DEC004-10A1-47EF-9D77-276188D2580C@martin.sperl.org/
Signed-off-by: David Lechner <dlechner@baylibre.com>
Link: https://msgid.link/r/20240219-mainline-spi-precook-message-v2-1-4a762c6701b9@baylibre.com
Reviewed-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 620d269f 07-Feb-2024 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Drop compat layer from renaming "master" to "controller"

Now that all in-tree users followed the rename, the compat stuff can go
away. This completes the renaming started with commit 8caab75fd2c2
("spi: Generalize SPI "master" to "controller"")

Acked-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>
Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/ad1d949325b61a4682e8d6ecf9d05da751e6a99f.1707324794.git.u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# c0c0293c 06-Feb-2024 David Lechner <dlechner@baylibre.com>

spi: drop gpf arg from __spi_split_transfer_maxsize()

The __spi_split_transfer_maxsize() function has a gpf argument to allow
callers to specify the type of memory allocation that needs to be used.
However, this function only allocates struct spi_transfer and is not
intended to be used from atomic contexts so this type should always be
GFP_KERNEL, so we can just drop the argument.

Some callers of these functions also passed GFP_DMA, but since only
struct spi_transfer is allocated and not any tx/rx buffers, this is
not actually necessary and is removed in this commit.

Signed-off-by: David Lechner <dlechner@baylibre.com>
Link: https://lore.kernel.org/r/20240206200648.1782234-1-dlechner@baylibre.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# c8bec335 26-Jan-2024 David Lechner <dlechner@baylibre.com>

spi: move split xfers for CS_WORD emulation

This moves splitting transfers for CS_WORD software emulation to the
same place where we split transfers for controller-specific reasons.

This fixes a few subtle bugs.

The calculation for maxsize was wrong for bit sizes between 17 and 24.
This is fixed by making use of spi_split_transfers_maxwords() which
already has the correct calculation.

Also, since this indirectly calls spi_res_alloc(), to avoid leaking
resources, spi_finalize_current_message() would need to be called
on all error paths in __spi_validate() and callers of __spi_validate()
would need to do the same. This is fixed by moving the call to
__spi_pump_transfer_message() where it is already splitting transfers
for other reasons and correctly releases resources in the subsequent
error paths.

Fixes: cbaa62e0094a ("spi: add software implementation for SPI_CS_WORD")
Signed-off-by: David Lechner <dlechner@baylibre.com>
Link: https://lore.kernel.org/r/20240126212358.3916280-2-dlechner@baylibre.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0da9a579 25-Jan-2024 David Lechner <dlechner@baylibre.com>

spi: avoid double validation in __spi_sync()

The __spi_sync() function calls __spi_validate() early in the function.
Later, it can call spi_async_locked() which calls __spi_validate()
again. __spi_validate() is an expensive function, so we can improve
performance measurably by avoiding calling it twice.

Instead of calling spi_async_locked(), we can call __spi_async() with
the spin lock held.

spi_async_locked() is removed since there are no more callers.

Signed-off-by: David Lechner <dlechner@baylibre.com>
Link: https://msgid.link/r/20240125234732.3530278-2-dlechner@baylibre.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b204aa0f 23-Jan-2024 David Lechner <dlechner@baylibre.com>

spi: consolidate setting message->spi

Previously, __spi_sync() and __spi_async() set message->spi to the spi
device independently after calling __spi_validate(). __spi_validate()
also would conditionally set this if it needed to split the message
since it wasn't set yet.

Since both __spi_sync() and __spi_async() call __spi_validate(), we can
consolidate this into only setting message->spi once (unconditionally)
in __spi_validate(). This will also save any future callers of
__spi_validate() from also needing to set message->spi.

Signed-off-by: David Lechner <dlechner@baylibre.com>
Link: https://msgid.link/r/20240123214946.2616786-1-dlechner@baylibre.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6df534cc 05-Jan-2024 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

spi: make spi_bus_type const

Now that the driver core can properly handle constant struct bus_type,
move the spi_bus_type variable to be a constant structure as well,
placing it into read-only memory which can not be modified at runtime.

Cc: Mark Brown <broonie@kernel.org>
Cc: <linux-spi@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: https://msgid.link/r/2024010549-erasure-swoop-1cc6@gregkh
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8c2ae772 25-Jan-2024 David Lechner <dlechner@baylibre.com>

spi: fix finalize message on error return

In __spi_pump_transfer_message(), the message was not finalized in the
first error return as it is in the other error return paths. Not
finalizing the message could cause anything waiting on the message to
complete to hang forever.

This adds the missing call to spi_finalize_current_message().

Fixes: ae7d2346dc89 ("spi: Don't use the message queue if possible in spi_sync")
Signed-off-by: David Lechner <dlechner@baylibre.com>
Link: https://msgid.link/r/20240125205312.3458541-2-dlechner@baylibre.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4d8ff6b0 25-Nov-2023 Amit Kumar Mahapatra <amit.kumar-mahapatra@amd.com>

spi: Add multi-cs memories support in SPI core

AMD-Xilinx GQSPI controller has two advanced mode that allows the
controller to consider two flashes as one single device.

One of these two mode is the parallel mode in which each byte of data is
stored in both devices, the even bits in the lower flash & the odd bits in
the upper flash. The byte split is automatically handled by the QSPI
controller.

The other mode is the stacked mode in which both the flashes share the
same SPI bus but each of the device contain half of the data. In this mode,
the controller does not follow CS requests but instead internally wires the
two CS levels with the value of the most significant address bit.

For supporting both these modes SPI core need to be updated for providing
multiple CS for a single SPI device.

For adding multi CS support the SPI device need to be aware of all the CS
values. So, the "chip_select" member in the spi_device structure is now an
array that holds all the CS values.

spi_device structure now has a "cs_index_mask" member. This acts as an
index to the chip_select array. If nth bit of spi->cs_index_mask is set
then the driver would assert spi->chip_select[n].

In parallel mode all the chip selects are asserted/de-asserted
simultaneously and each byte of data is stored in both devices, the even
bits in one, the odd bits in the other. The split is automatically handled
by the GQSPI controller. The GQSPI controller supports a maximum of two
flashes connected in parallel mode. A SPI_CONTROLLER_MULTI_CS flag bit is
added in the spi controller flags, through ctlr->flags the spi core
will make sure that the controller is capable of handling multiple chip
selects at once.

For supporting multiple CS via GPIO the cs_gpiod member of the spi_device
structure is now an array that holds the gpio descriptor for each
chipselect.

CS GPIO is not tested on our hardware, but it has been tested by @Stefan
https://lore.kernel.org/all/005001da1efc$619ad5a0$24d080e0$@opensource.cirrus.com/

Signed-off-by: Amit Kumar Mahapatra <amit.kumar-mahapatra@amd.com>
Tested-by: Stefan Binding <sbinding@opensource.cirrus.com>
Link: https://lore.kernel.org/r/20231125092137.2948-4-amit.kumar-mahapatra@amd.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 39cefd85 29-Nov-2023 Nam Cao <namcao@linutronix.de>

spi: introduce SPI_TRANS_FAIL_IO for error reporting

The default message transfer implementation - spi_transfer_one_message -
invokes the specific device driver's transfer_one(), then waits for
completion. However, there is no mechanism for the device driver to
report failure in the middle of the transfer.

Introduce SPI_TRANS_FAIL_IO for drivers to report transfer failure.

Signed-off-by: Nam Cao <namcao@linutronix.de>
Acked-by: Linus Walleij <linus.walleij@linaro.org>
Link: https://lore.kernel.org/r/4b420dac528e60f122adde16851da88e4798c1ea.1701274975.git.namcao@linutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# bef4a48f 07-Nov-2023 Mark Hasemeyer <markhas@chromium.org>

spi: Fix null dereference on suspend

A race condition exists where a synchronous (noqueue) transfer can be
active during a system suspend. This can cause a null pointer
dereference exception to occur when the system resumes.

Example order of events leading to the exception:
1. spi_sync() calls __spi_transfer_message_noqueue() which sets
ctlr->cur_msg
2. Spi transfer begins via spi_transfer_one_message()
3. System is suspended interrupting the transfer context
4. System is resumed
6. spi_controller_resume() calls spi_start_queue() which resets cur_msg
to NULL
7. Spi transfer context resumes and spi_finalize_current_message() is
called which dereferences cur_msg (which is now NULL)

Wait for synchronous transfers to complete before suspending by
acquiring the bus mutex and setting/checking a suspend flag.

Signed-off-by: Mark Hasemeyer <markhas@chromium.org>
Link: https://lore.kernel.org/r/20231107144743.v1.1.I7987f05f61901f567f7661763646cb7d7919b528@changeid
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@kernel.org


# a8ecbc54 14-Oct-2023 Hans de Goede <hdegoede@redhat.com>

spi: Export acpi_spi_find_controller_by_adev()

Export acpi_spi_find_controller_by_adev() so that ACPI glue code which
wants to dynamically create a spi_device using acpi_spi_device_alloc() or
spi_new_device() on a controller, to which the code does not already have
a reference, can find the controller.

Signed-off-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20231014205314.59333-2-hdegoede@redhat.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9386c958 16-Sep-2023 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Drop warning from spi_stop_queue()

Both callers of spi_stop_queue() (i.e. spi_destroy_queue() and
spi_controller_suspend()) already emit an error message if
spi_stop_queue() fails. Another warning in this case isn't helpful, so
drop it.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20230916161235.1050176-1-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 169f5312 13-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Use BITS_TO_BYTES()

BITS_TO_BYTES() is the existing macro which takes care about full
bytes that may fully hold the given amount of bits. Use it.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230714091748.89681-4-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7b5c6a54 13-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Kill spi_add_device_locked()

Now, spi_add_device_locked() has just a line on top of __spi_add_device().
Besides that, it has a single caller. So, just kill it and embed its parts
into the caller.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230714091748.89681-3-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 36124dea 13-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Remove code duplication in spi_add_device*()

The commit 0c79378c0199 ("spi: add ancillary device support")
added a dozen of duplicating lines of code. We may move them
to the __spi_add_device(). Note, that the code may be called
under the mutex.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Reviewed-by: Sebastian Reichel <sebastian.reichel@collabora.com>
Link: https://lore.kernel.org/r/20230714091748.89681-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 702ca026 10-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Fix spelling typos and acronyms capitalization

Fix
- spelling typos
- capitalization of acronyms
in the comments.

While at it, fix the multi-line comment style.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230710154932.68377-16-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 82238d2c 10-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Rename SPI_MASTER_GPIO_SS to SPI_CONTROLLER_GPIO_SS

Rename SPI_MASTER_GPIO_SS to SPI_CONTROLLER_GPIO_SS and
convert the users to SPI_CONTROLLER_GPIO_SS to follow
the new naming shema.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230710154932.68377-14-andriy.shevchenko@linux.intel.com
Reviewed-by: Serge Semin <fancer.lancer@gmail.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# edf6a864 10-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Sort headers alphabetically

Sorting headers alphabetically helps locating duplicates, and
make it easier to figure out where to insert new headers.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230710154932.68377-8-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# f2daa466 10-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Use sysfs_emit() to instead of s*printf()

Follow the advice of the Documentation/filesystems/sysfs.rst and show()
should only use sysfs_emit() or sysfs_emit_at() when formatting the
value to be returned to user space.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230710154932.68377-7-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 2b308e71 10-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Replace if-else-if by bitops and multiplications

Instead of if-else-if, simply call roundup_pow_of_two(BITS_PER_BYTES()).
Note, there is no division assumed as compiler may optimize it away.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230710154932.68377-4-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 440c4733 10-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Drop duplicate IDR allocation code in spi_register_controller()

Refactor spi_register_controller() to drop duplicate IDR allocation.
Instead of if-else-if branching use two sequential if:s, which allows
to re-use the logic of IDR allocation in all cases.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230710154932.68377-3-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# fbab5b2c 10-Jul-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Remove unneeded OF node NULL checks

In the couple of places the NULL check of OF node is implied by the call
that takes it as a parameter. Drop the respective duplicate checks.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230710154932.68377-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 673aa1ed 04-Apr-2023 Miquel Raynal <miquel.raynal@bootlin.com>

of: Rename of_modalias_node()

This helper does not produce a real modalias, but tries to get the
"product" compatible part of the "vendor,product" compatibles only. It
is far from creating a purely useful modalias string and does not seem
to be used like that directly anyway, so let's try to give this helper a
more meaningful name before moving there a real modalias helper (already
existing under of/device.c).

Also update the various documentations to refer to the strings as
"aliases" rather than "modaliases" which has a real meaning in the Linux
kernel.

There is no functional change.

Cc: Rafael J. Wysocki <rafael@kernel.org>
Cc: Len Brown <lenb@kernel.org>
Cc: Maarten Lankhorst <maarten.lankhorst@linux.intel.com>
Cc: Maxime Ripard <mripard@kernel.org>
Cc: Thomas Zimmermann <tzimmermann@suse.de>
Cc: Sebastian Reichel <sre@kernel.org>
Cc: Wolfram Sang <wsa@kernel.org>
Cc: Mark Brown <broonie@kernel.org>
Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
Reviewed-by: Rob Herring <robh@kernel.org>
Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Srinivas Kandagatla <srinivas.kandagatla@linaro.org>
Acked-by: Sebastian Reichel <sre@kernel.org>
Link: https://lore.kernel.org/r/20230404172148.82422-9-srinivas.kandagatla@linaro.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 10a03c36 13-Mar-2023 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

drivers: remove struct module * setting from struct class

There is no need to manually set the owner of a struct class, as the
registering function does it automatically, so remove all of the
explicit settings from various drivers that did so as it is unneeded.

This allows us to remove this pointer entirely from this structure going
forward.

Cc: "Rafael J. Wysocki" <rafael@kernel.org>
Link: https://lore.kernel.org/r/20230313181843.1207845-2-gregkh@linuxfoundation.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 027781f3 10-Mar-2023 Leonard Göhrs <l.goehrs@pengutronix.de>

spi: core: add spi_split_transfers_maxwords

Add spi_split_transfers_maxwords() function that splits
spi_transfers transparently into multiple transfers
that are below a given number of SPI words.

This function reuses most of its code from
spi_split_transfers_maxsize() and for transfers with
eight or less bits per word actually behaves the same.

Signed-off-by: Leonard Göhrs <l.goehrs@pengutronix.de>
Link: https://lore.kernel.org/r/20230310092053.1006459-1-l.goehrs@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 20064c47 06-Mar-2023 William Zhang <william.zhang@broadcom.com>

spi: Fix cocci warnings

cocci reported warning: !A || A && B is equivalent to !A || B. This fix
simplified the condition check to !A || B.

Fixes: 76a85704cb91 ("spi: spi-mem: Allow controller supporting mem_ops without exec_op")
Reported-by: kernel test robot <lkp@intel.com>
Link: https://lore.kernel.org/oe-kbuild-all/202303010051.HrHWSr9y-lkp@intel.com/

Signed-off-by: William Zhang <william.zhang@broadcom.com>
Link: https://lore.kernel.org/r/20230307012004.414502-1-william.zhang@broadcom.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# c7cc588b 06-Mar-2023 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Propagate firmware node

Propagate firmware node by using a specific API call, i.e. device_set_node().

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20230306182913.87231-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# fc12d4bb 28-Feb-2023 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Replace spi_pcpu_stats_totalize() macro by a C function

spi_pcpu_stats_totalize() is a rather large macro, and is instantiated
28 times, causing a large amount of duplication in the amount of
generated code.

Reduce the duplication by replacing spi_pcpu_stats_totalize() by a real
C function, and absorb all other common code from
spi_statistics_##name##_show(). As (a) the old "field" parameter was
the name of a structure member, which cannot be passed to a function,
and (b) passing a pointer to the member is also not an option, due to
the loop over all possible CPUs, the "field" parameter is replaced by an
"offset" parameter, pointing to a location within the structure.

This reduces kernel size by ca. 4 KiB (on arm32 and arm64).

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Link: https://lore.kernel.org/r/cb7690d9d04c06eec23dbb98fbb5444082125cff.1677594432.git.geert+renesas@glider.be
Signed-off-by: Mark Brown <broonie@kernel.org>


# 1a50d940 30-Mar-2023 Geert Uytterhoeven <geert+renesas@glider.be>

treewide: Fix probing of devices in DT overlays

When loading a DT overlay that creates a device, the device is not
probed, unless the DT overlay is unloaded and reloaded again.

After the recent refactoring to improve fw_devlink, it no longer depends
on the "compatible" property to identify which device tree nodes will
become struct devices. fw_devlink now picks up dangling consumers
(consumers pointing to descendent device tree nodes of a device that
aren't converted to child devices) when a device is successfully bound
to a driver. See __fw_devlink_pickup_dangling_consumers().

However, during DT overlay, a device's device tree node can have
sub-nodes added/removed without unbinding/rebinding the driver. This
difference in behavior between the normal device instantiation and
probing flow vs. the DT overlay flow has a bunch of implications that
are pointed out elsewhere[1]. One of them is that the fw_devlink logic
to pick up dangling consumers is never exercised.

This patch solves the fw_devlink issue by marking all DT nodes added by
DT overlays with FWNODE_FLAG_NOT_DEVICE (fwnode that won't become
device), and by clearing the flag when a struct device is actually
created for the DT node. This way, fw_devlink knows not to have
consumers waiting on these newly added DT nodes, and to propagate the
dependency to an ancestor DT node that has the corresponding struct
device.

Based on a patch by Saravana Kannan, which covered only platform and spi
devices.

[1] https://lore.kernel.org/r/CAGETcx_bkuFaLCiPrAWCPQz+w79ccDp6=9e881qmK=vx3hBMyg@mail.gmail.com

Fixes: 4a032827daa89350 ("of: property: Simplify of_link_to_phandle()")
Link: https://lore.kernel.org/r/CAGETcx_+rhHvaC_HJXGrr5_WAd2+k5f=rWYnkCZ6z5bGX-wj4w@mail.gmail.com
Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Acked-by: Mark Brown <broonie@kernel.org>
Acked-by: Wolfram Sang <wsa@kernel.org> # for I2C
Acked-by: Shawn Guo <shawnguo@kernel.org>
Acked-by: Saravana Kannan <saravanak@google.com>
Tested-by: Ivan Bornyakov <i.bornyakov@metrotek.ru>
Link: https://lore.kernel.org/r/e1fa546682ea4c8474ff997ab6244c5e11b6f8bc.1680182615.git.geert+renesas@glider.be
Signed-off-by: Rob Herring <robh@kernel.org>


# 2a81ada3 10-Jan-2023 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

driver core: make struct bus_type.uevent() take a const *

The uevent() callback in struct bus_type should not be modifying the
device that is passed into it, so mark it as a const * and propagate the
function signature changes out into all relevant subsystems that use
this callback.

Acked-by: Rafael J. Wysocki <rafael@kernel.org>
Acked-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20230111113018.459199-16-gregkh@linuxfoundation.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 9d77522b 14-Feb-2023 Christophe JAILLET <christophe.jaillet@wanadoo.fr>

spi: Reorder fields in 'struct spi_transfer'

Group some variables based on their sizes to reduce hole and avoid padding.
On x86_64, this shrinks the size from 144 to 128 bytes.

Turn 'timestamped' into a bitfield so that it can be easily merged with
some other bifields and move 'error'.

This should have no real impact on memory allocation because 'struct
spi_transfer' is mostly used on stack, but it can save a few cycles
when the structure is initialized or copied.

Signed-off-by: Christophe JAILLET <christophe.jaillet@wanadoo.fr>
Link: https://lore.kernel.org/r/93a051da85a895bc6003aedfb00a13e1c2fc6338.1676370870.git.christophe.jaillet@wanadoo.fr
Signed-off-by: Mark Brown <broonie@kernel.org>


# 76a85704 09-Feb-2023 William Zhang <william.zhang@broadcom.com>

spi: spi-mem: Allow controller supporting mem_ops without exec_op

Currently exec_op is always required if controller driver provides
mem_ops. But some controller such as bcm63xx-hsspi may only need to
implement other operation like supports_op and use the default
execution operation. This patch removes this restriction.

Signed-off-by: William Zhang <william.zhang@broadcom.com>
Link: https://lore.kernel.org/r/20230209200246.141520-13-william.zhang@broadcom.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6e80133a 09-Feb-2023 William Zhang <william.zhang@broadcom.com>

spi: export spi_transfer_cs_change_delay_exec function

For SPI controller that implements transfer_one_message, it needs to
insert the delay that required by cs change event between the transfers.
Add a wrapper for the local function _spi_transfer_cs_change_delay_exec
and export it for SPI controller driver to use.

Signed-off-by: William Zhang <william.zhang@broadcom.com>
Link: https://lore.kernel.org/r/20230209200246.141520-9-william.zhang@broadcom.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 303feb3c 19-Jan-2023 Amit Kumar Mahapatra <amit.kumar-mahapatra@amd.com>

spi: Add APIs in spi core to set/get spi->chip_select and spi->cs_gpiod

Supporting multi-cs in spi core and spi controller drivers would require
the chip_select & cs_gpiod members of struct spi_device to be an array.
But changing the type of these members to array would break the spi driver
functionality. To make the transition smoother introduced four new APIs to
get/set the spi->chip_select & spi->cs_gpiod and replaced all
spi->chip_select and spi->cs_gpiod references in spi core with the API
calls.
While adding multi-cs support in further patches the chip_select & cs_gpiod
members of the spi_device structure would be converted to arrays & the
"idx" parameter of the APIs would be used as array index i.e.,
spi->chip_select[idx] & spi->cs_gpiod[idx] respectively.

Suggested-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Amit Kumar Mahapatra <amit.kumar-mahapatra@amd.com>
Reviewed-by: Michal Simek <michal.simek@amd.com>
Link: https://lore.kernel.org/r/20230119185342.2093323-2-amit.kumar-mahapatra@amd.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5827b31d 13-Jan-2023 Janne Grunau <j@jannau.net>

spi: Parse hold/inactive CS delay values from the DT

Now that we support parsing the setup time from the Device Tree, we can
also easily support the remaining hold and inactive time delay values.

Signed-off-by: Janne Grunau <j@jannau.net>
Signed-off-by: Hector Martin <marcan@marcan.st>
Link: https://lore.kernel.org/r/20230113102309.18308-4-marcan@marcan.st
Signed-off-by: Mark Brown <broonie@kernel.org>


# f276aacf 13-Jan-2023 Janne Grunau <j@jannau.net>

spi: Use a 32-bit DT property for spi-cs-setup-delay-ns

65us is not a reasonable maximum for this property, as some devices
might need a much longer setup time (e.g. those driven by firmware on
the other end). Plus, device tree property values are in 32-bit cells
and smaller widths should not be used without good reason.

Also move the logic to a helper function, since this will later be used
to parse other CS delay properties too.

Fixes: 33a2fde5f77b ("spi: Introduce spi-cs-setup-ns property")
Signed-off-by: Janne Grunau <j@jannau.net>
Signed-off-by: Hector Martin <marcan@marcan.st>
Link: https://lore.kernel.org/r/20230113102309.18308-2-marcan@marcan.st
Signed-off-by: Mark Brown <broonie@kernel.org>


# e0fe6a31 04-Jan-2023 Hector Martin <marcan@marcan.st>

spi: Rename spi-cs-setup-ns property to spi-cs-setup-delay-ns

As mentioned in the corresponding DT binding commit, the naming scheme
for delay properties includes "delay" in the name, so let's keep that
consistent.

Fixes: 33a2fde5f77b ("spi: Introduce spi-cs-setup-ns property")
Signed-off-by: Hector Martin <marcan@marcan.st>
Link: https://lore.kernel.org/r/20230104093631.15611-3-marcan@marcan.st
Signed-off-by: Mark Brown <broonie@kernel.org>


# 684a4784 16-Nov-2022 Tudor Ambarus <tudor.ambarus@microchip.com>

spi: Reintroduce spi_set_cs_timing()

commit 4ccf359849ce ("spi: remove spi_set_cs_timing()"), removed the
method as noboby used it. Nobody used it probably because some SPI
controllers use some default large cs-setup time that covers the usual
cs-setup time required by the spi devices. There are though SPI controllers
that have a smaller granularity for the cs-setup time and their default
value can't fulfill the spi device requirements. That's the case for the
at91 QSPI IPs where the default cs-setup time is half of the QSPI clock
period. This was observed when using an sst26vf064b SPI NOR flash which
needs a spi-cs-setup-ns = <7>; in order to be operated close to its maximum
104 MHz frequency.

Call spi_set_cs_timing() in spi_setup() just before calling spi_set_cs(),
as the latter needs the CS timings already set.
If spi->controller->set_cs_timing is not set, the method will return 0.
There's no functional impact expected for the existing drivers. Even if the
spi-mt65xx.c and spi-tegra114.c drivers set the set_cs_timing method,
there's no user for them as of now. The only tested user of this support
will be a SPI NOR flash that comunicates with the Atmel QSPI controller for
which the support follows in the next patches.

One will notice that this support is a bit different from the one that was
removed in commit 4ccf359849ce ("spi: remove spi_set_cs_timing()"),
because this patch adapts to the changes done after the removal: the move
of the cs delays to the spi device, the retirement of the lelgacy GPIO
handling. The mutex handling was removed from spi_set_cs_timing() because
we now always call spi_set_cs_timing() in spi_setup(), which already
handles the spi->controller->io_mutex, so use the mutex handling from
spi_setup().

Signed-off-by: Tudor Ambarus <tudor.ambarus@microchip.com>
Link: https://lore.kernel.org/r/20221117105249.115649-4-tudor.ambarus@microchip.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 33a2fde5 16-Nov-2022 Tudor Ambarus <tudor.ambarus@microchip.com>

spi: Introduce spi-cs-setup-ns property

SPI NOR flashes have specific cs-setup time requirements without which
they can't work at frequencies close to their maximum supported frequency,
as they miss the first bits of the instruction command. Unrecognized
commands are ignored, thus the flash will be unresponsive. Introduce the
spi-cs-setup-ns property to allow spi devices to specify their cs setup
time.

Signed-off-by: Tudor Ambarus <tudor.ambarus@microchip.com>
Link: https://lore.kernel.org/r/20221117105249.115649-3-tudor.ambarus@microchip.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b8d3b056 11-Oct-2022 Yang Yingliang <yangyingliang@huawei.com>

spi: introduce new helpers with using modern naming

For using modern names host/target to instead of all the legacy names,
I think it takes 3 steps:
- step1: introduce new helpers with modern naming.
- step2: switch to use these new helpers in all drivers.
- step3: remove all legacy helpers and update all legacy names.

This patch is for step1, it introduces new helpers with host/target
naming for drivers using.

Signed-off-by: Yang Yingliang <yangyingliang@huawei.com>
Link: https://lore.kernel.org/r/20221011092204.950288-1-yangyingliang@huawei.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 93cc2559 26-Oct-2022 Thomas Gleixner <tglx@linutronix.de>

spi: Remove the obsolte u64_stats_fetch_*_irq() users.

Now that the 32bit UP oddity is gone and 32bit uses always a sequence
count, there is no need for the fetch_irq() variants anymore.

Convert to the regular interface.

Cc: Mark Brown <broonie@kernel.org>
Cc: linux-spi@vger.kernel.org
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: Sebastian Andrzej Siewior <bigeasy@linutronix.de>
Acked-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Link: https://lore.kernel.org/r/20221026122951.331638-1-bigeasy@linutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# aea672d0 20-Oct-2022 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Introduce spi_get_device_match_data() helper

The proposed spi_get_device_match_data() helper is for retrieving
a driver data associated with the ID in an ID table. First, it tries
to get driver data of the device enumerated by firmware interface
(usually Device Tree or ACPI). If none is found it falls back to
the SPI ID table matching.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20221020195421.10482-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8e9204cd 30-Sep-2022 Marek Szyprowski <m.szyprowski@samsung.com>

spi: Ensure that sg_table won't be used after being freed

SPI code checks for non-zero sgt->orig_nents to determine if the buffer
has been DMA-mapped. Ensure that sg_table is really zeroed after free to
avoid potential NULL pointer dereference if the given SPI xfer object is
reused again without being DMA-mapped.

Fixes: 0c17ba73c08f ("spi: Fix cache corruption due to DMA/PIO overlap")
Signed-off-by: Marek Szyprowski <m.szyprowski@samsung.com>
Link: https://lore.kernel.org/r/20220930113408.19720-1-m.szyprowski@samsung.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8d699ff9 27-Sep-2022 Vincent Whitchurch <vincent.whitchurch@axis.com>

spi: Split transfers larger than max size

A couple of drivers call spi_split_transfers_maxsize() from their
->prepare_message() callbacks to split transfers which are too big for
them to handle. Add support in the core to do this based on
->max_transfer_size() to avoid code duplication.

Signed-off-by: Vincent Whitchurch <vincent.whitchurch@axis.com>
Link: https://lore.kernel.org/r/20220927112117.77599-4-vincent.whitchurch@axis.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0c17ba73 27-Sep-2022 Vincent Whitchurch <vincent.whitchurch@axis.com>

spi: Fix cache corruption due to DMA/PIO overlap

The SPI core DMA mapping support performs cache management once for the
entire message and not between transfers, and this leads to cache
corruption if a message has two or more RX transfers with both
transfers targeting the same cache line, and the controller driver
decides to handle one using DMA and the other using PIO (for example,
because one is much larger than the other).

Fix it by syncing before/after the actual transfers. This also means
that we can skip the sync during the map/unmap of the message.

Fixes: 99adef310f68 ("spi: Provide core support for DMA mapping transfers")
Signed-off-by: Vincent Whitchurch <vincent.whitchurch@axis.com>
Link: https://lore.kernel.org/r/20220927112117.77599-3-vincent.whitchurch@axis.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# f25723dc 27-Sep-2022 Vincent Whitchurch <vincent.whitchurch@axis.com>

spi: Save current RX and TX DMA devices

Save the current RX and TX DMA devices to avoid having to duplicate the
logic to pick them, since we'll need access to them in some more
functions to fix a bug in the cache handling.

Signed-off-by: Vincent Whitchurch <vincent.whitchurch@axis.com>
Link: https://lore.kernel.org/r/20220927112117.77599-2-vincent.whitchurch@axis.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5e0531f6 07-Sep-2022 Christophe Leroy <christophe.leroy@csgroup.eu>

spi: Add capability to perform some transfer with chipselect off

Some components require a few clock cycles with chipselect off before
or/and after the data transfer done with CS on.

Typically IDT 801034 QUAD PCM CODEC datasheet states "Note *: CCLK
should have one cycle before CS goes low, and two cycles after
CS goes high".

The cycles "before" are implicitely provided by all previous activity
on the SPI bus. But the cycles "after" must be provided in order to
terminate the SPI transfer.

In order to use that kind of component, add a cs_off flag to
spi_transfer struct. When this flag is set, the transfer is performed
with chipselect off. This allows consummer to add a dummy transfer
at the end of the transfer list which is performed with chipselect
OFF, providing the required additional clock cycles.

Signed-off-by: Christophe Leroy <christophe.leroy@csgroup.eu>
Link: https://lore.kernel.org/r/434165c46f06d802690208a11e7ea2500e8da4c7.1662558898.git.christophe.leroy@csgroup.eu
Signed-off-by: Mark Brown <broonie@kernel.org>


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

spi: 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/
Signed-off-by: Wolfram Sang <wsa+renesas@sang-engineering.com>
Link: https://lore.kernel.org/r/20220818210107.7373-1-wsa+renesas@sang-engineering.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 62fcb99b 24-Aug-2022 Rafael J. Wysocki <rafael.j.wysocki@intel.com>

ACPI: Drop parent field from struct acpi_device

The parent field in struct acpi_device is, in fact, redundant,
because the dev.parent field in it effectively points to the same
object and it is used by the driver core.

Accordingly, the parent field can be dropped from struct acpi_device
and for this purpose define acpi_dev_parent() to retrieve a parent
struct acpi_device pointer from the dev.parent field in struct
acpi_device. Next, update all of the users of the parent field
in struct acpi_device to use acpi_dev_parent() instead of it and
drop it.

While at it, drop the ACPI_IS_ROOT_DEVICE() macro that is only used
in one place in a confusing way.

No intentional functional impact.

Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Acked-by: Mark Brown <broonie@kernel.org>
Acked-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Acked-by: Wei Liu <wei.liu@kernel.org>
Reviewed-by: Punit Agrawal <punit.agrawal@bytedance.com>


# 9c9c9da7 01-Sep-2022 David Jander <david@protonic.nl>

spi: spi: Fix queue hang if previous transfer failed

The queue worker always needs to be kicked one final time after a transfer
is done in order to transition to idle (ctlr->busy = false).

Commit 69fa95905d40 ("spi: Ensure the io_mutex is held until
spi_finalize_current_message()") moved this code into
__spi_pump_messages(), but it was executed only if the transfer was
successful. This condition check causes ctlr-busy to stay true in case of
a failed transfer.
This in turn causes that no new work is ever scheduled to the work queue.

Fixes: 69fa95905d40 ("spi: Ensure the io_mutex is held until spi_finalize_current_message()")
Reported-by: Vincent Whitchurch <vincent.whitchurch@axis.com>
Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220901123630.1098433-1-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# b30f7c8e 01-Sep-2022 Mark Brown <broonie@kernel.org>

spi: mux: Fix mux interaction with fast path optimisations

The spi-mux driver is rather too clever and attempts to resubmit any
message that is submitted to it to the parent controller with some
adjusted callbacks. This does not play at all nicely with the fast
path which now sets flags on the message indicating that it's being
handled through the fast path, we see async messages flagged as being on
the fast path. Ideally the spi-mux code would duplicate the message but
that's rather invasive and a bit fragile in that it relies on the mux
knowing which fields in the message to copy. Instead teach the core
that there are controllers which can't cope with the fast path and have
the mux flag itself as being such a controller, ensuring that messages
going via the mux don't get partially handled via the fast path.

This will reduce the performance of any spi-mux connected device since
we'll now always use the thread for both the actual controller and the
mux controller instead of just the actual controller but given that we
were always hitting the slow path anyway it's hopefully not too much of
an additional cost and it allows us to keep the fast path.

Fixes: ae7d2346dc89 ("spi: Don't use the message queue if possible in spi_sync")
Reported-by: Casper Andersson <casper.casan@gmail.com>
Tested-by: Casper Andersson <casper.casan@gmail.com>
Signed-off-by: Mark Brown <broonie@kernel.org>
Link: https://lore.kernel.org/r/20220901120732.49245-1-broonie@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# d501cc4c 05-Aug-2022 David Jander <david@protonic.nl>

spi: spi.c: Add missing __percpu annotations in users of spi_statistics

Fixes sparse warnings of this kind:
drivers/spi/spi.c:117:16: sparse: expected struct spi_statistics *
drivers/spi/spi.c:117:16: sparse: got struct spi_statistics [noderef]
__percpu *[assigned] pcpu_stats

Reported-by: kernel test robot <lkp@intel.com>
Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220805084458.1602277-1-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# c21b0837 10-Jun-2022 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Use device_find_any_child() instead of custom approach

We have already a helper to get the first child device, use it and
drop custom approach.

Reviewed-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20220610120219.18988-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 43cc5a0a 12-Jul-2022 Yang Yingliang <yangyingliang@huawei.com>

spi: Fix simplification of devm_spi_register_controller

This reverts commit 59ebbe40fb51 ("spi: simplify
devm_spi_register_controller").

If devm_add_action() fails in devm_add_action_or_reset(),
devm_spi_unregister() will be called, it decreases the
refcount of 'ctlr->dev' to 0, then it will cause uaf in
the drivers that calling spi_put_controller() in error path.

Fixes: 59ebbe40fb51 ("spi: simplify devm_spi_register_controller")
Signed-off-by: Yang Yingliang <yangyingliang@huawei.com>
Reviewed-by: Conor Dooley <conor.dooley@microchip.com>
Link: https://lore.kernel.org/r/20220712135504.1055688-1-yangyingliang@huawei.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# cdb0cc93 08-Jul-2022 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: remove duplicate parameters check in acpi_spi_add_resource()

The acpi_spi_add_resource() is never called with ctrl == NULL and
index == -1. The only caller already performs the check. Hence
remove the duplication from the acpi_spi_add_resource().

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20220709000709.35622-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b6747f4f 08-Jul-2022 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: propagate error code to the caller of acpi_spi_device_alloc()

Since acpi_spi_device_alloc() has been designed to return an error
pointer we may now properly propagate error codes to the caller of
it. It helps debugging a lot.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20220709000709.35622-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9c22ec4a 09-Jul-2022 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Return deferred probe error when controller isn't yet available

If the controller is not available, it might be in the future and
we would like to re-probe the peripheral again. For that purpose
return deferred probe.

BugLink: https://bugzilla.kernel.org/show_bug.cgi?id=215993
Fixes: 87e59b36e5e2 ("spi: Support selection of the index of the ACPI Spi Resource before alloc")
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20220709212956.25530-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 31d4c1bd 29-Jun-2022 David Jander <david@protonic.nl>

spi: spi.c: Remove redundant else block

Reported-by: Andy Shevchenko <andy.shevchenko@gmail.com>
Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220629142519.3985486-4-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 95c8222f 29-Jun-2022 David Jander <david@protonic.nl>

spi: spi.c: Fix comment style

Capitalize first word in comment where appropriate and add
parentheses to function names.

Reported-by: Andy Shevchenko <andy.shevchenko@gmail.com>
Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220629142519.3985486-3-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# c191543e 29-Jun-2022 David Jander <david@protonic.nl>

spi: spi.c: White-space fix in __spi_pump_messages()

Reported-by: Andy Shevchenko <andy.shevchenko@gmail.com>
Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220629142519.3985486-2-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# dc302905 21-Jun-2022 David Jander <david@protonic.nl>

spi: opportunistically skip ctlr->cur_msg_completion

There are only a few drivers that do not call
spi_finalize_current_message() in the context of transfer_one_message(),
and even for those cases the completion ctlr->cur_msg_completion is not
needed always. The calls to complete() and wait_for_completion() each
take a spin-lock, which is costly. This patch makes it possible to avoid
those calls in the big majority of cases, by introducing two flags that
with the help of ordering via barriers can avoid using the completion
safely. In case of a race with the context calling
spi_finalize_current_message(), the scheme errs on the safe side and takes
the completion.
The impact of this patch is worth the effort: On a i.MX8MM SoC, the time
the SPI bus is idle between two consecutive calls to spi_sync(), is
reduced from 19.6us to 16.8us... roughly 15%.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-12-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 69fa9590 21-Jun-2022 David Jander <david@protonic.nl>

spi: Ensure the io_mutex is held until spi_finalize_current_message()

This patch introduces a completion that is completed in
spi_finalize_current_message() and waited for in
__spi_pump_transfer_message(). This way all manipulation of ctlr->cur_msg
is done with the io_mutex held and strictly ordered:
__spi_pump_transfer_message() will not return until
spi_finalize_current_message() is done using ctlr->cur_msg, and its
calling context is only touching ctlr->cur_msg after returning.
Due to this, we can safely drop the spin-locks around ctlr->cur_msg.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-11-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 72c5c59b 21-Jun-2022 David Jander <david@protonic.nl>

spi: Set ctlr->cur_msg also in the sync transfer case

Some drivers rely on this to point to the currently processed message, so
set this here also.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-10-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 1a9cafcb 21-Jun-2022 David Jander <david@protonic.nl>

spi: Remove unneeded READ_ONCE for ctlr->busy flag

Now this flag is written entirely in the mutex, so no need for READ_ONCE

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-9-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 66a22159 21-Jun-2022 David Jander <david@protonic.nl>

spi: Remove the now unused ctlr->idling flag

The ctlr->idling flag is never checked now, so we don't need to set it
either.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-8-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 049d6ccc 21-Jun-2022 David Jander <david@protonic.nl>

spi: Remove check for idling in __spi_pump_messages()

Since the whole idling transition is locked by the io_mutex now, there is
no need to check this flag anymore.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-7-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# d5256cce 21-Jun-2022 David Jander <david@protonic.nl>

spi: Remove check for controller idling in spi sync path

Now that the idling flag is wholly behind the io_mutex, this broken piece
of code can be safely removed.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-6-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8711a2ab 21-Jun-2022 David Jander <david@protonic.nl>

spi: __spi_pump_messages: Consolidate spin_unlocks to goto target

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-5-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# c1038165 21-Jun-2022 David Jander <david@protonic.nl>

spi: Lock controller idling transition inside the io_mutex

This way, the spi sync path does not need to deal with the idling
transition.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-4-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# ae7d2346 21-Jun-2022 David Jander <david@protonic.nl>

spi: Don't use the message queue if possible in spi_sync

The interaction with the controller message queue and its corresponding
auxiliary flags and variables requires the use of the queue_lock which is
costly. Since spi_sync will transfer the complete message anyway, and not
return until it is finished, there is no need to put the message into the
queue if the queue is empty. This can save a lot of overhead.

As an example of how significant this is, when using the MCP2518FD SPI CAN
controller on a i.MX8MM SoC, the time during which the interrupt line
stays active (during 3 relatively short spi_sync messages), is reduced
from 98us to 72us by this patch.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-3-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 1714582a 21-Jun-2022 David Jander <david@protonic.nl>

spi: Move ctlr->cur_msg_prepared to struct spi_message

This enables the possibility to transfer a message that is not at the
current tip of the async message queue.
This is in preparation of the next patch(es) which enable spi_sync messages
to skip the queue altogether.

Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220621061234.3626638-2-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# d52b095b 14-Jun-2022 Dan Carpenter <dan.carpenter@oracle.com>

spi: core: Fix error code in spi_register_controller()

Return -ENOMEM if the allocation fails. Don't return success.

Fixes: 6598b91b5ac3 ("spi: spi.c: Convert statistics to per-cpu u64_stats_t")
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Link: https://lore.kernel.org/r/Yqh6bdNYO2XNhPBa@kili
Signed-off-by: Mark Brown <broonie@kernel.org>


# 67b9d641 09-Jun-2022 David Jander <david@protonic.nl>

spi: Fix per-cpu stats access on 32 bit systems

On 32 bit systems, the following kernel BUG is hit:

BUG: using smp_processor_id() in preemptible [00000000] code: swapper/0/1
caller is debug_smp_processor_id+0x18/0x24
CPU: 1 PID: 1 Comm: swapper/0 Not tainted 5.19.0-rc1-00001-g6ae0aec8a366 #181
Hardware name: Freescale i.MX6 Quad/DualLite (Device Tree)
Backtrace:
dump_backtrace from show_stack+0x20/0x24
r7:81024ffd r6:00000000 r5:81024ffd r4:60000013
show_stack from dump_stack_lvl+0x60/0x78
dump_stack_lvl from dump_stack+0x14/0x1c
r7:81024ffd r6:80f652de r5:80bec180 r4:819a2500
dump_stack from check_preemption_disabled+0xc8/0xf0
check_preemption_disabled from debug_smp_processor_id+0x18/0x24
r8:8119b7e0 r7:81205534 r6:819f5c00 r5:819f4c00 r4:c083d724
debug_smp_processor_id from __spi_sync+0x78/0x220
__spi_sync from spi_sync+0x34/0x4c
r10:bb7bf4e0 r9:c083d724 r8:00000007 r7:81a068c0 r6:822a83c0 r5:c083d724
r4:819f4c00
spi_sync from spi_mem_exec_op+0x338/0x370
r5:000000b4 r4:c083d910
spi_mem_exec_op from spi_nor_read_id+0x98/0xdc
r10:bb7bf4e0 r9:00000000 r8:00000000 r7:00000000 r6:00000000 r5:82358040
r4:819f7c40
spi_nor_read_id from spi_nor_detect+0x38/0x114
r7:82358040 r6:00000000 r5:819f7c40 r4:819f7c40
spi_nor_detect from spi_nor_scan+0x11c/0xbec
r10:bb7bf4e0 r9:00000000 r8:00000000 r7:c083da4c r6:00000000 r5:00010101
r4:819f7c40
spi_nor_scan from spi_nor_probe+0x10c/0x2d0
r10:bb7bf4e0 r9:bb7bf4d0 r8:00000000 r7:819f4c00 r6:00000000 r5:00000000
r4:819f7c40

per-cpu access needs to be guarded against preemption.

Fixes: 6598b91b5ac3 ("spi: spi.c: Convert statistics to per-cpu u64_stats_t")
Reported-by: Marc Kleine-Budde <mkl@pengutronix.de>
Signed-off-by: David Jander <david@protonic.nl>
Tested-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
Link: https://lore.kernel.org/r/20220609121334.2984808-1-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6598b91b 24-May-2022 David Jander <david@protonic.nl>

spi: spi.c: Convert statistics to per-cpu u64_stats_t

This change gives a dramatic performance improvement in the hot path,
since many costly spin_lock_irqsave() calls can be avoided.

On an i.MX8MM system with a MCP2518FD CAN controller connected via SPI,
the time the driver takes to handle interrupts, or in other words the time
the IRQ line of the CAN controller stays low is mainly dominated by the
time it takes to do 3 relatively short sync SPI transfers. The effect of
this patch is a reduction of this time from 136us down to only 98us.

Suggested-by: Andrew Lunn <andrew@lunn.ch>
Signed-off-by: David Jander <david@protonic.nl>
Link: https://lore.kernel.org/r/20220524091808.2269898-1-david@protonic.nl
Signed-off-by: Mark Brown <broonie@kernel.org>


# 19368f0f 19-Apr-2022 Krzysztof Kozlowski <krzysztof.kozlowski@linaro.org>

spi: Use helper for safer setting of driver_override

Use a helper to set driver_override to the reduce amount of duplicated
code.

Reviewed-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Krzysztof Kozlowski <krzysztof.kozlowski@linaro.org>
Link: https://lore.kernel.org/r/20220419113435.246203-8-krzysztof.kozlowski@linaro.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# ebf2a352 25-May-2022 Eddie James <eajames@linux.ibm.com>

spi: core: Display return code when failing to transfer message

All the other calls to the controller driver display the error
return code. The return code is helpful to understand what went
wrong, so include it when failing to transfer one message.

Signed-off-by: Eddie James <eajames@linux.ibm.com>
Link: https://lore.kernel.org/r/20220525165852.33167-3-eajames@linux.ibm.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# dd769f15 18-Apr-2022 Minghao Chi <chi.minghao@zte.com.cn>

spi: using pm_runtime_resume_and_get instead of pm_runtime_get_sync

Using pm_runtime_resume_and_get is more appropriate
for simplifing code

Reported-by: Zeal Robot <zealci@zte.com.cn>
Signed-off-by: Minghao Chi <chi.minghao@zte.com.cn>
Link: https://lore.kernel.org/r/20220418110226.2559081-1-chi.minghao@zte.com.cn
Signed-off-by: Mark Brown <broonie@kernel.org>


# 73f93db5 14-Apr-2022 Paul Kocialkowski <paul.kocialkowski@bootlin.com>

spi: core: Initialize returned status in spi_setup

The previous commit that made bits-per-word validation conditional
results in leaving no unconditional affectation of the status variable.

Since the variable is returned at the end of the function, initialize
it to avoid returning an undefined value.

Signed-off-by: Paul Kocialkowski <paul.kocialkowski@bootlin.com>
Fixes: b3fe2e516741 ("spi: core: Only check bits_per_word validity when explicitly provided")
Reported-by: Dan Carpenter <dan.carpenter@oracle.com>
Link: https://lore.kernel.org/r/20220414084040.975520-1-paul.kocialkowski@bootlin.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b3fe2e51 12-Apr-2022 Paul Kocialkowski <paul.kocialkowski@bootlin.com>

spi: core: Only check bits_per_word validity when explicitly provided

On SPI device probe, the core will call spi_setup in spi_add_device
before the corresponding driver was probed. When this happens, the
bits_per_word member of the device is not yet set by the driver,
resulting in the default being set to 8 bits-per-word.

However some controllers do not support 8 bits-per-word at all, which
results in a failure when checking the bits-per-word validity.

In order to support these devices, skip the bits-per-word validity
check when it is not explicitly provided by drivers.

Signed-off-by: Paul Kocialkowski <paul.kocialkowski@bootlin.com>
Link: https://lore.kernel.org/r/20220412122207.130181-1-paul.kocialkowski@bootlin.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 409543ce 06-Apr-2022 Vinod Koul <vkoul@kernel.org>

spi: core: add dma_map_dev for __spi_unmap_msg()

Commit b470e10eb43f ("spi: core: add dma_map_dev for dma device") added
dma_map_dev for _spi_map_msg() but missed to add for unmap routine,
__spi_unmap_msg(), so add it now.

Fixes: b470e10eb43f ("spi: core: add dma_map_dev for dma device")
Cc: stable@vger.kernel.org # v5.14+
Signed-off-by: Vinod Koul <vkoul@kernel.org>
Link: https://lore.kernel.org/r/20220406132238.1029249-1-vkoul@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# ac2a3fee 05-Apr-2022 Rafael J. Wysocki <rafael.j.wysocki@intel.com>

ACPI: bus: Eliminate acpi_bus_get_device()

Replace the last instance of acpi_bus_get_device(), added recently
by commit 87e59b36e5e2 ("spi: Support selection of the index of the
ACPI Spi Resource before alloc"), with acpi_fetch_acpi_dev() and
finally drop acpi_bus_get_device() that has no more users.

Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Acked-by: Mark Brown <broonie@kernel.org>


# ebc4cb43 16-Mar-2022 Biju Das <biju.das.jz@bp.renesas.com>

spi: Fix erroneous sgs value with min_t()

While computing sgs in spi_map_buf(), the data type
used in min_t() for max_seg_size is 'unsigned int' where
as that of ctlr->max_dma_len is 'size_t'.

min_t(unsigned int,x,y) gives wrong results if one of x/y is
'size_t'

Consider the below examples on a 64-bit machine (ie size_t is
64-bits, and unsigned int is 32-bit).
case 1) min_t(unsigned int, 5, 0x100000001);
case 2) min_t(size_t, 5, 0x100000001);

Case 1 returns '1', where as case 2 returns '5'. As you can see
the result from case 1 is wrong.

This patch fixes the above issue by using the data type of the
parameters that are used in min_t with maximum data length.

Fixes: commit 1a4e53d2fc4f68aa ("spi: Fix invalid sgs value")
Reported-by: Linus Torvalds <torvalds@linux-foundation.org>
Suggested-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Biju Das <biju.das.jz@bp.renesas.com>
Reviewed-by: Lad Prabhakar <prabhakar.mahadev-lad.rj@bp.renesas.com>
Link: https://lore.kernel.org/r/20220316175317.465-1-biju.das.jz@bp.renesas.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6bb477df 17-Feb-2022 Yun Zhou <yun.zhou@windriver.com>

spi: use specific last_cs instead of last_cs_enable

Commit d40f0b6f2e21 instroduced last_cs_enable to avoid setting
chipselect if it's not necessary, but it also introduces a bug. The
chipselect may not be set correctly on multi-device SPI busses. The
reason is that we can't judge the chipselect by bool last_cs_enable,
since chipselect may be modified after other devices were accessed.

So we should record the specific state of chipselect in case of
confusion.

Signed-off-by: Yun Zhou <yun.zhou@windriver.com>
Link: https://lore.kernel.org/r/20220217141234.72737-1-yun.zhou@windriver.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 04378630 18-Feb-2022 Heiner Kallweit <hkallweit1@gmail.com>

spi: use sysfs_emit() for printing statistics and add trailing newline

Use dedicated function sysfs_emit() that does some extra checking,
e.g. to ensure that no more than PAGESIZE bytes are written.
In addition add a trailing newline to the output, that makes it
better readable from the console.

Signed-off-by: Heiner Kallweit <hkallweit1@gmail.com>
Link: https://lore.kernel.org/r/56e1588d-d53b-73e9-fdc8-7fe30bf91f11@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# f48dc6b9 10-Feb-2022 Linus Walleij <linus.walleij@linaro.org>

spi: Retire legacy GPIO handling

All drivers using GPIOs as chip select have been rewritten to use
GPIO descriptors passing the ->use_gpio_descriptors flag. Retire
the code and fields used by the legacy GPIO API.

Do not drop the ->use_gpio_descriptors flag: it now only indicates
that we want to use GPIOs in addition to native chip selects.

Signed-off-by: Linus Walleij <linus.walleij@linaro.org>
Link: https://lore.kernel.org/r/20220210231954.807904-1-linus.walleij@linaro.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# a0386bba 23-Jan-2022 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: make remove callback a void function

The value returned by an spi driver's remove function is mostly ignored.
(Only an error message is printed if the value is non-zero that the
error is ignored.)

So change the prototype of the remove function to return no value. This
way driver authors are not tempted to assume that passing an error to
the upper layer is a good idea. All drivers are adapted accordingly.
There is no intended change of behaviour, all callbacks were prepared to
return 0 before.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Acked-by: Marc Kleine-Budde <mkl@pengutronix.de>
Acked-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be>
Acked-by: Jérôme Pouiller <jerome.pouiller@silabs.com>
Acked-by: Miquel Raynal <miquel.raynal@bootlin.com>
Acked-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>
Acked-by: Claudius Heine <ch@denx.de>
Acked-by: Stefan Schmidt <stefan@datenfreihafen.org>
Acked-by: Alexandre Belloni <alexandre.belloni@bootlin.com>
Acked-by: Ulf Hansson <ulf.hansson@linaro.org> # For MMC
Acked-by: Marcus Folkesson <marcus.folkesson@gmail.com>
Acked-by: Łukasz Stelmach <l.stelmach@samsung.com>
Acked-by: Lee Jones <lee.jones@linaro.org>
Link: https://lore.kernel.org/r/20220123175201.34839-6-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7030c428 01-Feb-2022 Rafael J. Wysocki <rafael.j.wysocki@intel.com>

spi: Replace acpi_bus_get_device()

Replace acpi_bus_get_device() that is going to be dropped with
acpi_fetch_acpi_dev().

No intentional functional impact.

Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Link: https://lore.kernel.org/r/2231987.ElGaqSPkdT@kreacher
Signed-off-by: Mark Brown <broonie@kernel.org>


# e612af7a 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Add API to count spi acpi resources

Some ACPI nodes may have more than one Spi Resource.
To be able to handle these case, its necessary to have
a way of counting these resources.

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-5-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 87e59b36 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Support selection of the index of the ACPI Spi Resource before alloc

If a node contains more than one SPI resource it may be necessary to
use an index to select which one you want to allocate a spi device for.

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-4-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 000bee0e 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Create helper API to lookup ACPI info for spi device

This can then be used to find a spi resource inside an
ACPI node, and allocate a spi device.

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-3-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# e3dc1399 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Make spi_alloc_device and spi_add_device public again

This functions were previously made private since they
were not used. However, these functions will be needed
again.

Partial revert of commit da21fde0fdb3
("spi: Make several public functions private to spi.c")

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-2-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 11396230 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Add API to count spi acpi resources

Some ACPI nodes may have more than one Spi Resource.
To be able to handle these case, its necessary to have
a way of counting these resources.

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-5-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 92640f98 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Support selection of the index of the ACPI Spi Resource before alloc

If a node contains more than one SPI resource it may be necessary to
use an index to select which one you want to allocate a spi device for.

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-4-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 70dd264b 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Create helper API to lookup ACPI info for spi device

This can then be used to find a spi resource inside an
ACPI node, and allocate a spi device.

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-3-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 941bffd7 21-Jan-2022 Stefan Binding <sbinding@opensource.cirrus.com>

spi: Make spi_alloc_device and spi_add_device public again

This functions were previously made private since they
were not used. However, these functions will be needed
again.

Partial revert of commit da21fde0fdb3
("spi: Make several public functions private to spi.c")

Signed-off-by: Stefan Binding <sbinding@opensource.cirrus.com>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Link: https://lore.kernel.org/r/20220121172431.6876-2-sbinding@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 1a4e53d2 07-Mar-2022 Biju Das <biju.das.jz@bp.renesas.com>

spi: Fix invalid sgs value

max_seg_size is unsigned int and it can have a value up to 2^32
(for eg:-RZ_DMAC driver sets dma_set_max_seg_size as U32_MAX)
When this value is used in min_t() as an integer type, it becomes
-1 and the value of sgs becomes 0.

Fix this issue by replacing the 'int' data type with 'unsigned int'
in min_t().

Signed-off-by: Biju Das <biju.das.jz@bp.renesas.com>
Reviewed-by: Lad Prabhakar <prabhakar.mahadev-lad.rj@bp.renesas.com>
Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be>
Link: https://lore.kernel.org/r/20220307184843.9994-1-biju.das.jz@bp.renesas.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 44ea6281 03-Sep-2021 Jakub Kicinski <kuba@kernel.org>

spi: don't include ptp_clock_kernel.h in spi.h

Commit b42faeee718c ("spi: Add a PTP system timestamp
to the transfer structure") added an include of ptp_clock_kernel.h
to spi.h for struct ptp_system_timestamp but a forward declaration
is enough. Let's use that to limit the number of objects we have
to rebuild every time we touch networking headers.

Signed-off-by: Jakub Kicinski <kuba@kernel.org>
Tested-by: Vladimir Oltean <vladimir.oltean@nxp.com>
Link: https://lore.kernel.org/r/20210904013140.2377609-1-kuba@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 95c07247 10-Dec-2021 Hector Martin <marcan@marcan.st>

spi: Fix incorrect cs_setup delay handling

Move the cs_setup delay to the end of spi_set_cs.

From include/linux/spi/spi.h:

* @cs_setup: delay to be introduced by the controller after CS is
asserted

The cs_setup delay needs to happen *after* CS is asserted, that is, at
the end of spi_set_cs, not at the beginning. Otherwise we're just
delaying before the SPI transaction starts at all, which isn't very
useful.

No drivers use this right now, but that is likely to change soon with an
upcoming Apple SPI HID transport driver.

Fixes: 25093bdeb6bc ("spi: implement SW control for CS times")
Signed-off-by: Hector Martin <marcan@marcan.st>
Link: https://lore.kernel.org/r/20211210170534.177139-1-marcan@marcan.st
Signed-off-by: Mark Brown <broonie@kernel.org>


# b79332ef 23-Nov-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Fix condition in the __spi_register_driver()

The recent commit 3f07657506df ("spi: deduplicate spi_match_id()
in __spi_register_driver()") inadvertently inverted a condition
that provokes a (harmless) warning:

WARNING KERN SPI driver mtd_dataflash has no spi_device_id for atmel,at45

Restore logic to avoid such warning to be issued.

Fixes: 3f07657506df ("spi: deduplicate spi_match_id() in __spi_register_driver()")
Reported-by: Jon Hunter <jonathanh@nvidia.com>
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Tested-by: Jon Hunter <jonathanh@nvidia.com>
Link: https://lore.kernel.org/r/20211123170034.41253-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 350de7ce 22-Nov-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Fix multi-line comment style

/*
* Fix multi-line comment style as in this short example. Pay attention
* to the capitalization, period and starting line of the text.
*/

While at it, split the (supposedly short) description of couple of functions
to summary (short description) and (long) description.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20211122171721.61553-3-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b00bab9d 22-Nov-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Replace memset() with __GFP_ZERO

krealloc() as any other kernel memory allocation calls accepts GFP flags,
one of which is __GFP_ZERO. Hence, no need to call memset() explicitly on
the reallocated buffer.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20211122171721.61553-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3f076575 19-Nov-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: deduplicate spi_match_id() in __spi_register_driver()

The same logic is used in spi_match_id() and in the __spi_register_driver().
By switching the former from taking struct spi_device * to const char * as
the second parameter we may deduplicate the code.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20211119173718.52938-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6c53b45c 11-Nov-2021 Michael Walle <michael@walle.cc>

spi: fix use-after-free of the add_lock mutex

Commit 6098475d4cb4 ("spi: Fix deadlock when adding SPI controllers on
SPI buses") introduced a per-controller mutex. But mutex_unlock() of
said lock is called after the controller is already freed:

spi_unregister_controller(ctlr)
-> put_device(&ctlr->dev)
-> spi_controller_release(dev)
-> mutex_unlock(&ctrl->add_lock)

Move the put_device() after the mutex_unlock().

Fixes: 6098475d4cb4 ("spi: Fix deadlock when adding SPI controllers on SPI buses")
Signed-off-by: Michael Walle <michael@walle.cc>
Reviewed-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Reviewed-by: Lukas Wunner <lukas@wunner.de>
Cc: stable@vger.kernel.org # v5.15
Link: https://lore.kernel.org/r/20211111083713.3335171-1-michael@walle.cc
Signed-off-by: Mark Brown <broonie@kernel.org>


# da21fde0 07-Oct-2021 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Make several public functions private to spi.c

All these functions have no callers apart from drivers/spi/spi.c. So
drop their declarations in include/linux/spi/spi.h and don't export
them.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20211007121415.2401638-5-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# fb51601b 07-Oct-2021 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Reorder functions to simplify the next commit

Currently the "Core methods for SPI resource management" are exported
and public functions. They are however only used in drivers/spi/spi.c.
To allow to drop the global declarations and not to have to insert local
ones instead, move them before their users.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20211007121415.2401638-4-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# bdc7ca00 07-Oct-2021 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Remove unused function spi_busnum_to_master()

The last user is gone since commit

2962db71c703 ("staging/fbtft: Remove fbtft_device")

in 2019.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20211007121415.2401638-3-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6bfb15f3 07-Oct-2021 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Move comment about chipselect check to the right place

The part of the comment about locking isn't that relevant compared to
the chip select check. So drop the sentence about locking.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20211007121415.2401638-2-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5fa6863b 21-Sep-2021 Mark Brown <broonie@kernel.org>

spi: Check we have a spi_device_id for each DT compatible

Currently for SPI devices we use the spi_device_id for module autoloading
even on systems using device tree, meaning that listing a compatible string
in the of_match_table isn't enough to have the module for a SPI driver
autoloaded.

We attempted to fix this by generating OF based modaliases for devices
instantiated from DT in 3ce6c9e2617e ("spi: add of_device_uevent_modalias
support") but this meant we no longer reported spi_device_id based aliases
which broke drivers such as spi-nor which don't list all the compatible
strings they support directly for DT, and in at least that case it's not
super practical to do so given the very large number of compatibles
needed, much larger than the number spi_device_ids due to vendor strings.
As a result fell back to using spi_device_id based modalises.

Try to close the gap by printing a warning when a SPI driver has a DT
compatible that won't be matched as a SPI device ID with the goal of having
drivers provide both. Given fallback compatibles this check is going to be
excessive but it should be robust which is probably more important here.

Signed-off-by: Mark Brown <broonie@kernel.org>
Link: https://lore.kernel.org/r/20210921192149.50740-1-broonie@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 16a8e2fb 13-Oct-2021 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi-mux: Fix false-positive lockdep splats

io_mutex is taken by spi_setup() and spi-mux's .setup() callback calls
spi_setup() which results in a nested lock of io_mutex.

add_lock is taken by spi_add_device(). The device_add() call in there
can result in calling spi-mux's .probe() callback which registers its
own spi controller which in turn results in spi_add_device() being
called again.

To fix this initialize the controller's locks already in
spi_alloc_controller() to give spi_mux_probe() a chance to set the
lockdep subclass.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20211013133710.2679703-2-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6098475d 08-Oct-2021 Mark Brown <broonie@kernel.org>

spi: Fix deadlock when adding SPI controllers on SPI buses

Currently we have a global spi_add_lock which we take when adding new
devices so that we can check that we're not trying to reuse a chip
select that's already controlled. This means that if the SPI device is
itself a SPI controller and triggers the instantiation of further SPI
devices we trigger a deadlock as we try to register and instantiate
those devices while in the process of doing so for the parent controller
and hence already holding the global spi_add_lock. Since we only care
about concurrency within a single SPI bus move the lock to be per
controller, avoiding the deadlock.

This can be easily triggered in the case of spi-mux.

Reported-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 96c8395e 21-Sep-2021 Mark Brown <broonie@kernel.org>

spi: Revert modalias changes

During the v5.13 cycle we updated the SPI subsystem to generate OF style
modaliases for SPI devices, replacing the old Linux style modalises we
used to generate based on spi_device_id which are the DT style name with
the vendor removed. Unfortunately this means that we start only
reporting OF style modalises and not the old ones and there is nothing
that ensures that drivers list every possible OF compatible string in
their OF ID table. The result is that there are systems which have been
relying on loading modules based on the old style that are now broken,
as found by Russell King with spi-nor on Macchiatobin.

spi-nor is a particularly problematic case for this, it only lists a
single generic DT compatible jedec,spi-nor in the driver but supports a
huge raft of device specific compatibles, with a large set of part
numbers many of which are offered by multiple vendors. Russell's
searches of upstream device trees has turned up examples with vendor
names written in non-standard ways too. To make matters worse up until
8ff16cf77ce3 ("Documentation: devicetree: m25p80: add "nor-jedec"
binding") the generic compatible was not part of the binding so there
are device trees out there written to that binding version which don't
list it all. The sheer number of parts supported together with our
previous approach of ignoring the vendor ID makes robustly fixing this
by adding compatibles to the spi-nor driver seem problematic, the
current DT binding document does not list all the parts supported by the
driver at the minute (further patches will fix this).

I've also investigated supporting both formats of modalias
simultaneously but that doesn't seem possible, especially without
breaking our userspace ABI which is obviously not viable.

Instead revert the relevant changes for now:

e09f2ab8eecc ("spi: update modalias_show after of_device_uevent_modalias support")
3ce6c9e2617e ("spi: add of_device_uevent_modalias support")

This will unfortunately mean that any system which had started having
modules autoload based on the OF compatibles for drivers that list
things there but not in the spi_device_ids will now not have those
modules load which is itself a regression. Since it affects a narrower
time window and the particularly problematic spi-nor driver may be
critical to system boot on smaller systems this seems the best of a
series of bad options. I will start an audit of SPI drivers to identify
and fix cases where things won't autoload using spi_device_id, this is
not great but seems to be the best way forward that anyone has been able
to identify.

Thanks to Russell for both his report and the additional diagnostic and
analysis work he has done here, the detailed research above was his
work.

Fixes: e09f2ab8eecc ("spi: update modalias_show after of_device_uevent_modalias support")
Fixes: 3ce6c9e2617e ("spi: add of_device_uevent_modalias support")
Reported-by: Russell King (Oracle) <linux@armlinux.org.uk>
Suggested-by: Russell King (Oracle) <linux@armlinux.org.uk>
Signed-off-by: Mark Brown <broonie@kernel.org>
Tested-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk>
Cc: Andreas Schwab <schwab@suse.de>
Cc: Marco Felsch <m.felsch@pengutronix.de>


# fc7a6209 13-Jul-2021 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

bus: Make remove callback return void

The driver core ignores the return value of this callback because there
is only little it can do when a device disappears.

This is the final bit of a long lasting cleanup quest where several
buses were converted to also return void from their remove callback.
Additionally some resource leaks were fixed that were caused by drivers
returning an error code in the expectation that the driver won't go
away.

With struct bus_type::remove returning void it's prevented that newly
implemented buses return an ignored error code and so don't anticipate
wrong expectations for driver authors.

Reviewed-by: Tom Rix <trix@redhat.com> (For fpga)
Reviewed-by: Mathieu Poirier <mathieu.poirier@linaro.org>
Reviewed-by: Cornelia Huck <cohuck@redhat.com> (For drivers/s390 and drivers/vfio)
Acked-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk> (For ARM, Amba and related parts)
Acked-by: Mark Brown <broonie@kernel.org>
Acked-by: Chen-Yu Tsai <wens@csie.org> (for sunxi-rsb)
Acked-by: Pali Rohár <pali@kernel.org>
Acked-by: Mauro Carvalho Chehab <mchehab@kernel.org> (for media)
Acked-by: Hans de Goede <hdegoede@redhat.com> (For drivers/platform)
Acked-by: Alexandre Belloni <alexandre.belloni@bootlin.com>
Acked-By: Vinod Koul <vkoul@kernel.org>
Acked-by: Juergen Gross <jgross@suse.com> (For xen)
Acked-by: Lee Jones <lee.jones@linaro.org> (For mfd)
Acked-by: Johannes Thumshirn <jth@kernel.org> (For mcb)
Acked-by: Johan Hovold <johan@kernel.org>
Acked-by: Srinivas Kandagatla <srinivas.kandagatla@linaro.org> (For slimbus)
Acked-by: Kirti Wankhede <kwankhede@nvidia.com> (For vfio)
Acked-by: Maximilian Luz <luzmaximilian@gmail.com>
Acked-by: Heikki Krogerus <heikki.krogerus@linux.intel.com> (For ulpi and typec)
Acked-by: Samuel Iglesias Gonsálvez <siglesias@igalia.com> (For ipack)
Acked-by: Geoff Levand <geoff@infradead.org> (For ps3)
Acked-by: Yehezkel Bernat <YehezkelShB@gmail.com> (For thunderbolt)
Acked-by: Alexander Shishkin <alexander.shishkin@linux.intel.com> (For intel_th)
Acked-by: Dominik Brodowski <linux@dominikbrodowski.net> (For pcmcia)
Acked-by: Rafael J. Wysocki <rafael@kernel.org> (For ACPI)
Acked-by: Bjorn Andersson <bjorn.andersson@linaro.org> (rpmsg and apr)
Acked-by: Srinivas Pandruvada <srinivas.pandruvada@linux.intel.com> (For intel-ish-hid)
Acked-by: Dan Williams <dan.j.williams@intel.com> (For CXL, DAX, and NVDIMM)
Acked-by: William Breathitt Gray <vilhelm.gray@gmail.com> (For isa)
Acked-by: Stefan Richter <stefanr@s5r6.in-berlin.de> (For firewire)
Acked-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> (For hid)
Acked-by: Thorsten Scherer <t.scherer@eckelmann.de> (For siox)
Acked-by: Sven Van Asbroeck <TheSven73@gmail.com> (For anybuss)
Acked-by: Ulf Hansson <ulf.hansson@linaro.org> (For MMC)
Acked-by: Wolfram Sang <wsa@kernel.org> # for I2C
Acked-by: Sudeep Holla <sudeep.holla@arm.com>
Acked-by: Geert Uytterhoeven <geert@linux-m68k.org>
Acked-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
Acked-by: Finn Thain <fthain@linux-m68k.org>
Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20210713193522.1770306-6-u.kleine-koenig@pengutronix.de
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 8c33ebfe 04-Aug-2021 Mason Zhang <Mason.Zhang@mediatek.com>

spi: move cs spi_delay to spi_device

As we know, spi core layer has removed spi_set_cs_timing() API.
So this patch moved spi_delay for cs_timing from spi_controller
to spi_device, because cs timing should be set by spi_device but
not controller.

Signed-off-by: Mason Zhang <Mason.Zhang@mediatek.com>
Link: https://lore.kernel.org/r/20210804133716.32040-1-Mason.Zhang@mediatek.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# e09f2ab8 22-Jul-2021 Andreas Schwab <schwab@suse.de>

spi: update modalias_show after of_device_uevent_modalias support

Commit 3ce6c9e2617e ("spi: add of_device_uevent_modalias support") is
incomplete, as it didn't update the modalias_show function to generate the
of: modalias string if available.

Fixes: 3ce6c9e2617e ("spi: add of_device_uevent_modalias support")
Signed-off-by: Andreas Schwab <schwab@suse.de>
Link: https://lore.kernel.org/r/mvmwnpi4fya.fsf@suse.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# b470e10e 24-Jun-2021 Vinod Koul <vkoul@kernel.org>

spi: core: add dma_map_dev for dma device

Some controllers like qcom geni need the parent device to be used for
dma mapping, so add a dma_map_dev field and let drivers fill this to be
used as mapping device

Signed-off-by: Vinod Koul <vkoul@kernel.org>
Link: https://lore.kernel.org/r/20210625052213.32260-4-vkoul@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# b01d5506 23-Jun-2021 Colin Ian King <colin.king@canonical.com>

spi: Fix self assignment issue with ancillary->mode

There is an assignment of ancillary->mode to itself which looks
dubious since the proceeding comment states that the speed and
mode is taken over from the SPI main device, indicating that
ancillary->mode should assigned using the value spi->mode.
Fix this.

Addresses-Coverity: ("Self assignment")
Fixes: 0c79378c0199 ("spi: add ancillary device support")
Signed-off-by: Colin Ian King <colin.king@canonical.com>
Link: https://lore.kernel.org/r/20210623172300.161484-1-colin.king@canonical.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0c79378c 21-Jun-2021 Sebastian Reichel <sebastian.reichel@collabora.com>

spi: add ancillary device support

Introduce support for ancillary devices, similar to existing
implementation for I2C. This is useful for devices having
multiple chip-selects, for example some microcontrollers
provide a normal SPI interface and a flashing SPI interface.

Signed-off-by: Sebastian Reichel <sebastian.reichel@collabora.com>
Link: https://lore.kernel.org/r/20210621175359.126729-2-sebastian.reichel@collabora.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3ce6c9e2 25-May-2021 Marco Felsch <m.felsch@pengutronix.de>

spi: add of_device_uevent_modalias support

Add OF support as already done for ACPI to take driver
MODULE_DEVICE_TABLE(of, ..) into account.

For example with this change a spi nor device MODALIAS changes from:

MODALIAS=spi:spi-nor

to

MODALIAS=of:Nspi-flashT(null)Cjedec,spi-nor

Signed-off-by: Marco Felsch <m.felsch@pengutronix.de>
Link: https://lore.kernel.org/r/20210525091003.18228-1-m.felsch@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4ccf3598 09-Jun-2021 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

spi: remove spi_set_cs_timing()

No one seems to be using this global and exported function, so remove it
as it is no longer needed.

Cc: Mark Brown <broonie@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: https://lore.kernel.org/r/20210609071918.2852069-1-gregkh@linuxfoundation.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5cb4e1f3 26-May-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Enable tracing of the SPI setup CS selection

It is helpful to see what state of CS signal was during one
or another SPI operation. All the same for SPI setup.

Enable tracing of the SPI setup and CS selection.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Message-Id: <20210526195655.75691-1-andriy.shevchenko@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 40b82c2d 10-May-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Use SPI_MODE_X_MASK

Use SPI_MODE_X_MASK instead of open coded variant.

While at it, fix format specifier and drop explicit casting.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20210510131217.49357-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 86b8bff7 10-May-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Convert to use predefined time multipliers

We have a lot of hard coded values in nanoseconds or other units.
Use predefined constants to make it more clear.

While at it, add or amend comments in the corresponding functions.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20210510131120.49253-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# f60d7270 20-Apr-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Avoid undefined behaviour when counting unused native CSs

ffz(), that has been used to count unused native CSs,
might cause undefined behaviour when called against ~0U.
To fix that, open code it with ffs(~value) - 1.

Fixes: 7d93aecdb58d ("spi: Add generic support for unused native cs with cs-gpios")
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20210420164425.40287-2-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# dbaca8e5 20-Apr-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Allow to have all native CSs in use along with GPIOs

The commit 7d93aecdb58d ("spi: Add generic support for unused native cs
with cs-gpios") excludes the valid case for the controllers that doesn't
need to switch native CS in order to perform the transfer, i.e. when

0 native
... ...
<n> - 1 native
<n> GPIO
<n> + 1 GPIO
... ...

where <n> defines maximum of native CSs supported by the controller.

To allow this, bail out from spi_get_gpio_descs() conditionally for
the controllers which explicitly marked with SPI_MASTER_GPIO_SS.

Fixes: 7d93aecdb58d ("spi: Add generic support for unused native cs with cs-gpios")
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20210420164425.40287-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0e793ba7 21-Apr-2021 Charles Keepax <ckeepax@opensource.cirrus.com>

spi: Make of_register_spi_device also set the fwnode

Currently, the SPI core doesn't set the struct device fwnode pointer
when it creates a new SPI device. This means when the device is
registered the fwnode is NULL and the check in device_add which sets
the fwnode->dev pointer is skipped. This wasn't previously an issue,
however these two patches:

commit 4731210c09f5 ("gpiolib: Bind gpio_device to a driver to enable
fw_devlink=on by default")
commit ced2af419528 ("gpiolib: Don't probe gpio_device if it's not the
primary device")

Added some code to the GPIO core which relies on using that
fwnode->dev pointer to determine if a driver is bound to the fwnode
and if not bind a stub GPIO driver. This means the GPIO providers
behind SPI will get both the expected driver and this stub driver
causing the stub driver to fail if it attempts to request any pin
configuration. For example on my system:

madera-pinctrl madera-pinctrl: pin gpio5 already requested by madera-pinctrl; cannot claim for gpiochip3
madera-pinctrl madera-pinctrl: pin-4 (gpiochip3) status -22
madera-pinctrl madera-pinctrl: could not request pin 4 (gpio5) from group aif1 on device madera-pinctrl
gpio_stub_drv gpiochip3: Error applying setting, reverse things back
gpio_stub_drv: probe of gpiochip3 failed with error -22

The firmware node on the device created by the GPIO framework is set
through the of_node pointer hence things generally actually work,
however that fwnode->dev is never set, as the check was skipped at
device_add time. This fix appears to match how the I2C subsystem
handles the same situation.

Signed-off-by: Charles Keepax <ckeepax@opensource.cirrus.com>
Link: https://lore.kernel.org/r/20210421101402.8468-1-ckeepax@opensource.cirrus.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 27e7db56 05-May-2021 Saravana Kannan <saravanak@google.com>

spi: Don't have controller clean up spi device before driver unbind

When a spi device is unregistered and triggers a driver unbind, the
driver might need to access the spi device. So, don't have the
controller clean up the spi device before the driver is unbound. Clean
up the spi device after the driver is unbound.

Fixes: c7299fea6769 ("spi: Fix spi device unregister flow")
Reported-by: Lukas Wunner <lukas@wunner.de>
Signed-off-by: Saravana Kannan <saravanak@google.com>
Tested-by: Andy Shevchenko <andy.shevchenko@gmail.com>
Link: https://lore.kernel.org/r/20210505164734.175546-1-saravanak@google.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6b695469 11-May-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Assume GPIO CS active high in ACPI case

Currently GPIO CS handling, when descriptors are in use, doesn't
take into consideration that in ACPI case the default polarity
is Active High and can't be altered. Instead we have to use the
per-chip definition provided by SPISerialBus() resource.

Fixes: 766c6b63aa04 ("spi: fix client driver breakages when using GPIO descriptors")
Cc: Liguang Zhang <zhangliguang@linux.alibaba.com>
Cc: Jay Fang <f.fangjian@huawei.com>
Cc: Sven Van Asbroeck <thesven73@gmail.com>
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Tested-by: Xin Hao <xhao@linux.alibaba.com>
Link: https://lore.kernel.org/r/20210511140912.30757-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# dc5fa590 08-May-2021 Leilk Liu <leilk.liu@mediatek.com>

spi: take the SPI IO-mutex in the spi_set_cs_timing method

this patch takes the io_mutex to prevent an unprotected HW
register modification in the set_cs_timing callback.

Fixes: 4cea6b8cc34e ("spi: add power control when set_cs_timing")
Signed-off-by: Leilk Liu <leilk.liu@mediatek.com>
Link: https://lore.kernel.org/r/20210508060214.1485-1-leilk.liu@mediatek.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# c7299fea 26-Apr-2021 Saravana Kannan <saravanak@google.com>

spi: Fix spi device unregister flow

When an SPI device is unregistered, the spi->controller->cleanup() is
called in the device's release callback. That's wrong for a couple of
reasons:

1. spi_dev_put() can be called before spi_add_device() is called. And
it's spi_add_device() that calls spi_setup(). This will cause clean()
to get called without the spi device ever being setup.

2. There's no guarantee that the controller's driver would be present by
the time the spi device's release function gets called.

3. It also causes "sleeping in atomic context" stack dump[1] when device
link deletion code does a put_device() on the spi device.

Fix these issues by simply moving the cleanup from the device release
callback to the actual spi_unregister_device() function.

[1] - https://lore.kernel.org/lkml/CAHp75Vc=FCGcUyS0v6fnxme2YJ+qD+Y-hQDQLa2JhWNON9VmsQ@mail.gmail.com/

Signed-off-by: Saravana Kannan <saravanak@google.com>
Link: https://lore.kernel.org/r/20210426235638.1285530-1-saravanak@google.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 86527bcb 20-Apr-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Rename enable1 to activate in spi_set_cs()

The enable1 is confusing name. Change it to clearly show what is
the intention behind it. No functional changes.

Fixes: 25093bdeb6bc ("spi: implement SW control for CS times")
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20210420131846.75983-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 31ed8ebc 20-Apr-2021 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Make error handling of gpiod_count() call cleaner

Each time we call spi_get_gpio_descs() the num_chipselect is overwritten
either by new value or by the old one. This is an extra operation in case
gpiod_count() returns an error. Besides that it slashes the error handling
of gpiod_count().

Refactor the code to make error handling of gpiod_count() call cleaner.

Note, that gpiod_count() never returns 0, take this into account as well.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20210420164040.40055-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# c914dbf8 19-Apr-2021 Joe Burmeister <joe.burmeister@devtank.co.uk>

spi: Handle SPI device setup callback failure.

If the setup callback failed, but the controller has auto_runtime_pm
and set_cs, the setup failure could be missed.

Signed-off-by: Joe Burmeister <joe.burmeister@devtank.co.uk>
Link: https://lore.kernel.org/r/20210419130631.4586-1-joe.burmeister@devtank.co.uk
Signed-off-by: Mark Brown <broonie@kernel.org>


# d347b4aa 16-Apr-2021 David Bauer <mail@david-bauer.net>

spi: sync up initial chipselect state

When initially probing the SPI slave device, the call for disabling an
SPI device without the SPI_CS_HIGH flag is not applied, as the
condition for checking whether or not the state to be applied equals the
one currently set evaluates to true.

This however might not necessarily be the case, as the chipselect might
be active.

Add a force flag to spi_set_cs which allows to override this
early exit condition. Set it to false everywhere except when called
from spi_setup to sync up the initial CS state.

Fixes commit d40f0b6f2e21 ("spi: Avoid setting the chip select if we don't
need to")

Signed-off-by: David Bauer <mail@david-bauer.net>
Link: https://lore.kernel.org/r/20210416195956.121811-1-mail@david-bauer.net
Signed-off-by: Mark Brown <broonie@kernel.org>


# 59ebbe40 07-Apr-2021 Tian Tao <tiantao6@hisilicon.com>

spi: simplify devm_spi_register_controller

Use devm_add_action_or_reset() instead of devres_alloc() and
devres_add(), which works the same. This will simplify the
code. There is no functional changes.

Signed-off-by: Tian Tao <tiantao6@hisilicon.com>
Signed-off-by: Yicong Yang <yangyicong@hisilicon.com>
Link: https://lore.kernel.org/r/1617843307-53853-1-git-send-email-tiantao6@hisilicon.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 794aaf01 07-Apr-2021 William A. Kennington III <wak@google.com>

spi: Fix use-after-free with devm_spi_alloc_*

We can't rely on the contents of the devres list during
spi_unregister_controller(), as the list is already torn down at the
time we perform devres_find() for devm_spi_release_controller. This
causes devices registered with devm_spi_alloc_{master,slave}() to be
mistakenly identified as legacy, non-devm managed devices and have their
reference counters decremented below 0.

------------[ cut here ]------------
WARNING: CPU: 1 PID: 660 at lib/refcount.c:28 refcount_warn_saturate+0x108/0x174
[<b0396f04>] (refcount_warn_saturate) from [<b03c56a4>] (kobject_put+0x90/0x98)
[<b03c5614>] (kobject_put) from [<b0447b4c>] (put_device+0x20/0x24)
r4:b6700140
[<b0447b2c>] (put_device) from [<b07515e8>] (devm_spi_release_controller+0x3c/0x40)
[<b07515ac>] (devm_spi_release_controller) from [<b045343c>] (release_nodes+0x84/0xc4)
r5:b6700180 r4:b6700100
[<b04533b8>] (release_nodes) from [<b0454160>] (devres_release_all+0x5c/0x60)
r8:b1638c54 r7:b117ad94 r6:b1638c10 r5:b117ad94 r4:b163dc10
[<b0454104>] (devres_release_all) from [<b044e41c>] (__device_release_driver+0x144/0x1ec)
r5:b117ad94 r4:b163dc10
[<b044e2d8>] (__device_release_driver) from [<b044f70c>] (device_driver_detach+0x84/0xa0)
r9:00000000 r8:00000000 r7:b117ad94 r6:b163dc54 r5:b1638c10 r4:b163dc10
[<b044f688>] (device_driver_detach) from [<b044d274>] (unbind_store+0xe4/0xf8)

Instead, determine the devm allocation state as a flag on the
controller which is guaranteed to be stable during cleanup.

Fixes: 5e844cc37a5c ("spi: Introduce device-managed SPI controller allocation")
Signed-off-by: William A. Kennington III <wak@google.com>
Link: https://lore.kernel.org/r/20210407095527.2771582-1-wak@google.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9d902c2a 17-Mar-2021 Colin Ian King <colin.king@canonical.com>

spi: Fix spelling mistake "softwade" -> "software"

There is a spelling mistake in a dev_err message. Fix it.

Signed-off-by: Colin Ian King <colin.king@canonical.com>
Link: https://lore.kernel.org/r/20210317093936.5572-1-colin.king@canonical.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# df41a5da 03-Mar-2021 Heikki Krogerus <heikki.krogerus@linux.intel.com>

spi: Remove support for dangling device properties

>From now on only accepting complete software nodes.

Signed-off-by: Heikki Krogerus <heikki.krogerus@linux.intel.com>
Link: https://lore.kernel.org/r/20210303152814.35070-5-heikki.krogerus@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 47afc77b 03-Mar-2021 Heikki Krogerus <heikki.krogerus@linux.intel.com>

spi: Add support for software nodes

Making it possible for the drivers to assign complete
software fwnodes to the devices instead of only the device
properties in those nodes.

Signed-off-by: Heikki Krogerus <heikki.krogerus@linux.intel.com>
Link: https://lore.kernel.org/r/20210303152814.35070-2-heikki.krogerus@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3ab1cce5 08-Mar-2021 Alexandru Ardelean <aardelean@deviqon.com>

spi: core: remove 'delay_usecs' field from spi_transfer

The 'delay' field in the spi_transfer struct is meant to replace the
'delay_usecs' field. However some cleanup was required to remove the
uses of 'delay_usecs'. Now that it's been cleaned up, we can remove it
from the kernel tree.

Signed-off-by: Alexandru Ardelean <aardelean@deviqon.com>
Link: https://lore.kernel.org/r/20210308145502.1075689-10-aardelean@deviqon.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b3063203 11-Feb-2021 Nicolas Saenz Julienne <nsaenzjulienne@suse.de>

spi: Skip zero-length transfers in spi_transfer_one_message()

With the introduction of 26751de25d25 ("spi: bcm2835: Micro-optimise
FIFO loops") it has become apparent that some users might initiate
zero-length SPI transfers. A fact the micro-optimization omitted, and
which turned out to cause crashes[1].

Instead of changing the micro-optimization itself, use a bigger hammer
and skip zero-length transfers altogether for drivers using the default
transfer_one_message() implementation.

Reported-by: Phil Elwell <phil@raspberrypi.com>
Fixes: 26751de25d25 ("spi: bcm2835: Micro-optimise FIFO loops")
Signed-off-by: Nicolas Saenz Julienne <nsaenzjulienne@suse.de>

[1] https://github.com/raspberrypi/linux/issues/4100
Link: https://lore.kernel.org/r/20210211180820.25757-1-nsaenzjulienne@suse.de

Signed-off-by: Mark Brown <broonie@kernel.org>


# 0486d9f9 06-Feb-2021 leilk.liu <leilk.liu@mediatek.com>

spi: support CS timing for HW & SW mode

this patch supports the controller's HW CS and SW CS via use cs_gpio.

Signed-off-by: leilk.liu <leilk.liu@mediatek.com>
Link: https://lore.kernel.org/r/20210207030953.9297-3-leilk.liu@mediatek.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4cea6b8c 06-Feb-2021 leilk.liu <leilk.liu@mediatek.com>

spi: add power control when set_cs_timing

As to set_cs_timing takes effect immediately, power spi
is needed when call spi_set_cs_timing.

Signed-off-by: leilk.liu <leilk.liu@mediatek.com>
Link: https://lore.kernel.org/r/20210207030953.9297-2-leilk.liu@mediatek.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# d962608c 21-Dec-2020 Dragos Bogdan <dragos.bogdan@analog.com>

spi: Add SPI_NO_TX/RX support

Transmit/receive only is a valid SPI mode. For example, the MOSI/TX line
might be missing from an ADC while for a DAC the MISO/RX line may be
optional. This patch adds these two new modes: SPI_NO_TX and
SPI_NO_RX. This way, the drivers will be able to identify if any of
these two lines is missing and to adjust the transfers accordingly.

Signed-off-by: Dragos Bogdan <dragos.bogdan@analog.com>
Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20201221152936.53873-2-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 10e92724 26-Jan-2021 Bjorn Helgaas <bhelgaas@google.com>

ACPI: Test for ACPI_SUCCESS rather than !ACPI_FAILURE

The double negative makes it hard to read "if (!ACPI_FAILURE(status))".
Replace it with "if (ACPI_SUCCESS(status))".

Signed-off-by: Bjorn Helgaas <bhelgaas@google.com>
Acked-by: Guenter Roeck <linux@roeck-us.net>
Acked-by: Alex Deucher <alexander.deucher@amd.com>
Acked-by: Takashi Iwai <tiwai@suse.de>
Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# 6170d077 03-Jan-2021 Xu Yilun <yilun.xu@intel.com>

spi: fix the divide by 0 error when calculating xfer waiting time

The xfer waiting time is the result of xfer->len / xfer->speed_hz. This
patch makes the assumption of 100khz xfer speed if the xfer->speed_hz is
not assigned and stays 0. This avoids the divide by 0 issue and ensures
a reasonable tolerant waiting time.

Signed-off-by: Xu Yilun <yilun.xu@intel.com>
Link: https://lore.kernel.org/r/1609723749-3557-1-git-send-email-yilun.xu@intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6820e812 16-Dec-2020 Tudor Ambarus <tudor.ambarus@microchip.com>

spi: Fix the clamping of spi->max_speed_hz

If spi->controller->max_speed_hz is zero, a non-zero spi->max_speed_hz
will be overwritten by zero. Make sure spi->controller->max_speed_hz
is not zero when clamping spi->max_speed_hz.

Put the spi->controller->max_speed_hz non-zero check higher in the if,
so that we avoid a superfluous init to zero when both spi->max_speed_hz
and spi->controller->max_speed_hz are zero.

Fixes: 9326e4f1e5dd ("spi: Limit the spi device max speed to controller's max speed")
Reported-by: Geert Uytterhoeven <geert@linux-m68k.org>
Suggested-by: Geert Uytterhoeven <geert@linux-m68k.org>
Signed-off-by: Tudor Ambarus <tudor.ambarus@microchip.com>
Tested-by: Geert Uytterhoeven <geert+renesas@glider.be>
Link: https://lore.kernel.org/r/20201216092321.413262-1-tudor.ambarus@microchip.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9326e4f1 09-Dec-2020 Tudor Ambarus <tudor.ambarus@microchip.com>

spi: Limit the spi device max speed to controller's max speed

Make sure the max_speed_hz of spi_device does not override
the max_speed_hz of controller.

Signed-off-by: Tudor Ambarus <tudor.ambarus@microchip.com>
Link: https://lore.kernel.org/r/20201209173514.93328-1-tudor.ambarus@microchip.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# a6f483b2 24-Nov-2020 Marek Szyprowski <m.szyprowski@samsung.com>

spi: Fix potential NULL pointer dereference in spi_shutdown()

Shutdown bus function might be called on the unbound device, so add a
check if there is a driver before calling its shutdown function.

This fixes following kernel panic obserbed during system reboot:
Unable to handle kernel NULL pointer dereference at virtual address 0000000000000018
...
Call trace:
spi_shutdown+0x10/0x38
kernel_restart_prepare+0x34/0x40
kernel_restart+0x14/0x88
__do_sys_reboot+0x148/0x248
__arm64_sys_reboot+0x1c/0x28
el0_svc_common.constprop.3+0x74/0x198
do_el0_svc+0x20/0x98
el0_sync_handler+0x140/0x1a8
el0_sync+0x140/0x180
Code: f9403402 d1008041 f100005f 9a9f1021 (f9400c21)
---[ end trace 266c07205a2d632e ]---

Fixes: 9db34ee64ce4 (spi: Use bus_type functions for probe, remove and shutdown)
Signed-off-by: Marek Szyprowski <m.szyprowski@samsung.com>
Link: https://lore.kernel.org/r/20201124131523.32287-1-m.szyprowski@samsung.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4fae3a58 16-Nov-2020 Serge Semin <Sergey.Semin@baikalelectronics.ru>

spi: Take the SPI IO-mutex in the spi_setup() method

I've discovered that due to the recent commit 49d7d695ca4b ("spi: dw:
Explicitly de-assert CS on SPI transfer completion") a concurrent usage of
the spidev devices with different chip-selects causes the "SPI transfer
timed out" error. The root cause of the problem has turned to be in a race
condition of the SPI-transfer execution procedure and the spi_setup()
method being called at the same time. In particular in calling the
spi_set_cs(false) while there is an SPI-transfer being executed. In my
case due to the commit cited above all CSs get to be switched off by
calling the spi_setup() for /dev/spidev0.1 while there is an concurrent
SPI-transfer execution performed on /dev/spidev0.0. Of course a situation
of the spi_setup() being called while there is an SPI-transfer being
executed for two different SPI peripheral devices of the same controller
may happen not only for the spidev driver, but for instance for MMC SPI +
some another device, or spi_setup() being called from an SPI-peripheral
probe method while some other device has already been probed and is being
used by a corresponding driver...

Of course I could have provided a fix affecting the DW APB SSI driver
only, for instance, by creating a mutual exclusive access to the set_cs
callback and setting/clearing only the bit responsible for the
corresponding chip-select. But after a short research I've discovered that
the problem most likely affects a lot of the other drivers:
- drivers/spi/spi-sun4i.c - RMW the chip-select register;
- drivers/spi/spi-rockchip.c - RMW the chip-select register;
- drivers/spi/spi-qup.c - RMW a generic force-CS flag in a CSR.
- drivers/spi/spi-sifive.c - set a generic CS-mode flag in a CSR.
- drivers/spi/spi-bcm63xx-hsspi.c - uses an internal mutex to serialize
the bus config changes, but still isn't protected from the race
condition described above;
- drivers/spi/spi-geni-qcom.c - RMW a chip-select internal flag and set the
CS state in HW;
- drivers/spi/spi-orion.c - RMW a chip-select register;
- drivers/spi/spi-cadence.c - RMW a chip-select register;
- drivers/spi/spi-armada-3700.c - RMW a chip-select register;
- drivers/spi/spi-lantiq-ssc.c - overwrites the chip-select register;
- drivers/spi/spi-sun6i.c - RMW a chip-select register;
- drivers/spi/spi-synquacer.c - RMW a chip-select register;
- drivers/spi/spi-altera.c - directly sets the chip-select state;
- drivers/spi/spi-omap2-mcspi.c - RMW an internally cached CS state and
writes it to HW;
- drivers/spi/spi-mt65xx.c - RMW some CSR;
- drivers/spi/spi-jcore.c - directly sets the chip-selects state;
- drivers/spi/spi-mt7621.c - RMW a chip-select register;

I could have missed some drivers, but a scale of the problem is obvious.
As you can see most of the drivers perform an unprotected
Read-modify-write chip-select register modification in the set_cs callback.
Seeing the spi_setup() function is calling the spi_set_cs() and it can be
executed concurrently with SPI-transfers exec procedure, which also calls
spi_set_cs() in the SPI core spi_transfer_one_message() method, the race
condition of the register modification turns to be obvious.

To sum up the problem denoted above affects each driver for a controller
having more than one chip-select lane and which:
1) performs the RMW to some CS-related register with no serialization;
2) directly disables any CS on spi_set_cs(dev, false).
* the later is the case of the DW APB SSI driver.

The controllers which equipped with a single CS theoretically can also
experience the problem, but in practice will not since normally the
spi_setup() isn't called concurrently with the SPI-transfers executed on
the same SPI peripheral device.

In order to generically fix the denoted bug I'd suggest to serialize an
access to the controller IO by taking the IO mutex in the spi_setup()
callback. The mutex is held while there is an SPI communication going on
on the SPI-bus of the corresponding SPI-controller. So calling the
spi_setup() method and disabling/updating the CS state within it would be
safe while there is no any SPI-transfers being executed. Also note I
suppose it would be safer to protect the spi_controller->setup() callback
invocation too, seeing some of the SPI-controller drivers update a HW
state in there.

Fixes: 49d7d695ca4b ("spi: dw: Explicitly de-assert CS on SPI transfer completion")
Signed-off-by: Serge Semin <Sergey.Semin@baikalelectronics.ru>
Link: https://lore.kernel.org/r/20201117094517.5654-1-Sergey.Semin@baikalelectronics.ru
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7795d475 19-Nov-2020 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Warn when a driver's remove callback returns an error

The driver core ignores the return value of struct device_driver::remove
(because in general there is nothing that can be done about that). So
add a warning when an spi driver returns an error.

This simplifies the quest to make struct device_driver::remove return void.
A consequent change would be to make struct spi_driver::remove return void,
but I'm keeping this quest for later (or someone else).

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20201119161604.2633521-3-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9db34ee6 19-Nov-2020 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: Use bus_type functions for probe, remove and shutdown

The eventual goal is to get rid of the callbacks in struct
device_driver. Other than not using driver callbacks there should be no
side effect of this patch.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20201119161604.2633521-2-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 440408db 19-Nov-2020 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: fix resource leak for drivers without .remove callback

Consider an spi driver with a .probe but without a .remove callback (e.g.
rtc-ds1347). The function spi_drv_probe() is called to bind a device and
so dev_pm_domain_attach() is called. As there is no remove callback
spi_drv_remove() isn't called at unbind time however and so calling
dev_pm_domain_detach() is missed and the pm domain keeps active.

To fix this always use both spi_drv_probe() and spi_drv_remove() and
make them handle the respective callback not being set. This has the
side effect that for a (hypothetical) driver that has neither .probe nor
remove the clk and pm domain setup is done.

Fixes: 33cf00e57082 ("spi: attach/detach SPI device to the ACPI power domain")
Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Link: https://lore.kernel.org/r/20201119161604.2633521-1-u.kleine-koenig@pengutronix.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5e844cc3 11-Nov-2020 Lukas Wunner <lukas@wunner.de>

spi: Introduce device-managed SPI controller allocation

SPI driver probing currently comprises two steps, whereas removal
comprises only one step:

spi_alloc_master()
spi_register_controller()

spi_unregister_controller()

That's because spi_unregister_controller() calls device_unregister()
instead of device_del(), thereby releasing the reference on the
spi_controller which was obtained by spi_alloc_master().

An SPI driver's private data is contained in the same memory allocation
as the spi_controller struct. Thus, once spi_unregister_controller()
has been called, the private data is inaccessible. But some drivers
need to access it after spi_unregister_controller() to perform further
teardown steps.

Introduce devm_spi_alloc_master() and devm_spi_alloc_slave(), which
release a reference on the spi_controller struct only after the driver
has unbound, thereby keeping the memory allocation accessible. Change
spi_unregister_controller() to not release a reference if the
spi_controller was allocated by one of these new devm functions.

The present commit is small enough to be backportable to stable.
It allows fixing drivers which use the private data in their ->remove()
hook after it's been freed. It also allows fixing drivers which neglect
to release a reference on the spi_controller in the probe error path.

Long-term, most SPI drivers shall be moved over to the devm functions
introduced herein. The few that can't shall be changed in a treewide
commit to explicitly release the last reference on the controller.
That commit shall amend spi_unregister_controller() to no longer release
a reference, thereby completing the migration.

As a result, the behaviour will be less surprising and more consistent
with subsystems such as IIO, which also includes the private data in the
allocation of the generic iio_dev struct, but calls device_del() in
iio_device_unregister().

Signed-off-by: Lukas Wunner <lukas@wunner.de>
Link: https://lore.kernel.org/r/272bae2ef08abd21388c98e23729886663d19192.1605121038.git.lukas@wunner.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 766c6b63 06-Nov-2020 Sven Van Asbroeck <thesven73@gmail.com>

spi: fix client driver breakages when using GPIO descriptors

Commit f3186dd87669 ("spi: Optionally use GPIO descriptors for CS GPIOs")
introduced the optional use of GPIO descriptors for chip selects.

A side-effect of this change: when a SPI bus uses GPIO descriptors,
all its client devices have SPI_CS_HIGH set in spi->mode. This flag is
required for the SPI bus to operate correctly.

This unfortunately breaks many client drivers, which use the following
pattern to configure their underlying SPI bus:

static int client_device_probe(struct spi_device *spi)
{
...
spi->mode = SPI_MODE_0;
spi->bits_per_word = 8;
err = spi_setup(spi);
..
}

In short, many client drivers overwrite the SPI_CS_HIGH bit in
spi->mode, and break the underlying SPI bus driver.

This is especially true for Freescale/NXP imx ecspi, where large
numbers of spi client drivers now no longer work.

Proposed fix:
-------------
When using gpio descriptors, depend on gpiolib to handle CS polarity.
Existing quirks in gpiolib ensure that this is handled correctly.

Existing gpiolib behaviour will force the polarity of any chip-select
gpiod to active-high (if 'spi-active-high' devicetree prop present) or
active-low (if 'spi-active-high' absent). Irrespective of whether
the gpio is marked GPIO_ACTIVE_[HIGH|LOW] in the devicetree.

Loose ends:
-----------
If this fix is applied:
- is commit 138c9c32f090
("spi: spidev: Fix CS polarity if GPIO descriptors are used")
still necessary / correct ?

Fixes: f3186dd87669 ("spi: Optionally use GPIO descriptors for CS GPIOs")
Signed-off-by: Sven Van Asbroeck <thesven73@gmail.com>
Acked-by: Linus Walleij <linus.walleij@linaro.org>
Link: https://lore.kernel.org/r/20201106150706.29089-1-TheSven73@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# ce2424d7 23-Oct-2020 Mauro Carvalho Chehab <mchehab+huawei@kernel.org>

spi: fix a typo inside a kernel-doc markup

spi_split_tranfers_maxsize -> spi_split_transfers_maxsize

Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>
Link: https://lore.kernel.org/r/a103f4f48735caa1a09fad94c5d76e73e2ce37b8.1603469755.git.mchehab+huawei@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# b59a7ca1 08-Sep-2020 Gustav Wiklander <gustavwi@axis.com>

spi: Fix memory leak on splited transfers

In the prepare_message callback the bus driver has the
opportunity to split a transfer into smaller chunks.
spi_map_msg is done after prepare_message.

Function spi_res_release releases the splited transfers
in the message. Therefore spi_res_release should be called
after spi_map_msg.

The previous try at this was commit c9ba7a16d0f1
which released the splited transfers after
spi_finalize_current_message had been called.
This introduced a race since the message struct could be
out of scope because the spi_sync call got completed.

Fixes this leak on spi bus driver spi-bcm2835.c when transfer
size is greater than 65532:

Kmemleak:
sg_alloc_table+0x28/0xc8
spi_map_buf+0xa4/0x300
__spi_pump_messages+0x370/0x748
__spi_sync+0x1d4/0x270
spi_sync+0x34/0x58
spi_test_execute_msg+0x60/0x340 [spi_loopback_test]
spi_test_run_iter+0x548/0x578 [spi_loopback_test]
spi_test_run_test+0x94/0x140 [spi_loopback_test]
spi_test_run_tests+0x150/0x180 [spi_loopback_test]
spi_loopback_test_probe+0x50/0xd0 [spi_loopback_test]
spi_drv_probe+0x84/0xe0

Signed-off-by: Gustav Wiklander <gustavwi@axis.com>
Link: https://lore.kernel.org/r/20200908151129.15915-1-gustav.wiklander@axis.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# ddf75be4 03-Aug-2020 Lukas Wunner <lukas@wunner.de>

spi: Prevent adding devices below an unregistering controller

CONFIG_OF_DYNAMIC and CONFIG_ACPI allow adding SPI devices at runtime
using a DeviceTree overlay or DSDT patch. CONFIG_SPI_SLAVE allows the
same via sysfs.

But there are no precautions to prevent adding a device below a
controller that's being removed. Such a device is unusable and may not
even be able to unbind cleanly as it becomes inaccessible once the
controller has been torn down. E.g. it is then impossible to quiesce
the device's interrupt.

of_spi_notify() and acpi_spi_notify() do hold a ref on the controller,
but otherwise run lockless against spi_unregister_controller().

Fix by holding the spi_add_lock in spi_unregister_controller() and
bailing out of spi_add_device() if the controller has been unregistered
concurrently.

Fixes: ce79d54ae447 ("spi/of: Add OF notifier handler")
Signed-off-by: Lukas Wunner <lukas@wunner.de>
Cc: stable@vger.kernel.org # v3.19+
Cc: Geert Uytterhoeven <geert+renesas@glider.be>
Cc: Octavian Purdila <octavian.purdila@intel.com>
Cc: Pantelis Antoniou <pantelis.antoniou@konsulko.com>
Link: https://lore.kernel.org/r/a8c3205088a969dc8410eec1eba9aface60f36af.1596451035.git.lukas@wunner.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# e1268597 15-Jul-2020 Mark Brown <broonie@kernel.org>

spi: Only defer to thread for cleanup when needed

Currently we always defer idling of controllers to the SPI thread, the goal
being to ensure that we're doing teardown that's not suitable for atomic
context in an appropriate context and to try to batch up more expensive
teardown operations when the system is under higher load, allowing more
work to be started before the SPI thread is scheduled. However when the
controller does not require any substantial work to idle there is no need
to do this, we can instead save the context switch and immediately mark
the controller as idle. This is particularly useful for systems where there
is frequent but not constant activity.

Signed-off-by: Mark Brown <broonie@kernel.org>
Link: https://lore.kernel.org/r/20200715163610.9475-1-broonie@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 60a883d1 09-Jul-2020 Marek Szyprowski <m.szyprowski@samsung.com>

spi: use kthread_create_worker() helper

Use kthread_create_worker() helper to simplify the code. It uses
the kthread worker API the right way. It will eventually allow
to remove the FIXME in kthread_worker_fn() and add more consistency
checks in the future.

Signed-off-by: Marek Szyprowski <m.szyprowski@samsung.com>
Reviewed-by: Petr Mladek <pmladek@suse.com>
Link: https://lore.kernel.org/r/20200709065007.26896-1-m.szyprowski@samsung.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# d40f0b6f 29-Jun-2020 Douglas Anderson <dianders@chromium.org>

spi: Avoid setting the chip select if we don't need to

On some SPI controllers (like spi-geni-qcom) setting the chip select
is a heavy operation. For instance on spi-geni-qcom, with the current
code, is was measured as taking upwards of 20 us. Even on SPI
controllers that aren't as heavy, setting the chip select is at least
something like a MMIO operation over some peripheral bus which isn't
as fast as a RAM access.

While it would be good to find ways to mitigate problems like this in
the drivers for those SPI controllers, it can also be noted that the
SPI framework could also help out. Specifically, in some situations,
we can see the SPI framework calling the driver's set_cs() with the
same parameter several times in a row. This is specifically observed
when looking at the way the Chrome OS EC SPI driver (cros_ec_spi)
works but other drivers likely trip it to some extent.

Let's solve this by caching the chip select state in the core and only
calling into the controller if there was a change. We check not only
the "enable" state but also the chip select mode (active high or
active low) since controllers may care about both the mode and the
enable flag in their callback.

Signed-off-by: Douglas Anderson <dianders@chromium.org>
Link: https://lore.kernel.org/r/20200629164103.1.Ied8e8ad8bbb2df7f947e3bc5ea1c315e041785a2@changeid
Signed-off-by: Mark Brown <broonie@kernel.org>


# 809b1b04 16-Jun-2020 Robin Gong <yibin.gong@nxp.com>

spi: introduce fallback to pio

Add fallback to pio mode in case dma transfer failed with error status
SPI_TRANS_FAIL_NO_START.
If spi client driver want to enable this feature please set xfer->error in
the proper place such as dmaengine_prep_slave_sg() failure detect(but no
any data put into spi bus yet). Besides, add master->fallback checking in
its can_dma() so that spi core could switch to pio next time. Please refer
to spi-imx.c.

Signed-off-by: Robin Gong <yibin.gong@nxp.com>
Link: https://lore.kernel.org/r/1592347329-28363-2-git-send-email-yibin.gong@nxp.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3070da33 20-Apr-2020 Peter Zijlstra <peterz@infradead.org>

sched,spi: Convert to sched_set_fifo*()

Because SCHED_FIFO is a broken scheduler model (see previous patches)
take away the priority field, the kernel can't possibly make an
informed decision.

No effective change.

Cc: broonie@kernel.org
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Reviewed-by: Ingo Molnar <mingo@kernel.org>
Reviewed-by: Douglas Anderson <dianders@chromium.org>
Reviewed-by: Guenter Roeck <groeck@chromium.org>


# c373643b 25-May-2020 Mark Brown <broonie@kernel.org>

spi: Remove note about transfer limit for spi_write_then_read()

Originally spi_write_then_read() used a fixed statically allocated
buffer which limited the maximum message size it could handle. This
restriction was removed a while ago so that we could dynamically
allocate a buffer if required but the kerneldoc was not updated to
reflect this, do so.

Reported-by: Marc Kleine-Budde <mkl@pengutronix.de>
Signed-off-by: Mark Brown <broonie@kernel.org>
Link: https://lore.kernel.org/r/20200525133120.57273-1-broonie@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# aee67fe8 24-May-2020 dillon min <dillon.minfei@gmail.com>

spi: flags 'SPI_CONTROLLER_MUST_RX' and 'SPI_CONTROLLER_MUST_TX' can't be coexit with 'SPI_3WIRE' mode

since chip spi driver need get the transfer direction by 'tx_buf' and
'rx_buf' of 'struct spi_transfer' in 'SPI_3WIRE' mode.

so, we need bypass 'SPI_CONTROLLER_MUST_RX' and 'SPI_CONTROLLER_MUST_TX'
feature in 'SPI_3WIRE' mode

Signed-off-by: dillon min <dillon.minfei@gmail.com>
Link: https://lore.kernel.org/r/1590378348-8115-9-git-send-email-dillon.minfei@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8fede89f 22-May-2020 Mark Brown <broonie@kernel.org>

spi: Make spi_delay_exec() warn if called from atomic context

If the delay used is long enough the spi_delay_exec() will use a sleeping
function to implement it. Add a might_sleep() here to help avoid callers
using this from an atomic context and running into problems at runtime on
other systems.

Suggested-by: Serge Semin <Sergey.Semin@baikalelectronics.ru>
Signed-off-by: Mark Brown <broonie@kernel.org>
Reviewed-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20200522155005.46099-1-broonie@kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 84855678 15-May-2020 Lukas Wunner <lukas@wunner.de>

spi: Fix controller unregister order

When an SPI controller unregisters, it unbinds all its slave devices.
For this, their drivers may need to access the SPI bus, e.g. to quiesce
interrupts.

However since commit ffbbdd21329f ("spi: create a message queueing
infrastructure"), spi_destroy_queue() is executed before unbinding the
slaves. It sets ctlr->running = false, thereby preventing SPI bus
access and causing unbinding of slave devices to fail.

Fix by unbinding slaves before calling spi_destroy_queue().

Fixes: ffbbdd21329f ("spi: create a message queueing infrastructure")
Signed-off-by: Lukas Wunner <lukas@wunner.de>
Cc: stable@vger.kernel.org # v3.4+
Cc: Linus Walleij <linus.walleij@linaro.org>
Link: https://lore.kernel.org/r/8aaf9d44c153fe233b17bc2dec4eb679898d7e7b.1589557526.git.lukas@wunner.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 49686df5 10-Apr-2020 Colin Ian King <colin.king@canonical.com>

spi: remove redundant assignment to variable ms

The variable ms is being initialized with a value that is never read
and it is being updated later with a new value. The initialization is
redundant and can be removed.

Signed-off-by: Colin Ian King <colin.king@canonical.com>
Reviewed-by: Geert Uytterhoeven <geert@linux-m68k.org>
Addresses-Coverity: ("Unused value")
Link: https://lore.kernel.org/r/20200410122315.17523-1-colin.king@canonical.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0dadde34 13-Apr-2020 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Respect DataBitLength field of SpiSerialBusV2() ACPI resource

By unknown reason the commit 64bee4d28c9e
("spi / ACPI: add ACPI enumeration support")
missed the DataBitLength property to encounter when parse SPI slave
device data from ACPI.

Fill the gap here.

Fixes: 64bee4d28c9e ("spi / ACPI: add ACPI enumeration support")
Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20200413180406.1826-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5b16668e 12-Mar-2020 Wolfram Sang <wsa+renesas@sang-engineering.com>

spi: acpi: remove superfluous parameter check

to_spi_device() already checks 'dev'. No need to do it before calling
it.

Signed-off-by: Wolfram Sang <wsa+renesas@sang-engineering.com>
Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be>
Reviewed-by: Niklas Söderlund <niklas.soderlund+renesas@ragnatech.se>
Link: https://lore.kernel.org/r/20200312134507.10000-1-wsa@the-dreams.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# 671c3bf5 06-Mar-2020 Chuanhong Guo <gch981213@gmail.com>

spi: make spi-max-frequency optional

We only need a spi-max-frequency when we specifically request a
spi frequency lower than the max speed of spi host.
This property is already documented as optional property and current
host drivers are implemented to operate at highest speed possible
when spi->max_speed_hz is 0.
This patch makes spi-max-frequency an optional property so that
we could just omit it to use max controller speed.

Signed-off-by: Chuanhong Guo <gch981213@gmail.com>
Link: https://lore.kernel.org/r/20200306085052.28258-2-gch981213@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6a726824 04-Mar-2020 Vladimir Oltean <vladimir.oltean@nxp.com>

spi: Do spi_take_timestamp_pre for as many times as necessary

When dealing with a SPI controller driver that is sending more than 1
byte at once (or the entire buffer at once), and the SPI peripheral
driver has requested timestamping for a byte in the middle of the
buffer, we find that spi_take_timestamp_pre never records a "pre"
timestamp.

This happens because the function currently expects to be called with
the "progress" argument >= to what the peripheral has requested to be
timestamped. But clearly there are cases when that isn't going to fly.

And since we can't change the past when we realize that the opportunity
to take a "pre" timestamp has just passed and there isn't going to be
another one, the approach taken is to keep recording the "pre" timestamp
on each call, overwriting the previously recorded one until the "post"
timestamp is also taken.

Signed-off-by: Vladimir Oltean <vladimir.oltean@nxp.com>
Link: https://lore.kernel.org/r/20200304220044.11193-8-olteanv@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# f9981d4f 04-Mar-2020 Aaro Koskinen <aaro.koskinen@nokia.com>

spi: spi_register_controller(): free bus id on error paths

Some error paths leave the bus id allocated. As a result the IDR
allocation will fail after a deferred probe. Fix by freeing the bus id
always on error.

Signed-off-by: Aaro Koskinen <aaro.koskinen@nokia.com>
Message-Id: <20200304111740.27915-1-aaro.koskinen@nokia.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ea235786 28-Feb-2020 John Garry <john.garry@huawei.com>

spi: Allow SPI controller override device buswidth

Currently ACPI firmware description for a SPI device does not have any
method to describe the data buswidth on the board.

So even through the controller and device may support higher modes than
standard SPI, it cannot be assumed that the board does - as such, that
device is limited to standard SPI in such a circumstance.

As a workaround, allow the controller driver supply buswidth override bits,
which are used inform the core code that the controller driver knows the
buswidth supported on that board for that device.

A host controller driver might know this info from DMI tables, for example.

Signed-off-by: John Garry <john.garry@huawei.com>
Link: https://lore.kernel.org/r/1582903131-160033-2-git-send-email-john.garry@huawei.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7d93aecd 02-Jan-2020 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Add generic support for unused native cs with cs-gpios

Some SPI master controllers always drive a native chip select when
performing a transfer. Hence when using both native and GPIO chip
selects, at least one native chip select must be left unused, to be
driven when performing transfers with slave devices using GPIO chip
selects.

Currently, to find an unused native chip select, SPI controller drivers
need to parse and process cs-gpios theirselves. This is not only
duplicated in each driver that needs it, but also duplicates part of the
work done later at SPI controller registration time. Note that this
cannot be done after spi_register_controller() returns, as at that time,
slave devices may have been probed already.

Hence add generic support to the SPI subsystem for finding an unused
native chip select. Optionally, this unused native chip select, and all
other in-use native chip selects, can be validated against the maximum
number of native chip selects available on the controller hardware.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Link: https://lore.kernel.org/r/20200102133822.29346-2-geert+renesas@glider.be
Signed-off-by: Mark Brown <broonie@kernel.org>


# 862dd2a9 26-Dec-2019 Vladimir Oltean <olteanv@gmail.com>

spi: Don't look at TX buffer for PTP system timestamping

The API for PTP system timestamping (associating a SPI transaction with
the system time at which it was transferred) is flawed: it assumes that
the xfer->tx_buf pointer will always be present.

This is, of course, not always the case.

So introduce a "progress" variable that denotes how many word have been
transferred.

Fix the Freescale DSPI driver, the only user of the API so far, in the
same patch.

Fixes: b42faeee718c ("spi: Add a PTP system timestamp to the transfer structure")
Fixes: d6b71dfaeeba ("spi: spi-fsl-dspi: Implement the PTP system timestamping for TCFQ mode")
Signed-off-by: Vladimir Oltean <olteanv@gmail.com>
Link: https://lore.kernel.org/r/20191227012417.1057-1-olteanv@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# f971a207 26-Dec-2019 Vladimir Oltean <olteanv@gmail.com>

spi: Catch improper use of PTP system timestamping API

We can catch whether the SPI controller has declared it can take care of
software timestamping transfers, but didn't. So do it.

Signed-off-by: Vladimir Oltean <olteanv@gmail.com>
Link: https://lore.kernel.org/r/20191227012444.1204-1-olteanv@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 57a94607 11-Nov-2019 Tony Lindgren <tony@atomide.com>

spi: Fix regression to return zero on success instead of positive value

Commit d948e6ca1899 ("spi: add power control when set_cs") added generic
runtime PM handling, but also changed the return value to be 1 instead
of 0 that we had earlier as pm_runtime_get functions return a positve
value on success.

This causes SPI devices to return errors for cases where they do:

ret = spi_setup(spi);
if (ret)
return ret;

As in many cases the SPI devices do not check for if (ret < 0).

Let's fix this by setting the status to 0 on succeess after the
runtime PM calls. Let's not return 0 at the end of the function
as this might break again later on if the function changes and
starts returning status again.

Fixes: d948e6ca1899 ("spi: add power control when set_cs")
Cc: Luhua Xu <luhua.xu@mediatek.com>
Cc: wsd_upstream@mediatek.com
Signed-off-by: Tony Lindgren <tony@atomide.com>
Link: https://lore.kernel.org/r/20191111195334.44833-1-tony@atomide.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# d948e6ca 30-Oct-2019 Luhua Xu <luhua.xu@mediatek.com>

spi: add power control when set_cs

As to set_cs takes effect immediately, power spi
is needed when setup spi.

Cc: Mark Brown <broonie@kernel.org>
Signed-off-by: Luhua Xu <luhua.xu@mediatek.com>
Link: https://lore.kernel.org/r/1572426234-30019-1-git-send-email-luhua.xu@mediatek.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 15f794bd 24-Oct-2019 Gregory CLEMENT <gregory.clement@bootlin.com>

spi: Fix NULL pointer when setting SPI_CS_HIGH for GPIO CS

Even if the flag use_gpio_descriptors is set, it is possible that
cs_gpiods was not allocated, which leads to a kernel crash.

Reported-by: "kernelci.org bot" <bot@kernelci.org>
Fixes: 3e5ec1db8bfe ("spi: Fix SPI_CS_HIGH setting when using native and GPIO CS")
Signed-off-by: Gregory CLEMENT <gregory.clement@bootlin.com>
Link: https://lore.kernel.org/r/20191024141309.22434-1-gregory.clement@bootlin.com
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: <stable@vger.kernel.org>


# be73e323 23-Oct-2019 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: Fix spelling in the comments

Two spelling mistakes are being fixed.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20191023121643.25237-1-andriy.shevchenko@linux.intel.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3e5ec1db 18-Oct-2019 Gregory CLEMENT <gregory.clement@bootlin.com>

spi: Fix SPI_CS_HIGH setting when using native and GPIO CS

When improving the CS GPIO support at core level, the SPI_CS_HIGH
has been enabled for all the CS lines used for a given SPI controller.

However, the SPI framework allows to have on the same controller native
CS and GPIO CS. The native CS may not support the SPI_CS_HIGH, so they
should not be setup automatically.

With this patch the setting is done only for the CS that will use a
GPIO as CS

Fixes: f3186dd87669 ("spi: Optionally use GPIO descriptors for CS GPIOs")
Cc: <stable@vger.kernel.org>
Signed-off-by: Gregory CLEMENT <gregory.clement@bootlin.com>
Link: https://lore.kernel.org/r/20191018152929.3287-1-gregory.clement@bootlin.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3984d39b 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: spi-fsl-espi: convert transfer delay to `spi_delay` format

The way the max delay is computed for this controller, it looks like it is
searching for the max delay from an SPI message a using that.

No idea if this is valid. But this change should support both `delay_usecs`
and the new `delay` data which is of `spi_delay` type.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-17-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 25093bde 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: implement SW control for CS times

This change implements CS control for setup, hold & inactive delays.

The `cs_setup` delay is completely new, and can help with cases where
asserting the CS, also brings the device out of power-sleep, where there
needs to be a longer (than usual), before transferring data.

The `cs_hold` time can overlap with the `delay` (or `delay_usecs`) from an
SPI transfer. The main difference is that `cs_hold` implies that CS will be
de-asserted.

The `cs_inactive` delay does not have a clear use-case yet. It has been
implemented mostly because the `spi_set_cs_timing()` function implements
it. To some degree, this could overlap or replace `cs_change_delay`, but
this will require more consideration/investigation in the future.

All these delays have been added to the `spi_controller` struct, as they
would typically be configured by calling `spi_set_cs_timing()` after an
`spi_setup()` call.

Software-mode for CS control, implies that the `set_cs_timing()` hook has
not been provided for the `spi_controller` object.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-16-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 81059366 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: tegra114: change format for `spi_set_cs_timing()` function

The initial version of `spi_set_cs_timing()` was implemented with
consideration only for clock-cycles as delay.

For cases like `CS setup` time, it's sometimes needed that micro-seconds
(or nano-seconds) are required, or sometimes even longer delays, for cases
where the device needs a little longer to start transferring that after CS
is asserted.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-15-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# bebcfd27 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: introduce `delay` field for `spi_transfer` + spi_transfer_delay_exec()

The change introduces the `delay` field to the `spi_transfer` struct as an
`struct spi_delay` type.
This intends to eventually replace `delay_usecs`.

But, since there are many users of `delay_usecs`, this needs some
intermediate work.
A helper called `spi_transfer_delay_exec()` is also added, which maintains
backwards compatibility with `delay_usecs`, by assigning the value to
`delay` if non-zero.
This should maintain backwards compatibility with current users of
`udelay_usecs`.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-9-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6c613f68 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: core,atmel: convert `word_delay_usecs` -> `word_delay` for spi_device

This change does a conversion from the `word_delay_usecs` -> `word_delay`
for the `spi_device` struct.

This allows users to specify inter-word delays in other unit types
(nano-seconds or clock cycles), depending on how users want.

The Atmel SPI driver is the only current user of the `word_delay_usecs`
field (from the `spi_device` struct).
So, it needed a slight conversion to use the `word_delay` as an `spi_delay`
struct.

In SPI core, the only required mechanism is to update the `word_delay`
information per `spi_transfer`. This requires a bit more logic than before,
because it needs that both delays be converted to a common unit
(nano-seconds) for comparison.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-8-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 329f0dac 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: make `cs_change_delay` the first user of the `spi_delay` logic

Since the logic for `spi_delay` struct + `spi_delay_exec()` has been copied
from the `cs_change_delay` logic, it's natural to make this delay, the
first user.

The `cs_change_delay` logic requires that the default remain 10 uS, in case
it is unspecified/unconfigured. So, there is some special handling needed
to do that.

The ADIS library is one of the few users of the new `cs_change_delay`
parameter for an spi_transfer.

The introduction of the `spi_delay` struct, requires that the users of of
`cs_change_delay` get an update. This change also updates the ADIS library.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-4-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b2c98153 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: introduce spi_delay struct as "value + unit" & spi_delay_exec()

There are plenty of delays that have been introduced in SPI core. Most of
them are in micro-seconds, some need to be in nano-seconds, and some in
clock-cycles.

For some of these delays (related to transfers & CS timing) it may make
sense to have a `spi_delay` struct that abstracts these a bit.

The important element of these delays [for unification] seems to be the
`unit` of the delay.
It looks like micro-seconds is good enough for most people, but every-once
in a while, some delays seem to require other units of measurement.

This change adds the `spi_delay` struct & a `spi_delay_exec()` function
that processes a `spi_delay` object/struct to execute the delay.
It's a copy of the `cs_change_delay` mechanism, but without the default
for 10 uS.

The clock-cycle delay unit is a bit special, as it needs to be bound to an
`spi_transfer` object to execute.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-3-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6b3f236a 26-Sep-2019 Alexandru Ardelean <alexandru.ardelean@analog.com>

spi: move `cs_change_delay` backwards compat logic outside switch

The `cs_change_delay` backwards compatibility value could be moved outside
of the switch statement.
The only reason to do it, is to make the next patches easier to diff.

Signed-off-by: Alexandru Ardelean <alexandru.ardelean@analog.com>
Link: https://lore.kernel.org/r/20190926105147.7839-2-alexandru.ardelean@analog.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 79591b7d 04-Sep-2019 Vladimir Oltean <olteanv@gmail.com>

spi: Add a PTP system timestamp to the transfer structure

SPI is one of the interfaces used to access devices which have a POSIX
clock driver (real time clocks, 1588 timers etc). The fact that the SPI
bus is slow is not what the main problem is, but rather the fact that
drivers don't take a constant amount of time in transferring data over
SPI. When there is a high delay in the readout of time, there will be
uncertainty in the value that has been read out of the peripheral.
When that delay is constant, the uncertainty can at least be
approximated with a certain accuracy which is fine more often than not.

Timing jitter occurs all over in the kernel code, and is mainly caused
by having to let go of the CPU for various reasons such as preemption,
servicing interrupts, going to sleep, etc. Another major reason is CPU
dynamic frequency scaling.

It turns out that the problem of retrieving time from a SPI peripheral
with high accuracy can be solved by the use of "PTP system
timestamping" - a mechanism to correlate the time when the device has
snapshotted its internal time counter with the Linux system time at that
same moment. This is sufficient for having a precise time measurement -
it is not necessary for the whole SPI transfer to be transmitted "as
fast as possible", or "as low-jitter as possible". The system has to be
low-jitter for a very short amount of time to be effective.

This patch introduces a PTP system timestamping mechanism in struct
spi_transfer. This is to be used by SPI device drivers when they need to
know the exact time at which the underlying device's time was
snapshotted. More often than not, SPI peripherals have a very exact
timing for when their SPI-to-interconnect bridge issues a transaction
for snapshotting and reading the time register, and that will be
dependent on when the SPI-to-interconnect bridge figures out that this
is what it should do, aka as soon as it sees byte N of the SPI transfer.
Since spi_device drivers are the ones who'd know best how the peripheral
behaves in this regard, expose a mechanism in spi_transfer which allows
them to specify which word (or word range) from the transfer should be
timestamped.

Add a default implementation of the PTP system timestamping in the SPI
core. This is not going to be satisfactory performance-wise, but should
at least increase the likelihood that SPI device drivers will use PTP
system timestamping in the future.
There are 3 entry points from the core towards the SPI controller
drivers:

- transfer_one: The driver is passed individual spi_transfers to
execute. This is the easiest to timestamp.

- transfer_one_message: The core passes the driver an entire spi_message
(a potential batch of spi_transfers). The core puts the same pre and
post timestamp to all transfers within a message. This is not ideal,
but nothing better can be done by default anyway, since the core has
no insight into how the driver batches the transfers.

- transfer: Like transfer_one_message, but for unqueued drivers (i.e.
the driver implements its own queue scheduling).

Signed-off-by: Vladimir Oltean <olteanv@gmail.com>
Link: https://lore.kernel.org/r/20190905010114.26718-3-olteanv@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# b42faeee 04-Sep-2019 Vladimir Oltean <olteanv@gmail.com>

spi: Add a PTP system timestamp to the transfer structure

SPI is one of the interfaces used to access devices which have a POSIX
clock driver (real time clocks, 1588 timers etc). The fact that the SPI
bus is slow is not what the main problem is, but rather the fact that
drivers don't take a constant amount of time in transferring data over
SPI. When there is a high delay in the readout of time, there will be
uncertainty in the value that has been read out of the peripheral.
When that delay is constant, the uncertainty can at least be
approximated with a certain accuracy which is fine more often than not.

Timing jitter occurs all over in the kernel code, and is mainly caused
by having to let go of the CPU for various reasons such as preemption,
servicing interrupts, going to sleep, etc. Another major reason is CPU
dynamic frequency scaling.

It turns out that the problem of retrieving time from a SPI peripheral
with high accuracy can be solved by the use of "PTP system
timestamping" - a mechanism to correlate the time when the device has
snapshotted its internal time counter with the Linux system time at that
same moment. This is sufficient for having a precise time measurement -
it is not necessary for the whole SPI transfer to be transmitted "as
fast as possible", or "as low-jitter as possible". The system has to be
low-jitter for a very short amount of time to be effective.

This patch introduces a PTP system timestamping mechanism in struct
spi_transfer. This is to be used by SPI device drivers when they need to
know the exact time at which the underlying device's time was
snapshotted. More often than not, SPI peripherals have a very exact
timing for when their SPI-to-interconnect bridge issues a transaction
for snapshotting and reading the time register, and that will be
dependent on when the SPI-to-interconnect bridge figures out that this
is what it should do, aka as soon as it sees byte N of the SPI transfer.
Since spi_device drivers are the ones who'd know best how the peripheral
behaves in this regard, expose a mechanism in spi_transfer which allows
them to specify which word (or word range) from the transfer should be
timestamped.

Add a default implementation of the PTP system timestamping in the SPI
core. This is not going to be satisfactory performance-wise, but should
at least increase the likelihood that SPI device drivers will use PTP
system timestamping in the future.
There are 3 entry points from the core towards the SPI controller
drivers:

- transfer_one: The driver is passed individual spi_transfers to
execute. This is the easiest to timestamp.

- transfer_one_message: The core passes the driver an entire spi_message
(a potential batch of spi_transfers). The core puts the same pre and
post timestamp to all transfers within a message. This is not ideal,
but nothing better can be done by default anyway, since the core has
no insight into how the driver batches the transfers.

- transfer: Like transfer_one_message, but for unqueued drivers (i.e.
the driver implements its own queue scheduling).

Signed-off-by: Vladimir Oltean <olteanv@gmail.com>
Link: https://lore.kernel.org/r/20190905010114.26718-3-olteanv@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 229e6af1 10-Sep-2019 Lukas Wunner <lukas@wunner.de>

spi: Guarantee cacheline alignment of driver-private data

__spi_alloc_controller() uses a single allocation to accommodate struct
spi_controller and the driver-private data, but places the latter behind
the former. This order does not guarantee cacheline alignment of the
driver-private data. (It does guarantee cacheline alignment of struct
spi_controller but the structure doesn't make any use of that property.)

Round up struct spi_controller to cacheline size. A forthcoming commit
leverages this to grant DMA access to driver-private data of the BCM2835
SPI master.

An alternative, less economical approach would be to use two allocations.

A third approach consists of reversing the order to conserve memory.
But Mark Brown is concerned that it may result in a performance penalty
on architectures that don't like unaligned accesses.

Signed-off-by: Lukas Wunner <lukas@wunner.de>
Link: https://lore.kernel.org/r/01625b9b26b93417fb09d2c15ad02dfe9cdbbbe5.1568187525.git.lukas@wunner.de
Signed-off-by: Mark Brown <broonie@kernel.org>


# d1c44c93 04-Sep-2019 Vladimir Oltean <olteanv@gmail.com>

spi: Use an abbreviated pointer to ctlr->cur_msg in __spi_pump_messages

This helps a bit with line fitting now (the list_first_entry call) as
well as during the next patch which needs to iterate through all
transfers of ctlr->cur_msg so it timestamps them.

Signed-off-by: Vladimir Oltean <olteanv@gmail.com>
Link: https://lore.kernel.org/r/20190905010114.26718-2-olteanv@gmail.com
Signed-off-by: Mark Brown <broonie@kernel.org>


# 43004f31 08-Aug-2019 Linus Walleij <linus.walleij@linaro.org>

spi: Rename of_spi_register_master() function

Rename this function to of_spi_get_gpio_numbers() as this
is what the function does, it does not register a master,
it is called in the path of registering a master so the
name is logical in a convoluted way, but it is better to
follow Rusty Russell's ABI level no 7:
"The obvious use is (probably) the correct one"

Signed-off-by: Linus Walleij <linus.walleij@linaro.org>
Link: https://lore.kernel.org/r/20190808150321.23319-1-linus.walleij@linaro.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4ff13d00 01-Aug-2019 Peter Zijlstra <peterz@infradead.org>

spi: Reduce kthread priority

The SPI thingies request FIFO-99 by default, reduce this to FIFO-50.

FIFO-99 is the very highest priority available to SCHED_FIFO and
it not a suitable default; it would indicate the SPI work is the
most important work on the machine.

Cc: Benson Leung <bleung@chromium.org>
Cc: Enric Balletbo i Serra <enric.balletbo@collabora.com>
Cc: Guenter Roeck <groeck@chromium.org>
Cc: Mark Brown <broonie@kernel.org>
Cc: linux-spi@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Reviewed-by: Douglas Anderson <dianders@chromium.org>
Link: https://lore.kernel.org/r/20190801111541.917256884@infradead.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# cc8b4659 31-Jul-2019 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Use DEVICE_ATTR_RW() for SPI slave control sysfs attribute

Convert the SPI slave control sysfs attribute from DEVICE_ATTR() to
DEVICE_ATTR_RW(), to reduce boilerplate.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Link: https://lore.kernel.org/r/20190731124738.14519-1-geert+renesas@glider.be
Signed-off-by: Mark Brown <broonie@kernel.org>


# 00500147 23-Jul-2019 Suzuki K Poulose <suzuki.poulose@arm.com>

drivers: Introduce device lookup variants by ACPI_COMPANION device

Add a generic helper to match a device by the ACPI_COMPANION device
and provide wrappers for the device lookup APIs.

Cc: Len Brown <lenb@kernel.org>
Cc: linux-acpi@vger.kernel.org
Cc: linux-spi@vger.kernel.org
Cc: Mika Westerberg <mika.westerberg@linux.intel.com>
Cc: linux-i2c@vger.kernel.org
Cc: "Rafael J. Wysocki" <rafael@kernel.org>
Signed-off-by: Suzuki K Poulose <suzuki.poulose@arm.com>
Acked-by: Mark Brown <broonie@kernel.org>
Acked-by: Wolfram Sang <wsa@the-dreams.de> # I2C parts
Link: https://lore.kernel.org/r/20190723221838.12024-6-suzuki.poulose@arm.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# cfba5de9 23-Jul-2019 Suzuki K Poulose <suzuki.poulose@arm.com>

drivers: Introduce device lookup variants by of_node

Introduce wrappers for {bus/driver/class}_find_device() to
locate devices by its of_node.

Cc: Maarten Lankhorst <maarten.lankhorst@linux.intel.com>
Cc: Maxime Ripard <maxime.ripard@bootlin.com>
Cc: dri-devel@lists.freedesktop.org
Cc: David Airlie <airlied@linux.ie>
Cc: Daniel Vetter <daniel@ffwll.ch>
Cc: devicetree@vger.kernel.org
Cc: Florian Fainelli <f.fainelli@gmail.com>
Cc: Frank Rowand <frowand.list@gmail.com>
Cc: Heiko Stuebner <heiko@sntech.de>
Cc: Liam Girdwood <lgirdwood@gmail.com>
Cc: linux-i2c@vger.kernel.org
Cc: linux-rockchip@lists.infradead.org
Cc: linux-spi@vger.kernel.org
Cc: Mathieu Poirier <mathieu.poirier@linaro.org>
Cc: Rob Herring <robh+dt@kernel.org>
Cc: Srinivas Kandagatla <srinivas.kandagatla@linaro.org>
Cc: Takashi Iwai <tiwai@suse.com>
Cc: Alan Tull <atull@kernel.org>
Cc: linux-fpga@vger.kernel.org
Cc: Peter Rosin <peda@axentia.se>
Cc: Florian Fainelli <f.fainelli@gmail.com>
Cc: Heiner Kallweit <hkallweit1@gmail.com>
Cc: "David S. Miller" <davem@davemloft.net>
Cc: Andrew Lunn <andrew@lunn.ch>
Cc: Liam Girdwood <lgirdwood@gmail.com>
Cc: "Rafael J. Wysocki" <rafael@kernel.org>
Cc: Thor Thayer <thor.thayer@linux.intel.com>
Cc: Jiri Slaby <jslaby@suse.com>
Cc: Andrew Lunn <andrew@lunn.ch>
Cc: Peter Rosin <peda@axentia.se>
Signed-off-by: Suzuki K Poulose <suzuki.poulose@arm.com>
Acked-by: Lee Jones <lee.jones@linaro.org>
Acked-by: Wolfram Sang <wsa@the-dreams.de> # I2C part
Acked-by: Moritz Fischer <mdf@kernel.org> # For FPGA part
Acked-by: Mark Brown <broonie@kernel.org>
Link: https://lore.kernel.org/r/20190723221838.12024-3-suzuki.poulose@arm.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# b28944c6 20-Jun-2019 Ard Biesheuvel <ardb@kernel.org>

spi/acpi: avoid spurious matches during slave enumeration

In the new SPI ACPI slave enumeration code, we use the value of
lookup.max_speed_khz as a flag to decide whether a match occurred.
However, doing so only makes sense if we initialize its value to
zero beforehand, or otherwise, random junk from the stack will
cause spurious matches.

So zero initialize the lookup struct fully, and only set the non-zero
members explicitly.

Fixes: 4c3c59544f33 ("spi/acpi: enumerate all SPI slaves in the namespace")
Cc: Mika Westerberg <mika.westerberg@linux.intel.com>
Cc: andy.shevchenko@gmail.com
Cc: masahisa.kojima@linaro.org
Cc: "Rafael J. Wysocki" <rjw@rjwysocki.net>
Cc: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Cc: linux-acpi@vger.kernel.org
Cc: Lukas Wunner <lukas@wunner.de>
Signed-off-by: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Tested-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Acked-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 418e3ea1 14-Jun-2019 Suzuki K Poulose <suzuki.poulose@arm.com>

bus_find_device: Unify the match callback with class_find_device

There is an arbitrary difference between the prototypes of
bus_find_device() and class_find_device() preventing their callers
from passing the same pair of data and match() arguments to both of
them, which is the const qualifier used in the prototype of
class_find_device(). If that qualifier is also used in the
bus_find_device() prototype, it will be possible to pass the same
match() callback function to both bus_find_device() and
class_find_device(), which will allow some optimizations to be made in
order to avoid code duplication going forward. Also with that, constify
the "data" parameter as it is passed as a const to the match function.

For this reason, change the prototype of bus_find_device() to match
the prototype of class_find_device() and adjust its callers to use the
const qualifier in accordance with the new prototype of it.

Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com>
Cc: Andrew Lunn <andrew@lunn.ch>
Cc: Andreas Noever <andreas.noever@gmail.com>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Bjorn Helgaas <bhelgaas@google.com>
Cc: Corey Minyard <minyard@acm.org>
Cc: Christian Borntraeger <borntraeger@de.ibm.com>
Cc: David Kershner <david.kershner@unisys.com>
Cc: "David S. Miller" <davem@davemloft.net>
Cc: David Airlie <airlied@linux.ie>
Cc: Felipe Balbi <balbi@kernel.org>
Cc: Frank Rowand <frowand.list@gmail.com>
Cc: Grygorii Strashko <grygorii.strashko@ti.com>
Cc: Harald Freudenberger <freude@linux.ibm.com>
Cc: Hartmut Knaack <knaack.h@gmx.de>
Cc: Heiko Stuebner <heiko@sntech.de>
Cc: Jason Gunthorpe <jgg@ziepe.ca>
Cc: Jonathan Cameron <jic23@kernel.org>
Cc: "James E.J. Bottomley" <jejb@linux.ibm.com>
Cc: Len Brown <lenb@kernel.org>
Cc: Mark Brown <broonie@kernel.org>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Michael Jamet <michael.jamet@intel.com>
Cc: "Martin K. Petersen" <martin.petersen@oracle.com>
Cc: Peter Oberparleiter <oberpar@linux.ibm.com>
Cc: Sebastian Ott <sebott@linux.ibm.com>
Cc: Srinivas Kandagatla <srinivas.kandagatla@linaro.org>
Cc: Yehezkel Bernat <YehezkelShB@gmail.com>
Cc: rafael@kernel.org
Acked-by: Corey Minyard <minyard@acm.org>
Acked-by: David Kershner <david.kershner@unisys.com>
Acked-by: Mark Brown <broonie@kernel.org>
Acked-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Acked-by: Srinivas Kandagatla <srinivas.kandagatla@linaro.org>
Acked-by: Wolfram Sang <wsa@the-dreams.de> # for the I2C parts
Acked-by: Rob Herring <robh@kernel.org>
Signed-off-by: Suzuki K Poulose <suzuki.poulose@arm.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# f9481b08 19-Jun-2019 Tudor Ambarus <tudor.ambarus@microchip.com>

spi: fix ctrl->num_chipselect constraint

at91sam9g25ek showed the following error at probe:
atmel_spi f0000000.spi: Using dma0chan2 (tx) and dma0chan3 (rx)
for DMA transfers
atmel_spi: probe of f0000000.spi failed with error -22

Commit 0a919ae49223 ("spi: Don't call spi_get_gpio_descs() before device name is set")
moved the calling of spi_get_gpio_descs() after ctrl->dev is set,
but didn't move the !ctrl->num_chipselect check. When there are
chip selects in the device tree, the spi-atmel driver lets the
SPI core discover them when registering the SPI master.
The ctrl->num_chipselect is thus expected to be set by
spi_get_gpio_descs().

Move the !ctlr->num_chipselect after spi_get_gpio_descs() as it was
before the aforementioned commit. While touching this block, get rid
of the explicit comparison with 0 and update the commenting style.

Fixes: 0a919ae49223 ("spi: Don't call spi_get_gpio_descs() before device name is set")
Signed-off-by: Tudor Ambarus <tudor.ambarus@microchip.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# b5e3cf41 19-Jun-2019 Ard Biesheuvel <ardb@kernel.org>

spi/acpi: fix incorrect ACPI parent check

The ACPI device object parsing code for SPI slaves enumerates the
entire ACPI namespace to look for devices that refer to the master
in question via the 'resource_source' field in the 'SPISerialBus'
resource. If that field does not refer to a valid ACPI device or
if it refers to the wrong SPI master, we should disregard the
device.

Current, the valid device check is wrong, since it gets the
polarity of 'status' wrong. This could cause issues if the
'resource_source' field is bogus but parent_handle happens to
refer to the correct master (which is not entirely imaginary
since this code runs in a loop)

So test for ACPI_FAILURE() instead, to make the code more
self explanatory.

Fixes: 4c3c59544f33 ("spi/acpi: enumerate all SPI slaves in the namespace")
Reported-by: kbuild test robot <lkp@intel.com>
Reported-by: Dan Carpenter <dan.carpenter@oracle.com>
Cc: Mika Westerberg <mika.westerberg@linux.intel.com>
Cc: andy.shevchenko@gmail.com
Cc: masahisa.kojima@linaro.org
Cc: "Rafael J. Wysocki" <rjw@rjwysocki.net>
Cc: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Cc: linux-acpi@vger.kernel.org
Cc: Lukas Wunner <lukas@wunner.de>
Signed-off-by: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Acked-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# f5694369 18-Jun-2019 Vladimir Zapolskiy <vz@mleia.com>

spi: don't open code list_for_each_entry_safe_reverse()

The loop declaration in function spi_res_release() can be simplified
by reusing the common list_for_each_entry_safe_reverse() helper
macro.

Signed-off-by: Vladimir Zapolskiy <vz@mleia.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ebc37af5 15-Jun-2019 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: No need to assign dummy value in spi_unregister_controller()

The device_for_each_child() doesn't require the returned value to be checked.
Thus, drop the dummy variable completely and have no warning anymore:

drivers/spi/spi.c: In function ‘spi_unregister_controller’:
drivers/spi/spi.c:2480:6: warning: variable ‘dummy’ set but not used [-Wunused-but-set-variable]
int dummy;
^~~~~

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4c3c5954 30-May-2019 Ard Biesheuvel <ardb@kernel.org>

spi/acpi: enumerate all SPI slaves in the namespace

Currently, the ACPI enumeration that takes place when registering a
SPI master only considers immediate child devices in the ACPI namespace,
rather than checking the ResourceSource field in the SpiSerialBus()
resource descriptor.

This is incorrect: SPI slaves could reside anywhere in the ACPI
namespace, and so we should enumerate the entire namespace and look for
any device that refers to the newly registered SPI master in its
resource descriptor.

So refactor the existing code and use a lookup structure so that
allocating the SPI device structure is deferred until we have identified
the device as an actual child of the controller. This approach is
loosely based on the way the I2C subsystem handles ACPI enumeration.

Note that Apple x86 hardware does not rely on SpiSerialBus() resources
in _CRS but uses nested devices below the controller's device node in
the ACPI namespace, with a special set of device properties. This means
we have to take care to only parse those properties for device nodes
that are direct children of the controller node.

Cc: Mika Westerberg <mika.westerberg@linux.intel.com>
Cc: linux-spi@vger.kernel.org
Cc: broonie@kernel.org
Cc: andy.shevchenko@gmail.com
Cc: masahisa.kojima@linaro.org
Cc: "Rafael J. Wysocki" <rjw@rjwysocki.net>
Cc: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Cc: linux-acpi@vger.kernel.org
Cc: Lukas Wunner <lukas@wunner.de>

Signed-off-by: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# aef97522 07-Jun-2019 Gustavo A. R. Silva <gustavo@embeddedor.com>

spi: Use struct_size() helper

One of the more common cases of allocation size calculations is finding
the size of a structure that has a zero-sized array at the end, along
with memory for some number of elements for that array. For example:

struct spi_replaced_transfers {
...
struct spi_transfer inserted_transfers[];
};

Make use of the struct_size() helper instead of an open-coded version
in order to avoid any potential type mistakes.

So, replace the following form:

insert * sizeof(struct spi_transfer) + sizeof(struct spi_replaced_transfers)

with:

struct_size(rxfer, inserted_transfers, insert)

This code was detected with the help of Coccinelle.

Signed-off-by: Gustavo A. R. Silva <gustavo@embeddedor.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 924b5867 15-May-2019 Douglas Anderson <dianders@chromium.org>

spi: Allow SPI devices to request the pumping thread be realtime

Right now the only way to get the SPI pumping thread bumped up to
realtime priority is for the controller to request it. However it may
be that the controller works fine with the normal priority but
communication to a particular SPI device on the bus needs realtime
priority.

Let's add a way for devices to request realtime priority when they set
themselves up.

NOTE: this will just affect the priority of transfers that end up on
the SPI core's pumping thread. In many cases transfers happen in the
context of the caller so if you need realtime priority for all
transfers you should ensure the calling context is also realtime
priority.

Signed-off-by: Douglas Anderson <dianders@chromium.org>
Reviewed-by: Guenter Roeck <groeck@chromium.org>
Tested-by: Enric Balletbo i Serra <enric.balletbo@collabora.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# f3440d9a 22-May-2019 Super Liu <supercjliu@google.com>

spi: abort spi_sync if failed to prepare_transfer_hardware

There is no chance to wait spi message complete if failed to
prepare_transfer_hardware(). Therefore, finalize this message and abort
transfer with corresponding return status to release this block case.

Logs:

[17400.283005] c7 3267 PM: PM: suspend entry 2019-05-04 03:01:14.403097147 UTC
[17400.283013] c7 3267 PM: suspend entry (deep)
[17400.283016] c6 3267 PM: Syncing filesystems ... done.
[17400.584395] c1 753 spi_geni 890000.spi: spi_geni_prepare_transfer_hardware:Error enabling SE resources -13
[17400.584404] c1 753 spi_master spi1: failed to prepare transfer hardware
[17400.664611] c4 3267 PM: PM: suspend exit 2019-05-04 03:01:15.235273018 UTC

Flow:

__spi_sync@spi.c
| if (status == 0) {
| /* Push out the messages in the calling context if we
| * can.
| */
| if (ctlr->transfer == spi_queued_transfer) {
| SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
| spi_sync_immediate);
| SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
| spi_sync_immediate);
| __spi_pump_messages(ctlr, false);
| }
|
| wait_for_completion(&done); <== stuck here!!!
| status = message->status;
| }
| message->context = NULL;
| return status;
|
--> __spi_pump_messages@spi.c
| if (!was_busy && ctlr->prepare_transfer_hardware) {
| ret = ctlr->prepare_transfer_hardware(ctlr);
| if (ret) {
| dev_err(&ctlr->dev,
| "failed to prepare transfer hardware\n");
|
| if (ctlr->auto_runtime_pm)
| pm_runtime_put(ctlr->dev.parent);
| mutex_unlock(&ctlr->io_mutex);
| return;
| }
| }
|
--> spi_geni_prepare_transfer_hardware@spi-geni-qcom.c
| ret = pm_runtime_get_sync(mas->dev);
| if (ret < 0) {
| dev_err(mas->dev,
| "%s:Error enabling SE resources %d\n",
| __func__, ret);
| pm_runtime_put_noidle(mas->dev);
| goto exit_prepare_transfer_hardware;

Signed-off-by: Super Liu <supercjliu@google.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5d7e2b5e 23-Feb-2019 Martin Sperl <kernel@martin.sperl.org>

spi: core: allow reporting the effectivly used speed_hz for a transfer

Provide a means for the spi bus driver to report the effectively used
spi clock frequency used for each spi_transfer.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0ed56252 08-May-2019 Mark Brown <broonie@kernel.org>

spi: Fix Raspberry Pi breakage

This reverts commit c9ba7a16d0f1 (Release spi_res after finalizing
message) which causes races during cleanup.

Reported-by: Nicolas Saenz Julienne <nsaenzjulienne@suse.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# d5864e5b 23-Feb-2019 Martin Sperl <kernel@martin.sperl.org>

spi: core: allow defining time that cs is deasserted as a multiple of SCK

Support setting a delay between cs assert and deassert as
a multiple of spi clock length.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0ff2de8b 23-Feb-2019 Martin Sperl <kernel@martin.sperl.org>

spi: core: allow defining time that cs is deasserted

For some SPI devices that support speed_hz > 1MHz the default 10 us delay
when cs_change = 1 is typically way to long and may result in poor spi bus
utilization.

This patch makes it possible to control the delay at micro or nano second
resolution on a per spi_transfer basis. It even allows an "as fast as
possible" mode with:
xfer.cs_change_delay_unit = SPI_DELAY_UNIT_NSECS;
xfer.cs_change_delay = 0;

The delay code is shared between delay_usecs and cs_change_delay for
consistency and reuse, so in the future this change_delay_unit could also
apply to delay_usec as well.

Note that on slower SOCs/CPU actually reaching ns deasserts on cs is not
realistic as the gpio overhead alone (without any delays added ) may
already leave cs deasserted for more than 1us - at least on a raspberry pi.
But at the very least this way we can keep it as short as possible.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# d61ad23c 26-Apr-2019 Serge Semin <fancer.lancer@gmail.com>

spi: Clear SPI_CS_HIGH flag from bad_bits for GPIO chip-select

When GPIO chip-select is used nothing prevents any available SPI
controllers to work with both CS-high and traditional CS-low modes.
In fact the SPI bus core code already does it, so we don't need to
introduce any modification there. But spi_setup() still fails to
switch the interface settings if CS-high flag is set for the case
of GPIO-driven slave chip-select when the SPI controller doesn't
support the hardwired CS-inversion. Lets fix it by clearing the
SPI_CS_HIGH flag out from bad_bits (unsupported by controller) when
client chip is selected by GPIO.

This feature is useful for slave devices, which in accordance with
communication protocol can work with both active-high and active-low
chip-selects. I am aware of one such device. It is MMC-SPI interface,
when at init sequence the driver needs to perform a read operation with
low and high chip-select sequentially (requirement of 74 clock cycles
with both chipselect, see the mmc_spi driver for details).

Signed-off-by: Serge Semin <fancer.lancer@gmail.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# c9ba7a16 13-Apr-2019 Noralf Trønnes <noralf@tronnes.org>

spi: Release spi_res after finalizing message

spi_split_transfers_maxsize() can be used to split a transfer. This
function uses spi_res to lifetime manage the added transfer structures.
So in order to finalize the current message while it contains the split
transfers, spi_res_release() must be called after finalizing.

Signed-off-by: Noralf Trønnes <noralf@tronnes.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4d1841d6 13-Apr-2019 Noralf Trønnes <noralf@tronnes.org>

spi: Remove warning in spi_split_transfers_maxsize()

Don't warn about splitting transfers, the info is available in the
statistics if needed.

Signed-off-by: Noralf Trønnes <noralf@tronnes.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 76d2f7ee 12-Apr-2019 Jarkko Nikula <jarkko.nikula@linux.intel.com>

spi: Remove one needless transfer speed fall back case

Falling back to maximum speed of the controller in case of SPI slave
maximum speed is not set is needless. It already defaults to maximum
speed of the controller since commit 052eb2d49006 ("spi: core: Set
max_speed_hz of spi_device default to max_speed_hz of controller").

Signed-off-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# f1ca9992 04-Apr-2019 Sowjanya Komatineni <skomatineni@nvidia.com>

spi: add a method for configuring CS timing

This patch creates set_cs_timing SPI master optional method for
SPI masters to implement configuring CS timing if applicable.

This patch also creates spi_cs_timing accessory for SPI clients to
use for requesting SPI master controllers to configure device requested
CS setup time, hold time and inactive delay.

Signed-off-by: Sowjanya Komatineni <skomatineni@nvidia.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# b93318a2 05-Apr-2019 Sergei Shtylyov <sergei.shtylyov@cogentembedded.com>

spi: kill useless initializer in spi_register_controller()

The 'status' local variable is initialized but this value is never used,
thus kill that initializer.

Signed-off-by: Sergei Shtylyov <sergei.shtylyov@cogentembedded.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0a919ae4 02-Apr-2019 Andrey Smirnov <andrew.smirnov@gmail.com>

spi: Don't call spi_get_gpio_descs() before device name is set

Move code calling spi_get_gpio_descs() to happen after ctlr->dev's
name is set in order to have proper GPIO consumer names.

Before:

cat /sys/kernel/debug/gpio
gpiochip0: GPIOs 0-31, parent: platform/40049000.gpio, vf610-gpio:
gpio-6 ( |regulator-usb0-vbus ) out lo

gpiochip1: GPIOs 32-63, parent: platform/4004a000.gpio, vf610-gpio:
gpio-36 ( |scl ) in hi
gpio-37 ( |sda ) in hi
gpio-40 ( |(null) CS1 ) out lo
gpio-41 ( |(null) CS0 ) out lo ACTIVE LOW
gpio-42 ( |miso ) in hi
gpio-43 ( |mosi ) in lo
gpio-44 ( |sck ) out lo

After:

cat /sys/kernel/debug/gpio
gpiochip0: GPIOs 0-31, parent: platform/40049000.gpio, vf610-gpio:
gpio-6 ( |regulator-usb0-vbus ) out lo

gpiochip1: GPIOs 32-63, parent: platform/4004a000.gpio, vf610-gpio:
gpio-36 ( |scl ) in hi
gpio-37 ( |sda ) in hi
gpio-40 ( |spi0 CS1 ) out lo
gpio-41 ( |spi0 CS0 ) out lo ACTIVE LOW
gpio-42 ( |miso ) in hi
gpio-43 ( |mosi ) in lo
gpio-44 ( |sck ) out lo

Signed-off-by: Andrey Smirnov <andrew.smirnov@gmail.com>
Cc: Mark Brown <broonie@kernel.org>
Cc: Chris Healy <cphealy@gmail.com>
Cc: linux-spi@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 1723fdec 03-Apr-2019 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Add missing error handling for CS GPIOs

While devm_gpiod_get_index_optional() returns NULL if the GPIO is not
present (i.e. -ENOENT), it may still return other error codes, like
-EPROBE_DEFER. Currently these are not handled, leading to
unrecoverable failures later in case of probe deferral:

gpiod_set_consumer_name: invalid GPIO (errorpointer)
gpiod_direction_output: invalid GPIO (errorpointer)
gpiod_set_value_cansleep: invalid GPIO (errorpointer)
gpiod_set_value_cansleep: invalid GPIO (errorpointer)
gpiod_set_value_cansleep: invalid GPIO (errorpointer)

Detect and propagate errors to fix this.

Fixes: f3186dd876697e69 ("spi: Optionally use GPIO descriptors for CS GPIOs")
Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ca1438dc 21-Mar-2019 Arnd Bergmann <arnd@arndb.de>

spi: export tracepoint symbols to modules

The newly added tracepoints in the spi-mxs driver cause a link
error when the driver is a loadable module:

ERROR: "__tracepoint_spi_transfer_stop" [drivers/spi/spi-mxs.ko] undefined!
ERROR: "__tracepoint_spi_transfer_start" [drivers/spi/spi-mxs.ko] undefined!

I'm not quite sure where to put the export statements, but
directly after the inclusion of the header seems as good as
any other place.

Fixes: f3fdea3af405 ("spi: mxs: add tracing to custom .transfer_one_message callback")
Signed-off-by: Arnd Bergmann <arnd@arndb.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5442dcaa 07-Mar-2019 Chris Lesiak <chris.lesiak@licor.com>

spi: Fix zero length xfer bug

This fixes a bug for messages containing both zero length and
unidirectional xfers.

The function spi_map_msg will allocate dummy tx and/or rx buffers
for use with unidirectional transfers when the hardware can only do
a bidirectional transfer. That dummy buffer will be used in place
of a NULL buffer even when the xfer length is 0.

Then in the function __spi_map_msg, if he hardware can dma,
the zero length xfer will have spi_map_buf called on the dummy
buffer.

Eventually, __sg_alloc_table is called and returns -EINVAL
because nents == 0.

This fix prevents the error by not using the dummy buffer when
the xfer length is zero.

Signed-off-by: Chris Lesiak <chris.lesiak@licor.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 28f7604f 09-Feb-2019 Felix Fietkau <nbd@nbd.name>

spi: use gpio[d]_set_value_cansleep for setting chipselect GPIO

Sleeping is safe inside spi_transfer_one_message, and some
GPIO chips are running on slow busses (such as I2C GPIO
expanders) and need to sleep for setting values.

Signed-off-by: Felix Fietkau <nbd@nbd.name>
Signed-off-by: Linus Walleij <linus.walleij@linaro.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# b7bb367a 30-Jan-2019 Jonas Bonn <jonas@norrbonn.se>

spi: support inter-word delay requirement for devices

Some devices are slow and cannot keep up with the SPI bus and therefore
require a short delay between words of the SPI transfer.

The example of this that I'm looking at is a SAMA5D2 with a minimum SPI
clock of 400kHz talking to an AVR-based SPI slave. The AVR cannot put
bytes on the bus fast enough to keep up with the SoC's SPI controller
even at the lowest bus speed.

This patch introduces the ability to specify a required inter-word
delay for SPI devices. It is up to the controller driver to configure
itself accordingly in order to introduce the requested delay.

Note that, for spi_transfer, there is already a field word_delay that
provides similar functionality. This field, however, is specified in
clock cycles (and worse, SPI controller cycles, not SCK cycles); that
makes this value dependent on the master clock instead of the device
clock for which the delay is intended to provide some relief. This
patch leaves this old word_delay in place and provides a time-based
word_delay_us alongside it; the new field fits in the struct padding
so struct size is constant. There is only one in-kernel user of the
word_delay field and presumably that driver could be reworked to use
the time-based value instead.

The time-based delay is limited to 8 bits as these delays are intended
to be short. The SAMA5D2 that I've tested this on limits delays to a
maximum of ~100us, which is already many word-transfer periods even at
the minimum transfer speed supported by the controller.

Signed-off-by: Jonas Bonn <jonas@norrbonn.se>
CC: Mark Brown <broonie@kernel.org>
CC: Rob Herring <robh+dt@kernel.org>
CC: Mark Rutland <mark.rutland@arm.com>
CC: linux-spi@vger.kernel.org
CC: devicetree@vger.kernel.org
Signed-off-by: Mark Brown <broonie@kernel.org>


# 2df201e0 16-Jan-2019 Linus Walleij <linus.walleij@linaro.org>

spi: Support high CS when using descriptors

All controllers using GPIO descriptors can by definition
support high CS connections, so just enforce this when
registering an SPI controller.

This fixes a regression where controllers were missing
SPI_CS_HIGH, the drivers would fail like this:

spi spi0.0: setup: unsupported mode bits 4
cdns-spi fd0b0000.spi: can't setup spi0.0, status -22

This is because as using descriptors moves the CS inversion
logic over to gpiolib, all such controllers are registered
with CS active high.

Cc: Jan Kotas <jank@cadence.com>
Reported-by: Jan Kotas <jank@cadence.com>
Tested-by: Jan Kotas <jank@cadence.com>
Fixes: f3186dd87669 ("spi: Optionally use GPIO descriptors for CS GPIOs")
Signed-off-by: Linus Walleij <linus.walleij@linaro.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# f0125f1a 23-Jan-2019 Mark Brown <broonie@kernel.org>

spi: Go back to immediate teardown

Commit 412e6037324 ("spi: core: avoid waking pump thread from spi_sync
instead run teardown delayed") introduced regressions on some boards,
apparently connected to spi_mem not triggering shutdown properly any
more. Since we've thus far been unable to figure out exactly where the
breakage is revert the optimisation for now.

Reported-by: Jon Hunter <jonathanh@nvidia.com>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: kernel@martin.sperl.org


# 412e6037 07-Jan-2019 Martin Sperl <kernel@martin.sperl.org>

spi: core: avoid waking pump thread from spi_sync instead run teardown delayed

When spi_sync is running alone with no other spi devices connected
to the bus the worker thread is woken during spi_finalize_current_message
to run the teardown code every time.

This is totally unnecessary in the case that there is no message queued.

On a multi-core system this results in one wakeup of the thread for each
spi_message processed via spi_sync where in most cases the teardown does
not happen as the hw is already in use.

This patch now delays the teardown by 1 second by using a separate
kthread_delayed_work for the teardown.

This avoids waking the kthread too often.

For spi_sync transfers in a tight loop (say 40k messages/s) this
avoids the penalty of waking the worker thread 40k times/s.
On a rasperry pi 3 with 4 cores the results in 32% of a single core
only to find out that there is nothing in the queue and it can go back
to sleep.

With this patch applied the spi-worker is woken exactly once: after
the load finishes and the spi bus is idle for 1 second.

I believe I have also seen situations where during a spi_sync loop
the worker thread (triggered by the last message finished) is slightly
faster and _wins_ the race to process the message, so we are actually
running the kthread and letting it do some work...

This is also no longer observed with this patch applied as.

Tested with a new CAN controller driver for the mcp2517fd which
uses spi_sync for interrupt handling and spi_async for scheduling
of can frames for transmission (in a different thread)

Some statistics when receiving 100000 CAN frames with the mcp25xxfd driver
on a Raspberry pi 3:

without the patch:
------------------
root@raspcm3:~# for x in $(pgrep spi0) $(pgrep irq/94-mcp25xxf) ; do awk '{printf "%-20s %6i\n", $2,$15}' /proc/$x/stat; done
(spi0) 5
(irq/94-mcp25xxf) 0
root@raspcm3:~# vmstat 1
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 0 821960 13592 50848 0 0 80 2 1986 105 1 2 97 0 0
0 0 0 821968 13592 50876 0 0 0 0 8046 30 0 0 100 0 0
0 0 0 821936 13592 50876 0 0 0 0 8032 24 0 0 100 0 0
0 0 0 821936 13592 50876 0 0 0 0 8035 30 0 0 100 0 0
0 0 0 821936 13592 50876 0 0 0 0 8033 22 0 0 100 0 0
2 0 0 821936 13592 50876 0 0 0 0 11598 7129 0 3 97 0 0
1 0 0 821872 13592 50876 0 0 0 0 37741 59003 0 31 69 0 0
2 0 0 821840 13592 50876 0 0 0 0 37762 59078 0 29 71 0 0
2 0 0 821776 13592 50876 0 0 0 0 37593 58792 0 28 72 0 0
1 0 0 821744 13592 50876 0 0 0 0 37642 58881 0 30 70 0 0
2 0 0 821680 13592 50876 0 0 0 0 37490 58602 0 27 73 0 0
1 0 0 821648 13592 50876 0 0 0 0 37412 58418 0 29 71 0 0
1 0 0 821584 13592 50876 0 0 0 0 37337 58288 0 27 73 0 0
1 0 0 821552 13592 50876 0 0 0 0 37584 58774 0 27 73 0 0
0 0 0 821520 13592 50876 0 0 0 0 18363 20566 0 9 91 0 0
0 0 0 821520 13592 50876 0 0 0 0 8037 32 0 0 100 0 0
0 0 0 821520 13592 50876 0 0 0 0 8031 23 0 0 100 0 0
0 0 0 821520 13592 50876 0 0 0 0 8034 26 0 0 100 0 0
0 0 0 821520 13592 50876 0 0 0 0 8033 24 0 0 100 0 0
^C
root@raspcm3:~# for x in $(pgrep spi0) $(pgrep irq/94-mcp25xxf) ; do awk '{printf "%-20s %6i\n", $2,$15}' /proc/$x/stat; done
(spi0) 228
(irq/94-mcp25xxf) 794
root@raspcm3:~# cat /proc/interrupts
CPU0 CPU1 CPU2 CPU3
17: 34 0 0 0 ARMCTRL-level 1 Edge 3f00b880.mailbox
27: 1 0 0 0 ARMCTRL-level 35 Edge timer
33: 1416870 0 0 0 ARMCTRL-level 41 Edge 3f980000.usb, dwc2_hsotg:usb1
34: 1 0 0 0 ARMCTRL-level 42 Edge vc4
35: 0 0 0 0 ARMCTRL-level 43 Edge 3f004000.txp
40: 1753 0 0 0 ARMCTRL-level 48 Edge DMA IRQ
42: 11 0 0 0 ARMCTRL-level 50 Edge DMA IRQ
44: 11 0 0 0 ARMCTRL-level 52 Edge DMA IRQ
45: 0 0 0 0 ARMCTRL-level 53 Edge DMA IRQ
66: 0 0 0 0 ARMCTRL-level 74 Edge vc4 crtc
69: 0 0 0 0 ARMCTRL-level 77 Edge vc4 crtc
70: 0 0 0 0 ARMCTRL-level 78 Edge vc4 crtc
77: 20 0 0 0 ARMCTRL-level 85 Edge 3f205000.i2c, 3f804000.i2c, 3f805000.i2c
78: 6346 0 0 0 ARMCTRL-level 86 Edge 3f204000.spi
80: 205 0 0 0 ARMCTRL-level 88 Edge mmc0
81: 493 0 0 0 ARMCTRL-level 89 Edge uart-pl011
89: 0 0 0 0 bcm2836-timer 0 Edge arch_timer
90: 4291 3821 2180 1649 bcm2836-timer 1 Edge arch_timer
94: 14289 0 0 0 pinctrl-bcm2835 16 Level mcp25xxfd
IPI0: 0 0 0 0 CPU wakeup interrupts
IPI1: 0 0 0 0 Timer broadcast interrupts
IPI2: 3645 242371 7919 1328 Rescheduling interrupts
IPI3: 112 543 273 194 Function call interrupts
IPI4: 0 0 0 0 CPU stop interrupts
IPI5: 1 0 0 0 IRQ work interrupts
IPI6: 0 0 0 0 completion interrupts
Err: 0

top shows 93% for the mcp25xxfd interrupt handler, 31% for spi0.

with the patch:
---------------
root@raspcm3:~# for x in $(pgrep spi0) $(pgrep irq/94-mcp25xxf) ; do awk '{printf "%-20s %6i\n", $2,$15}' /proc/$x/stat; done
(spi0) 0
(irq/94-mcp25xxf) 0
root@raspcm3:~# vmstat 1
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
0 0 0 804768 13584 62628 0 0 0 0 8038 24 0 0 100 0 0
0 0 0 804768 13584 62628 0 0 0 0 8042 25 0 0 100 0 0
1 0 0 804704 13584 62628 0 0 0 0 9603 2967 0 20 80 0 0
1 0 0 804672 13584 62628 0 0 0 0 9828 3380 0 24 76 0 0
1 0 0 804608 13584 62628 0 0 0 0 9823 3375 0 23 77 0 0
1 0 0 804608 13584 62628 0 0 0 12 9829 3394 0 23 77 0 0
1 0 0 804544 13584 62628 0 0 0 0 9816 3362 0 22 78 0 0
1 0 0 804512 13584 62628 0 0 0 0 9817 3367 0 23 77 0 0
1 0 0 804448 13584 62628 0 0 0 0 9822 3370 0 22 78 0 0
1 0 0 804416 13584 62628 0 0 0 0 9815 3367 0 23 77 0 0
0 0 0 804352 13584 62628 0 0 0 84 9222 2250 0 14 86 0 0
0 0 0 804352 13592 62620 0 0 0 24 8131 209 0 0 93 7 0
0 0 0 804320 13592 62628 0 0 0 0 8041 27 0 0 100 0 0
0 0 0 804352 13592 62628 0 0 0 0 8040 26 0 0 100 0 0
root@raspcm3:~# for x in $(pgrep spi0) $(pgrep irq/94-mcp25xxf) ; do awk '{printf "%-20s %6i\n", $2,$15}' /proc/$x/stat; done
(spi0) 0
(irq/94-mcp25xxf) 767
root@raspcm3:~# cat /proc/interrupts
CPU0 CPU1 CPU2 CPU3
17: 29 0 0 0 ARMCTRL-level 1 Edge 3f00b880.mailbox
27: 1 0 0 0 ARMCTRL-level 35 Edge timer
33: 1024412 0 0 0 ARMCTRL-level 41 Edge 3f980000.usb, dwc2_hsotg:usb1
34: 1 0 0 0 ARMCTRL-level 42 Edge vc4
35: 0 0 0 0 ARMCTRL-level 43 Edge 3f004000.txp
40: 1773 0 0 0 ARMCTRL-level 48 Edge DMA IRQ
42: 11 0 0 0 ARMCTRL-level 50 Edge DMA IRQ
44: 11 0 0 0 ARMCTRL-level 52 Edge DMA IRQ
45: 0 0 0 0 ARMCTRL-level 53 Edge DMA IRQ
66: 0 0 0 0 ARMCTRL-level 74 Edge vc4 crtc
69: 0 0 0 0 ARMCTRL-level 77 Edge vc4 crtc
70: 0 0 0 0 ARMCTRL-level 78 Edge vc4 crtc
77: 20 0 0 0 ARMCTRL-level 85 Edge 3f205000.i2c, 3f804000.i2c, 3f805000.i2c
78: 6417 0 0 0 ARMCTRL-level 86 Edge 3f204000.spi
80: 237 0 0 0 ARMCTRL-level 88 Edge mmc0
81: 489 0 0 0 ARMCTRL-level 89 Edge uart-pl011
89: 0 0 0 0 bcm2836-timer 0 Edge arch_timer
90: 4048 3704 2383 1892 bcm2836-timer 1 Edge arch_timer
94: 14287 0 0 0 pinctrl-bcm2835 16 Level mcp25xxfd
IPI0: 0 0 0 0 CPU wakeup interrupts
IPI1: 0 0 0 0 Timer broadcast interrupts
IPI2: 2361 2948 7890 1616 Rescheduling interrupts
IPI3: 65 617 301 166 Function call interrupts
IPI4: 0 0 0 0 CPU stop interrupts
IPI5: 1 0 0 0 IRQ work interrupts
IPI6: 0 0 0 0 completion interrupts
Err: 0
top shows 91% for the mcp25xxfd interrupt handler, 0% for spi0

So we see that spi0 is no longer getting scheduled wasting CPU cycles
There are a lot less context switches and corresponding Rescheduling interrupts
All of these show that this improves efficiency of the system and reduces
CPU utilization.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# f3186dd8 07-Jan-2019 Linus Walleij <linus.walleij@linaro.org>

spi: Optionally use GPIO descriptors for CS GPIOs

This augments the SPI core to optionally use GPIO descriptors
for chip select on a per-master-driver opt-in basis.

Drivers using this will rely on the SPI core to look up
GPIO descriptors associated with the device, such as
when using device tree or board files with GPIO descriptor
tables.

When getting descriptors from the device tree, this will in
turn activate the code in gpiolib that was
added in commit 6953c57ab172
("gpio: of: Handle SPI chipselect legacy bindings")
which means that these descriptors are aware of the active
low semantics that is the default for SPI CS GPIO lines
and we can assume that all of these are "active high" and
thus assign SPI_CS_HIGH to all CS lines on the DT path.

The previously used gpio_set_value() would call down into
gpiod_set_raw_value() and ignore the polarity inversion
semantics.

It seems like many drivers go to great lengths to set up the
CS GPIO line as non-asserted, respecting SPI_CS_HIGH. We pull
this out of the SPI drivers and into the core, and by simply
requesting the line as GPIOD_OUT_LOW when retrieveing it from
the device and relying on the gpiolib to handle any inversion
semantics. This way a lot of code can be simplified and
removed in each converted driver.

The end goal after dealing with each driver in turn, is to
delete the non-descriptor path (of_spi_register_master() for
example) and let the core deal with only descriptors.

The different SPI drivers have complex interactions with the
core so we cannot simply change them all over, we need to use
a stepwise, bisectable approach so that each driver can be
converted and fixed in isolation.

This patch has the intended side effect of adding support for
ACPI GPIOs as it starts relying on gpiod_get_*() to get
the GPIO handle associated with the device.

Cc: Linuxarm <linuxarm@huawei.com>
Acked-by: Jonathan Cameron <jonathan.cameron@huawei.com>
Tested-by: Fangjian (Turing) <f.fangjian@huawei.com>
Signed-off-by: Linus Walleij <linus.walleij@linaro.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 194276b0 05-Dec-2018 Rob Herring <robh@kernel.org>

spi: Use of_node_name_eq for node name comparisons

Convert string compares of DT node names to use of_node_name_eq helper
instead. This removes direct access to the node name pointer.

Signed-off-by: Rob Herring <robh@kernel.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6b03061f 03-Dec-2018 Yogesh Narayan Gaur <yogeshnarayan.gaur@nxp.com>

spi: add support for octal mode I/O data transfer

Add flags for Octal mode I/O data transfer
Required for the SPI controller which can do the data transfer (TX/RX)
on 8 data lines e.g. NXP FlexSPI controller.
SPI_TX_OCTAL: transmit with 8 wires
SPI_RX_OCTAL: receive with 8 wires

Signed-off-by: Yogesh Gaur <yogeshnarayan.gaur@nxp.com>
Reviewed-by: Boris Brezillon <boris.brezillon@bootlin.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 787f4889 29-Nov-2018 Mark Brown <broonie@kernel.org>

spi: Fix formatting of header block

Make everything look intentional by having a C++ comment for the whole
block, not just the SPDX line.

Signed-off-by: Mark Brown <broonie@kernel.org>


# d57e7960 15-Nov-2018 Mark Brown <broonie@kernel.org>

spi: Fix core transfer waits after slave support

The refactoring done as part of adding the core support for handling
waiting for slave transfer dropped a conditional which meant that we
started waiting for completion of all transfers, not just those that the
controller asked for. This caused hangs and massive delays on platforms
that don't need the core delay. Re-add the delay to fix this.

Fixes: 810923f3bf06c11 (spi: Deal with slaves that return from transfer_one() unfinished)
Reported-by: Tony Lindgren <tony@atomide.com>
Tested-by: Tony Lindgren <tony@atomide.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 810923f3 13-Nov-2018 Lubomir Rintel <lkundrak@v3.sk>

spi: Deal with slaves that return from transfer_one() unfinished

Some drivers, such as spi-pxa2xx return from the transfer_one callback
immediately, idicating that the transfer will be finished asynchronously.

Normally, spi_transfer_one_message() synchronously waits for the
transfer to finish with wait_for_completion_timeout(). For slaves, we
don't want the transaction to time out as it can complete in a long time
in future. Use wait_for_completion_interruptible() instead.

Signed-off-by: Lubomir Rintel <lkundrak@v3.sk>
Acked-by: Pavel Machek <pavel@ucw.cz>
Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 25972d0c 12-Oct-2018 Phil Elwell <phil@raspberrypi.org>

spi: Make GPIO CSs honour the SPI_NO_CS flag

The SPI configuration state includes an SPI_NO_CS flag that disables
all CS line manipulation, for applications that want to manage their
own chip selects. However, this flag is ignored by the GPIO CS code
in the SPI framework.

Correct this omission with a trivial patch.

Signed-off-by: Phil Elwell <phil@raspberrypi.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5039563e 20-Sep-2018 Trent Piepho <tpiepho@impinj.com>

spi: Add driver_override SPI device attribute

This attribute works the same was as the identically named attribute
for PCI, AMBA, and platform devices. For reference, see:

commit 3cf385713460 ("ARM: 8256/1: driver coamba: add device binding
path 'driver_override'")
commit 3d713e0e382e ("driver core: platform: add device binding path
'driver_override'")
commit 782a985d7af2 ("PCI: Introduce new device binding path using
pci_dev.driver_override")

If the name of a driver is written to this attribute, then the device
will bind to the named driver and only the named driver.

The device will bind to the driver even if the driver does not list the
device in its id table. This behavior is different than the driver's
bind attribute, which only allows binding to devices that are listed as
supported by the driver.

It can be used to bind a generic driver, like spidev, to a device.

Signed-off-by: Trent Piepho <tpiepho@impinj.com>
Reviewed-by: Jan Kundrát <jan.kundrat@cesnet.cz>
Tested-by: Jan Kundrát <jan.kundrat@cesnet.cz>
Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5f143af7 25-Sep-2018 Marco Felsch <m.felsch@pengutronix.de>

spi: make OF helper available for others

The of_find_spi_device_by_node() helper function is useful for other
modules too. Export the funciton as GPL like all other spi helper
functions and make it available if CONFIG_OF is enabled, because it isn't
related to the CONFIG_OF_DYNAMIC context. Finally add a stub if
CONFIG_OF isn't enabled, so others must not care about it.

Signed-off-by: Marco Felsch <m.felsch@pengutronix.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# b445bfcb 25-Sep-2018 Marco Felsch <m.felsch@pengutronix.de>

spi: switch to SPDX license identifier

Use the appropriate SPDX license identifier and drop the previous
license text.

Signed-off-by: Marco Felsch <m.felsch@pengutronix.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 71388b21 17-Sep-2018 David Lechner <david@lechnology.com>

spi: always use software fallback for SPI_CS_WORD when using cs_gio

This modifies the condition for using the software fallback
implementation for SPI_CS_WORD when the SPI controller is using a GPIO
for the CS line. When using a GPIO for CS, the hardware implementation
won't work, so we just enable the software fallback globally in this
case.

Signed-off-by: David Lechner <david@lechnology.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# cbaa62e0 12-Sep-2018 David Lechner <david@lechnology.com>

spi: add software implementation for SPI_CS_WORD

This adds a default software implementation for the SPI_CS_WORD flag for
controllers that don't have such a feature.

The SPI_CS_WORD flag indicates that the CS line should be toggled
between each word sent, not just between each transfer. The
implementation works by using existing functions to split transfers into
one-word-sized transfers and sets the cs_change bit for each of the
new transfers.

Signed-off-by: David Lechner <david@lechnology.com>
Acked-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 04b2d03a 21-Aug-2018 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Fix double IDR allocation with DT aliases

If the SPI bus number is provided by a DT alias, idr_alloc() is called
twice, leading to:

WARNING: CPU: 1 PID: 1 at drivers/spi/spi.c:2179 spi_register_controller+0x11c/0x5d8
couldn't get idr

Fix this by moving the handling of fixed SPI bus numbers up, before the
DT handling code fills in ctlr->bus_num.

Fixes: 1a4327fbf4554d5b ("spi: fix IDR collision on systems with both fixed and dynamic SPI bus numbers")
Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Tested-by: Fabio Estevam <fabio.estevam@nxp.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 1a4327fb 13-Aug-2018 Kirill Kapranov <kirill.kapranov@compulab.co.il>

spi: fix IDR collision on systems with both fixed and dynamic SPI bus numbers

On systems where some controllers get a dynamic ID assigned and some have
a fixed number (e.g. from ACPI tables), the current implementation might
run into an IDR collision: in case of a fixed bus number is gotten by a
driver (but not marked busy in IDR tree) and a driver with dynamic bus
number gets the same ID and predictably fails.

Fix this by means of checking-in fixed IDsin IDR as far as dynamic ones
at the moment of the controller registration.

Fixes: 9b61e302210e (spi: Pick spi bus number from Linux idr or spi alias)
Signed-off-by: Kirill Kapranov <kirill.kapranov@compulab.co.il>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# a86854d0 12-Jun-2018 Kees Cook <keescook@chromium.org>

treewide: devm_kzalloc() -> devm_kcalloc()

The devm_kzalloc() function has a 2-factor argument form, devm_kcalloc().
This patch replaces cases of:

devm_kzalloc(handle, a * b, gfp)

with:
devm_kcalloc(handle, a * b, gfp)

as well as handling cases of:

devm_kzalloc(handle, a * b * c, gfp)

with:

devm_kzalloc(handle, array3_size(a, b, c), gfp)

as it's slightly less ugly than:

devm_kcalloc(handle, array_size(a, b), c, gfp)

This does, however, attempt to ignore constant size factors like:

devm_kzalloc(handle, 4 * 1024, gfp)

though any constants defined via macros get caught up in the conversion.

Any factors with a sizeof() of "unsigned char", "char", and "u8" were
dropped, since they're redundant.

Some manual whitespace fixes were needed in this patch, as Coccinelle
really liked to write "=devm_kcalloc..." instead of "= devm_kcalloc...".

The Coccinelle script used for this was:

// Fix redundant parens around sizeof().
@@
expression HANDLE;
type TYPE;
expression THING, E;
@@

(
devm_kzalloc(HANDLE,
- (sizeof(TYPE)) * E
+ sizeof(TYPE) * E
, ...)
|
devm_kzalloc(HANDLE,
- (sizeof(THING)) * E
+ sizeof(THING) * E
, ...)
)

// Drop single-byte sizes and redundant parens.
@@
expression HANDLE;
expression COUNT;
typedef u8;
typedef __u8;
@@

(
devm_kzalloc(HANDLE,
- sizeof(u8) * (COUNT)
+ COUNT
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(__u8) * (COUNT)
+ COUNT
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(char) * (COUNT)
+ COUNT
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(unsigned char) * (COUNT)
+ COUNT
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(u8) * COUNT
+ COUNT
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(__u8) * COUNT
+ COUNT
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(char) * COUNT
+ COUNT
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(unsigned char) * COUNT
+ COUNT
, ...)
)

// 2-factor product with sizeof(type/expression) and identifier or constant.
@@
expression HANDLE;
type TYPE;
expression THING;
identifier COUNT_ID;
constant COUNT_CONST;
@@

(
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(TYPE) * (COUNT_ID)
+ COUNT_ID, sizeof(TYPE)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(TYPE) * COUNT_ID
+ COUNT_ID, sizeof(TYPE)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(TYPE) * (COUNT_CONST)
+ COUNT_CONST, sizeof(TYPE)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(TYPE) * COUNT_CONST
+ COUNT_CONST, sizeof(TYPE)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(THING) * (COUNT_ID)
+ COUNT_ID, sizeof(THING)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(THING) * COUNT_ID
+ COUNT_ID, sizeof(THING)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(THING) * (COUNT_CONST)
+ COUNT_CONST, sizeof(THING)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(THING) * COUNT_CONST
+ COUNT_CONST, sizeof(THING)
, ...)
)

// 2-factor product, only identifiers.
@@
expression HANDLE;
identifier SIZE, COUNT;
@@

- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- SIZE * COUNT
+ COUNT, SIZE
, ...)

// 3-factor product with 1 sizeof(type) or sizeof(expression), with
// redundant parens removed.
@@
expression HANDLE;
expression THING;
identifier STRIDE, COUNT;
type TYPE;
@@

(
devm_kzalloc(HANDLE,
- sizeof(TYPE) * (COUNT) * (STRIDE)
+ array3_size(COUNT, STRIDE, sizeof(TYPE))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(TYPE) * (COUNT) * STRIDE
+ array3_size(COUNT, STRIDE, sizeof(TYPE))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(TYPE) * COUNT * (STRIDE)
+ array3_size(COUNT, STRIDE, sizeof(TYPE))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(TYPE) * COUNT * STRIDE
+ array3_size(COUNT, STRIDE, sizeof(TYPE))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(THING) * (COUNT) * (STRIDE)
+ array3_size(COUNT, STRIDE, sizeof(THING))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(THING) * (COUNT) * STRIDE
+ array3_size(COUNT, STRIDE, sizeof(THING))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(THING) * COUNT * (STRIDE)
+ array3_size(COUNT, STRIDE, sizeof(THING))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(THING) * COUNT * STRIDE
+ array3_size(COUNT, STRIDE, sizeof(THING))
, ...)
)

// 3-factor product with 2 sizeof(variable), with redundant parens removed.
@@
expression HANDLE;
expression THING1, THING2;
identifier COUNT;
type TYPE1, TYPE2;
@@

(
devm_kzalloc(HANDLE,
- sizeof(TYPE1) * sizeof(TYPE2) * COUNT
+ array3_size(COUNT, sizeof(TYPE1), sizeof(TYPE2))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(TYPE1) * sizeof(THING2) * (COUNT)
+ array3_size(COUNT, sizeof(TYPE1), sizeof(TYPE2))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(THING1) * sizeof(THING2) * COUNT
+ array3_size(COUNT, sizeof(THING1), sizeof(THING2))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(THING1) * sizeof(THING2) * (COUNT)
+ array3_size(COUNT, sizeof(THING1), sizeof(THING2))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(TYPE1) * sizeof(THING2) * COUNT
+ array3_size(COUNT, sizeof(TYPE1), sizeof(THING2))
, ...)
|
devm_kzalloc(HANDLE,
- sizeof(TYPE1) * sizeof(THING2) * (COUNT)
+ array3_size(COUNT, sizeof(TYPE1), sizeof(THING2))
, ...)
)

// 3-factor product, only identifiers, with redundant parens removed.
@@
expression HANDLE;
identifier STRIDE, SIZE, COUNT;
@@

(
devm_kzalloc(HANDLE,
- (COUNT) * STRIDE * SIZE
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
|
devm_kzalloc(HANDLE,
- COUNT * (STRIDE) * SIZE
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
|
devm_kzalloc(HANDLE,
- COUNT * STRIDE * (SIZE)
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
|
devm_kzalloc(HANDLE,
- (COUNT) * (STRIDE) * SIZE
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
|
devm_kzalloc(HANDLE,
- COUNT * (STRIDE) * (SIZE)
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
|
devm_kzalloc(HANDLE,
- (COUNT) * STRIDE * (SIZE)
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
|
devm_kzalloc(HANDLE,
- (COUNT) * (STRIDE) * (SIZE)
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
|
devm_kzalloc(HANDLE,
- COUNT * STRIDE * SIZE
+ array3_size(COUNT, STRIDE, SIZE)
, ...)
)

// Any remaining multi-factor products, first at least 3-factor products,
// when they're not all constants...
@@
expression HANDLE;
expression E1, E2, E3;
constant C1, C2, C3;
@@

(
devm_kzalloc(HANDLE, C1 * C2 * C3, ...)
|
devm_kzalloc(HANDLE,
- (E1) * E2 * E3
+ array3_size(E1, E2, E3)
, ...)
|
devm_kzalloc(HANDLE,
- (E1) * (E2) * E3
+ array3_size(E1, E2, E3)
, ...)
|
devm_kzalloc(HANDLE,
- (E1) * (E2) * (E3)
+ array3_size(E1, E2, E3)
, ...)
|
devm_kzalloc(HANDLE,
- E1 * E2 * E3
+ array3_size(E1, E2, E3)
, ...)
)

// And then all remaining 2 factors products when they're not all constants,
// keeping sizeof() as the second factor argument.
@@
expression HANDLE;
expression THING, E1, E2;
type TYPE;
constant C1, C2, C3;
@@

(
devm_kzalloc(HANDLE, sizeof(THING) * C2, ...)
|
devm_kzalloc(HANDLE, sizeof(TYPE) * C2, ...)
|
devm_kzalloc(HANDLE, C1 * C2 * C3, ...)
|
devm_kzalloc(HANDLE, C1 * C2, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(TYPE) * (E2)
+ E2, sizeof(TYPE)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(TYPE) * E2
+ E2, sizeof(TYPE)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(THING) * (E2)
+ E2, sizeof(THING)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- sizeof(THING) * E2
+ E2, sizeof(THING)
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- (E1) * E2
+ E1, E2
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- (E1) * (E2)
+ E1, E2
, ...)
|
- devm_kzalloc
+ devm_kcalloc
(HANDLE,
- E1 * E2
+ E1, E2
, ...)
)

Signed-off-by: Kees Cook <keescook@chromium.org>


# 7e48e23a 18-May-2018 Tony Lindgren <tony@atomide.com>

spi: Add missing pm_runtime_put_noidle() after failed get

If pm_runtime_get_sync() fails we should call pm_runtime_put_noidle().
This is probably not a critical fix as we should only hit this when
things are broken elsewhere.

Signed-off-by: Tony Lindgren <tony@atomide.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 71f277a7 26-Apr-2018 Ulf Hansson <ulf.hansson@linaro.org>

spi: Respect all error codes from dev_pm_domain_attach()

The limitation of being able to check only for -EPROBE_DEFER from
dev_pm_domain_attach() has been removed. Hence let's respect all error
codes and bail out accordingly.

Signed-off-by: Ulf Hansson <ulf.hansson@linaro.org>
Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# c1f5ba70 26-Apr-2018 Boris Brezillon <bbrezillon@kernel.org>

spi: Get rid of the spi_flash_read() API

This API has been replaced by the spi_mem_xx() one, its only user
(spi-nor) has been converted to spi_mem_xx() and all SPI controller
drivers that were implementing the ->spi_flash_xxx() hooks are also
implementing the spi_mem ones. So we can safely get rid of this API.

Signed-off-by: Boris Brezillon <boris.brezillon@bootlin.com>
Reviewed-by: Frieder Schrempf <frieder.schrempf@exceet.de>
Tested-by: Frieder Schrempf <frieder.schrempf@exceet.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# b5932f5c 26-Apr-2018 Boris Brezillon <bbrezillon@kernel.org>

spi: Make support for regular transfers optional when ->mem_ops != NULL

Some SPI/QuadSPI controllers only expose a high-level SPI memory
interface, thus preventing any regular SPI transfers from being done.

In that case, SPI controller drivers can leave all ->transfer_xxx()
hooks empty and only implement the spi_mem_ops interface.

Adjust the core to allow such situations:
- extend spi_controller_check_ops() to accept situations where all
->transfer_xxx() pointers are NULL only if ->mem_ops != NULL
- make sure we do not initialize the SPI message queue if
ctlr->transfer_one and ctlr->transfer_one_message are missing
- return -ENOTSUPP if someone tries to do a regular SPI transfer on
a controller that does not support it

Signed-off-by: Boris Brezillon <boris.brezillon@bootlin.com>
Reviewed-by: Frieder Schrempf <frieder.schrempf@exceet.de>
Tested-by: Frieder Schrempf <frieder.schrempf@exceet.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# bdf3a3b5 10-Apr-2018 Boris Brezillon <bbrezillon@kernel.org>

spi: Check presence the of ->transfer[_xxx]() before registering a controller

Right now, no checks are done on the presence of a ->transfer[_xxx]()
method, which can lead to a NULL pointer dereference when someone
starts sending something on the bus.

Do the check at registration time and refuse to add the controller if
all ->transfer[_xxx]() pointers are NULL.

Signed-off-by: Boris Brezillon <boris.brezillon@bootlin.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 988f259b 22-Apr-2018 Boris Brezillon <bbrezillon@kernel.org>

spi: Add an helper to flush the message queue

This is needed by the spi-mem logic to force all messages that have been
queued before a memory operation to be sent before we start the memory
operation. We do that in order to guarantee that spi-mem operations do
not preempt regular SPI transfers.

Signed-off-by: Boris Brezillon <boris.brezillon@bootlin.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 46336966 22-Apr-2018 Boris Brezillon <bbrezillon@kernel.org>

spi: Expose spi_{map,unmap}_buf() for internal use

spi_{map,unmap}_buf() are needed by the spi-mem logic that is about to
be introduced to prepare data buffer for DMA operations.

Remove the static specifier on these functions and add their prototypes
to drivers/spi/internals.h. We do not export the symbols here because
both SPI_MEM and SPI can't be enabled as modules and we'd like to
prevent controller/device drivers from using these functions.

Signed-off-by: Boris Brezillon <boris.brezillon@bootlin.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 613bd1ea 20-Mar-2018 Jarkko Nikula <jarkko.nikula@linux.intel.com>

spi: Fix unregistration of controller with fixed SPI bus number

Commit 9b61e302210e (spi: Pick spi bus number from Linux idr or spi alias)
ceased to unregister SPI buses with fixed bus numbers. Moreover this is
visible only if CONFIG_SPI_DEBUG=y is set or when trying to re-register
the same SPI controller.

rmmod spi_pxa2xx_platform (with CONFIG_SPI_DEBUG=y):
[ 26.788362] spi_master spi1: attempting to delete unregistered controller [spi1]

modprobe spi_pxa2xx_platform:
[ 37.883137] sysfs: cannot create duplicate filename '/devices/pci0000:00/0000:00:19.0/pxa2xx-spi.12/spi_master/spi1'
[ 37.894984] CPU: 1 PID: 1467 Comm: modprobe Not tainted 4.16.0-rc4+ #21
[ 37.902384] Call Trace:
...
[ 38.122680] kobject_add_internal failed for spi1 with -EEXIST, don't try to register things with the same name in the same directory.
[ 38.136154] WARNING: CPU: 1 PID: 1467 at lib/kobject.c:238 kobject_add_internal+0x2a5/0x2f0
...
[ 38.513817] pxa2xx-spi pxa2xx-spi.12: problem registering spi master
[ 38.521036] pxa2xx-spi: probe of pxa2xx-spi.12 failed with error -17

Fix this by not returning immediately from spi_unregister_controller() if
idr_find() doesn't find controller with given ID/bus number. It finds
only those controllers that were registered with dynamic SPI bus
numbers. Only conditional cleanup between dynamic and fixed bus numbers
is to remove allocated IDR.

Fixes: 9b61e302210e (spi: Pick spi bus number from Linux idr or spi alias)
Cc: stable@vger.kernel.org
Signed-off-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ce99319a 02-Mar-2018 Maxime Chevallier <maxime.chevallier@bootlin.com>

spi: Fix scatterlist elements size in spi_map_buf

When SPI transfers can be offloaded using DMA, the SPI core need to
build a scatterlist to make sure that the buffer to be transferred is
dma-able.

This patch fixes the scatterlist entry size computation in the case
where the maximum acceptable scatterlist entry supported by the DMA
controller is less than PAGE_SIZE, when the buffer is vmalloced.

For each entry, the actual size is given by the minimum between the
desc_len (which is the max buffer size supported by the DMA controller)
and the remaining buffer length until we cross a page boundary.

Fixes: 65598c13fd66 ("spi: Fix per-page mapping of unaligned vmalloc-ed buffer")
Signed-off-by: Maxime Chevallier <maxime.chevallier@bootlin.com>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# 42bdd706 15-Oct-2017 Lucas Stach <l.stach@pengutronix.de>

spi: fix IDR collision on systems with both fixed and dynamic SPI bus numbers

On systems where some controllers get a dynamic ID assigned and some have
a fixed number from DT, the current implemention might run into an IDR
collision if the dynamic controllers gets probed first and get an IDR number,
which is later requested by the controller with the fixed numbering. When
this happens the fixed controller will fail to register with the SPI core.

Fix this by skipping all known alias numbers when assigning the dynamic IDs.

Fixes: 9b61e302210e (spi: Pick spi bus number from Linux idr or spi alias)
Signed-off-by: Lucas Stach <l.stach@pengutronix.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 68b892f1 30-Oct-2017 Johan Hovold <johan@kernel.org>

spi: document odd controller reference handling

Document the fact that a reference to the controller is dropped as part
of deregistration.

This is an odd pattern as the reference is typically taken in
__spi_alloc_controller() rather than spi_register_controller(). Most
controller drivers gets it right these days and notably the
device-managed interface relies on this behaviour.

Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 67f7b278 30-Oct-2017 Johan Hovold <johan@kernel.org>

spi: fix use-after-free at controller deregistration

The controller is typically freed as part of device_unregister() so
store the bus id before deregistration to avoid use-after-free when the
id is later released.

Fixes: 9b61e302210e ("spi: Pick spi bus number from Linux idr or spi alias")
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable <stable@vger.kernel.org>


# 226584ae 15-Oct-2017 Lucas Stach <l.stach@pengutronix.de>

spi: fix IDR collision on systems with both fixed and dynamic SPI bus numbers

On systems where some controllers get a dynamic ID assigned and some have
a fixed number from DT, the current implemention might run into an IDR
collision if the dynamic controllers gets probed first and get an IDR number,
which is later requested by the controller with the fixed numbering. When
this happens the fixed controller will fail to register with the SPI core.

Fix this by skipping all known alias numbers when assigning the dynamic IDs.

Fixes: 9b61e302210e (spi: Pick spi bus number from Linux idr or spi alias)
Signed-off-by: Lucas Stach <l.stach@pengutronix.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9a9a047a 17-Aug-2017 Suniel Mahesh <sunil.m@techveda.org>

spi: Kernel coding style fixes

Earlier commit:
"spi: Pick spi bus number from Linux idr or spi alias"
(SHA1:9b61e302210eba55768962f2f11e96bb508c2408)
has introduced some checkpatch issues. As pointed by
Lukas Wunner this patch does the following:
- remove whitespaces
- fix warnings, suspect code indent for conditional statements
- fix errors, code indent should use tabs
- remove spaces at the start of the line

Signed-off-by: Suniel Mahesh <sunil.m@techveda.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 9b61e302 02-Aug-2017 Suniel Mahesh <sunil.m@techveda.org>

spi: Pick spi bus number from Linux idr or spi alias

Modify existing code, for automatically picking the spi bus number based
on Linux idr scheme as mentioned in FIXME.
This patch does the following:
(a) Remove the now unnecessary code which was allocating bus numbers using
ATOMIC_INIT and atomic_dec_return macros.
(b) If we have an alias, pick the bus number from alias ID
(c) Convert to linux idr interface

Signed-off-by: Suniel Mahesh <sunil.m@techveda.org>
Signed-off-by: Karthik Tummala <karthik@techveda.org>
Tested-by: Karthik Tummala <karthik@techveda.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# e0bcb680 06-Aug-2017 Sergei Shtylyov <sergei.shtylyov@cogentembedded.com>

spi: use of_property_read_bool()

Use a bit more compact of_property_read_bool() calls instead of the
of_find_property() calls -- symmetrically with the of_property_read_u32()
calls already done in of_spi_parse_dt().

Signed-off-by: Sergei Shtylyov <sergei.shtylyov@cogentembedded.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8a2e487e 01-Aug-2017 Lukas Wunner <lukas@wunner.de>

spi: Use Apple device properties in absence of ACPI resources

MacBooks and MacBook Pros introduced since 2015 return empty _CRS data
for SPI slaves, causing device initialization to fail. Most of the
information that would normally be conveyed via _CRS is available
through ACPI device properties instead, so take advantage of them.

The meaning and appropriate usage of the device properties was reverse
engineered by Ronald Tschalär and carried over from these commits
authored by him:

https://github.com/cb22/macbook12-spi-driver/commit/9a416d699ef4
https://github.com/cb22/macbook12-spi-driver/commit/0c34936ed9a1

According to Ronald, the device properties have the following meaning:

spiSclkPeriod /* period in ns */
spiWordSize /* in number of bits */
spiBitOrder /* 1 = MSB_FIRST, 0 = LSB_FIRST */
spiSPO /* clock polarity: 0 = low, 1 = high */
spiSPH /* clock phase: 0 = first, 1 = second */
spiCSDelay /* delay between cs and receive on reads in 10 us */
resetA2RUsec /* active-to-receive delay? */
resetRecUsec /* receive delay? */

Reported-by: Leif Liddy <leif.liddy@gmail.com>
Tested-by: Ronald Tschalär <ronald@innovation.ch>
Acked-by: Mark Brown <broonie@kernel.org>
Acked-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Reviewed-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Lukas Wunner <lukas@wunner.de>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# 2856670f 26-Jul-2017 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: core: Propagate error code of add_uevent_var()

add_uevent_var() can fail, let caller know about this.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 25c56c88 18-Jul-2017 Rob Herring <robh@kernel.org>

spi: Convert to using %pOF instead of full_name

Now that we have a custom printf format specifier, convert users of
full_name to use %pOF instead. This is preparation to remove storing
of the full path string for each node.

Signed-off-by: Rob Herring <robh@kernel.org>
Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8caab75f 13-Jun-2017 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Generalize SPI "master" to "controller"

Now struct spi_master is used for both SPI master and slave controllers,
it makes sense to rename it to struct spi_controller, and replace
"master" by "controller" where appropriate.

For now this conversion is done for SPI core infrastructure only.
Wrappers are provided for backwards compatibility, until all SPI drivers
have been converted.

Noteworthy details:
- SPI_MASTER_GPIO_SS is retained, as it only makes sense for SPI
master controllers,
- spi_busnum_to_master() is retained, as it looks up masters only,
- A new field spi_device.controller is added, but spi_device.master is
retained for compatibility (both are always initialized by
spi_alloc_device()),
- spi_flash_read() is used by SPI masters only.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6c364062 22-May-2017 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Add support for registering SPI slave controllers

Add support for registering SPI slave controllers using the existing SPI
master framework:
- SPI slave controllers must use spi_alloc_slave() instead of
spi_alloc_master(), and should provide an additional callback
"slave_abort" to abort an ongoing SPI transfer request,
- SPI slave controllers are added to a new "spi_slave" device class,
- SPI slave handlers can be bound to the SPI slave device represented
by an SPI slave controller using a DT child node named "slave",
- Alternatively, (un)binding an SPI slave handler to the SPI slave
device represented by an SPI slave controller can be done by
(un)registering the slave device through a sysfs virtual file named
"slave".

From the point of view of an SPI slave protocol handler, an SPI slave
controller looks almost like an ordinary SPI master controller. The only
exception is that a transfer request will block on the remote SPI
master, and may be cancelled using spi_slave_abort().

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ad25c92e 04-May-2017 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Replace S_IRUGO permissions by 0444

Octal permissions are preferred over symbolic permissions.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# b56ffae8 04-May-2017 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Fix devm_spi_register_master() function name in kerneldoc

Fixes: 666d5b4c742ba666 ("spi: core: Add devm_spi_register_master()")
Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 2bca3445 11-Apr-2017 Vignesh R <vigneshr@ti.com>

spi: Add can_dma like interface for spi_flash_read

Add an interface analogous to ->can_dma() for spi_flash_read()
interface. This will enable SPI controller drivers to inform SPI core
when not to do DMA mappings.

Signed-off-by: Vignesh R <vigneshr@ti.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 833bfade 16-Apr-2017 Hauke Mehrtens <hauke@hauke-m.de>

spi: double time out tolerance

The generic SPI code calculates how long the issued transfer would take
and adds 100ms in addition to the timeout as tolerance. On my 500 MHz
Lantiq Mips SoC I am getting timeouts from the SPI like this when the
system boots up:

m25p80 spi32766.4: SPI transfer timed out
blk_update_request: I/O error, dev mtdblock3, sector 2
SQUASHFS error: squashfs_read_data failed to read block 0x6e

After increasing the tolerance for the timeout to 200ms I haven't seen
these SPI transfer time outs any more.
The Lantiq SPI driver in use here has an extra work queue in between,
which gets triggered when the controller send the last word and the
hardware FIFOs used for reading and writing are only 8 words long.

Signed-off-by: Hauke Mehrtens <hauke@hauke-m.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# f974cf57 28-Feb-2017 Dmitry Torokhov <dmitry.torokhov@gmail.com>

spi: allow registering empty spi_board_info lists

Many boards form list of spi_board_info entries depending on config,
and it is possible to end up with empty list. Do not report error
in such cases.

Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 826cf175 28-Feb-2017 Dmitry Torokhov <dmitry.torokhov@gmail.com>

spi: allow attaching device properties to SPI board info

Generic device properties support statically defined property sets. For
them to be usable, we need to attach these property sets before devices
are registered and probed. Allowing to attach property list to
spi_board_info structure will allow non-ACPI non-DT boards switch to using
generic properties and get rid of custom platform data.

Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ae7e81c0 01-Feb-2017 Ingo Molnar <mingo@kernel.org>

sched/headers: Prepare for new header dependencies before moving code to <uapi/linux/sched/types.h>

We are going to move scheduler ABI details to <uapi/linux/sched/types.h>,
which will be used from a number of .c files.

Create empty placeholder header that maps to <linux/types.h>.

Include the new header in the files that are going to need it.

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>


# 0c6543f6 05-Feb-2017 Dan O'Donovan <dan@emutex.com>

spi: acpi: Initialize modalias from of_compatible

When using devicetree spi_device.modalias is set to the compatible
string with the vendor prefix removed. For SPI devices described via
ACPI the spi_device.modalias string is initialized by acpi_device_hid.
When using ACPI and DT ids this string ends up something like "PRP0001".

Change acpi_register_spi_device to use the of_compatible property if
present. This makes it easier to instantiate spi drivers through ACPI
with DT ids.

Signed-off-by: Dan O'Donovan <dan@emutex.com>
Reviewed-by: Andy Shevchenko <andy.shevchenko@gmail.com>
Reviewed-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Tested-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# 8324147f 30-Jan-2017 Johan Hovold <johan@kernel.org>

spi: fix device-node leaks

Make sure to release the device-node reference taken in
of_register_spi_device() on errors and when deregistering the device.

Fixes: 284b01897340 ("spi: Add OF binding support for SPI busses")
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 88b0aa54 26-Jan-2017 Daniel Kurtz <djkurtz@chromium.org>

spi: When no dma_chan map buffers with spi_master's parent

Back before commit 1dccb598df54 ("arm64: simplify dma_get_ops"), for
arm64, devices for which dma_ops were not explicitly set were automatically
configured to use swiotlb_dma_ops, since this was hard-coded as the
global "dma_ops" in arm64_dma_init().

Now that global "dma_ops" has been removed, all devices much have their
dma_ops explicitly set by a call to arch_setup_dma_ops(), otherwise the
device is assigned dummy_dma_ops, and thus calls to map_sg for such a
device will fail (return 0).

Mediatek SPI uses DMA but does not use a dma channel. Support for this
was added by commit c37f45b5f1cd ("spi: support spi without dma channel
to use can_dma()"), which uses the master_spi dev to DMA map buffers.

The master_spi device is not a platform device, rather it is created
in spi_alloc_device(), and therefore its dma_ops are never set.

Therefore, when the mediatek SPI driver when it does DMA (for large SPI
transactions > 32 bytes), SPI will use spi_map_buf()->dma_map_sg() to
map the buffer for use in DMA. But dma_map_sg()->dma_map_sg_attrs() returns
0, because ops->map_sg is dummy_dma_ops->__dummy_map_sg, and hence
spi_map_buf() returns -ENOMEM (-12).

Fix this by using the real spi_master's parent device which should be a
real physical device with DMA properties.

Signed-off-by: Daniel Kurtz <djkurtz@chromium.org>
Fixes: c37f45b5f1cd ("spi: support spi without dma channel to use can_dma()")
Cc: Leilk Liu <leilk.liu@mediatek.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# f9bdb7fd 12-Jan-2017 Markus Elfring <elfring@users.sourceforge.net>

spi: Use kcalloc() in spi_register_board_info()

A multiplication for the size determination of a memory allocation
indicated that an array data structure should be processed.
Thus reuse the corresponding function "kcalloc".

This issue was detected by using the Coccinelle software.

Signed-off-by: Markus Elfring <elfring@users.sourceforge.net>
Signed-off-by: Mark Brown <broonie@kernel.org>


# c2e51ac3 12-Sep-2016 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Extract of_spi_parse_dt()

Extract the parsing of SPI slave-specific properties into its own
function, so it can be reused later for SPI slave controllers.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8dd4a016 21-Nov-2016 Juan Gutierrez <juan.gutierrez@nxp.com>

spi: use sg_next for walking through the allocated scatterlist table

A null dereference or Oops exception might occurs when reading at once the
whole content of an spi-nor of big enough size that requires an scatterlist
table that does not fit into one single page.

The spi_map_buf function is ignoring the chained sg case by dereferenceing
the scatterlist elements in an array fashion. This wrongly assumes that
the allocation of the scatterlist elements are contiguous. This is true as
long as the scatterlist table fits within a PAGE_SIZE. However, for
allocation where the scatter table is bigger than that, the pages allocated
by sg_alloc might not be contigous.

The sg table can be properly walked by sg_next instead of using an array.

Signed-off-by: Juan Gutierrez <juan.gutierrez@nxp.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8244bd3a 07-Oct-2016 Daniel Kurtz <djkurtz@chromium.org>

spi: change post transfer udelay() to usleep_range() for long delays

The spi_transfer parameter delay_usecs allows specifying a time to wait
after transferring a spi message. This wait can be quite long - some
devices, such as some Chrome OS ECs, require as much as 2000 usecs after
a SPI transaction, before it can respond.

(cf: arch/arm64/boot/dts/nvidia/tegra132-norrin.dts:
google,cros-ec-spi-msg-delay = <2000>
)

Blocking a CPU for 2 msecs in a busy loop like this doesn't seem very
friendly to other processes, so change the blocking delay to a sleep
to allow other things to use this CPU (or so it can sleep).

This should be safe to do, because:
(a) A post-transaction delay like this is always specified as a minimum
wait time
(b) A delay here is most likely not very time sensitive, as it occurs
after all data has been transferred
(c) This delay occurs in a non-critical section of the spi worker thread
so where it is safe to sleep.

Two caveats:
1) To avoid penalizing short delays, still use udelay for delays < 10us.
2) usleep_range() very often picks the upper bound, an upper bounds 10%
should be plenty.

Signed-off-by: Daniel Kurtz <djkurtz@chromium.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# e0af98a7 17-Oct-2016 Ralf Ramsauer <ralf@ramses-pyramidenbau.de>

spi: mark device nodes only in case of successful instantiation

Instantiated SPI device nodes are marked with OF_POPULATE. This was
introduced in bd6c164. On unloading, loaded device nodes will of course
be unmarked. The problem are nodes that fail during initialisation: If a
node fails, it won't be unloaded and hence not be unmarked.

If a SPI driver module is unloaded and reloaded, it will skip nodes that
failed before.

Skip device nodes that are already populated and mark them only in case
of success.

Note that the same issue exists for I2C.

Fixes: bd6c164 ("spi: Mark instantiated device nodes with OF_POPULATE")
Signed-off-by: Ralf Ramsauer <ralf@ramses-pyramidenbau.de>
Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be>
Acked-by: Pantelis Antoniou <pantelis.antoniou@konsulko.com>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# 8eee6b9d 10-Oct-2016 Thor Thayer <tthayer@opensource.altera.com>

spi: Add Flag to Enable Slave Select with GPIO Chip Select.

Some SPI masters require slave selection before the transfer
can begin [1]. The SPI framework currently selects the chip using
either 1) the internal CS mechanism or 2) the GPIO CS, but not both.

This patch adds a new master->flags define to indicate both the GPIO
CS and the internal chip select mechanism should be used.

Tested On:
Altera CycloneV development kit
Compile tested for build errors on x86_64 (allyesconfigs)

[1] DesignWare dw_apb_ssi Databook, Version 3.20a (page 39)

Signed-off-by: Thor Thayer <tthayer@opensource.altera.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3989144f 11-Oct-2016 Petr Mladek <pmladek@suse.com>

kthread: kthread worker API cleanup

A good practice is to prefix the names of functions by the name
of the subsystem.

The kthread worker API is a mix of classic kthreads and workqueues. Each
worker has a dedicated kthread. It runs a generic function that process
queued works. It is implemented as part of the kthread subsystem.

This patch renames the existing kthread worker API to use
the corresponding name from the workqueues API prefixed by
kthread_:

__init_kthread_worker() -> __kthread_init_worker()
init_kthread_worker() -> kthread_init_worker()
init_kthread_work() -> kthread_init_work()
insert_kthread_work() -> kthread_insert_work()
queue_kthread_work() -> kthread_queue_work()
flush_kthread_work() -> kthread_flush_work()
flush_kthread_worker() -> kthread_flush_worker()

Note that the names of DEFINE_KTHREAD_WORK*() macros stay
as they are. It is common that the "DEFINE_" prefix has
precedence over the subsystem names.

Note that INIT() macros and init() functions use different
naming scheme. There is no good solution. There are several
reasons for this solution:

+ "init" in the function names stands for the verb "initialize"
aka "initialize worker". While "INIT" in the macro names
stands for the noun "INITIALIZER" aka "worker initializer".

+ INIT() macros are used only in DEFINE() macros

+ init() functions are used close to the other kthread()
functions. It looks much better if all the functions
use the same scheme.

+ There will be also kthread_destroy_worker() that will
be used close to kthread_cancel_work(). It is related
to the init() function. Again it looks better if all
functions use the same naming scheme.

+ there are several precedents for such init() function
names, e.g. amd_iommu_init_device(), free_area_init_node(),
jump_label_init_type(), regmap_init_mmio_clk(),

+ It is not an argument but it was inconsistent even before.

[arnd@arndb.de: fix linux-next merge conflict]
Link: http://lkml.kernel.org/r/20160908135724.1311726-1-arnd@arndb.de
Link: http://lkml.kernel.org/r/1470754545-17632-3-git-send-email-pmladek@suse.com
Suggested-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Petr Mladek <pmladek@suse.com>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Tejun Heo <tj@kernel.org>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com>
Cc: Josh Triplett <josh@joshtriplett.org>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: Jiri Kosina <jkosina@suse.cz>
Cc: Borislav Petkov <bp@suse.de>
Cc: Michal Hocko <mhocko@suse.cz>
Cc: Vlastimil Babka <vbabka@suse.cz>
Signed-off-by: Arnd Bergmann <arnd@arndb.de>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 6b1576aa 10-Oct-2016 Thor Thayer <tthayer@opensource.altera.com>

spi: Add Flag to Enable Slave Select with GPIO Chip Select.

Some SPI masters require slave selection before the transfer
can begin [1]. The SPI framework currently selects the chip using
either 1) the internal CS mechanism or 2) the GPIO CS, but not both.

This patch adds a new master->flags define to indicate both the GPIO
CS and the internal chip select mechanism should be used.

Tested On:
Altera CycloneV development kit
Compile tested for build errors on x86_64 (allyesconfigs)

[1] DesignWare dw_apb_ssi Databook, Version 3.20a (page 39)

Signed-off-by: Thor Thayer <tthayer@opensource.altera.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# d0716dde 01-Sep-2016 Sien Wu <sien.wu@ni.com>

spi: Prevent unexpected SPI time out due to arithmetic overflow

When reading SPI flash as MTD device, the transfer length is
directly passed to the spi driver. If the requested data size
exceeds 512KB, it will cause the time out calculation to
overflow since transfer length is 32-bit unsigned integer.
This issue is resolved by using 64-bit unsigned integer
to perform the arithmetic.

Signed-off-by: Sien Wu <sien.wu@ni.com>
Acked-by: Brad Keryan <brad.keryan@ni.com>
Acked-by: Gratian Crisan <gratian.crisan@ni.com>
Acked-by: Brad Mouring <brad.mouring@ni.com>

Natinst-ReviewBoard-ID 150232
Signed-off-by: Mark Brown <broonie@kernel.org>


# b1b8153c 17-Aug-2016 Vignesh R <vigneshr@ti.com>

spi: Add support to handle kmap'd buffers in spi_map_buf()

JFFS2 FS might sometime provide kmap'd buffers as destination
buffers to read data from flash. Update spi_map_buf() function to
generate sg_list for such buffers, so that SPI controllers drivers can
use DMA to read data into such buffers.

Signed-off-by: Vignesh R <vigneshr@ti.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 764f2166 09-Aug-2016 Mark Brown <broonie@kernel.org>

spi: Drop io_mutex in error paths

A couple of error paths were missing drops of io_mutex.

Reported-by: Julia Lawall <julia.lawall@lip6.fr>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ef4d96ec 21-Jul-2016 Mark Brown <broonie@kernel.org>

spi: Split bus and I/O locking

The current SPI code attempts to use bus_lock_mutex for two purposes. One
is to implement spi_bus_lock() which grants exclusive access to the bus.
The other is to serialize access to the physical hardware. This duplicate
purpose causes confusion which leads to cases where access is not locked
when a caller holds the bus lock mutex. Fix this by splitting out the I/O
functionality into a new io_mutex.

This means taking both mutexes in the DMA path, replacing the existing
mutex with the new I/O one in the message pump (the mutex now always
being taken in the message pump) and taking the bus lock mutex in
spi_sync(), allowing __spi_sync() to have no mutex handling.

While we're at it hoist the mutex further up the message pump before we
power up the device so that all power up/down of the block is covered by
it and there are no races with in-line pumping of messages.

Reported-by: Rich Felker <dalias@libc.org>
Tested-by: Rich Felker <dalias@libc.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7f24467f 08-Jul-2016 Octavian Purdila <octavian.purdila@intel.com>

spi / ACPI: add support for ACPI reconfigure notifications

This patch adds supports for SPI device enumeration and removal via
ACPI reconfiguration notifications that are send as a result of an
ACPI table load or unload operation.

The code is very similar with the device tree reconfiguration code
with only small differences in the way we test and set the enumerated
state of the device:

* the equivalent of device tree's OF_POPULATED flag is the
flags.visited field in the ACPI device and the following wrappers
are used to manipulate it: acpi_device_enumerated(),
acpi_device_set_enumerated() and acpi_device_clear_enumerated()

* the device tree code checks of status of the OF_POPULATED flag to
avoid trying to create duplicate Linux devices in two places: once
when the controller is probed, and once when the reconfigure event
is received; in the ACPI code the check is performed only once when
the ACPI namespace is searched because this code path is invoked in
both of the two mentioned cases

The rest of the enumeration handling is similar with device tree: when
the Linux device is unregistered the ACPI device is marked as not
enumerated; also, when a device remove notification is received we
check that the device is in the enumerated state before continuing
with the removal of the Linux device.

Signed-off-by: Octavian Purdila <octavian.purdila@intel.com>
Reviewed-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# f4502dd1 07-Jun-2016 Vignesh R <vigneshr@ti.com>

spi: Add DMA support for spi_flash_read()

Few SPI devices provide accelerated read interfaces to read from
SPI-NOR flash devices. These hardwares also support DMA to transfer data
from flash to memory either via mem-to-mem DMA or dedicated slave DMA
channels. Hence, add support for DMA in order to improve throughput and
reduce CPU load.
Use spi_map_buf() to get sg table for the buffer and pass it to SPI
driver.

Signed-off-by: Vignesh R <vigneshr@ti.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8ba811a7 03-May-2016 Moritz Fischer <moritz.fischer@ettus.com>

spi: Fix simple typo s/impelment/implement

This fixes a simple typo in one of the comments.

Signed-off-by: Moritz Fischer <moritz.fischer@ettus.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 0569a88f 25-Apr-2016 Vignesh R <vigneshr@ti.com>

spi: return error if kmap'd buffers passed to spi_map_buf()

Current spi_map_buf() implementation supports creates sg_table for
vmalloc'd and kmalloc'd buffers. Therefore return error if kmap'd buffer
(or any other buffer) is passed to spi_map_buf().

Signed-off-by: Vignesh R <vigneshr@ti.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# d7e2ee25 11-Apr-2016 Linus Walleij <linus.walleij@linaro.org>

spi: let SPI masters ignore their children for PM

Let all SPI masters ignore their children: when it comes
to power management: SPI children have no business doing
keeping their parents awake: they are completely autonomous
devices that just use their parent to talk, and the latter
usecase must be power managed by the host itself on a
per-message basis.

Reviewed-by: Ulf Hansson <ulf.hansson@linaro.org>
Signed-off-by: Linus Walleij <linus.walleij@linaro.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 24c8cd1b 18-Mar-2016 Heiko Stübner <heiko@sntech.de>

spi: fix possible deadlock between internal bus locks and bus_lock_flag

External users may use spi_bus_lock to get exclusive access. This will
also grab the bus_lock_mutex and may therefore result in a deadlock if
__spi_pump_messages also tries to get the mutex.

Therefore adapt spi_pump_messages as well as spi_sync to preset the
bus_locked parameter according to the master->bus_lock_flag.

Fixes: 49023d2e4ead ("spi: core: Fix deadlock when sending messages")
Signed-off-by: Heiko Stuebner <heiko@sntech.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 10f11a22 10-Mar-2016 Javier Martinez Canillas <javier@osg.samsung.com>

spi: Add gfp parameter to kernel-doc to fix build warning

The spi_split_transfers_maxsize() gfp parameter is missing in the
function kernel-doc so building gives the following warning:

.//drivers/spi/spi.c:2359: warning: No description found for parameter 'gfp'

Signed-off-by: Javier Martinez Canillas <javier@osg.samsung.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# df88e91b 09-Mar-2016 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: respect the maximum segment size of DMA device

The device which is actually does DMA may have a limitation of the maximum
segment size. Respect this setting when preparing scatter-gather list.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 49023d2e 07-Mar-2016 Jon Hunter <jonathanh@nvidia.com>

spi: core: Fix deadlock when sending messages

The function __spi_pump_messages() is called by spi_pump_messages() and
__spi_sync(). The function __spi_sync() has an argument 'bus_locked'
that indicates if it is called with the SPI bus mutex held or not. If
'bus_locked' is false then __spi_sync() will acquire the mutex itself.

Commit 556351f14e74 ("spi: introduce accelerated read support for spi
flash devices") made a change to acquire the SPI bus mutex within
__spi_pump_messages(). However, this change did not check to see if the
mutex is already held. If __spi_sync() is called with the mutex held
(ie. 'bus_locked' is true), then a deadlock occurs when
__spi_pump_messages() is called.

Fix this deadlock by passing the 'bus_locked' state from __spi_sync() to
__spi_pump_messages() and only acquire the mutex if not already held. In
the case where __spi_pump_messages() is called from spi_pump_messages()
it is assumed that the mutex is not held and so call
__spi_pump_messages() with 'bus_locked' set to false. Finally, move the
unlocking of the mutex to the end of the __spi_pump_messages() function
to simplify the code and only call cond_resched() if there are no
errors.

Fixes: 556351f14e74 ("spi: introduce accelerated read support for spi flash devices")

Signed-off-by: Jon Hunter <jonathanh@nvidia.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3700ce95 22-Feb-2016 Masanari Iida <standby24x7@gmail.com>

spi: make xmldocs warning caused by spi.c

This patch fix following warnings while make xmldocs.

.//drivers/spi/spi.c:2354: warning: Excess function parameter
'message' description in 'spi_split_transfers_maxsize'
.//drivers/spi/spi.c:2354: warning: Excess function parameter
'max_size' description in 'spi_split_transfers_maxsize'

Signed-off-by: Masanari Iida <standby24x7@gmail.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 62826970 15-Feb-2016 Mark Brown <broonie@kernel.org>

spi: Add cond_resched() in main message processing loop

When a controller has only PIO support it is very likely that we will
run into use cases where we spend a very large amount of time consuming
CPU. Code that does this should call cond_resched() every once in a
while to give other tasks more of a chance to run so do that in the main
SPI loop, the overhead is negligable if it's not needed.

Suggested-by: Arnd Bergmann <arnd@arndb.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 05885397 18-Feb-2016 Martin Sperl <kernel@martin.sperl.org>

spi: docbook: add missing parameter documentation

Add missing docbook documentation for the gfp parameter
in function spi_replace_transfers.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# c8dab77a 17-Feb-2016 Fabio Estevam <fabio.estevam@nxp.com>

spi: core: Use min_t(size_t,..)

Use min_t(size_t,..) in order to avoid the following
build warning on ARM64:

include/linux/kernel.h:754:17: warning: comparison of distinct pointer types lacks a cast
(void) (&_min1 == &_min2); \
^
drivers/spi/spi.c:2304:17: note: in expansion of macro 'min'
xfers[0].len = min(maxsize, xfer[0].len);

Suggested-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Fabio Estevam <fabio.estevam@nxp.com>
Acked-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7d62f51e 17-Feb-2016 Fabio Estevam <fabio.estevam@nxp.com>

spi: core: Use %zu for printing 'size_t' type

Use %zu for printing 'size_t' type in order to fix the following
build warning on ARM64:

drivers/spi/spi.c: In function '__spi_split_transfer_maxsize':
drivers/spi/spi.c:2278:2: warning: format '%i' expects argument of type 'int', but argument 4 has type 'size_t' [-Wformat=]

Signed-off-by: Fabio Estevam <fabio.estevam@nxp.com>
Acked-by: Geert Uytterhoeven <geert+renesas@glider.be>
Acked-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 08933418 14-Feb-2016 Fabio Estevam <fabio.estevam@nxp.com>

spi: core: Staticize __spi_split_transfer_maxsize()

__spi_split_transfer_maxsize() can be made static as it is only
used in this file.

This fixes the following sparse warning:

drivers/spi/spi.c:2266:5: warning: symbol '__spi_split_transfer_maxsize' was not declared. Should it be static?

Signed-off-by: Fabio Estevam <fabio.estevam@nxp.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 657d32ef 11-Feb-2016 Dan Carpenter <dan.carpenter@oracle.com>

spi: checking for NULL instead of IS_ERR

spi_replace_transfers() returns error pointers on error, it never
returns NULL.

Fixes: d9f121227281 ('spi: core: add spi_split_transfers_maxsize')
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 556351f1 10-Dec-2015 Vignesh R <vigneshr@ti.com>

spi: introduce accelerated read support for spi flash devices

In addition to providing direct access to SPI bus, some spi controller
hardwares (like ti-qspi) provide special port (like memory mapped port)
that are optimized to improve SPI flash read performance.
This means the controller can automatically send the SPI signals
required to read data from the SPI flash device.
For this, SPI controller needs to know flash specific information like
read command to use, dummy bytes and address width.

Introduce spi_flash_read() interface to support accelerated read
over SPI flash devices. SPI master drivers can implement this callback to
support interfaces such as memory mapped read etc. m25p80 flash driver
and other flash drivers can call this make use of such interfaces. The
interface should only be used with SPI flashes and cannot be used with
other SPI devices.

Signed-off-by: Vignesh R <vigneshr@ti.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# d9f12122 14-Dec-2015 Martin Sperl <kernel@martin.sperl.org>

spi: core: add spi_split_transfers_maxsize

Add spi_split_transfers_maxsize method that splits
spi_transfers transparently into multiple transfers
that are below the given max-size.

This makes use of the spi_res framework via
spi_replace_transfers to allocate/free the extra
transfers as well as reverting back the changes applied
while processing the spi_message.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 523baf5a 14-Dec-2015 Martin Sperl <kernel@martin.sperl.org>

spi: core: add spi_replace_transfers method

Add the spi_replace_transfers method that can get used
to replace some spi_transfers from a spi_message with other
transfers.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# d780c371 14-Dec-2015 Martin Sperl <kernel@martin.sperl.org>

spi: core: added spi_resource management

SPI resource management framework used while processing a spi_message
via the spi-core.

The basic idea is taken from devres, but as the allocation may happen
fairly frequently, some provisioning (in the form of an unused spi_device
pointer argument to spi_res_alloc) has been made so that at a later stage
we may implement reuse objects allocated earlier avoiding the repeated
allocation by keeping a cache of objects that we can reuse.

This framework can get used for:
* rewriting spi_messages
* to fullfill alignment requirements of the spi_master HW
* to fullfill transfer length requirements
(e.g: transfers need to be less than 64k)
* consolidate spi_messages with multiple transfers into a single transfer
when the total transfer length is below a threshold.
* reimplement spi_unmap_buf without explicitly needing to check if it has
been mapped

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# a0a90718 08-Feb-2016 Mika Westerberg <mika.westerberg@linux.intel.com>

spi: Let drivers translate ACPI DeviceSelection to suitable Linux chip select

In Windows it is up to the SPI host controller driver to handle the ACPI
DeviceSelection as it likes. The SPI core does not take any part in it.
This is different in Linux because we always expect to have chip select in
range of 0 .. master->num_chipselect - 1.

In order to support this in Linux we need a way to allow the driver to
translate between ACPI DeviceSelection field and Linux chip select number
so provide a new optional hook ->fw_translate_cs() that can be used by a
driver to handle translation and call this hook if set during SPI slave
ACPI enumeration.

Signed-off-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Reviewed-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 33ada67d 23-Dec-2015 Christophe Ricard <christophe.ricard@gmail.com>

ACPI / spi: attach GPIO IRQ from ACPI description to SPI device

spi->irq was ignoring GpioInt property setting it to -1.
acpi_dev_gpio_irq_get returns and configure the slave IRQ according to
the ACPI slave node description.

It is now inline with devicetree behavior.

Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Christophe Ricard <christophe-h.ricard@st.com>
Acked-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# d1eba93b 22-Dec-2015 Geliang Tang <geliangtang@163.com>

spi: use to_spi_device

Use to_spi_device() instead of open-coding it.

Signed-off-by: Geliang Tang <geliangtang@163.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 157f38f9 14-Dec-2015 Johan Hovold <johan@kernel.org>

spi: fix parent-device reference leak

Fix parent-device reference leak due to SPI-core taking an unnecessary
reference to the parent when allocating the master structure, a
reference that was never released.

Note that driver core takes its own reference to the parent when the
master device is registered.

Fixes: 49dce689ad4e ("spi doesn't need class_device")
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# bd6c1644 30-Nov-2015 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Mark instantiated device nodes with OF_POPULATE

Mark (and unmark) device nodes with the POPULATE flag as appropriate.
This is required to avoid multi probing when enabling and populating SPI
buses in DT overlays.

Based on commit 4f001fd30145a6a8 ("i2c: Mark instantiated device nodes
with OF_POPULATE").

Suggested-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 3b1884c2 30-Nov-2015 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Uninline spi_unregister_device()

Uninline spi_unregister_device() in preparation of adding more code to
it. Add kerneldoc documentation while we're at it.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 77e80588 26-Nov-2015 Martin Sperl <kernel@martin.sperl.org>

spi: bugfix: spi_message.transfer_length does not get reset

When submitting an identical spi_message multiple times via spi_sync
the spi_message.frame_length does not get reset to 0 in __spi_validate
before adding up all spi_transfer.len resulting in
frame_length > actual_length on all but the first spi_sync call.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 88c9321d 10-Nov-2015 Thierry Reding <treding@nvidia.com>

spi: Add missing kerneldoc description for parameter

Commit ca5d24854210 ("spi: Add THIS_MODULE to spi_driver in SPI core")
adds the new __spi_register_driver() function, but keeps the kerneldoc
for the spi_register_driver() function in place and forgets to add the
description for the new owner parameter.

Signed-off-by: Thierry Reding <treding@nvidia.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ca5d2485 23-Oct-2015 Andrew F. Davis <afd@ti.com>

spi: Add THIS_MODULE to spi_driver in SPI core

Add spi_register_driver helper macro that adds THIS_MODULE to
spi_driver for the registering driver. We rename and modify
the existing spi_register_driver to enable this.

Signed-off-by: Andrew F. Davis <afd@ti.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# abeedb01 16-Oct-2015 Franklin S Cooper Jr <fcooper@ti.com>

spi: Setup the master controller driver before setting the chipselect

SPI controllers may need to be properly setup before chip selects
can be used. Therefore, wait until the spi controller has a chance
to perform their setup procedure before trying to use the chip
select.

This also insures that the chip selects pins are in a good
state before asseting them which otherwise may cause confusion.

Signed-off-by: Franklin S Cooper Jr <fcooper@ti.com>
Tested-by: Grygorii Strashko <grygorii.strashko@ti.com>
Tested-by: Ivan Khoronzhuk <ivan.khoronzhuk@linaro.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 97d56dc6 22-Oct-2015 Javier Martinez Canillas <javier@osg.samsung.com>

spi: fix kernel-doc warnings about missing return desc in spi.c

When building docs with make htmldocs, warnings about not having
a description for the return value are reported, i.e:

warning: No description found for return value of 'spi_register_driver'

Fix these by following the kernel-doc conventions explained in
Documentation/kernel-doc-nano-HOWTO.txt.

Signed-off-by: Javier Martinez Canillas <javier@osg.samsung.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 243f07be 19-Oct-2015 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: core: use gpio_is_valid() helper

Check if GPIO pin is valid by API helper function.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5ab8d262 14-Oct-2015 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: core: propagate return code of __spi_validate_bits_per_word()

Propagate the actual return code of __spi_validate_bits_per_word() in
spi_setup().

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 44af7927 09-Oct-2015 Jon Hunter <jonathanh@nvidia.com>

spi: Map SPI OF client IRQ at probe time

Currently the IRQs for SPI client devices, registered via device-tree,
are mapped when the client devices are registered. If the corresponding
irq-chip has not been probed yet, then the probing of the client device
will fail and will not be retried. Resolve this by mapping the IRQ at
probe time and allow the probe to be deferred if the IRQ is not yet
available.

If of_irq_get() returns an error that is not -EPROBE_DEFER, then assume
that the SPI client does not have an IRQ and set the IRQ number to zero
(which is equivalent to irq_of_parse_and_map()).

This is based on some inputs from Thierry Reding <treding@nvidia.com>.

Cc: Thierry Reding <treding@nvidia.com>
Cc: Tomeu Vizoso <tomeu.vizoso@collabora.com>
Signed-off-by: Jon Hunter <jonathanh@nvidia.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 6b7bc061 22-Jun-2015 Martin Sperl <kernel@martin.sperl.org>

spi: add transfer histogram statistics via sysfs

report transfer sizes as a histogram via the following files:
/sys/class/spi_master/spi*/statistics/transfer_bytes_histo_*
/sys/class/spi_master/spi*/spi*.*/statistics/transfer_bytes_histo_*

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# a394d635 05-Sep-2015 Guenter Roeck <linux@roeck-us.net>

spi: Fix documentation of spi_alloc_master()

Actually, spi_master_put() after spi_alloc_master() must _not_ be followed
by kfree(). The memory is already freed with the call to spi_master_put()
through spi_master_class, which registers a release function. Calling both
spi_master_put() and kfree() results in often nasty (and delayed) crashes
elsewhere in the kernel, often in the networking stack.

This reverts commit eb4af0f5349235df2e4a5057a72fc8962d00308a.

Link to patch and concerns: https://lkml.org/lkml/2012/9/3/269
or
http://lkml.iu.edu/hypermail/linux/kernel/1209.0/00790.html

Alexey Klimov: This revert becomes valid after
94c69f765f1b4a658d96905ec59928e3e3e07e6a when spi-imx.c
has been fixed and there is no need to call kfree() so comment
for spi_alloc_master() should be fixed.

Signed-off-by: Guenter Roeck <linux@roeck-us.net>
Signed-off-by: Alexey Klimov <alexey.klimov@linaro.org>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# 63ab645f 23-Aug-2015 Stefan Brüns <stefan.bruens@rwth-aachen.de>

spi: check bits_per_word in spi_setup

This allows drivers for devices connected via SPI to check if the
controller supports a given bits_per_word value during setup.
Currently any BPW value is accepted durings setup, and transfers
are rejected later.

Signed-off-by: Stefan Brüns <stefan.bruens@rwth-aachen.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 7dc9fbc3 20-Aug-2015 Mark Brown <broonie@kernel.org>

spi: Fall back to master maximum speed if no slave speed specified

If a slave appears with no maximum transfer speed specified fall back to
using the maximum for the master instead. It's questionable if we
should let slaves do this but let's be defensive.

Signed-off-by: Mark Brown <broonie@kernel.org>


# c37f45b5 23-Jul-2015 Leilk Liu <leilk.liu@mediatek.com>

spi: support spi without dma channel to use can_dma()

For spi without dma channel and use can_dma(), it can
use master->dev for struct device.

Signed-off-by: Leilk Liu <leilk.liu@mediatek.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# eca2ebc7 22-Jun-2015 Martin Sperl <kernel@martin.sperl.org>

spi: expose spi_master and spi_device statistics via sysfs

per spi-master statistics accessible as:
/sys/class/spi_master/spi*/statistics/*

per spi-device statistics accessible via:
/sys/class/spi_master/spi*/spi*.*/statistics/*

The following statistics are exposed as separate "files" inside
these directories:
* messages number of spi_messages
* transfers number of spi_transfers
* bytes number of bytes transferred
* bytes_rx number of bytes transmitted
* bytes_tx number of bytes received
* errors number of errors encounterd
* timedout number of messages that have timed out
* spi_async number of spi_messages submitted using spi_async
* spi_sync number of spi_messages submitted using spi_sync
* spi_sync_immediate number of spi_messages submitted using spi_sync,
that are handled immediately without a context switch
to the spi_pump worker-thread

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 65598c13 30-Jun-2015 Andrew Gabbasov <andrew_gabbasov@mentor.com>

spi: Fix per-page mapping of unaligned vmalloc-ed buffer

spi_map_buf() processes mapping of vmalloc-ed buffers in a special way,
making mapping of every page separately. However, if the buffer is not
aligned to page boundary (e.g. sub-array in a vmalloc-ed array), it
fills the scatter table with page-size unaligned pieces, that cross
page boundaries. This is incorrect and can, for example, cause memory
corruption and various crashes when working with ubifs on spi-nor chips
(though those drivers are themselves buggy in that they should be
providing DMAable memory to the SPI framework).

Fix this by using proper scatter table size and intra-page buffer lengths,
so that the whole buffer splits into separate scatter table entries on
page boundaries.

Signed-off-by: Andrew Gabbasov <andrew_gabbasov@mentor.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 4b786458 25-May-2015 Martin Sperl <kernel@martin.sperl.org>

spi: restore rx/tx_buf in case of unset CONFIG_HAS_DMA

The case where spi_master sets the flags SPI_MASTER_MUST_RX/TX while
CONFIG_HAS_DMA is unset (which is unlikley) together with a driver
that reuses spi_messages with rx/tx_buff set to NULL, can result in:
* data disclosure over the SPI (for tx_buf == NULL)
* memory corruption (for rx_buf == NULL)

This happenes when dummy_rx/dummy_tx are changing address due to krealloc
or free and an allocation of the memory by a different part of the kernel.

Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 8e76ef88 10-May-2015 Martin Sperl <kernel@martin.sperl.org>

spi: fix race freeing dummy_tx/rx before it is unmapped

Fix a race (with some kernel configurations) where a queued
master->pump_messages runs and frees dummy_tx/rx before
spi_unmap_msg is running (or is finished).

This results in the following messages:
BUG: Bad page state in process
page:db7ba030 count:0 mapcount:0 mapping: (null) index:0x0
flags: 0x200(arch_1)
page dumped because: PAGE_FLAGS_CHECK_AT_PREP flag set
...

Reported-by: Noralf Trønnes <noralf@tronnes.org>
Suggested-by: Noralf Trønnes <noralf@tronnes.org>
Tested-by: Noralf Trønnes <noralf@tronnes.org>
Signed-off-by: Martin Sperl <kernel@martin.sperl.org>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# f8bb820d 15-Apr-2015 Robin Gong <b38343@freescale.com>

spi: check tx_buf and rx_buf in spi_unmap_msg

Some spi device drivers use the same tx_buf and rx_buf repeatly for better
performance such as driver/input/touchsreen/ads7846.c, but spi core grab tx_buf
/rx_buf of transfer and set them as dummy_tx/dummy_rx once they are NULL. Thus,
in the second time the tx_buf/rx_buf will be replaced by dummy_tx/dummy_rx and
the data which produced by the last tx or rx may be wrongly sent to the device
or handled by the upper level protocol. This patch just keep the orignal value
of tx_buf/rx_buf if they are NULL after this transfer processed.

Signed-off-by: Robin Gong <b38343@freescale.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ff61eb42 07-Apr-2015 Geert Uytterhoeven <geert+renesas@glider.be>

spi: Make master->handle_err() callback optional to avoid crashes

If a driver doesn't implement the master->handle_err() callback and an
SPI transfer fails, the kernel will crash with a NULL pointer
dereference:

Unable to handle kernel NULL pointer dereference at virtual address 00000000
pgd = c0003000
[00000000] *pgd=80000040004003, *pmd=00000000
Internal error: Oops: 80000206 [#1] SMP ARM
Modules linked in:
CPU: 1 PID: 1 Comm: swapper/0 Not tainted 4.0.0-rc7-koelsch-05861-g1fc9fdd4add4f783 #1046
Hardware name: Generic R8A7791 (Flattened Device Tree)
task: eec359c0 ti: eec54000 task.ti: eec54000
PC is at 0x0
LR is at spi_transfer_one_message+0x1cc/0x1f0

Make the master->handle_err() callback optional to avoid the crash.

Also fix a spelling mistake in the callback documentation while we're at
it.

Fixes: b716c4ffc6a2b0bf ("spi: introduce master->handle_err() callback")
Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 22de3ef9 25-Mar-2015 Dmitry Torokhov <dmitry.torokhov@gmail.com>

spi: of: do explicitly request modules for of-registered devices

Trying to register an SPI device asynchronously (via async_schedule() call)
results in an ugly complaint from request_module() warning about potential
deadlock (because request_module tries to wait for async works to
complete, the caller is also an async work in this case).

While we could try to switch to using request_module_nowait(), other buses,
as well as SPI itself when not using device tree, do not try to load
modules explicitly, but rather rely on the standard infrastructure (such as
udev) to execute module loading. There is no reason why SPI OF-described
devices should be treated differently.

Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 391949b6 18-Mar-2015 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi: trigger trace event for message-done before mesg->complete

With spidev the mesg->complete callback points to spidev_complete.
Calling this unblocks spidev_sync and so spidev_sync_write finishes. As
the struct spi_message just read is a local variable in
spidev_sync_write and recording the trace event accesses this message
the recording is better done first. The same can happen for
spidev_sync_read.

This fixes an oops observed on a 3.14-rt system with spidev activity
after

echo 1 > /sys/kernel/debug/tracing/events/spi/enable

.

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# 1a7b7ee7 13-Mar-2015 Ivan T. Ivanov <iivanov@mm-sol.com>

spi: Ensure that CS line is in non-active state after spi_setup()

Some devices samples state of the chip select signal during power up
and act differently based on this state, so SPI core should ensure
that CS line is driven in non-active state after spi_setup().

Signed-off-by: Ivan T. Ivanov <iivanov@mm-sol.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# ea022bbb 08-Mar-2015 Lars-Peter Clausen <lars@metafoo.de>

spi: Remove support for legacy PM

All SPI drivers have been converted from legacy suspend/resume callbacks to
dev_pm_ops. So we can finally remove support for legacy PM from the SPI
core.

Since there aren't any special bus specific things to do during
suspend/resume and since the PM core will automatically fallback directly to
using the device's PM ops if no bus PM ops are specified there is no need to
have any special SPI bus PM ops.

Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Mark Brown <broonie@kernel.org>


# b716c4ff 27-Feb-2015 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

spi: introduce master->handle_err() callback

This callback would be useful to handle an error that occurs in the generic
implementation of transfer_one_message(). The good candidate for this is to
drain FIFO and / or to terminate DMA transfers when timeout happened.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 682a71b2 02-Feb-2015 Nicholas Mc Guire <der.herr@hofr.at>

spi: match var type to return type of wait_for_completion

return type of wait_for_completion_timeout is unsigned long not int, this
patch changes the type of m from int to unsigned long.

Signed-off-by: Nicholas Mc Guire <der.herr@hofr.at>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 2c658e21 18-Dec-2014 Jarkko Nikula <jarkko.nikula@linux.intel.com>

spi: Remove FSF mailing addresses

Signed-off-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# fc9e0f71 10-Dec-2014 Mark Brown <broonie@kernel.org>

spi: Only idle the message pump in the worker kthread

In order to avoid the situation where the kthread is waiting for another
context to make the hardware idle let the message pump know if it's being
called from the worker thread context and if it isn't then defer to the
worker thread instead of idling the hardware immediately. This will ensure
that if this situation happens we block rather than busy waiting.

Signed-off-by: Mark Brown <broonie@kernel.org>


# 0461a414 09-Dec-2014 Mark Brown <broonie@kernel.org>

spi: Pump transfers inside calling context for spi_sync()

If we are using the standard SPI message pump (which all drivers should be
transitioning over to) then special case the message enqueue and instead of
starting the worker thread to push messages to the hardware do so in the
context of the caller if the controller is idle. This avoids a context
switch in the common case where the controller has a single user in a
single thread, for short PIO transfers there may be no need to context
switch away from the calling context to complete the transfer.

The code is a bit more complex than is desirable in part due to the need
to handle drivers not using the standard queue and in part due to handling
the various combinations of bus locking and asynchronous submission in
interrupt context.

It is still suboptimal since it will still wake the message pump for each
transfer in order to schedule idling of the hardware and if multiple
contexts are using the controller simultaneously a caller may end up
pumping a message for some random other thread rather than for itself,
and if the thread ends up deferring due to another context idling the
hardware then it will just busy wait. It can, however, have the benefit
of aggregating power up and down of the hardware when a caller performs
a series of transfers back to back without any need for the use of
spi_async().

Signed-off-by: Mark Brown <broonie@kernel.org>


# 983aee5d 09-Dec-2014 Mark Brown <broonie@kernel.org>

spi: Check to see if the device is processing a message before we idle

cur_msg is updated under the queue lock and holds the message we are
currently processing. Since currently we only ever do removals in the
pump kthread it doesn't matter in what order we do things but we want
to be able to push things out from the submitting thread so pull the
check to see if we're currently handling a message before we check to
see if the queue is idle.

Signed-off-by: Mark Brown <broonie@kernel.org>


# 5424d43e 10-Dec-2014 Mark Brown <broonie@kernel.org>

spi: Move queue data structure initialisation to main master init

Since most devices now do use the standard queue and in order to avoid
initialisation ordering issues being introduced by further refactorings
to improve performance move the initialisation of the queue and the lock
for it to the main master allocation.

Signed-off-by: Mark Brown <broonie@kernel.org>


# 98a8f5a0 04-Dec-2014 Jarkko Nikula <jarkko.nikula@linux.intel.com>

spi: core: Do not mangle error code from kthread_run()

kthread_run() could return ERR_PTR(-EINTR) from kthread_create_on_node().
Return the actual error code in spi_init_queue() instead of mangling it to
-ENOMEM.

Signed-off-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 5267720e 26-Nov-2014 Fabio Estevam <fabio.estevam@freescale.com>

spi: Check for spi_of_notifier when CONFIG_OF_DYNAMIC=y

Since commit ce79d54ae447d651173 ("spi/of: Add OF notifier handler") the
following warning is seen on a imx53 system that has CONFIG_OF_DYNAMIC=n:

[ 0.048119] ------------[ cut here ]------------
[ 0.048146] WARNING: CPU: 0 PID: 1 at drivers/spi/spi.c:2419 spi_init+0x60/0xa8()
[ 0.048158] Modules linked in:
[ 0.048183] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 3.18.0-rc6-next-20141126-00003-g9388e85 #2080
[ 0.048193] Hardware name: Freescale i.MX53 (Device Tree Support)
[ 0.048203] Backtrace:
[ 0.048235] [<80011f74>] (dump_backtrace) from [<80012110>] (show_stack+0x18/0x1c)
[ 0.048246] r6:00000973 r5:00000000 r4:00000000 r3:00000000
[ 0.048284] [<800120f8>] (show_stack) from [<806b3ad8>] (dump_stack+0x88/0xa4)
[ 0.048312] [<806b3a50>] (dump_stack) from [<8002a55c>] (warn_slowpath_common+0x80/0xbc)
[ 0.048320] r5:8096cfcc r4:00000000
[ 0.048343] [<8002a4dc>] (warn_slowpath_common) from [<8002a5bc>] (warn_slowpath_null+0x24/0x2c)
[ 0.048354] r8:8096cf6c r7:809355ec r6:ddcd7c00 r5:812029e4 r4:00000000
[ 0.048389] [<8002a598>] (warn_slowpath_null) from [<8096cfcc>] (spi_init+0x60/0xa8)
[ 0.048405] [<8096cf6c>] (spi_init) from [<80008a7c>] (do_one_initcall+0x88/0x1e0)
[ 0.048415] r5:8099e018 r4:8099e018
[ 0.048438] [<800089f4>] (do_one_initcall) from [<80935e38>] (kernel_init_freeable+0x110/0x1e0)
[ 0.048448] r10:80980700 r9:809806e4 r8:000000cc r7:809355ec r6:809f8940 r5:00000002
[ 0.048478] r4:8098d744
[ 0.048508] [<80935d28>] (kernel_init_freeable) from [<806ae574>] (kernel_init+0x10/0xf4)
[ 0.048517] r10:00000000 r9:00000000 r8:00000000 r7:00000000 r6:00000000 r5:806ae564
[ 0.048547] r4:00000000
[ 0.048565] [<806ae564>] (kernel_init) from [<8000ed68>] (ret_from_fork+0x14/0x2c)
[ 0.048574] r4:00000000 r3:00000000
[ 0.048616] ---[ end trace 405a65d177dae4fd ]---

Only check of_reconfig_notifier_register() in the CONFIG_OF_DYNAMIC=y case,
as intended by commit ce79d54ae447d65.

Signed-off-by: Fabio Estevam <fabio.estevam@freescale.com>
Signed-off-by: Grant Likely <grant.likely@linaro.org>


# ce79d54a 28-Oct-2014 Pantelis Antoniou <pantelis.antoniou@konsulko.com>

spi/of: Add OF notifier handler

Add OF notifier handler needed for creating/destroying spi devices
according to dynamic runtime changes in the DT live tree. This code is
enabled when CONFIG_OF_DYNAMIC is selected.

Signed-off-by: Pantelis Antoniou <pantelis.antoniou@konsulko.com>
Signed-off-by: Grant Likely <grant.likely@linaro.org>
Reviewed-by: Mark Brown <broonie@kernel.org>
Cc: <linux-spi@vger.kernel.org>


# aff5e3f8 29-Oct-2014 Pantelis Antoniou <pantelis.antoniou@konsulko.com>

spi/of: Create new device registration method and accessors

Dynamically inserting spi device nodes requires the use of a single
device registration method. Refactor the existing
of_register_spi_devices() to split out the core functionality for a
single device into a separate function; of_register_spi_device(). This
function will be used by the OF_DYNAMIC overlay code to make live
modifications to the tree.

Methods to lookup a device/master using a device node are added
as well, of_find_spi_master_by_node() & of_find_spi_device_by_node().

Signed-off-by: Pantelis Antoniou <pantelis.antoniou@konsulko.com>
[grant.likely] Split patch into two pieces for clarity
Signed-off-by: Grant Likely <grant.likely@linaro.org>
Reviewed-by: Mark Brown <broonie@kernel.org>
Cc: <linux-spi@vger.kernel.org>


# c1aefbdd 17-Nov-2014 Charles Keepax <ckeepax@opensource.wolfsonmicro.com>

spi: Fix mapping from vmalloc-ed buffer to scatter list

We can only use page_address on memory that has been mapped using kmap,
when the buffer passed to the SPI has been allocated by vmalloc the page
has not necessarily been mapped through kmap. This means sometimes
page_address will return NULL causing the pointer we pass to sg_set_buf
to be invalid.

As we only call page_address so that we can pass a virtual address to
sg_set_buf which will then immediately call virt_to_page on it, fix this
by calling sg_set_page directly rather then relying on the sg_set_buf
helper.

Signed-off-by: Charles Keepax <ckeepax@opensource.wolfsonmicro.com>
Signed-off-by: Mark Brown <broonie@kernel.org>
Cc: stable@vger.kernel.org


# f48c767c 29-Sep-2014 Ulf Hansson <ulf.hansson@linaro.org>

PM / Domains: Move dev_pm_domain_attach|detach() to pm_domain.h

The commit 46420dd73b80 (PM / Domains: Add APIs to attach/detach a PM
domain for a device) started using errno values in pm.h header file.
It also failed to include the header for these, thus it caused
compiler errors.

Instead of including the errno header to pm.h, let's move the functions
to pm_domain.h, since it's a better match.

Fixes: 46420dd73b80 (PM / Domains: Add APIs to attach/detach a PM domain for a device)
Signed-off-by: Ulf Hansson <ulf.hansson@linaro.org>
Acked-by: Geert Uytterhoeven <geert+renesas@glider.be>
Acked-by: Wolfram Sang <wsa@the-dreams.de>
Acked-by: Mark Brown <broonie@kernel.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# c7908a37 24-Sep-2014 Xiubo Li <Li.Xiubo@freescale.com>

spi: Fix possible ZERO_SIZE_PTR pointer dereferencing error.

Since we cannot make sure the 'n' will always be none zero here, and
then if either equal to zero, the kzalloc() will return ZERO_SIZE_PTR,
which equals to ((void *)16).

So this patch fix this with just doing the zero check before calling
kzalloc().

Signed-off-by: Xiubo Li <Li.Xiubo@freescale.com>
Signed-off-by: Mark Brown <broonie@kernel.org>


# 676e7c25 19-Sep-2014 Ulf Hansson <ulf.hansson@linaro.org>

spi: core: Convert to dev_pm_domain_attach|detach()

Previously only the ACPI PM domain was supported by the spi bus.

Let's convert to the common attach/detach functions for PM domains,
which currently means we are extending the support to include the
generic PM domain as well.

Signed-off-by: Ulf Hansson <ulf.hansson@linaro.org>
Reviewed-by: Kevin Hilman <khilman@linaro.org>
Reviewed-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# 38ec10f6 16-Aug-2014 Mark Brown <broonie@linaro.org>

spi: Only call transfer_one() if we have buffers to transfer

Client drivers such as the ChomeOS EC driver sometimes use transfers with
no buffers and only a delay specified in order to allow a delay after the
assertion of /CS. Rather than require controller drivers handle this noop
case gracefully put checks in the core to ensure that we don't call into
the controller for such transfers.

Reported-by: Addy Ke <addy.ke@rock-chips.com>
Tested-by: Doug Anderson <dianders@chromium.org>
Reviewed-by: Doug Anderson <dianders@chromium.org>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 2c675689 08-Aug-2014 Thierry Reding <treding@nvidia.com>

spi: Add missing kerneldoc bits

These are all arguments or fields that got added without updating the
kerneldoc comments.

Signed-off-by: Thierry Reding <treding@nvidia.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 86be408b 18-Jun-2014 Sylwester Nawrocki <s.nawrocki@samsung.com>

clk: Support for clock parents and rates assigned from device tree

This patch adds helper functions to configure clock parents and rates
as specified through 'assigned-clock-parents', 'assigned-clock-rates'
DT properties for a clock provider or clock consumer device.
The helpers are now being called by the bus code for the platform, I2C
and SPI busses, before the driver probing and also in the clock core
after registration of a clock provider.

Signed-off-by: Sylwester Nawrocki <s.nawrocki@samsung.com>
Acked-by: Kyungmin Park <kyungmin.park@samsung.com>
Signed-off-by: Mike Turquette <mturquette@linaro.org>


# 3fc25421 10-Jul-2014 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Pass correct device to dma_map_sg()

According to Documentation/dmaengine.txt, scatterlists must be mapped
using the DMA struct device.

However, "dma_chan.dev->device" is the sysfs class device's device.
Use "dma_chan.device->dev" instead, which is the real DMA device's device.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 89e4b66a 10-Jul-2014 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Fix check for dma_map_sg() failures

According to Documentation/DMA-API.txt, dma_map_sg() returns 0 on failure.
As spi_map_buf() returns an error code, convert zero into -ENOMEM.
Keep the existing check for negative numbers just in case.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 840e9c35 21-Jun-2014 Mark Brown <broonie@linaro.org>

spi: Remove unused variable

Reported-by: kbuild test robot
Signed-off-by: Mark Brown <broonie@linaro.org>


# 8331acb3 12-Jun-2014 Sachin Kamat <sachin.kamat@samsung.com>

spi: Remove redundant OOM message in spi.c

Let memory subsystem handle the error logging.

Signed-off-by: Sachin Kamat <sachin.kamat@samsung.com>
Reviewed-by: Naveen Krishna Chatradhi <ch.naveen@samsung.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 80874d8c 26-May-2014 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Ignore unsupported spi-[tr]x-bus-width property values

Rejecting unsupported values of spi-tx-bus-width and spi-rx-bus-width
may break compatibility with future DTs. Just ignore them, falling back
to Single SPI Transfers.

Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@linaro.org>


# c3676d5c 01-May-2014 Mark Brown <broonie@linaro.org>

spi: core: Don't destroy master queue if we fail to create it

If we fail to create the master queue for some reason we should not attempt
to clean it up since attempting to stop a kthread that was not created will
hang and it's just generally bad practice. Unfortunately at present we call
spi_destroy_queue() even in cases where the creation fails.

Fix this by fixing the error handling in spi_master_initialize_queue() so
that we only flag the master as queued or destroy the queue if creation
succeeded. The change to the flag is done since the general master
cleanup uses this to destroy the queue.

Reported-by: Ricardo Ribalda Delgado <ricardo.ribalda@gmail.com>
Signed-off-by: Mark Brown <broonie@linaro.org>
Acked-by: Geert Uytterhoeven <geert@linux-m68k.org>


# 2de440f5 01-May-2014 Geert Uytterhoeven <geert@linux-m68k.org>

spi: core: Protect DMA code by #ifdef CONFIG_HAS_DMA

If NO_DMA=y:

drivers/built-in.o: In function `spi_map_buf':
spi.c:(.text+0x21bc60): undefined reference to `dma_map_sg'
drivers/built-in.o: In function `spi_unmap_buf.isra.33':
spi.c:(.text+0x21c32e): undefined reference to `dma_unmap_sg'
make[3]: *** [vmlinux] Error 1

Protect the DMA code by #ifdef CONFIG_HAS_DMA to fix this:
- Extract __spi_map_msg() from spi_map_msg(),
- Provide dummy definitions of __spi_map_msg() and spi_unmap_msg() if
!CONFIG_HAS_DMA.

Signed-off-by: Geert Uytterhoeven <geert@linux-m68k.org>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 83596fbe 14-Apr-2014 Geert Uytterhoeven <geert+renesas@glider.be>

spi: core: Ignore unsupported Dual/Quad Transfer Mode bits

The availability of SPI Dual or Quad Transfer Mode as indicated by the
"spi-tx-bus-width" and "spi-rx-bus-width" properties in the device tree is
a hardware property of the SPI master, SPI slave, and board wiring. Hence
the SPI core should not reject an SPI slave because an SPI master driver
doesn't (yet) support Dual or Quad Transfer Mode.

Change the lack of Dual or Quad Transfer Mode support in the SPI master
driver from an error condition to a warning condition, and ignore the
unsupported mode bits, falling back to Single Transfer Mode, to avoid
breakages when running old kernels with new device trees.

Fixes: f477b7fb13df (spi: DUAL and QUAD support)
Signed-off-by: Geert Uytterhoeven <geert+renesas@glider.be>
Signed-off-by: Mark Brown <broonie@linaro.org>
Cc: stable@vger.kernel.org


# cd6339e6 01-Apr-2014 Zhao Qiang <B45475@freescale.com>

spi: add "spi-lsb-first" to devicetree

add optional property devicetree for SPI slave nodes
into devicetree so that LSB mode can be enabled by devicetree.

Signed-off-by: Zhao Qiang <B45475@freescale.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# eee668a9 10-Apr-2014 Harini Katakam <harinik@xilinx.com>

spi: core: Increase timeout value

The existing timeout value in wait_for_completion_timeout is
calculated from the transfer length and speed with tolerance of 10msec.
This is too low because this is used for error conditions such as
hardware hang etc.
The xfer->speed_hz considered may not be the actual speed set
because the best clock divisor is chosen from a limited set such that
the actual speed <= requested speed. This will lead to timeout being
less than actual transfer time.
Considering acceptable latencies, this timeout can be set to a
value double the expected transfer plus 100 msecs.
This patch adds the same in the core.

Signed-off-by: Harini Katakam <harinik@xilinx.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 0b73aa63 29-Mar-2014 Mark Brown <broonie@linaro.org>

spi: Fix handling of cs_change in core implementation

The core implementation of cs_change didn't follow the documentation
which says that cs_change in the middle of the transfer means to briefly
deassert chip select, instead it followed buggy drivers which change the
polarity of chip select. Use a delay of 10us between deassert and
reassert simply from pulling numbers out of a hat.

Reported-by: Gerhard Sittig <gsi@denx.de>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 1e25cd47 25-Mar-2014 Mark Brown <broonie@linaro.org>

spi: Do not require a completion

There is no real reason why we require transfers to have a completion and
the only user of the completion now checks to see if one has been provided
before using it so stop enforcing this. This makes it more convenient for
drivers to chain multiple asynchronous transfers together.

Signed-off-by: Mark Brown <broonie@linaro.org>


# a6f87fad 16-Mar-2014 Axel Lin <axel.lin@ingics.com>

spi: core: Use master->max_speed_hz as transfer speed when xfer->speed_hz > master->max_speed_hz

When xfer->speed_hz is greater than master->max_speed_hz, it's generally safe
to use master->max_speed_hz as transfer speed.
Thus use master->max_speed_hz as transfer speed rather than return error when
xfer->speed_hz > master->max_speed_hz.

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Tested-by: Guenter Roeck <linux@roeck-us.net>
Reviewed-by: Guenter Roeck <linux@roeck-us.net>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 6ea31293 28-Feb-2014 Atsushi Nemoto <anemo@mba.ocn.ne.jp>

spi: core: make zero length transfer valid again

Zero length transfer becomes invalid since
"spi: core: Validate length of the transfers in message" commit,
but it should be valid to support an odd device, for example, which
requires long delay between chipselect and the first transfer, etc.

Signed-off-by: Atsushi Nemoto <anemo@mba.ocn.ne.jp>
Tested-by: Thierry Reding <treding@nvidia.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# f97b26b0 20-Feb-2014 Axel Lin <axel.lin@ingics.com>

spi: core: Replace msleep with usleep_range to get more accurate sleep time

Fixes below checkpatch warning:
WARNING: msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt
+ msleep(10);

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 4d94bd21 19-Feb-2014 Ivan T. Ivanov <iivanov@mm-sol.com>

spi: core: Validate length of the transfers in message

SPI transfer length should be multiple of SPI word size,
where SPI word size should be power-of-two multiple

Signed-off-by: Ivan T. Ivanov <iivanov@mm-sol.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# aec35f4e 13-Feb-2014 Jean Delvare <jdelvare@suse.de>

spi: Clean up probe and remove functions

While backporting 33cf00e5 ("spi: attach/detach SPI device to the ACPI
power domain"), I noticed that the code changes were suboptimal:

* Why use &spi->dev when we have dev at hand?

* After fixing the above, spi is used only once, so we don't really
need a local variable for it.

This results in the following clean-up.

Signed-off-by: Jean Delvare <jdelvare@suse.de>
Acked-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 51327353 12-Feb-2014 Mark Brown <broonie@linaro.org>

spi: Make max_tx and max_rx the same type

Prevents spurious compiler warnings.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 052eb2d4 09-Feb-2014 Axel Lin <axel.lin@ingics.com>

spi: core: Set max_speed_hz of spi_device default to max_speed_hz of controller

In __spi_validate(), xfer->speed_hz is set to be spi->max_speed_hz if it is not
set for this transfer. However, if spi->max_speed_hz is also not set,
xfer->speed_hz is 0. Some drivers (e.g. au1550, tegra114, tegra20-sflash,
tegra20-slink, etc.) then use below code to avoid setting xfer->speed_hz to 0.

/* Set speed to the spi max fequency if spi device has not set */
spi->max_speed_hz = spi->max_speed_hz ? : tspi->spi_max_frequency;

Let's handle it in spi core.
If spi->max_speed_hz is not set, make it default to spi->master->max_speed_hz.
So In __spi_validate() if both xfer->speed_hz and spi->max_speed_hz are not set,
xfer->speed_hz will be set to spi->master->max_speed_hz.

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 6ad45a27 02-Feb-2014 Mark Brown <broonie@linaro.org>

spi: Make core DMA mapping functions generate scatterlists

We cannot unconditionally use dma_map_single() to map data for use with
SPI since transfers may exceed a page and virtual addresses may not be
provided with physically contiguous pages. Further, addresses allocated
using vmalloc() need to be mapped differently to other addresses.

Currently only the MXS driver handles all this, a few drivers do handle
the possibility that buffers may not be physically contiguous which is
the main potential problem but many don't even do that. Factoring this
out into the core will make it easier for drivers to do a good job so if
the driver is using the core DMA code then generate a scatterlist
instead of mapping to a single address so do that.

This code is mainly based on a combination of the existing code in the MXS
and PXA2xx drivers. In future we should be able to extend it to allow the
core to concatenate adjacent transfers if they are compatible, improving
performance.

Currently for simplicity clients are not allowed to use the scatterlist
when they do DMA mapping, in the future the existing single address
mappings will be replaced with use of the scatterlist most likely as
part of pre-verifying transfers.

This change makes it mandatory to use scatterlists when using the core DMA
mapping so update the s3c64xx driver to do this when used with dmaengine.
Doing so makes the code more ugly but it is expected that the old s3c-dma
code can be removed very soon.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 3a2eba9b 28-Jan-2014 Mark Brown <broonie@linaro.org>

spi: Provide core support for full duplex devices

It is fairly common for SPI devices to require that one or both transfer
directions is always active. Currently drivers open code this in various
ways with varying degrees of efficiency. Start factoring this out by
providing flags SPI_MASTER_MUST_TX and SPI_MASTER_MUST_RX. These will cause
the core to provide buffers for the requested direction if none are
specified in the underlying transfer.

Currently this is fairly inefficient since we actually allocate a data
buffer which may get large, support for mapping transfers using a
scatterlist will allow us to avoid this for DMA based transfers.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 99adef31 15-Jan-2014 Mark Brown <broonie@linaro.org>

spi: Provide core support for DMA mapping transfers

The process of DMA mapping buffers for SPI transfers does not vary between
devices so in order to save duplication of code in drivers this can be
factored out into the core, allowing it to be integrated with the work that
is being done on factoring out the common elements from the data path
including more sharing of dmaengine code.

In order to use this masters need to provide a can_dma() operation and while
the hardware is prepared they should ensure that DMA channels are provided
in tx_dma and rx_dma. The core will then ensure that the buffers are mapped
for DMA prior to calling transfer_one_message().

Currently the cleanup on error is not complete, this needs to be improved.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 16a0ce4e 30-Jan-2014 Mark Brown <broonie@linaro.org>

spi: Add a timeout when waiting for transfers

Don't wait indefinitely for transfers to complete but time out after 10ms
more than we expect the transfer to take on the wire.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 1f802f82 28-Jan-2014 Geert Uytterhoeven <geert+renesas@linux-m68k.org>

spi: Fix crash with double message finalisation on error handling

This reverts commit e120cc0dcf2880a4c5c0a6cb27b655600a1cfa1d.

It causes a NULL pointer dereference with drivers using the generic
spi_transfer_one_message(), which always calls
spi_finalize_current_message(), which zeroes master->cur_msg.

Drivers implementing transfer_one_message() theirselves must always call
spi_finalize_current_message(), even if the transfer failed:

* @transfer_one_message: the subsystem calls the driver to transfer a single
* message while queuing transfers that arrive in the meantime. When the
* driver is finished with this message, it must call
* spi_finalize_current_message() so the subsystem can issue the next
* transfer

Signed-off-by: Geert Uytterhoeven <geert+renesas@linux-m68k.org>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 13a42798 18-Jan-2014 Axel Lin <axel.lin@ingics.com>

spi: core: Fix transfer failure when master->transfer_one returns positive value

master->transfer_one returns positive value is not a error.
So set ret to 0 when master->transfer_one returns positive value.
Otherwise, I hit "spi_master spi0: failed to transfer one message from queue"
error when my transfer_one callback returns 1.

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 9e8f4882 21-Jan-2014 Geert Uytterhoeven <geert+renesas@linux-m68k.org>

spi: Spelling s/finised/finished/

Signed-off-by: Geert Uytterhoeven <geert+renesas@linux-m68k.org>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 8c4ff6d0 14-Jan-2014 Zhang Rui <rui.zhang@intel.com>

ACPI: fix module autoloading for ACPI enumerated devices

ACPI enumerated devices has ACPI style _HID and _CID strings,
all of these strings can be used for both driver loading and matching.

Currently, in Platform, I2C and SPI bus, the ACPI style driver matching
is supported by invoking acpi_driver_match_device() in bus .match() callback.
But, the module autoloading is still broken.

For example, there is any ACPI device with _HID "INTABCD" that is
enumerated to platform bus, and we have a driver that can probe it.

The driver exports its module_alias as "acpi:INTABCD" use the following code
static const struct acpi_device_id xxx_acpi_match[] = {
{ "INTABCD", 0 },
{ }
};
MODULE_DEVICE_TABLE(acpi, xxx_acpi_match);

But, unfortunately, the device' modalias is shown as "platform:INTABCD:00",
please refer to modalias_show() and platform_uevent() in
drivers/base/platform.c.
This results in that the driver will not be loaded automatically when the
device node is created, because their modalias do not match.

This also applies to I2C and SPI bus.

With this patch, the device' modalias will be shown as "acpi:INTABCD" as well.

Signed-off-by: Zhang Rui <rui.zhang@intel.com>
Acked-by: Mark Brown <broonie@linaro.org>
Acked-by: Wolfram Sang <wsa@the-dreams.de>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# 1afd9989 12-Jan-2014 Geert Uytterhoeven <geert+renesas@linux-m68k.org>

spi: core: Improve tx/rx_nbits check comments

- Rephrase the comments about tx/rx_nbits validity checks,
- Remove the stale comment about SPI_3WIRE (the code it refers to was
removed in commit 368ca4e0c75612c0a4d6bbcef7efb944604340c2 ("spi:
Eliminate 3WIRE spi_transfer check")).

Signed-off-by: Geert Uytterhoeven <geert+renesas@linux-m68k.org>
Signed-off-by: Mark Brown <broonie@linaro.org>


# b6fb8d3a 09-Jan-2014 Mika Westerberg <mika.westerberg@linux.intel.com>

spi: Check conflicting CS based on spi->chip_select instead of device name

Commit e13ac47bec20 (spi: Use stable dev_name for ACPI enumerated SPI
slaves) changed the SPI device naming to be based on ACPI device name
instead of carrying bus number and chip select for devices enumerated
from ACPI namespace.

In case of a buggy BIOS that lists multiple SPI devices sharing the same
chip select (even though they should use different) the current code fails
to detect that and allows the devices to be added to the bus.

Fix this by walking through the bus and comparing spi->chip_select instead
of device name. This should work regardless what the device name will be in
future.

Signed-off-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Acked-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# a89e2d27 09-Jan-2014 Axel Lin <axel.lin@ingics.com>

spi: core: Use list_first_entry to extract head of queue

For slightly better readability.

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# e120cc0d 05-Jan-2014 Daniel Santos <daniel.santos@pobox.com>

spidev: fix hang when transfer_one_message fails

This corrects a problem in spi_pump_messages() that leads to an spi
message hanging forever when a call to transfer_one_message() fails.
This failure occurs in my MCP2210 driver when the cs_change bit is set
on the last transfer in a message, an operation which the hardware does
not support.

Rationale
Since the transfer_one_message() returns an int, we must presume that it
may fail. If transfer_one_message() should never fail, it should return
void. Thus, calls to transfer_one_message() should properly manage a
failure.

Fixes: ffbbdd21329f3 (spi: create a message queueing infrastructure)
Signed-off-by: Daniel Santos <daniel.santos@pobox.com>
Signed-off-by: Mark Brown <broonie@linaro.org>
Cc: stable@vger.kernel.org


# 1cfd97f9 02-Jan-2014 Axel Lin <axel.lin@ingics.com>

spi: core: Use list_first_entry_or_null() instead of open-coded

Use list_first_entry_or_null() to save a few lines.

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 368ca4e0 26-Dec-2013 Trent Piepho <tpiepho@gmail.com>

spi: Eliminate 3WIRE spi_transfer check

Checking for SPI_3WIRE isn't needed. spi_setup() already prevents 3WIRE
mode from being combined with DUAL or QUAD mode support. So there is no
need to differentiate between a single bit device with SPI_3WIRE set and
one with without. It doesn't change the allowed bit widths.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 90808738 13-Nov-2013 Mark Brown <broonie@linaro.org>

spi: Factor validation and initialisation of messages outside lock

Currently we do a bunch of per-message validation and initialisation in
__spi_async() which is called with the bus lock held. Since none of this
validation depends on the current bus status there's no need to hold the
lock to do it so split it out into a separate __spi_validate() function
which is called prior to taking the bus lock.

This could be slightly neater but keep things simple for now to show the
code motion clearly.

Based on observations from Martin Sperl.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 4b92894e 21-Nov-2013 Stephen Warren <swarren@nvidia.com>

spi: core: invert success test in devm_spi_register_master

devres_add() should be called when the action to be undone succeeded,
not when it failed. Fix the inverted test in devm_spi_register_master()
which was doing the opposite.

The user-visible issue without this fix is:
insmod spi-tegra114.ko
Assume there's an MTD device on that SPI bus, which creates /dev/mtd0.
rmmod spi-tegra114
Doesn't remove devices on the SPI bus.
insmod spi-tegra114.ko
Creates a duplicate SPI device which creates /dev/mtd1.
hexdump -C /dev/mtd0
That's the old device, which uses an SPI bus hosted by a non-existent
module, which causes the oops below.

Unable to handle kernel paging request at virtual address bf0017c0
pgd = c0004000
[bf0017c0] *pgd=ad51b811, *pte=00000000, *ppte=00000000
Internal error: Oops: 80000007 [#1] PREEMPT SMP ARM
...
PC is at 0xbf0017c0
LR is at spi_pump_messages+0x15c/0x204
pc : [<bf0017c0>] lr : [<c02f0af8>] psr: 60000113
...

Fixes: 666d5b4c742b ("spi: core: Add devm_spi_register_master()")
Signed-off-by: Stephen Warren <swarren@nvidia.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 16735d02 14-Nov-2013 Wolfram Sang <wsa@kernel.org>

tree-wide: use reinit_completion instead of INIT_COMPLETION

Use this new function to make code more comprehensible, since we are
reinitialzing the completion, not initializing.

[akpm@linux-foundation.org: linux-next resyncs]
Signed-off-by: Wolfram Sang <wsa@the-dreams.de>
Acked-by: Linus Walleij <linus.walleij@linaro.org> (personally at LCE13)
Cc: Ingo Molnar <mingo@kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# e13ac47b 14-Nov-2013 Jarkko Nikula <jarkko.nikula@linux.intel.com>

spi: Use stable dev_name for ACPI enumerated SPI slaves

Current spi bus_num.chip_select "spix.y" based device naming scheme may not
be stable enough to be used in name based matching, for instance within
ALSA SoC subsystem.

This can be problem in PC kind of platforms if there are changes in SPI bus
configuration, amount of busses or probe order.

This patch addresses the problem by using the ACPI device name with
"spi-" prefix for ACPI enumerated SPI slave. For them device name
"spix.y" becomes "spi-INTABCD:ij".

Signed-off-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Acked-by: Mark Brown <broonie@linaro.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# 7b199811 11-Nov-2013 Rafael J. Wysocki <rafael.j.wysocki@intel.com>

ACPI / driver core: Store an ACPI device pointer in struct acpi_dev_node

Modify struct acpi_dev_node to contain a pointer to struct acpi_device
associated with the given device object (that is, its ACPI companion
device) instead of an ACPI handle corresponding to it. Introduce two
new macros for manipulating that pointer in a CONFIG_ACPI-safe way,
ACPI_COMPANION() and ACPI_COMPANION_SET(), and rework the
ACPI_HANDLE() macro to take the above changes into account.
Drop the ACPI_HANDLE_SET() macro entirely and rework its users to
use ACPI_COMPANION_SET() instead. For some of them who used to
pass the result of acpi_get_child() directly to ACPI_HANDLE_SET()
introduce a helper routine acpi_preset_companion() doing an
equivalent thing.

The main motivation for doing this is that there are things
represented by struct acpi_device objects that don't have valid
ACPI handles (so called fixed ACPI hardware features, such as
power and sleep buttons) and we would like to create platform
device objects for them and "glue" them to their ACPI companions
in the usual way (which currently is impossible due to the
lack of valid ACPI handles). However, there are more reasons
why it may be useful.

First, struct acpi_device pointers allow of much better type checking
than void pointers which are ACPI handles, so it should be more
difficult to write buggy code using modified struct acpi_dev_node
and the new macros. Second, the change should help to reduce (over
time) the number of places in which the result of ACPI_HANDLE() is
passed to acpi_bus_get_device() in order to obtain a pointer to the
struct acpi_device associated with the given "physical" device,
because now that pointer is returned by ACPI_COMPANION() directly.
Finally, the change should make it easier to write generic code that
will build both for CONFIG_ACPI set and unset without adding explicit
compiler directives to it.

Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Tested-by: Mika Westerberg <mika.westerberg@linux.intel.com> # on Haswell
Reviewed-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Reviewed-by: Aaron Lu <aaron.lu@intel.com> # for ATA and SDIO part


# 5fe5f05e 13-Oct-2013 Jingoo Han <jg1.han@samsung.com>

spi: Fix checkpatch issue

Fix the following checkpatch error and warnings.

ERROR: space required after that ',' (ctx:VxV)
WARNING: quoted string split across lines
WARNING: max() should probably be max_t(int, nb, master->num_chipselect)
WARNING: sizeof *spi should be sizeof(*spi)
WARNING: sizeof *master should be sizeof(*master)
WARNING: sizeof x should be sizeof(x)

Signed-off-by: Jingoo Han <jg1.han@samsung.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# b158935f 05-Oct-2013 Mark Brown <broonie@linaro.org>

spi: Provide common spi_message processing loop

The loops which SPI controller drivers use to process the list of transfers
in a spi_message are typically very similar and have some error prone areas
such as the handling of /CS. Help simplify drivers by factoring this code
out into the core - if drivers provide a transfer_one() function instead
of a transfer_one_message() function the core will handle processing at the
message level.

/CS can be controlled by either setting cs_gpio or providing a set_cs
function. If this is not possible for hardware reasons then both can be
omitted and the driver should continue to implement manual /CS handling.

This is a first step in refactoring and it is expected that there will be
further enhancements, for example factoring out of the mapping of transfers
for DMA and the initiation and completion of interrupt driven transfers.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 2841a5fc 04-Oct-2013 Mark Brown <broonie@linaro.org>

spi: Provide per-message prepare and unprepare operations

Many SPI drivers perform setup and tear down on every message, usually
doing things like DMA mapping the message. Provide hooks for them to use
to provide such operations.

This is of limited value for drivers that implement transfer_one_message()
but will be of much greater utility with future factoring out of standard
implementations of that function.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 33cf00e5 10-Oct-2013 Mika Westerberg <mika.westerberg@linux.intel.com>

spi: attach/detach SPI device to the ACPI power domain

If the SPI device is enumerated from ACPI namespace (it has an ACPI handle)
it might have ACPI methods that needs to be called in order to transition
the device to different power states (such as _PSx).

We follow what has been done for platform and I2C buses here and attach the
SPI device to the ACPI power domain if the device has an ACPI handle. This
makes sure that the device is powered on when its ->probe() is called.

For non-ACPI devices this patch is a no-op.

Signed-off-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Acked-by: Mark Brown <broonie@linaro.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# cf9eb39c 10-Oct-2013 Jarkko Nikula <jarkko.nikula@linux.intel.com>

spi: Fix modalias for ACPI enumerated SPI devices

There is a minor fault about ACPI enumerated SPI devices with their modalias
attribute. Now modalias is set by device instance not by hardware ID.
For example "spi:INTABCD:00", "spi:INTABCD:01" etc.

This means each device instance gets different modalias which does match
with generated modules.alias. Currently this is not problem as matching can
happen also with "acpi:INTABCD" modalias.

Fix this by using ACPI hardware ID.

Signed-off-by: Jarkko Nikula <jarkko.nikula@linux.intel.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# aa7da564 07-Oct-2013 Greg Kroah-Hartman <gregkh@linuxfoundation.org>

spi: convert bus code to use dev_groups

The dev_attrs field of struct bus_type is going away soon, dev_groups
should be used instead. This converts the spi bus code to use the
correct field.

Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 56ec1978 07-Oct-2013 Mark Brown <broonie@linaro.org>

spi: Provide trace points for message processing

Provide tracepoints for the lifecycle of a message from submission to
completion and for the active time for masters to help with performance
analysis of SPI I/O.

Signed-off-by: Mark Brown <broonie@linaro.org>


# 89da4293 27-Sep-2013 Trent Piepho <tpiepho@gmail.com>

spi: Use of_property_read_u32

Instead of getting the raw property, checking the length, and doing
endian conversion each time, use the OF function
of_property_read_u32() that does all that.

Error messages are slightly improved with error codes from
of_property_read_u32() for different ways the property may be invalid
(missing, too short, etc.)

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 70fac17c 31-Aug-2013 Mathias Krause <minipli@googlemail.com>

spi: simplify call to request_module()

request_module() can handle format strings on its own, no need to create
the full module name ourself.

Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 666d5b4c 31-Aug-2013 Mark Brown <broonie@linaro.org>

spi: core: Add devm_spi_register_master()

Help simplify the cleanup code for SPI master drivers by providing a
managed master registration function, ensuring that the master is
automatically unregistered whenever the device is unbound.

Signed-off-by: Mark Brown <broonie@linaro.org>


# a110f93d 01-Sep-2013 wangyuhang <wangyuhang2014@gmail.com>

spi: quad: fix the name of DT property

spi: quad: fix the name of DT property in patch

The previous property name spi-tx-nbits and spi-rx-nbits looks not
human-readable. To make it consistent with other devices, using property
name spi-tx-bus-width and spi-rx-bus-width instead of the previous one
specify the number of data wires that spi controller will work in.
Add the specification in spi-bus.txt.

Signed-off-by: wangyuhang <wangyuhang2014@gmail.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# e93b0724 31-Aug-2013 Axel Lin <axel.lin@ingics.com>

spi: core: Fix spi_register_master error handling

In the case spi_master_initialize_queue() fails, current code calls
device_unregister() before return error from spi_register_master().
However, all the drivers call spi_master_put() in the error path if
spi_register_master() fails. Thus we should call device_del() rather than
device_unregister() before return error from spi_register_master().

This also makes all the spi_register_master() error handling consistent,
because all other error paths of spi_register_master() expect drivers to
call spi_master_put() if spi_register_master() fails.

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# a822e99c 30-Aug-2013 Mark Brown <broonie@linaro.org>

spi: quad: Make DT properties optional

The addition SPI quad support made the DT properties mandatory, breaking
compatibility with existing systems. Fix that by making them optional,
also improving the error messages while we're at it.

Signed-off-by: Mark Brown <broonie@linaro.org>
Tested-by: Stephen Warren <swarren@nvidia.com>


# d5ee722a 30-Aug-2013 wangyuhang <wangyuhang2014@gmail.com>

spi: quad: Fix missing return

Delete a "return" when commit the patch to a new kernel version
by mistake. So recover it.

Signed-off-by: wangyuhang <wangyuhang2014@gmail.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 96b3eace 22-Aug-2013 Axel Lin <axel.lin@ingics.com>

spi: Remove a redundant test for master->running in spi_queued_transfer

We have tested master->running immediately after grab the master->queue_lock.
The status of master->running won't be changed until we release the lock.
Thus remove a redundant test for master->running.

Signed-off-by: Axel Lin <axel.lin@ingics.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# db90a441 22-Aug-2013 Sourav Poddar <sourav.poddar@ti.com>

spi: conditional checking of mode and transfer bits.

There is a bug in the following patch:
http://comments.gmane.org/gmane.linux.kernel.spi.devel/14420

spi: DUAL and QUAD support

fix the previous patch some mistake below:
1. DT in slave node, use "spi-tx-nbits = <1/2/4>" in place of using
"spi-tx-dual, spi-tx-quad" directly, same to rx. So correct the
previous way to get the property in @of_register_spi_devices().
2. Change the value of transfer bit macro(SPI_NBITS_SINGLE, SPI_NBITS_DUAL
SPI_NBITS_QUAD) to 0x01, 0x02 and 0x04 to match the actual wires.
3. Add the following check
(1)keep the tx_nbits and rx_nbits in spi_transfer is not beyond the
single, dual and quad.
(2)keep tx_nbits and rx_nbits are contained by @spi_device->mode
example: if @spi_device->mode = DUAL, then tx/rx_nbits can not be set
to QUAD(SPI_NBITS_QUAD)
(3)if "@spi_device->mode & SPI_3WIRE", then tx/rx_nbits should be in
single(SPI_NBITS_SINGLE)

Checking of the tx/rx transfer bits and mode bits should be done conditionally
based on type of buffer filled else EINVAL condition will
always get hit either for rx or tx.

Signed-off-by: Sourav Poddar <sourav.poddar@ti.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# f477b7fb 11-Aug-2013 wangyuhang <wangyuhang2014@gmail.com>

spi: DUAL and QUAD support

fix the previous patch some mistake below:
1. DT in slave node, use "spi-tx-nbits = <1/2/4>" in place of using
"spi-tx-dual, spi-tx-quad" directly, same to rx. So correct the
previous way to get the property in @of_register_spi_devices().
2. Change the value of transfer bit macro(SPI_NBITS_SINGLE, SPI_NBITS_DUAL
SPI_NBITS_QUAD) to 0x01, 0x02 and 0x04 to match the actual wires.
3. Add the following check
(1)keep the tx_nbits and rx_nbits in spi_transfer is not beyond the
single, dual and quad.
(2)keep tx_nbits and rx_nbits are contained by @spi_device->mode
example: if @spi_device->mode = DUAL, then tx/rx_nbits can not be set
to QUAD(SPI_NBITS_QUAD)
(3)if "@spi_device->mode & SPI_3WIRE", then tx/rx_nbits should be in
single(SPI_NBITS_SINGLE)

Signed-off-by: wangyuhang <wangyuhang2014@gmail.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 56ede94a 14-Aug-2013 Gabor Juhos <juhosg@openwrt.org>

spi: limit default transfer speed to controller's max speed

Since the 'spi: Support transfer speed checking in the core'
change, the SPI core validates the desired speed of a given
transfer against the minimum and maximum speeds supported by
the controller.

If the speed of a transfer is not specified, the core uses
the maximum speed of the actual SPI device. However if the
maximum speed of the actual device is greater than the
maximum speed of the controller, the core will reject the
transfer due to the aforementioned change.

Change the code to use the maximum speed of the controller
by default if that is below the device's maximum speed.

Signed-off-by: Gabor Juhos <juhosg@openwrt.org>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 49834de2 28-Jul-2013 Mark Brown <broonie@linaro.org>

spi: Provide core support for runtime PM during transfers

Most SPI drivers that implement runtime PM support use identical code to
do so: they acquire a runtime PM lock in prepare_transfer_hardware() and
then they release it in unprepare_transfer_hardware(). The variations in
this are mostly missing error checking and the choice to use autosuspend.

Since these runtime PM calls are normally the only thing in the prepare
and unprepare callbacks and the autosuspend API transparently does the
right thing on devices with autosuspend disabled factor all of this out
into the core with a flag to enable the behaviour.

Signed-off-by: Mark Brown <broonie@linaro.org>
Reviewed-by: Stephen Warren <swarren@nvidia.com>
Acked-by: Linus Walleij <linus.walleij@linaro.org>


# 078726ce 18-Jul-2013 Sourav Poddar <sourav.poddar@ti.com>

driver: spi: Modify core to compute the message length

Make spi core calculate the message length while
populating the other transfer parameters.

Usecase, driver can use it to populate framelength filed in their
controller.

Signed-off-by: Sourav Poddar <sourav.poddar@ti.com>
Signed-off-by: Mark Brown <broonie@linaro.org>


# 24a0013a 10-Jul-2013 Mark Brown <broonie@linaro.org>

spi: More sanity checks for transfers

Check that transfers are non-empty and that there is a completion for
them.

Signed-off-by: Mark Brown <broonie@linaro.org>


# a2fd4f9f 10-Jul-2013 Mark Brown <broonie@linaro.org>

spi: Support transfer speed checking in the core

Allow drivers to avoid implementing their own checks for simple rates by
specifying the limits in the master structure.

Signed-off-by: Mark Brown <broonie@linaro.org>


# f170168b 03-Jul-2013 Kees Cook <keescook@chromium.org>

drivers: avoid parsing names as kthread_run() format strings

Calling kthread_run with a single name parameter causes it to be handled
as a format string. Many callers are passing potentially dynamic string
content, so use "%s" in those cases to avoid any potential accidents.

Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 45f0a85c 03-Jun-2013 Rafael J. Wysocki <rafael.j.wysocki@intel.com>

PM / Runtime: Rework the "runtime idle" helper routine

The "runtime idle" helper routine, rpm_idle(), currently ignores
return values from .runtime_idle() callbacks executed by it.
However, it turns out that many subsystems use
pm_generic_runtime_idle() which checks the return value of the
driver's callback and executes pm_runtime_suspend() for the device
unless that value is not 0. If that logic is moved to rpm_idle()
instead, pm_generic_runtime_idle() can be dropped and its users
will not need any .runtime_idle() callbacks any more.

Moreover, the PCI, SCSI, and SATA subsystems' .runtime_idle()
routines, pci_pm_runtime_idle(), scsi_runtime_idle(), and
ata_port_runtime_idle(), respectively, as well as a few drivers'
ones may be simplified if rpm_idle() calls rpm_suspend() after 0 has
been returned by the .runtime_idle() callback executed by it.

To reduce overall code bloat, make the changes described above.

Tested-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Tested-by: Kevin Hilman <khilman@linaro.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Acked-by: Kevin Hilman <khilman@linaro.org>
Reviewed-by: Ulf Hansson <ulf.hansson@linaro.org>
Acked-by: Alan Stern <stern@rowland.harvard.edu>


# 8ec5d84e 13-Feb-2013 Andreas Larsson <andreas@gaisler.com>

spi: Return error from of_spi_register_master on bad "cs-gpios" property

This makes sure that an error is returned on an incorrectly formed
"cs-gpios" property, but reports success when the "cs-gpios" property is
well formed or missing.

When holes in the cs-gpios property phandle list is used to indicate
that some other form of chipselect is to be used it is important that
failure to read a broken "cs-gpios" property does not silently fail
leading to the spi controller to use an unintended chipselect.

Signed-off-by: Andreas Larsson <andreas@gaisler.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 446411e1 13-Feb-2013 Andreas Larsson <andreas@gaisler.com>

spi: Initialize cs_gpio and cs_gpios with -ENOENT

The return value from of_get_named_gpio is -ENOENT when the given index
matches a hole in the "cs-gpios" property phandle list. However, the
default value of cs_gpio in struct spi_device and entries of cs_gpios in
struct spi_master is -EINVAL, which is documented to indicate that a
GPIO line should not be used for the given spi_device.

This sets the default value of cs_gpio in struct spi_device and entries
of cs_gpios in struct spi_master to -ENOENT. Thus, -ENOENT is the only
value used to indicate that no GPIO line should be used.

Signed-off-by: Andreas Larsson <andreas@gaisler.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 29896178 31-Mar-2013 Rafael J. Wysocki <rafael.j.wysocki@intel.com>

ACPI / SPI: Use parent's ACPI_HANDLE() in acpi_register_spi_devices()

The ACPI handle of struct spi_master's dev member should not be
set, because this causes that struct spi_master to be associated
with the ACPI device node corresponding to its parent as the
second "physical_device", which is incorrect (this happens during
the registration of struct spi_master). Consequently,
acpi_register_spi_devices() should use the ACPI handle of the
parent of the struct spi_master it is called for rather than that
struct spi_master's ACPI handle (which should be NULL).

Make that happen and modify the spi-pxa2xx driver, which currently is
the only driver for ACPI-enumerated SPI controller chips, not to set
the ACPI handle for the struct spi_master it creates.

Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
Acked-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Acked-by: Mark Brown <broonie@opensource.wolfsonmicro.com>


# b0b36b86 13-Mar-2013 Bryan Freed <bfreed@chromium.org>

spi: Unlock a spinlock before calling into the controller driver.

spi_pump_messages() calls into a controller driver with
unprepare_transfer_hardware() which is documented as "This may sleep".
As in the prepare_transfer_hardware() call below, we should release the
queue_lock spinlock before making the call.
Rework the logic a bit to hold queue_lock to protect the 'busy' flag,
then release it to call unprepare_transfer_hardware().

Signed-off-by: Bryan Freed <bfreed@chromium.org>
Reviewed-by: Doug Anderson <dianders@chromium.org>
Signed-off-by: Doug Anderson <dianders@chromium.org>
Acked-by: Linus Walleij <linus.walleij@linaro.org>
Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>


# 543bb255 26-Mar-2013 Stephen Warren <swarren@wwwdotorg.org>

spi: add ability to validate xfer->bits_per_word in SPI core

Allow SPI masters to define the set of bits_per_word values they support.
If they do this, then the SPI core will reject transfers that attempt to
use an unsupported bits_per_word value. This eliminates the need for each
SPI driver to implement this checking in most cases.

Signed-off-by: Stephen Warren <swarren@wwwdotorg.org>
Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>


# e80beb27 12-Feb-2013 Grant Likely <grant.likely@secretlab.ca>

gpio: Make of_count_named_gpios() use new of_count_phandle_with_args()

This patch replaces the horribly coded of_count_named_gpios() with a
call to of_count_phandle_with_args() which is far more efficient. This
also changes the return value of of_gpio_count() & of_gpio_named_count()
from 'unsigned int' to 'int' so that it can return an error code. All
the users of that function are fixed up to correctly handle a negative
return value.

v2: Split GPIO portion into a separate patch

Tested-by: Andreas Larsson <andreas@gaisler.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>
Cc: Linus Walleij <linus.walleij@linaro.org>
Cc: Rob Herring <rob.herring@calxeda.com>


# 0da83bb1 29-Jan-2013 Andreas Larsson <andreas@gaisler.com>

spi/of: Fix initialization of cs_gpios array

Using memset does not set an array of integers properly. Replace with a
loop to set each element properly.

Signed-off-by: Andreas Larsson <andreas@gaisler.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 8bd75c77 07-Feb-2013 Clark Williams <williams@redhat.com>

sched/rt: Move rt specific bits into new header file

Move rt scheduler definitions out of include/linux/sched.h into
new file include/linux/sched/rt.h

Signed-off-by: Clark Williams <williams@redhat.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Link: http://lkml.kernel.org/r/20130207094707.7b9f825f@riff.lan
Signed-off-by: Ingo Molnar <mingo@kernel.org>


# 9f3b795a 01-Feb-2013 Michał Mirosław <mirq-linux@rere.qmqm.pl>

driver-core: constify data for class_find_device()

All in-kernel users of class_find_device() don't really need mutable
data for match callback.

In two places (kernel/power/suspend_test.c, drivers/scsi/osd/osd_uld.c)
this patch changes match callbacks to use const search data.

The const is propagated to rtc_class_open() and power_supply_get_by_name()
parameters.

Note that there's a dev reference leak in suspend_test.c that's not
touched in this patch.

Signed-off-by: Michał Mirosław <mirq-linux@rere.qmqm.pl>
Acked-by: Grant Likely <grant.likely@secretlab.ca>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 2cd94c8a 26-Jan-2013 Mark Brown <broonie@opensource.wolfsonmicro.com>

spi: Ensure memory used for spi_write_then_read() is DMA safe

Use GFP_DMA in order to ensure that the memory we allocate for transfers
in spi_write_then_read() can be DMAed. On most platforms this will have
no effect.

Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 059b8ffe 04-Jan-2013 Laxman Dewangan <ldewangan@nvidia.com>

spi: make sure all transfer has proper speed set

When spi client does the spi transfer and if it does not set
the speed for each transfer then set it as default
of spi device in spi core before calling low level transfer.

This will remove the extra check in low level driver for setting
speed.

Signed-off-by: Laxman Dewangan <ldewangan@nvidia.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# bb29785e 21-Dec-2012 Grant Likely <grant.likely@secretlab.ca>

spi/of: Use DT aliases for assigning bus number

Linux assigns a number to each spi_master in the system, but when the
platform used the device tree, the numbers are dynamically assigned and
are not predictable. In general this shouldn't matter since the kernel
doesn't use the bus number for anything other than matching a bus to
spi_boardinfo (not used for DT). However, sometimes userspace needs to
figure out which bus is which, so it makes sense to use the global
/aliases namespace to choose a specific bus number.

It is safe to derive the bus number from an alias because aliases will
never cause two buses to try and use the same bus number. (At one time
the cell-index property was used for this purpose, but cell-index has
the risk of an id collision).

Signed-off-by: Grant Likely <grant.likely@secretlab.ca>
Cc: Anatolij Gustschin <agust@denx.de>
Cc: Mark Brown <broonie@opensource.wolfsonmicro.com>


# cb71941a 22-May-2012 David Daney <david.daney@cavium.com>

of/spi: Fix SPI module loading by using proper "spi:" modalias prefixes.

To get modprobe to automatically load the proper modules, we need to
prefix things with "spi:". Partially based on Grant Likely's suggestions.

Signed-off-by: David Daney <david.daney@cavium.com>
[grant.likely: reworked because drivers/of/of_spi.c has been removed]
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 7cb94361 04-Dec-2012 Andreas Larsson <andreas@gaisler.com>

spi/sparc: Allow of_register_spi_devices for sparc

The spi support code works on SPARC too. No reason to exclude it from
the party.

Signed-off-by: Andreas Larsson <andreas@gaisler.com>
Acked-by: David S. Miller <davem@davemloft.net>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# fd4a319b 07-Dec-2012 Grant Likely <grant.likely@secretlab.ca>

spi: Remove HOTPLUG section attributes

CONFIG_HOTPLUG is going away as an option. As result the __dev*
markings will be going away.

Remove use of __devinit, __devexit_p, __devinitdata, __devinitconst,
and __devexit.

Bill Pemberton has done most of the legwork on this series. I've used
his script to purge the attributes from the drivers/gpio tree.

Reported-by: Bill Pemberton <wfp5p@virginia.edu>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# c20151df 06-Dec-2012 Lars-Peter Clausen <lars@metafoo.de>

spi: Add support for specifying 3-wire mode via device tree

This patch allows to specify that a SPI device is connected in 3-wire mode via
device tree.

Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Acked-by: Rob Herring <rob.herring@calxeda.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 5323f498 06-Dec-2012 Grant Likely <grant.likely@secretlab.ca>

spi: Fix comparison of different integer types

Fix problem discovered with sparse:
+ drivers/spi/spi.c:1554:37: sparse: incompatible types in comparison expression (different signedness)
drivers/spi/spi.c: In function 'spi_write_then_read':
drivers/spi/spi.c:1554:23: warning: comparison of distinct pointer types lacks a cast [enabled by default]

The change to SPI_BUFSIZ was introduced in commit b3a223ee2, "spi:
Remove SPI_BUFSIZ restriction on spi_write_then_read()"

Cc: Mark Brown <broonie@opensource.wolfsonmicro.com>
Reported-by: kbuild test robot <fengguang.wu@intel.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# b3a223ee 01-Dec-2012 Mark Brown <broonie@opensource.wolfsonmicro.com>

spi: Remove SPI_BUFSIZ restriction on spi_write_then_read()

In order to avoid constantly allocating and deallocating there is a fixed
buffer which spi_write_then_read() uses for transfers, with an early error
check to ensure that the transfer fits within the buffer. This limits the
size of transfers to this size, currently max(32, SMP_CACHE_BYTES).

Since we can dynamically allocate and in fact already have a fallback
to do so when there is contention for the fixed buffer remove this
restriction and instead dynamically allocate a suitably sized buffer if
the transfer won't fit.

Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 64bee4d2 29-Nov-2012 Mika Westerberg <mika.westerberg@linux.intel.com>

spi / ACPI: add ACPI enumeration support

ACPI 5 introduced SPISerialBus resource that allows us to enumerate and
configure the SPI slave devices behind the SPI controller. This patch adds
support for this to the SPI core.

In addition we bind ACPI nodes to SPI devices. This makes it possible for
the slave drivers to get the ACPI handle for further configuration.

Signed-off-by: Mika Westerberg <mika.westerberg@linux.intel.com>
Acked-by: Grant Likely <grant.likely@secretlab.ca>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>


# f3b6159e 29-Nov-2012 Alexander Sverdlin <alexander.sverdlin@sysgo.com>

of/spi: Honour "status=disabled" property of device

Currently of_register_spi_devices() function registers all SPI devices,
independetly from their status property in device tree. According to
"ePAPR 1.1" spec, device should only be registered if there is no
"status" property, or it has "ok" (or "okay") value (see
of_device_is_available()). In case of "platform devices",
of_platform_device_create_pdata() checks for "status" and ensures
that disabled devices are not pupulated. But such check for SPI buses
was missing until now. Fix it.

Signed-off-by: Alexander Sverdlin <alexander.sverdlin@sysgo.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 74317984 15-Nov-2012 Jean-Christophe PLAGNIOL-VILLARD <plagnioj@jcrosoft.com>

of_spi: add generic binding support to specify cs gpio

This will allow to use gpio for chip select with no modification in the
driver binding

When use the cs-gpios, the gpio number will be passed via the cs_gpio field
and the number of chip select will automatically increased with max(hw cs, gpio cs).

So if for example the controller has 2 CS lines, and the cs-gpios
property looks like this:

cs-gpios = <&gpio1 0 0> <0> <&gpio1 1 0> <&gpio1 2 0>;

Then it should be configured so that num_chipselect = 4 with the
following mapping:

cs0 : &gpio1 0 0
cs1 : native
cs2 : &gpio1 1 0
cs3 : &gpio1 2 0

Signed-off-by: Jean-Christophe PLAGNIOL-VILLARD <plagnioj@jcrosoft.com>
Cc: devicetree-discuss@lists.ozlabs.org
Cc: spi-devel-general@lists.sourceforge.net
Signed-off-by: Richard Genoud <richard.genoud@gmail.com>
[grant.likely: fixed up type of cs count so min() can do type checking]
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# caae070c 09-Nov-2012 Laxman Dewangan <ldewangan@nvidia.com>

spi: Dont call master->setup if not populated

Currently the master->setup() is called unconditionally.
The assumption is that every driver need to implement this
callback. This encourages drivers to populate empty functions
to prevent crashing.

This patch prevents the call of master->setup() if it is not
populated.

Signed-off-by: Laxman Dewangan <ldewangan@nvidia.com>
Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>


# e6811d1d 09-Nov-2012 Laxman Dewangan <ldewangan@nvidia.com>

spi: make sure all transfer has bits_per_word set

When spi client does the spi transfer and does not sets
the bits_per_word for each transfer then set it as default
of spi device in spi core before calling low level transfer.

Removing the similar code from spi-tegra20-slink driver as
it is not required.

Signed-off-by: Laxman Dewangan <ldewangan@nvidia.com>
Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>


# d8e328b3 20-May-2012 Grant Likely <grant.likely@secretlab.ca>

spi: Add "spi:" prefix to modalias attribute of spi devices

The modalias attribute of spi devices doesn't have the "spi:" prefix
that is used in the UEVENT and in spi device drivers. This patch adds
the prefix so the modprobe can correctly match modules to devices.

Reported-by: David Daney <david.daney@cavium.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 1e8a52e1 19-May-2012 Grant Likely <grant.likely@secretlab.ca>

spi: By default setup spi_masters with 1 chipselect and dynamics bus number

Trivial simplification. Instead of requiring spi master drivers to
always set the bus number (even when a dynamic number is desired),
this patch modifies spi_alloc_master() to initialize num_chipselect to
1 (because there will always be at least one CS) and bus_num to -1 for
dynamic allocation. This simplifies the code needed to be written for
drivers.

Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 7dfd2bd7 10-May-2012 Shubhrajyoti D <shubhrajyoti@ti.com>

spi: Dont call prepare/unprepare transfer if not populated

Currently the prepare/unprepare transfer are called unconditionally.
The assumption is that every driver using the spi core queue infrastructure
has to populate the prepare and unprepare functions. This encourages
drivers to populate empty functions to prevent crashing.
This patch prevents the call to prepare/unprepare if not populated.

Signed-off-by: Shubhrajyoti D <shubhrajyoti@ti.com>
Acked-by: Linus Walleij <linus.walleij@linaro.org>
[grant.likely: fix whitespace defect]
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# d57a4282 07-Apr-2012 Grant Likely <grant.likely@secretlab.ca>

spi/devicetree: Move devicetree support code into spi directory

The SPI device tree support code isn't shared by any other subsystem. It can
be moved into the core drivers/spi directory and the exported symbol can be
removed.

Signed-off-by: Grant Likely <grant.likely@secretlab.ca>
Cc: Rob Herring <rob.herring@calxeda.com>


# a66590de 14-Mar-2012 Guennadi Liakhovetski <g.liakhovetski@gmx.de>

spi: remove redundant variable assignment

The status variable is guaranteed to be 0 at that location anyway.

Signed-off-by: Guennadi Liakhovetski <g.liakhovetski@gmx.de>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 9af4acc0 10-Mar-2012 Dan Carpenter <dan.carpenter@oracle.com>

spi: release lock on error path in spi_pump_messages()

We should release the lock here and enable IRQs before returning.

Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
[grant.likely: move unlock above dev_err() call]
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 690fb11b 17-Feb-2012 Mark Brown <broonie@opensource.wolfsonmicro.com>

spi: Mark spi_register_board_info() __devinit

Some systems have SPI devices located on plugin modules which are
enumerated at runtime as devices. The drivers for these plugin modules
need to register their SPI devices at probe() time so want to be able
to call spi_register_board_info() but that function is currently marked
as __init rather than __devinit so this usage isn't legal. Change the
annotation to __devinit to handle this.

Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# eb4af0f5 23-Feb-2012 Uwe Kleine-König <u.kleine-koenig@pengutronix.de>

spi/doc: spi_master_put must be followed up by kfree

Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# ffbbdd21 22-Feb-2012 Linus Walleij <linus.walleij@linaro.org>

spi: create a message queueing infrastructure

This rips the message queue in the PL022 driver out and pushes
it into (optional) common infrastructure. Drivers that want to
use the message pumping thread will need to define the new
per-messags transfer methods and leave the deprecated transfer()
method as NULL.

Most of the design is described in the documentation changes that
are included in this patch.

Since there is a queue that need to be stopped when the system
is suspending/resuming, two new calls are implemented for the
device drivers to call in their suspend()/resume() functions:
spi_master_suspend() and spi_master_resume().

ChangeLog v1->v2:
- Remove Kconfig entry and do not make the queue support optional
at all, instead be more agressive and have it as part of the
compulsory infrastructure.
- If the .transfer() method is implemented, delete print a small
deprecation notice and do not start the transfer pump.
- Fix a bitrotted comment.
ChangeLog v2->v3:
- Fix up a problematic sequence courtesy of Chris Blair.
- Stop rather than destroy the queue on suspend() courtesy of
Chris Blair.

Signed-off-by: Chris Blair <chris.blair@stericsson.com>
Signed-off-by: Linus Walleij <linus.walleij@linaro.org>
Tested-by: Mark Brown <broonie@opensource.wolfsonmicro.com>
Reviewed-by: Mark Brown <broonie@opensource.wolfsonmicro.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 178db7d3 11-Dec-2011 Laurent Pinchart <laurent.pinchart@ideasonboard.com>

spi: Fix device unregistration when unregistering the bus master

Device are added as children of the bus master's parent device, but
spi_unregister_master() looks for devices to unregister in the bus
master's children. This results in the child devices not being
unregistered.

Fix this by registering devices as direct children of the bus master.

Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 025ed130 09-Jul-2011 Paul Gortmaker <paul.gortmaker@windriver.com>

spi: Add export.h for THIS_MODULE/EXPORT_SYMBOL to spi.c

This uses both EXPORT_SYMBOL and THIS_MODULE, both which come from
the export.h file now.

Signed-off-by: Paul Gortmaker <paul.gortmaker@windriver.com>


# ca632f55 06-Jun-2011 Grant Likely <grant.likely@secretlab.ca>

spi: reorganize drivers

Sort the SPI makefile and enforce the naming convention spi_*.c for
spi drivers.

This change also rolls the contents of atmel_spi.h into the .c file
since there is only one user of that particular include file.

v2: - Use 'spi-' prefix instead of 'spi_' to match what seems to be
be the predominant pattern for subsystem prefixes.
- Clean up filenames in Kconfig and header comment blocks

Signed-off-by: Grant Likely <grant.likely@secretlab.ca>
Acked-by: Wolfram Sang <w.sang@pengutronix.de>
Acked-by: Linus Walleij <linus.walleij@linaro.org>


# 0c4a1590 10-May-2011 Mark Brown <broonie@opensource.wolfsonmicro.com>

spi: Use void pointers for data in simple SPI I/O operations

Currently the simple SPI I/O operations all take pointers to u8 * buffers
to operate on. This creates needless type compatibility issues and the
underlying spi_transfer structure uses void pointers anyway so convert the
API over to take void pointers too.

Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 25985edc 30-Mar-2011 Lucas De Marchi <lucas.demarchi@profusion.mobi>

Fix common misspellings

Fixes generated by 'codespell' and manually reviewed.

Signed-off-by: Lucas De Marchi <lucas.demarchi@profusion.mobi>


# 3ae22e8c 25-Dec-2010 Mark Brown <broonie@opensource.wolfsonmicro.com>

spi / PM: Support dev_pm_ops

Allow SPI drivers to use runtime PM and other dev_pm_ops features by
implementing dev_pm_ops for the bus. The existing bus specific suspend
and resume functions will be called if a driver does not provide dev_pm_ops
allowing for transition to the new model.

Signed-off-by: Mark Brown <broonie@opensource.wolfsonmicro.com>
Acked-by: Grant Likely <grant.likely@secretlab.ca>
Signed-off-by: Rafael J. Wysocki <rjw@sisk.pl>


# 97dbf37d 21-Dec-2010 Sebastian Andrzej Siewior <bigeasy@linutronix.de>

drivers/spi/spi.c: don't release the spi device twice

This was fixed by David Lamparter in v2.6.36-rc5 3486008 ("spi: free
children in spi_unregister_master, not siblings") and broken again in
v2.6.37-rc1~2^2~4 during the merge of 2b9603a0 ("spi: enable
spi_board_info to be registered after spi_master").

Signed-off-by: Sebastian Andrzej Siewior <bigeasy@linutronix.de>
Signed-off-by: David Lamparter <equinox@diac24.net>
Cc: Grant Likely <grant.likely@secretlab.ca>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# eb288a1f 21-Oct-2010 Linus Walleij <linus.walleij@stericsson.com>

spi: fixed odd static string conventions in core code

This patch removes convention of passing a static string as a
parameter to another static string. The convention is intended to
reduce text usage by sharing the common bits of the string, but the
implementation is inherently fragile (a change to one format string
but not the other will nullify any possible advantage), it isn't
necessarily a net win depending on what this compiler does, and it
it reduces code readability.

Signed-off-by: Linus Walleij <linus.walleij@stericsson.com>
[grant.likely@secretlab.ca: removed dev_dbg->dev_err hunk]
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 2b9603a0 02-Aug-2010 Feng Tang <feng.tang@intel.com>

spi: enable spi_board_info to be registered after spi_master

Currently spi_register_board_info() has to be called before its related
spi_master be registered, otherwise these board info will be just ignored.

This patch will remove this order limit, it adds a global spi master list
like the existing global board info listr. Whenever a board info or a
spi_master is registered, the spi master list or board info list
will be scanned, and a new spi device will be created if there is a
master-board info match.

Signed-off-by: Feng Tang <feng.tang@intel.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 2b7a32f7 02-Oct-2010 Sinan Akman <sinan@writeme.com>

of/spi: Fix OF-style driver binding of spi devices

This patch adds the OF hook to the spi core so that devices
can automatically be registered based on device tree data. This fixes
a problem with spi devices not binding to drivers after the cleanup of
the spi & i2c binding code.

Signed-off-by: Sinan Akman <sinan@writeme.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 34860089 30-Aug-2010 David Lamparter <equinox@diac24.net>

spi: free children in spi_unregister_master, not siblings

introduced by 49dce689 ("spi doesn't need class_device") and bad-fixed
by 350d0076 ("spi: fix double-free on spi_unregister_master"),
spi_unregister_master would previously device_unregister all of the spi
master's siblings (instead of its children). hilarity ensues.

fix it to unregister children.

Signed-off-by: David Lamparter <equinox@diac24.net>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 12b15e83 27-Jul-2010 Anatolij Gustschin <agust@denx.de>

of/spi: call of_register_spi_devices() from spi core code

Move of_register_spi_devices() call from drivers to
spi_register_master(). Also change the function to use
the struct device_node pointer from master spi device
instead of passing it as function argument.

Signed-off-by: Anatolij Gustschin <agust@denx.de>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# cf32b71e 28-Jun-2010 Ernst Schwab <eschwab@online.de>

spi/mmc_spi: SPI bus locking API, using mutex

SPI bus locking API to allow exclusive access to the SPI bus, especially, but
not limited to, for the mmc_spi driver.

Coded according to an outline from Grant Likely; here is his
specification (accidentally swapped function names corrected):

It requires 3 things to be added to struct spi_master.
- 1 Mutex
- 1 spin lock
- 1 flag.

The mutex protects spi_sync, and provides sleeping "for free"
The spinlock protects the atomic spi_async call.
The flag is set when the lock is obtained, and checked while holding
the spinlock in spi_async(). If the flag is checked, then spi_async()
must fail immediately.

The current runtime API looks like this:
spi_async(struct spi_device*, struct spi_message*);
spi_sync(struct spi_device*, struct spi_message*);

The API needs to be extended to this:
spi_async(struct spi_device*, struct spi_message*)
spi_sync(struct spi_device*, struct spi_message*)
spi_bus_lock(struct spi_master*) /* although struct spi_device* might
be easier */
spi_bus_unlock(struct spi_master*)
spi_async_locked(struct spi_device*, struct spi_message*)
spi_sync_locked(struct spi_device*, struct spi_message*)

Drivers can only call the last two if they already hold the spi_master_lock().

spi_bus_lock() obtains the mutex, obtains the spin lock, sets the
flag, and releases the spin lock before returning. It doesn't even
need to sleep while waiting for "in-flight" spi_transactions to
complete because its purpose is to guarantee no additional
transactions are added. It does not guarantee that the bus is idle.

spi_bus_unlock() clears the flag and releases the mutex, which will
wake up any waiters.

The difference between spi_async() and spi_async_locked() is that the
locked version bypasses the check of the lock flag. Both versions
need to obtain the spinlock.

The difference between spi_sync() and spi_sync_locked() is that
spi_sync() must hold the mutex while enqueuing a new transfer.
spi_sync_locked() doesn't because the mutex is already held. Note
however that spi_sync must *not* continue to hold the mutex while
waiting for the transfer to complete, otherwise only one transfer
could be queued up at a time!

Almost no code needs to be written. The current spi_async() and
spi_sync() can probably be renamed to __spi_async() and __spi_sync()
so that spi_async(), spi_sync(), spi_async_locked() and
spi_sync_locked() can just become wrappers around the common code.

spi_sync() is protected by a mutex because it can sleep
spi_async() needs to be protected with a flag and a spinlock because
it can be called atomically and must not sleep

Signed-off-by: Ernst Schwab <eschwab@online.de>
[grant.likely@secretlab.ca: use spin_lock_irqsave()]
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>
Tested-by: Matt Fleming <matt@console-pimps.org>
Tested-by: Antonio Ospite <ospite@studenti.unina.it>


# 07a389fe 12-Apr-2010 Roman Tereshonkov <roman.tereshonkov@nokia.com>

spi: spi_device memory should be released instead of device.

The memory for dev variable is allocated as a part of
spi_device structure memory which the dev belongs to.
Thus when the memory is released the right pointer is used.

Signed-off-by: Roman Tereshonkov <roman.tereshonkov@nokia.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 8ec130a0 16-Apr-2010 Roman Tereshonkov <roman.tereshonkov@nokia.com>

spi: release device claimed by bus_find_device_by_name

In success case the function bus_find_device_by_name calls
get_device. In our context put_device should be called to
decrease the device count usage.

Signed-off-by: Roman Tereshonkov <roman.tereshonkov@nokia.com>
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>


# 5a0e3ad6 24-Mar-2010 Tejun Heo <tj@kernel.org>

include cleanup: Update gfp.h and slab.h includes to prepare for breaking implicit slab.h inclusion from percpu.h

percpu.h is included by sched.h and module.h and thus ends up being
included when building most .c files. percpu.h includes slab.h which
in turn includes gfp.h making everything defined by the two files
universally available and complicating inclusion dependencies.

percpu.h -> slab.h dependency is about to be removed. Prepare for
this change by updating users of gfp and slab facilities include those
headers directly instead of assuming availability. As this conversion
needs to touch large number of source files, the following script is
used as the basis of conversion.

http://userweb.kernel.org/~tj/misc/slabh-sweep.py

The script does the followings.

* Scan files for gfp and slab usages and update includes such that
only the necessary includes are there. ie. if only gfp is used,
gfp.h, if slab is used, slab.h.

* When the script inserts a new include, it looks at the include
blocks and try to put the new include such that its order conforms
to its surrounding. It's put in the include block which contains
core kernel includes, in the same order that the rest are ordered -
alphabetical, Christmas tree, rev-Xmas-tree or at the end if there
doesn't seem to be any matching order.

* If the script can't find a place to put a new include (mostly
because the file doesn't have fitting include block), it prints out
an error message indicating which .h file needs to be added to the
file.

The conversion was done in the following steps.

1. The initial automatic conversion of all .c files updated slightly
over 4000 files, deleting around 700 includes and adding ~480 gfp.h
and ~3000 slab.h inclusions. The script emitted errors for ~400
files.

2. Each error was manually checked. Some didn't need the inclusion,
some needed manual addition while adding it to implementation .h or
embedding .c file was more appropriate for others. This step added
inclusions to around 150 files.

3. The script was run again and the output was compared to the edits
from #2 to make sure no file was left behind.

4. Several build tests were done and a couple of problems were fixed.
e.g. lib/decompress_*.c used malloc/free() wrappers around slab
APIs requiring slab.h to be added manually.

5. The script was run on all .h files but without automatically
editing them as sprinkling gfp.h and slab.h inclusions around .h
files could easily lead to inclusion dependency hell. Most gfp.h
inclusion directives were ignored as stuff from gfp.h was usually
wildly available and often used in preprocessor macros. Each
slab.h inclusion directive was examined and added manually as
necessary.

6. percpu.h was updated not to include slab.h.

7. Build test were done on the following configurations and failures
were fixed. CONFIG_GCOV_KERNEL was turned off for all tests (as my
distributed build env didn't work with gcov compiles) and a few
more options had to be turned off depending on archs to make things
build (like ipr on powerpc/64 which failed due to missing writeq).

* x86 and x86_64 UP and SMP allmodconfig and a custom test config.
* powerpc and powerpc64 SMP allmodconfig
* sparc and sparc64 SMP allmodconfig
* ia64 SMP allmodconfig
* s390 SMP allmodconfig
* alpha SMP allmodconfig
* um on x86_64 SMP allmodconfig

8. percpu.h modifications were reverted so that it could be applied as
a separate patch and serve as bisection point.

Given the fact that I had only a couple of failures from tests on step
6, I'm fairly confident about the coverage of this conversion patch.
If there is a breakage, it's likely to be something in one of the arch
headers which should be easily discoverable easily on most builds of
the specific arch.

Signed-off-by: Tejun Heo <tj@kernel.org>
Guess-its-ok-by: Christoph Lameter <cl@linux-foundation.org>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: Lee Schermerhorn <Lee.Schermerhorn@hp.com>


# 568d0697 22-Sep-2009 David Brownell <dbrownell@users.sourceforge.net>

spi: handle TX-only/RX-only

Support two new half-duplex SPI implementation restrictions, for links
that talk to TX-only or RX-only devices. (Existing half-duplex flavors
support both transfer directions, just not at the same time.)

Move spi_async() into the spi.c core, and stop inlining it. Then make
that function perform error checks and reject messages that demand more
than the underlying controller can support.

Based on a patch from Marek Szyprowski which did this only for the
bitbanged GPIO driver.

Cc: Marek Szyprowski <m.szyprowski@samsung.com>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# e0626e38 22-Sep-2009 Anton Vorontsov <avorontsov@ru.mvista.com>

spi: prefix modalias with "spi:"

This makes it consistent with other buses (platform, i2c, vio, ...). I'm
not sure why we use the prefixes, but there must be a reason.

This was easy enough to do it, and I did it.

Signed-off-by: Anton Vorontsov <avorontsov@ru.mvista.com>
Cc: David Brownell <dbrownell@users.sourceforge.net>
Cc: David Woodhouse <dwmw2@infradead.org>
Cc: Grant Likely <grant.likely@secretlab.ca>
Cc: Jean Delvare <khali@linux-fr.org>
Cc: Ben Dooks <ben-linux@fluff.org>
Cc: Benjamin Herrenschmidt <benh@kernel.crashing.org>
Cc: Dmitry Torokhov <dtor@mail.ru>
Cc: Samuel Ortiz <sameo@openedhand.com>
Cc: "John W. Linville" <linville@tuxdriver.com>
Acked-by: Mike Frysinger <vapier.adi@gmail.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 75368bf6 22-Sep-2009 Anton Vorontsov <avorontsov@ru.mvista.com>

spi: add support for device table matching

With this patch spi drivers can use standard spi_driver.id_table and
MODULE_DEVICE_TABLE() mechanisms to bind against the devices. Just like
we do with I2C drivers.

This is useful when a single driver supports several variants of devices
but it is not possible to detect them in run-time (like non-JEDEC chips
probing in drivers/mtd/devices/m25p80.c), and when platform_data usage is
overkill.

This patch also makes life a lot easier on OpenFirmware platforms, since
with OF we extensively use proper device IDs in modaliases.

Signed-off-by: Anton Vorontsov <avorontsov@ru.mvista.com>
Cc: David Brownell <dbrownell@users.sourceforge.net>
Cc: David Woodhouse <dwmw2@infradead.org>
Cc: Grant Likely <grant.likely@secretlab.ca>
Cc: Jean Delvare <khali@linux-fr.org>
Cc: Ben Dooks <ben-linux@fluff.org>
Cc: Benjamin Herrenschmidt <benh@kernel.crashing.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 27570497 17-Jun-2009 Jiri Pirko <jpirko@redhat.com>

spi: fix spi_write_then_read() comment

Buffer needs not be dma-safe, not rx data length.

Signed-off-by: Jiri Pirko <jpirko@redhat.com>
Cc: David Brownell <david-b@pacbell.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# e7db06b5 17-Jun-2009 David Brownell <dbrownell@users.sourceforge.net>

spi: move more spi_setup() functionality into core

Move some common spi_setup() error checks into the SPI framework from the
spi_master controller drivers:

- Add a new "mode_bits" field to spi_master

- Use that in spi_setup to validate the spi->mode value being
requested. Setting this new field is now mandatory for any
controller supporting more than vanilla SPI_MODE_0.

- Update all spi_master drivers to:

* Initialize that field
* Remove current spi_setup() checks using that value.

This is a net minor code shrink.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 7d077197 17-Jun-2009 David Brownell <dbrownell@users.sourceforge.net>

spi: move common spi_setup() functionality into core

Start moving some spi_setup() functionality into the SPI core from the
various spi_master controller drivers:

- Make that function stop being an inline;

- Move two common idioms from drivers into that new function:
* Default bits_per_word to 8 if that field isn't set
* Issue a standardized dev_dbg() message

This is a net minor source code shrink, and supports enhancments found in
some follow-up patches.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# bdff549e 13-Apr-2009 David Brownell <dbrownell@users.sourceforge.net>

spi: spi_write_then_read() bugfixes

The "simplify spi_write_then_read()" patch included two regressions from
the 2.6.27 behaviors:

- The data it wrote out during the (full duplex) read side
of the transfer was not zeroed.

- It fails completely on half duplex hardware, such as
Microwire and most "3-wire" SPI variants.

So, revert that patch. A revised version should be submitted at some
point, which can get the speedup on standard hardware (full duplex)
without breaking on less-capable half-duplex stuff.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Cc: <stable@kernel.org> [2.6.28.x, 2.6.29.x]
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 35f74fca 06-Jan-2009 Kay Sievers <kay.sievers@vrfy.org>

spi: struct device - replace bus_id with dev_name(), dev_set_name()

Acked-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Kay Sievers <kay.sievers@vrfy.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 673c0c00 15-Oct-2008 David Brownell <dbrownell@users.sourceforge.net>

spi: core and gpio expanders use subsys_init

Make the SPI external GPIO expander drivers register themselves at
subsys_initcall() time when they're statically linked, and make the SPI
core do its driver model initialization earlier so that's safe.

SOC-integrated GPIOs are available starting very early -- often before
initcalls start to run, or earily in arch_initcall() at latest -- so this
improves consistency, letting more subsystems rely on GPIOs being usable
by their own subsys_initcall() code.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# f9b90e39 15-Oct-2008 Vernon Sauder <vernoninhand@gmail.com>

spi: simplify spi_write_then_read()

Modify spi_write_then_read() to use one transfer. This speeds up all
callers, and is a minor code shrink.

Signed-off-by: Vernon Sauder <Vernon.Sauder@gmail.com>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# e48880e0 15-Aug-2008 David Brownell <dbrownell@users.sourceforge.net>

spi: bugfix spi_add_device() with duplicate chipselects

When reviewing a recent patch I noticed a potential trouble spot in the
registration of new SPI devices. The SPI master driver is told to set
the device up before adding it to the driver model, so that it's always
properly set up when probe() is called. (This is important, because in
the case of inverted chipselects, this device can make the bus misbehave
until it's properly deselected. It's got to be set up even if no driver
binds to the device.)

The trouble spot is that it doesn't first verify that no other device
has been added using that chipselect. If such a device has been added,
its configuration gets trashed. (Fortunately this has not been a common
error!)

The fix here adds an explicit check, and a mutex to protect the relevant
critical region.

[akpm@linux-foundation.org: make the lock local to spi_add_device()]
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# dc87c98e 15-May-2008 Grant Likely <grant.likely@secretlab.ca>

spi: split up spi_new_device() to allow two stage registration.

spi_new_device() allocates and registers an spi device all in one swoop.
If the driver needs to add extra data to the spi_device before it is
registered, then this causes problems. This is needed for OF device
tree support so that the SPI device tree helper can add a pointer to
the device node after the device is allocated, but before the device
is registered. OF aware SPI devices can then retrieve data out of the
device node to populate a platform data structure.

This patch splits the allocation and registration portions of code out
of spi_new_device() and creates two new functions; spi_alloc_device()
and spi_register_device(). spi_new_device() is modified to use the new
functions for allocation and registration. None of the existing users
of spi_new_device() should be affected by this change.

Drivers using the new API can forego the use of spi_board_info
structure to describe the device layout and populate data into the
spi_device structure directly.

This change is in preparation for adding an OF device tree parser to
generate spi_devices based on data in the device tree.

Signed-off-by: Grant Likely <grant.likely@secretlab.ca>
Acked-by: David Brownell <dbrownell@users.sourceforge.net>


# 102eb975 23-Jul-2008 Grant Likely <grant.likely@secretlab.ca>

spi: make spi_board_info.modalias a char array

Currently, 'modalias' in the spi_device structure is a 'const char *'.
The spi_new_device() function fills in the modalias value from a passed in
spi_board_info data block. Since it is a pointer copy, the new spi_device
remains dependent on the spi_board_info structure after the new spi_device
is registered (no other fields in spi_device directly depend on the
spi_board_info structure; all of the other data is copied).

This causes a problem when dynamically propulating the list of attached
SPI devices. For example, in arch/powerpc, the list of SPI devices can be
populated from data in the device tree. With the current code, the device
tree adapter must kmalloc() a new spi_board_info structure for each new
SPI device it finds in the device tree, and there is no simple mechanism
in place for keeping track of these allocations.

This patch changes modalias from a 'const char *' to a fixed char array.
By copying the modalias string instead of referencing it, the dependency
on the spi_board_info structure is eliminated and an outside caller does
not need to maintain a separate spi_board_info allocation for each device.

If searched through the code to the best of my ability for any references
to modalias which may be affected by this change and haven't found
anything. It has been tested with the lite5200b platform in arch/powerpc.

[dbrownell@users.sourceforge.net: cope with linux-next changes: KOBJ_NAME_LEN obliterated, etc]
Signed-off-by: Grant Likely <grant.likely@secretlab.ca>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 695794ae 22-May-2008 Greg Kroah-Hartman <gregkh@suse.de>

Driver Core: add ability for class_find_device to start in middle of list

This mirrors the functionality that driver_find_device has as well.

We add a start variable, and all callers of the function are fixed up at
the same time.

The block layer will be using this new functionality in a follow-on
patch.


Cc: Kay Sievers <kay.sievers@vrfy.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 3c72426f 06-Feb-2008 David Brownell <david-b@pacbell.net>

spi core: stop updating dev->power.power_state

Don't update dev->power.power_state any more in the SPI core. The only
reason to update this scheduled-to-be-removed field was to make the
already-removed /sys/devices/.../power/state files work better.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 911f2150 06-Feb-2008 Ralf Baechle <ralf@linux-mips.org>

Remove inclusions of <linux/autoconf.h>

Nothing should ever include this file.

Signed-off-by: Ralf Baechle <ralf@linux-mips.org>
Acked-by: "Mike Frysinger" <vapier.adi@gmail.com>
Acked-by: "Bryan Wu" <cooloney.lkml@gmail.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 5ed2c832 22-Jan-2008 Dave Young <hidave.darkstar@gmail.com>

spi: use class iteration api

Convert to use the class iteration api.

Signed-off-by: Dave Young <hidave.darkstar@gmail.com>
Acked-by: David Brownell <david-b@pacbell.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 9b938b74 05-Dec-2007 Marc Pignat <marc.pignat@hevs.ch>

spi: simplify spi_sync() calling convention

Simplify spi_sync calling convention, eliminating the need to check both
the return value AND the message->status. In consequence, this corrects
misbehaviours of spi_read and spi_write (which only checked the former) and
their callers.

Signed-off-by: Marc Pignat <marc.pignat@hevs.ch>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 068f4070 05-Dec-2007 David Brownell <david-b@pacbell.net>

SPI: use mutex not semaphore

Make spi_write_then_read() use a mutex not a binary semaphore.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 350d0076 14-Nov-2007 Atsushi Nemoto <anemo@mba.ocn.ne.jp>

spi: fix double-free on spi_unregister_master

After 49dce689ad4ef0fd1f970ef762168e4bd46f69a3, device_for_each_child
iteration hits the master device itself. Do not call spi_unregister_device()
for the master device.

Signed-off-by: Atsushi Nemoto <anemo@mba.ocn.ne.jp>
Acked-by: David Brownell <david-b@pacbell.net>
Cc: <stable@kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 49dce689 16-Oct-2007 Tony Jones <tonyj@suse.de>

spi doesn't need class_device

Make the SPI framework and drivers stop using class_device. Update docs
accordingly ... highlighting just which sysfs paths should be
"safe"/stable.

Signed-off-by: Tony Jones <tonyj@suse.de>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Cc: Greg KH <greg@kroah.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 7eff2e7a 14-Aug-2007 Kay Sievers <kay.sievers@vrfy.org>

Driver core: change add_uevent_var to use a struct

This changes the uevent buffer functions to use a struct instead of a
long list of parameters. It does no longer require the caller to do the
proper buffer termination and size accounting, which is currently wrong
in some places. It fixes a known bug where parts of the uevent
environment are overwritten because of wrong index calculations.

Many thanks to Mathieu Desnoyers for finding bugs and improving the
error handling.

Signed-off-by: Kay Sievers <kay.sievers@vrfy.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@polymtl.ca>
Cc: Cornelia Huck <cornelia.huck@de.ibm.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 082c8cb4 31-Jul-2007 David Brownell <david-b@pacbell.net>

spi device setup gets better error checking

This updates some error reporting paths in SPI device setup:

- Move validation logic for SPI chipselects to spi_new_device(),
which is where it should always have been.

- In spi_new_device(), emit error messages if the device can't
be created. This is LOTS better than a silent failure; though
eventually, the calling convention should probably change to
use the <linux/err.h> conventions.

- Includes one previously-missing check: SPI masters must always
have at least one chipselect, even for dedicated busses which
always keep it selected!

It also adds a FIXME (IDR for dynamic ID allocation) so the issue doesn't live
purely in my mailbox.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 149a6501 21-Jul-2007 Adrian Bunk <bunk@stusta.de>

spi.c:scan_boardinfo() mustn't be __init_or_module

WARNING: drivers/built-in.o(.text+0x889735): Section mismatch: reference to .init.text:scan_boardinfo (between 'spi_register_master' and '__unregister')

Signed-off-by: Adrian Bunk <bunk@stusta.de>
Acked-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 94040828 17-Jul-2007 Matthias Kaehlcke <matthias.kaehlcke@gmail.com>

use mutex instead of semaphore in SPI core/init code

The SPI core/init code uses a semaphore as mutex. Use the mutex API instead
of the (binary) semaphore.

Signed-off-by: Matthias Kaehlcke <matthias.kaehlcke@gmail.com>
Acked-by: David Brownell <david-b@pacbell.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# e44a45ae 03-Jun-2007 David Brownell <david-b@pacbell.net>

SPI dynamic busid generation bugfix

Fix SPI dynamic bus ID assignment to start at 2^15-1 rather than a negative
number. Valid bus ids are supposed to be positive, and are (now) stored in
an 's16' value.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 33e34dc6 08-May-2007 David Brownell <david-b@pacbell.net>

SPI kerneldoc

Various documentation updates for the SPI infrastructure, to clarify things
that may not have been clear, to cope with lack of editing, and fix
omissions.

Also, plug SPI into the kernel-api DocBook template, and fix all the
resulting glitches in document generation.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Cc: "Randy.Dunlap" <rdunlap@xenotime.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# e9d5a461 26-Mar-2007 Adrian Bunk <bunk@stusta.de>

[PATCH] drivers/spi/: fix section mismatches

WARNING: drivers/built-in.o - Section mismatch: reference to .init.text:spi_register_master from .text between 'spi_bitbang_start' (at offset 0x84e11a) and 'bitbang_work'
WARNING: drivers/built-in.o - Section mismatch: reference to .init.text:spi_alloc_master from .text between 'butterfly_attach' (at offset 0x84e681) and 'at25_remove'
WARNING: drivers/built-in.o - Section mismatch: reference to .init.text:spi_new_device from .text between 'butterfly_attach' (at offset 0x84e7e4) and 'at25_remove'

Signed-off-by: Adrian Bunk <bunk@stusta.de>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 0ffa0285 12-Feb-2007 Hans-Peter Nilsson <hans-peter.nilsson@axis.com>

[PATCH] SPI cleanup() method param becomes non-const

I'd like to assign NULL to kfree()d members of a structure. I can't do
that without ugly casting (see the PXA patch) when the structure pointed to
is const-qualified. I don't really see a reason why the cleanup method
isn't allowed to alter the object it should clean up. :-)

No, I didn't test the PXA patch, but I verified that the NULL-assignment
doesn't stop me from doing rmmod/insmodding my own spi_bitbang-based
driver.

Signed-off-by: Hans-Peter Nilsson <hp@axis.com>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 07b24630 07-Feb-2007 Greg Kroah-Hartman <gregkh@suse.de>

Revert "Driver core: convert SPI code to use struct device"

This reverts commit 2943ecf2ed32632473c06f1975db47a7aa98c10f.

This should go through the SPI maintainer, it was my fault that it did
not. Especially as it conflicts with other patches he has pending.

Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 2943ecf2 22-Jan-2007 Greg Kroah-Hartman <gregkh@suse.de>

Driver core: convert SPI code to use struct device

Converts from using struct "class_device" to "struct device" making
everything show up properly in /sys/devices/ with symlinks from the
/sys/class directory.

Cc: <dbrownell@users.sourceforge.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 1e9a51dc 26-Jan-2007 Atsushi Nemoto <anemo@mba.ocn.ne.jp>

[PATCH] SPI: alternative fix for spi_busnum_to_master

If a SPI master device exists, udev (udevtrigger) causes kernel crash, due
to wrong kobj pointer in kobject_uevent_env(). This problem was not in
2.6.19.

The backtrace (on MIPS) was:
[<8024db6c>] kobject_uevent_env+0x54c/0x5e8
[<802a8264>] store_uevent+0x1c/0x3c (in drivers/class.c)
[<801cb14c>] subsys_attr_store+0x2c/0x50
[<801cb80c>] flush_write_buffer+0x38/0x5c
[<801cb900>] sysfs_write_file+0xd0/0x190
[<80181444>] vfs_write+0xc4/0x1a0
[<80181cdc>] sys_write+0x54/0xa0
[<8010dae4>] stack_done+0x20/0x3c

flush_write_buffer() passes kobject of spi_master_class.subsys to
subsys_addr_store(), then subsys_addr_store() passes a pointer to a struct
subsystem to store_uevent() which expects a pointer to a struct
class_device. The problem seems subsys_attr_store() called instead of
class_device_attr_store().

This mismatch was caused by commit
3bd0f6943520e459659d10f3282285e43d3990f1, which overrides kset of master
class. This made spi_master_class.subsys.kset.ktype NULL so
subsys_sysfs_ops is used instead of class_dev_sysfs_ops.

The commit was to fix spi_busnum_to_master(). Here is a patch fixes
this function in other way, just searching children list of
class_device.

Signed-off-by: Atsushi Nemoto <anemo@mba.ocn.ne.jp>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 3bd0f694 06-Dec-2006 Hans-Christian Egtvedt <hcegtvedt@atmel.com>

[PATCH] spi: set kset of master class dev explicitly

<quote Imre Deak from Thu, 12 Jan 2006 21:18:54 +0200>
In order for spi_busnum_to_master to work spi master devices must be linked
into the spi_master_class.subsys.kset list. At the moment the default
class_obj_subsys.kset is used and we can't enumerate the master devices.
</quote>

Signed-off-by: Hans-Christian Egtvedt <hcegtvedt@atmel.com>
Cc: David Brownell <david-b@pacbell.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# 4740d387 06-Dec-2006 Hans-Christian Egtvedt <hcegtvedt@atmel.com>

[PATCH] spi: correct bus_num and buffer bug in spi core

Correct the following in driver/spi/spi.c in function spi_busnum_to_master:

* must allow bus_num 0, the if is really not needed.
* correct the name buffer which is too small for bus_num >= 10000. It

should be 9 bytes big, not 8.

Signed-off-by: Hans-Christian Egtvedt <hcegtvedt@atmel.com>
Cc: David Brownell <david-b@pacbell.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# 89fc9a1a 06-Dec-2006 Jeff Garzik <jeff@garzik.org>

[PATCH] SPI: improve sysfs compiler complaint handling

Signed-off-by: Jeff Garzik <jeff@garzik.org>
Cc: David Brownell <david-b@pacbell.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# e94b1766 06-Dec-2006 Christoph Lameter <clameter@sgi.com>

[PATCH] slab: remove SLAB_KERNEL

SLAB_KERNEL is an alias of GFP_KERNEL.

Signed-off-by: Christoph Lameter <clameter@sgi.com>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# d3e5a938 02-Nov-2006 Andrew Morton <akpm@osdl.org>

[PATCH] spi section fix

WARNING: vmlinux - Section mismatch: reference to .init.text:spi_register_board_info from __ksymtab_gpl between '__ksymtab_spi_register_board_info' (at offset 0xc032f7d0) and '__ksymtab_spi_alloc_master'

Fix this by removing the export.

Acked-by: David Brownell <david-b@pacbell.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# 60be6b9a 03-Jul-2006 Ingo Molnar <mingo@elte.hu>

[PATCH] lockdep: annotate on-stack completions

lockdep needs to have the waitqueue lock initialized for on-stack waitqueues
implicitly initialized by DECLARE_COMPLETION(). Annotate on-stack completions
accordingly.

Has no effect on non-lockdep kernels.

Signed-off-by: Ingo Molnar <mingo@elte.hu>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# 980a01c9 28-Jun-2006 David Brownell <david-b@pacbell.net>

[PATCH] SPI: infrastructure to initialize spi_device.mode early

This patch adds earlier initialization of spi_device.mode, as needed
on boards using nondefault chipselect polarity. An example would be
ones using the RS5C348 RTC without an external signal inverter between
the RTC chipselect and the SPI controller.

Without this mechanism, the first setup() call for that chip would
wrongly enable chips, corrupting transfers to/from other chips sharing
that SPI bus.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# ba1a0513 20-May-2006 dmitry pervushin <dpervushin@ru.mvista.com>

[PATCH] minor SPI doc fix

Because several developers asked me about referenced but missing
spi_add_master(), I think that this patch should be applied ... it
corrects comments so they refer to spi_register_master() instead.

Signed-off-by: dmitry pervushin <dpervushin@ru.mvista.com>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# a020ed75 03-Apr-2006 David Brownell <david-b@pacbell.net>

[PATCH] SPI: busnum == 0 needs to work

We need to be able to have a "SPI bus 0" matching chip numbering; but
that number was wrongly used to flag dynamic allocation of a bus number.

This patch resolves that issue; now negative numbers trigger dynamic alloc.

It also updates the how-to-write-a-controller-driver overview to mention
this stuff.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# a9948b61 02-Apr-2006 David Brownell <david-b@pacbell.net>

[PATCH] SPI: spi bounce buffer has a minimum length

Make sure that spi_write_then_read() can always handle at least 32 bytes
of transfer (total, both directions), minimizing one portability issue.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# d2799f08 20-Feb-2006 Stephen Street <stephen@streetfiresound.com>

[PATCH] spi: Fix modular master driver remove and device suspend/remove

Fix two problems in the spi subsystem:

1) spi subsystem core dumps when modular spi master is unloaded.
2) spi subsystem core dumps when spi slave device is suspended/resumed and
module slave driver is not loaded.

Signed-off-by: Stephen Street <stephen@streetfiresound.com>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Cc: Greg KH <greg@kroah.com>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>


# 5d870c8e 11-Jan-2006 Andrew Morton <akpm@osdl.org>

[PATCH] spi: remove fastcall crap

gcc4 generates warnings when a non-FASTCALL function pointer is assigned to a
FASTCALL one. Perhaps it has taste.

Cc: David Brownell <david-b@pacbell.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 8275c642 08-Jan-2006 Vitaly Wool <vwool@ru.mvista.com>

[PATCH] spi: use linked lists rather than an array

This makes the SPI core and its users access transfers in the SPI message
structure as linked list not as an array, as discussed on LKML.

From: David Brownell <dbrownell@users.sourceforge.net>

Updates including doc, bugfixes to the list code, add
spi_message_add_tail(). Plus, initialize things _before_ grabbing the
locks in some cases (in case it grows more expensive). This also merges
some bitbang updates of mine that didn't yet make it into the mm tree.

Signed-off-by: Vitaly Wool <vwool@ru.mvista.com>
Signed-off-by: Dmitry Pervushin <dpervushin@gmail.com>
Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 0c868461 08-Jan-2006 David Brownell <david-b@pacbell.net>

[PATCH] SPI core tweaks, bugfix

This includes various updates to the SPI core:

- Fixes a driver model refcount bug in spi_unregister_master() paths.

- The spi_master structures now have wrappers which help keep drivers
from needing class-level get/put for device data or for refcounts.

- Check for a few setup errors that would cause oopsing later.

- Docs say more about memory management. Highlights the use of DMA-safe
i/o buffers, and zero-initializing spi_message and such metadata.

- Provide a simple alloc/free for spi_message and its spi_transfer;
this is only one of the possible memory management policies.

Nothing to break code that already works.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# b885244e 08-Jan-2006 David Brownell <david-b@pacbell.net>

[PATCH] spi: add spi_driver to SPI framework

This is a refresh of the "Simple SPI Framework" found in 2.6.15-rc3-mm1
which makes the following changes:

* There's now a "struct spi_driver". This increase the footprint
of the core a bit, since it now includes code to do what the driver
core was previously handling directly. Documentation and comments
were updated to match.

* spi_alloc_master() now does class_device_initialize(), so it can
at least be refcounted before spi_register_master(). To match,
spi_register_master() switched over to class_device_add().

* States explicitly that after transfer errors, spi_devices will be
deselected. We want fault recovery procedures to work the same
for all controller drivers.

* Minor tweaks: controller_data no longer points to readonly data;
prevent some potential cast-from-null bugs with container_of calls;
clarifies some existing kerneldoc,

And a few small cleanups.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>


# 8ae12a0d 08-Jan-2006 David Brownell <david-b@pacbell.net>

[PATCH] spi: simple SPI framework

This is the core of a small SPI framework, implementing the model of a
queue of messages which complete asynchronously (with thin synchronous
wrappers on top).

- It's still less than 2KB of ".text" (ARM). If there's got to be a
mid-layer for something so simple, that's the right size budget. :)

- The guts use board-specific SPI device tables to build the driver
model tree. (Hardware probing is rarely an option.)

- This version of Kconfig includes no drivers. At this writing there
are two known master controller drivers (PXA/SSP, OMAP MicroWire)
and three protocol drivers (CS8415a, ADS7846, DataFlash) with LKML
mentions of other drivers in development.

- No userspace API. There are several implementations to compare.
Implement them like any other driver, and bind them with sysfs.

The changes from last version posted to LKML (on 11-Nov-2005) are minor,
and include:

- One bugfix (removes a FIXME), with the visible effect of making device
names be "spiB.C" where B is the bus number and C is the chipselect.

- The "caller provides DMA mappings" mechanism now has kerneldoc, for
DMA drivers that want to be fancy.

- Hey, the framework init can be subsys_init. Even though board init
logic fires earlier, at arch_init ... since the framework init is
for driver support, and the board init support uses static init.

- Various additional spec/doc clarifications based on discussions
with other folk. It adds a brief "thank you" at the end, for folk
who've helped nudge this framework into existence.

As I've said before, I think that "protocol tweaking" is the main support
that this driver framework will need to evolve.

From: Mark Underwood <basicmark@yahoo.com>

Update the SPI framework to remove a potential priority inversion case by
reverting to kmalloc if the pre-allocated DMA-safe buffer isn't available.

Signed-off-by: David Brownell <dbrownell@users.sourceforge.net>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>