code:
.. SPDX-License-Identifier: GPL-2.0

======================
SCSI Kernel Parameters
======================

See Documentation/admin-guide/kernel-parameters.rst for general information on
specifying module parameters.

This document may not be entirely up to date and comprehensive. The command
``modinfo -p ${modulename}`` shows a current list of all parameters of a loadable
module. Loadable modules, after being loaded into the running kernel, also
reveal their parameters in /sys/module/${modulename}/parameters/. Some of these
parameters may be changed at runtime by the command
``echo -n ${value} > /sys/module/${modulename}/parameters/${parm}``.

::

	advansys=	[HW,SCSI]
			See header of drivers/scsi/advansys.c.

	aha152x=	[HW,SCSI]
			See Documentation/scsi/aha152x.rst.

	aha1542=	[HW,SCSI]
			Format: <portbase>[,<buson>,<busoff>[,<dmaspeed>]]

	aic7xxx=	[HW,SCSI]
			See Documentation/scsi/aic7xxx.rst.

	aic79xx=	[HW,SCSI]
			See Documentation/scsi/aic79xx.rst.

	atascsi=	[HW,SCSI]
			See drivers/scsi/atari_scsi.c.

	BusLogic=	[HW,SCSI]
			See drivers/scsi/BusLogic.c, comment before function
			BusLogic_ParseDriverOptions().

	gvp11=		[HW,SCSI]

	ips=		[HW,SCSI] Adaptec / IBM ServeRAID controller
			See header of drivers/scsi/ips.c.

	mac5380=	[HW,SCSI]
			See drivers/scsi/mac_scsi.c.

	scsi_mod.max_luns=
			[SCSI] Maximum number of LUNs to probe.
			Should be between 1 and 2^32-1.

	scsi_mod.max_report_luns=
			[SCSI] Maximum number of LUNs received.
			Should be between 1 and 16384.

	NCR_D700=	[HW,SCSI]
			See header of drivers/scsi/NCR_D700.c.

	ncr5380=	[HW,SCSI]
			See Documentation/scsi/g_NCR5380.rst.

	ncr53c400=	[HW,SCSI]
			See Documentation/scsi/g_NCR5380.rst.

	ncr53c400a=	[HW,SCSI]
			See Documentation/scsi/g_NCR5380.rst.

	ncr53c8xx=	[HW,SCSI]

	osst=		[HW,SCSI] SCSI Tape Driver
			Format: <buffer_size>,<write_threshold>
			See also Documentation/scsi/st.rst.

	scsi_debug_*=	[SCSI]
			See drivers/scsi/scsi_debug.c.

	scsi_mod.default_dev_flags=
			[SCSI] SCSI default device flags
			Format: <integer>

	scsi_mod.dev_flags=
			[SCSI] Black/white list entry for vendor and model
			Format: <vendor>:<model>:<flags>
			(flags are integer value)

	scsi_mod.scsi_logging_level=
			[SCSI] a bit mask of logging levels
			See drivers/scsi/scsi_logging.h for bits.  Also
			settable via sysctl at dev.scsi.logging_level
			(/proc/sys/dev/scsi/logging_level).
			There is also a nice 'scsi_logging_level' script in the
			S390-tools package, available for download at
			https://github.com/ibm-s390-linux/s390-tools/blob/master/scripts/scsi_logging_level

	scsi_mod.scan=	[SCSI] sync (default) scans SCSI busses as they are
			discovered.  async scans them in kernel threads,
			allowing boot to proceed.  none ignores them, expecting
			user space to do the scan.

	sim710=		[SCSI,HW]
			See header of drivers/scsi/sim710.c.

	st=		[HW,SCSI] SCSI tape parameters (buffers, etc.)
			See Documentation/scsi/st.rst.

	wd33c93=	[HW,SCSI]
			See header of drivers/scsi/wd33c93.c.


code:
.. SPDX-License-Identifier: GPL-2.0

============================
SCSI subsystem documentation
============================

The Linux Documentation Project (LDP) maintains a document describing
the SCSI subsystem in the Linux kernel (lk) 2.4 series. See:
http://www.tldp.org/HOWTO/SCSI-2.4-HOWTO . The LDP has single
and multiple page HTML renderings as well as postscript and pdf.
It can also be found at:
http://web.archive.org/web/%2E/http://www.torque.net/scsi/SCSI-2.4-HOWTO

Notes on using modules in the SCSI subsystem
============================================
The scsi support in the linux kernel can be modularized in a number of
different ways depending upon the needs of the end user.  To understand
your options, we should first define a few terms.

The scsi-core (also known as the "mid level") contains the core of scsi
support.  Without it you can do nothing with any of the other scsi drivers.
The scsi core support can be a module (scsi_mod.o), or it can be built into
the kernel. If the core is a module, it must be the first scsi module
loaded, and if you unload the modules, it will have to be the last one
unloaded.  In practice the modprobe and rmmod commands (and "autoclean")
will enforce the correct ordering of loading and unloading modules in
the SCSI subsystem.

The individual upper and lower level drivers can be loaded in any order
once the scsi core is present in the kernel (either compiled in or loaded
as a module).  The disk driver (sd_mod.o), cdrom driver (sr_mod.o),
tape driver [1]_ (st.o) and scsi generics driver (sg.o) represent the upper
level drivers to support the various assorted devices which can be
controlled.  You can for example load the tape driver to use the tape drive,
and then unload it once you have no further need for the driver (and release
the associated memory).

The lower level drivers are the ones that support the individual cards that
are supported for the hardware platform that you are running under. Those
individual cards are often called Host Bus Adapters (HBAs). For example the
aic7xxx.o driver is used to control all recent SCSI controller cards from
Adaptec. Almost all lower level drivers can be built either as modules or
built into the kernel.

.. [1] There is a variant of the st driver for controlling OnStream tape
       devices. Its module name is osst.o .

repo_name: angery/linux


code:
.. SPDX-License-Identifier: GPL-2.0

=======
SCSI EH
=======

This document describes SCSI midlayer error handling infrastructure.
Please refer to Documentation/scsi/scsi_mid_low_api.rst for more
information regarding SCSI midlayer.

.. TABLE OF CONTENTS

   [1] How SCSI commands travel through the midlayer and to EH
       [1-1] struct scsi_cmnd
       [1-2] How do scmd's get completed?
   	[1-2-1] Completing a scmd w/ scsi_done
   	[1-2-2] Completing a scmd w/ timeout
       [1-3] How EH takes over
   [2] How SCSI EH works
       [2-1] EH through fine-grained callbacks
   	[2-1-1] Overview
   	[2-1-2] Flow of scmds through EH
   	[2-1-3] Flow of control
       [2-2] EH through transportt->eh_strategy_handler()
   	[2-2-1] Pre transportt->eh_strategy_handler() SCSI midlayer conditions
   	[2-2-2] Post transportt->eh_strategy_handler() SCSI midlayer conditions
   	[2-2-3] Things to consider

1. How SCSI commands travel through the midlayer and to EH
==========================================================

1.1 struct scsi_cmnd
--------------------

Each SCSI command is represented with struct scsi_cmnd (== scmd).  A
scmd has two list_head's to link itself into lists.  The two are
scmd->list and scmd->eh_entry.  The former is used for free list or
per-device allocated scmd list and not of much interest to this EH
discussion.  The latter is used for completion and EH lists and unless
otherwise stated scmds are always linked using scmd->eh_entry in this
discussion.

1.2 How do scmd's get completed?
--------------------------------

Once LLDD gets hold of a scmd, either the LLDD will complete the
command by calling scsi_done callback passed from midlayer when
invoking hostt->queuecommand() or the block layer will time it out.

1.2.1 Completing a scmd w/ scsi_done
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For all non-EH commands, scsi_done() is the completion callback.  It
just calls blk_complete_request() to delete the block layer timer and
raise SCSI_SOFTIRQ

SCSI_SOFTIRQ handler scsi_softirq calls scsi_decide_disposition() to
determine what to do with the command.  scsi_decide_disposition()
looks at the scmd->result value and sense data to determine what to do
with the command.

 - SUCCESS

	scsi_finish_command() is invoked for the command.  The
	function does some maintenance chores and then calls
	scsi_io_completion() to finish the I/O.
	scsi_io_completion() then notifies the block layer on
	the completed request by calling blk_end_request and
	friends or figures out what to do with the remainder
	of the data in case of an error.

 - NEEDS_RETRY

 - ADD_TO_MLQUEUE

	scmd is requeued to blk queue.

 - otherwise

	scsi_eh_scmd_add(scmd) is invoked for the command.  See
	[1-3] for details of this function.

1.2.2 Completing a scmd w/ timeout
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The timeout handler is scsi_timeout().  When a timeout occurs, this function

 1. invokes optional hostt->eh_timed_out() callback.  Return value can
    be one of

    - SCSI_EH_RESET_TIMER
	This indicates that more time is required to finish the
	command.  Timer is restarted.

    - SCSI_EH_NOT_HANDLED
        eh_timed_out() callback did not handle the command.
	Step #2 is taken.

    - SCSI_EH_DONE
        eh_timed_out() completed the command.

 2. scsi_abort_command() is invoked to schedule an asynchronous abort which may
    issue a retry scmd->allowed + 1 times.  Asynchronous aborts are not invoked
    for commands for which the SCSI_EH_ABORT_SCHEDULED flag is set (this
    indicates that the command already had been aborted once, and this is a
    retry which failed), when retries are exceeded, or when the EH deadline is
    expired. In these cases Step #3 is taken.

 3. scsi_eh_scmd_add(scmd, SCSI_EH_CANCEL_CMD) is invoked for the
    command.  See [1-4] for more information.

1.3 Asynchronous command aborts
-------------------------------

 After a timeout occurs a command abort is scheduled from
 scsi_abort_command(). If the abort is successful the command
 will either be retried (if the number of retries is not exhausted)
 or terminated with DID_TIME_OUT.

 Otherwise scsi_eh_scmd_add() is invoked for the command.
 See [1-4] for more information.

1.4 How EH takes over
---------------------

scmds enter EH via scsi_eh_scmd_add(), which does the following.

 1. Links scmd->eh_entry to shost->eh_cmd_q

 2. Sets SHOST_RECOVERY bit in shost->shost_state

 3. Increments shost->host_failed

 4. Wakes up SCSI EH thread if shost->host_busy == shost->host_failed

As can be seen above, once any scmd is added to shost->eh_cmd_q,
SHOST_RECOVERY shost_state bit is turned on.  This prevents any new
scmd to be issued from blk queue to the host; eventually, all scmds on
the host either complete normally, fail and get added to eh_cmd_q, or
time out and get added to shost->eh_cmd_q.

If all scmds either complete or fail, the number of in-flight scmds
becomes equal to the number of failed scmds - i.e. shost->host_busy ==
shost->host_failed.  This wakes up SCSI EH thread.  So, once woken up,
SCSI EH thread can expect that all in-flight commands have failed and
are linked on shost->eh_cmd_q.

Note that this does not mean lower layers are quiescent.  If a LLDD
completed a scmd with error status, the LLDD and lower layers are
assumed to forget about the scmd at that point.  However, if a scmd
has timed out, unless hostt->eh_timed_out() made lower layers forget
about the scmd, which currently no LLDD does, the command is still
active as long as lower layers are concerned and completion could
occur at any time.  Of course, all such completions are ignored as the
timer has already expired.

We'll talk about how SCSI EH takes actions to abort - make LLDD
forget about - timed out scmds later.

2. How SCSI EH works
====================

LLDD's can implement SCSI EH actions in one of the following two
ways.

 - Fine-grained EH callbacks
	LLDD can implement fine-grained EH callbacks and let SCSI
	midlayer drive error handling and call appropriate callbacks.
	This will be discussed further in [2-1].

 - eh_strategy_handler() callback
	This is one big callback which should perform whole error
	handling.  As such, it should do all chores the SCSI midlayer
	performs during recovery.  This will be discussed in [2-2].

Once recovery is complete, SCSI EH resumes normal operation by
calling scsi_restart_operations(), which

 1. Checks if door locking is needed and locks door.

 2. Clears SHOST_RECOVERY shost_state bit

 3. Wakes up waiters on shost->host_wait.  This occurs if someone
    calls scsi_block_when_processing_errors() on the host.
    (*QUESTION* why is it needed?  All operations will be blocked
    anyway after it reaches blk queue.)

 4. Kicks queues in all devices on the host in the asses

2.1 EH through fine-grained callbacks
-------------------------------------

2.1.1 Overview
^^^^^^^^^^^^^^

If eh_strategy_handler() is not present, SCSI midlayer takes charge
of driving error handling.  EH's goals are two - make LLDD, host and
device forget about timed out scmds and make them ready for new
commands.  A scmd is said to be recovered if the scmd is forgotten by
lower layers and lower layers are ready to process or fail the scmd
again.

To achieve these goals, EH performs recovery actions with increasing
severity.  Some actions are performed by issuing SCSI commands and
others are performed by invoking one of the following fine-grained
hostt EH callbacks.  Callbacks may be omitted and omitted ones are
considered to fail always.

::

    int (* eh_abort_handler)(struct scsi_cmnd *);
    int (* eh_device_reset_handler)(struct scsi_cmnd *);
    int (* eh_bus_reset_handler)(struct scsi_cmnd *);
    int (* eh_host_reset_handler)(struct scsi_cmnd *);

Higher-severity actions are taken only when lower-severity actions
cannot recover some of failed scmds.  Also, note that failure of the
highest-severity action means EH failure and results in offlining of
all unrecovered devices.

During recovery, the following rules are followed

 - Recovery actions are performed on failed scmds on the to do list,
   eh_work_q.  If a recovery action succeeds for a scmd, recovered
   scmds are removed from eh_work_q.

   Note that single recovery action on a scmd can recover multiple
   scmds.  e.g. resetting a device recovers all failed scmds on the
   device.

 - Higher severity actions are taken iff eh_work_q is not empty after
   lower severity actions are complete.

 - EH reuses failed scmds to issue commands for recovery.  For
   timed-out scmds, SCSI EH ensures that LLDD forgets about a scmd
   before reusing it for EH commands.

When a scmd is recovered, the scmd is moved from eh_work_q to EH
local eh_done_q using scsi_eh_finish_cmd().  After all scmds are
recovered (eh_work_q is empty), scsi_eh_flush_done_q() is invoked to
either retry or error-finish (notify upper layer of failure) recovered
scmds.

scmds are retried iff its sdev is still online (not offlined during
EH), REQ_FAILFAST is not set and ++scmd->retries is less than
scmd->allowed.

2.1.2 Flow of scmds through EH
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 1. Error completion / time out

    :ACTION: scsi_eh_scmd_add() is invoked for scmd

	- add scmd to shost->eh_cmd_q
	- set SHOST_RECOVERY
	- shost->host_failed++

    :LOCKING: shost->host_lock

 2. EH starts

    :ACTION: move all scmds to EH's local eh_work_q.  shost->eh_cmd_q
	     is cleared.

    :LOCKING: shost->host_lock (not strictly necessary, just for
             consistency)

 3. scmd recovered

    :ACTION: scsi_eh_finish_cmd() is invoked to EH-finish scmd

	- scsi_setup_cmd_retry()
	- move from local eh_work_q to local eh_done_q

    :LOCKING: none

    :CONCURRENCY: at most one thread per separate eh_work_q to
		  keep queue manipulation lockless

 4. EH completes

    :ACTION: scsi_eh_flush_done_q() retries scmds or notifies upper
	     layer of failure. May be called concurrently but must have
	     a no more than one thread per separate eh_work_q to
	     manipulate the queue locklessly

	     - scmd is removed from eh_done_q and scmd->eh_entry is cleared
	     - if retry is necessary, scmd is requeued using
	       scsi_queue_insert()
	     - otherwise, scsi_finish_command() is invoked for scmd
	     - zero shost->host_failed

    :LOCKING: queue or finish function performs appropriate locking

2.1.3 Flow of control
^^^^^^^^^^^^^^^^^^^^^^

 EH through fine-grained callbacks start from scsi_unjam_host().

``scsi_unjam_host``

    1. Lock shost->host_lock, splice_init shost->eh_cmd_q into local
       eh_work_q and unlock host_lock.  Note that shost->eh_cmd_q is
       cleared by this action.

    2. Invoke scsi_eh_get_sense.

    ``scsi_eh_get_sense``

	This action is taken for each error-completed
	(!SCSI_EH_CANCEL_CMD) commands without valid sense data.  Most
	SCSI transports/LLDDs automatically acquire sense data on
	command failures (autosense).  Autosense is recommended for
	performance reasons and as sense information could get out of
	sync between occurrence of CHECK CONDITION and this action.

	Note that if autosense is not supported, scmd->sense_buffer
	contains invalid sense data when error-completing the scmd
	with scsi_done().  scsi_decide_disposition() always returns
	FAILED in such cases thus invoking SCSI EH.  When the scmd
	reaches here, sense data is acquired and
	scsi_decide_disposition() is called again.

	1. Invoke scsi_request_sense() which issues REQUEST_SENSE
           command.  If fails, no action.  Note that taking no action
           causes higher-severity recovery to be taken for the scmd.

	2. Invoke scsi_decide_disposition() on the scmd

	   - SUCCESS
		scmd->retries is set to scmd->allowed preventing
		scsi_eh_flush_done_q() from retrying the scmd and
		scsi_eh_finish_cmd() is invoked.

	   - NEEDS_RETRY
		scsi_eh_finish_cmd() invoked

	   - otherwise
		No action.

    3. If !list_empty(&eh_work_q), invoke scsi_eh_abort_cmds().

    ``scsi_eh_abort_cmds``

	This action is taken for each timed out command when
	no_async_abort is enabled in the host template.
	hostt->eh_abort_handler() is invoked for each scmd.  The
	handler returns SUCCESS if it has succeeded to make LLDD and
	all related hardware forget about the scmd.

	If a timedout scmd is successfully aborted and the sdev is
	either offline or ready, scsi_eh_finish_cmd() is invoked for
	the scmd.  Otherwise, the scmd is left in eh_work_q for
	higher-severity actions.

	Note that both offline and ready status mean that the sdev is
	ready to process new scmds, where processing also implies
	immediate failing; thus, if a sdev is in one of the two
	states, no further recovery action is needed.

	Device readiness is tested using scsi_eh_tur() which issues
	TEST_UNIT_READY command.  Note that the scmd must have been
	aborted successfully before reusing it for TEST_UNIT_READY.

    4. If !list_empty(&eh_work_q), invoke scsi_eh_ready_devs()

    ``scsi_eh_ready_devs``

	This function takes four increasingly more severe measures to
	make failed sdevs ready for new commands.

	1. Invoke scsi_eh_stu()

	``scsi_eh_stu``

	    For each sdev which has failed scmds with valid sense data
	    of which scsi_check_sense()'s verdict is FAILED,
	    START_STOP_UNIT command is issued w/ start=1.  Note that
	    as we explicitly choose error-completed scmds, it is known
	    that lower layers have forgotten about the scmd and we can
	    reuse it for STU.

	    If STU succeeds and the sdev is either offline or ready,
	    all failed scmds on the sdev are EH-finished with
	    scsi_eh_finish_cmd().

	    *NOTE* If hostt->eh_abort_handler() isn't implemented or
	    failed, we may still have timed out scmds at this point
	    and STU doesn't make lower layers forget about those
	    scmds.  Yet, this function EH-finish all scmds on the sdev
	    if STU succeeds leaving lower layers in an inconsistent
	    state.  It seems that STU action should be taken only when
	    a sdev has no timed out scmd.

	2. If !list_empty(&eh_work_q), invoke scsi_eh_bus_device_reset().

	``scsi_eh_bus_device_reset``

	    This action is very similar to scsi_eh_stu() except that,
	    instead of issuing STU, hostt->eh_device_reset_handler()
	    is used.  Also, as we're not issuing SCSI commands and
	    resetting clears all scmds on the sdev, there is no need
	    to choose error-completed scmds.

	3. If !list_empty(&eh_work_q), invoke scsi_eh_bus_reset()

	``scsi_eh_bus_reset``

	    hostt->eh_bus_reset_handler() is invoked for each channel
	    with failed scmds.  If bus reset succeeds, all failed
	    scmds on all ready or offline sdevs on the channel are
	    EH-finished.

	4. If !list_empty(&eh_work_q), invoke scsi_eh_host_reset()

	``scsi_eh_host_reset``

	    This is the last resort.  hostt->eh_host_reset_handler()
	    is invoked.  If host reset succeeds, all failed scmds on
	    all ready or offline sdevs on the host are EH-finished.

	5. If !list_empty(&eh_work_q), invoke scsi_eh_offline_sdevs()

	``scsi_eh_offline_sdevs``

	    Take all sdevs which still have unrecovered scmds offline
	    and EH-finish the scmds.

    5. Invoke scsi_eh_flush_done_q().

	``scsi_eh_flush_done_q``

	    At this point all scmds are recovered (or given up) and
	    put on eh_done_q by scsi_eh_finish_cmd().  This function
	    flushes eh_done_q by either retrying or notifying upper
	    layer of failure of the scmds.

2.2 EH through transportt->eh_strategy_handler()
------------------------------------------------

transportt->eh_strategy_handler() is invoked in the place of
scsi_unjam_host() and it is responsible for whole recovery process.
On completion, the handler should have made lower layers forget about
all failed scmds and either ready for new commands or offline.  Also,
it should perform SCSI EH maintenance chores to maintain integrity of
SCSI midlayer.  IOW, of the steps described in [2-1-2], all steps
except for #1 must be implemented by eh_strategy_handler().

2.2.1 Pre transportt->eh_strategy_handler() SCSI midlayer conditions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 The following conditions are true on entry to the handler.

 - Each failed scmd's eh_flags field is set appropriately.

 - Each failed scmd is linked on scmd->eh_cmd_q by scmd->eh_entry.

 - SHOST_RECOVERY is set.

 - shost->host_failed == shost->host_busy

2.2.2 Post transportt->eh_strategy_handler() SCSI midlayer conditions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 The following conditions must be true on exit from the handler.

 - shost->host_failed is zero.

 - Each scmd is in such a state that scsi_setup_cmd_retry() on the
   scmd doesn't make any difference.

 - shost->eh_cmd_q is cleared.

 - Each scmd->eh_entry is cleared.

 - Either scsi_queue_insert() or scsi_finish_command() is called on
   each scmd.  Note that the handler is free to use scmd->retries and
   ->allowed to limit the number of retries.

2.2.3 Things to consider
^^^^^^^^^^^^^^^^^^^^^^^^

 - Know that timed out scmds are still active on lower layers.  Make
   lower layers forget about them before doing anything else with
   those scmds.

 - For consistency, when accessing/modifying shost data structure,
   grab shost->host_lock.

 - On completion, each failed sdev must have forgotten about all
   active scmds.

 - On completion, each failed sdev must be ready for new commands or
   offline.

Tejun Heo
htejun@gmail.com

11th September 2005


code:
.. SPDX-License-Identifier: GPL-2.0

================
SCSI FC Tansport
================

Date:  11/18/2008

Kernel Revisions for features::

  rports : <<TBS>>
  vports : 2.6.22
  bsg support : 2.6.30 (?TBD?)

Introduction
============
This file documents the features and components of the SCSI FC Transport.
It also provides documents the API between the transport and FC LLDDs.

The FC transport can be found at::

  drivers/scsi/scsi_transport_fc.c
  include/scsi/scsi_transport_fc.h
  include/scsi/scsi_netlink_fc.h
  include/scsi/scsi_bsg_fc.h

This file is found at Documentation/scsi/scsi_fc_transport.rst

FC Remote Ports (rports)
========================
<< To Be Supplied >>

FC Virtual Ports (vports)
=========================

Overview
--------

  New FC standards have defined mechanisms which allows for a single physical
  port to appear on as multiple communication ports. Using the N_Port Id
  Virtualization (NPIV) mechanism, a point-to-point connection to a Fabric
  can be assigned more than 1 N_Port_ID.  Each N_Port_ID appears as a
  separate port to other endpoints on the fabric, even though it shares one
  physical link to the switch for communication. Each N_Port_ID can have a
  unique view of the fabric based on fabric zoning and array lun-masking
  (just like a normal non-NPIV adapter).  Using the Virtual Fabric (VF)
  mechanism, adding a fabric header to each frame allows the port to
  interact with the Fabric Port to join multiple fabrics. The port will
  obtain an N_Port_ID on each fabric it joins. Each fabric will have its
  own unique view of endpoints and configuration parameters.  NPIV may be
  used together with VF so that the port can obtain multiple N_Port_IDs
  on each virtual fabric.

  The FC transport is now recognizing a new object - a vport.  A vport is
  an entity that has a world-wide unique World Wide Port Name (wwpn) and
  World Wide Node Name (wwnn). The transport also allows for the FC4's to
  be specified for the vport, with FCP_Initiator being the primary role
  expected. Once instantiated by one of the above methods, it will have a
  distinct N_Port_ID and view of fabric endpoints and storage entities.
  The fc_host associated with the physical adapter will export the ability
  to create vports. The transport will create the vport object within the
  Linux device tree, and instruct the fc_host's driver to instantiate the
  virtual port. Typically, the driver will create a new scsi_host instance
  on the vport, resulting in a unique <H,C,T,L> namespace for the vport.
  Thus, whether a FC port is based on a physical port or on a virtual port,
  each will appear as a unique scsi_host with its own target and lun space.

  .. Note::
    At this time, the transport is written to create only NPIV-based
    vports. However, consideration was given to VF-based vports and it
    should be a minor change to add support if needed.  The remaining
    discussion will concentrate on NPIV.

  .. Note::
    World Wide Name assignment (and uniqueness guarantees) are left
    up to an administrative entity controlling the vport. For example,
    if vports are to be associated with virtual machines, a XEN mgmt
    utility would be responsible for creating wwpn/wwnn's for the vport,
    using its own naming authority and OUI. (Note: it already does this
    for virtual MAC addresses).

Device Trees and Vport Objects:
-------------------------------

  Today, the device tree typically contains the scsi_host object,
  with rports and scsi target objects underneath it. Currently the FC
  transport creates the vport object and places it under the scsi_host
  object corresponding to the physical adapter.  The LLDD will allocate
  a new scsi_host for the vport and link its object under the vport.
  The remainder of the tree under the vports scsi_host is the same
  as the non-NPIV case. The transport is written currently to easily
  allow the parent of the vport to be something other than the scsi_host.
  This could be used in the future to link the object onto a vm-specific
  device tree. If the vport's parent is not the physical port's scsi_host,
  a symbolic link to the vport object will be placed in the physical
  port's scsi_host.

  Here's what to expect in the device tree :

   The typical Physical Port's Scsi_Host::

     /sys/devices/.../host17/

   and it has the typical descendant tree::

     /sys/devices/.../host17/rport-17:0-0/target17:0:0/17:0:0:0:

   and then the vport is created on the Physical Port::

     /sys/devices/.../host17/vport-17:0-0

   and the vport's Scsi_Host is then created::

     /sys/devices/.../host17/vport-17:0-0/host18

   and then the rest of the tree progresses, such as::

     /sys/devices/.../host17/vport-17:0-0/host18/rport-18:0-0/target18:0:0/18:0:0:0:

  Here's what to expect in the sysfs tree::

   scsi_hosts:
     /sys/class/scsi_host/host17                physical port's scsi_host
     /sys/class/scsi_host/host18                vport's scsi_host
   fc_hosts:
     /sys/class/fc_host/host17                  physical port's fc_host
     /sys/class/fc_host/host18                  vport's fc_host
   fc_vports:
     /sys/class/fc_vports/vport-17:0-0          the vport's fc_vport
   fc_rports:
     /sys/class/fc_remote_ports/rport-17:0-0    rport on the physical port
     /sys/class/fc_remote_ports/rport-18:0-0    rport on the vport

Vport Attributes
----------------

  The new fc_vport class object has the following attributes

     node_name:                                                 Read_Only
       The WWNN of the vport

     port_name:                                                 Read_Only
       The WWPN of the vport

     roles:                                                     Read_Only
       Indicates the FC4 roles enabled on the vport.

     symbolic_name:                                             Read_Write
       A string, appended to the driver's symbolic port name string, which
       is registered with the switch to identify the vport. For example,
       a hypervisor could set this string to "Xen Domain 2 VM 5 Vport 2",
       and this set of identifiers can be seen on switch management screens
       to identify the port.

     vport_delete:                                              Write_Only
       When written with a "1", will tear down the vport.

     vport_disable:                                             Write_Only
       When written with a "1", will transition the vport to a disabled.
       state.  The vport will still be instantiated with the Linux kernel,
       but it will not be active on the FC link.
       When written with a "0", will enable the vport.

     vport_last_state:                                          Read_Only
       Indicates the previous state of the vport.  See the section below on
       "Vport States".

     vport_state:                                               Read_Only
       Indicates the state of the vport.  See the section below on
       "Vport States".

     vport_type:                                                Read_Only
       Reflects the FC mechanism used to create the virtual port.
       Only NPIV is supported currently.

  For the fc_host class object, the following attributes are added for vports:

     max_npiv_vports:                                           Read_Only
       Indicates the maximum number of NPIV-based vports that the
       driver/adapter can support on the fc_host.

     npiv_vports_inuse:                                         Read_Only
       Indicates how many NPIV-based vports have been instantiated on the
       fc_host.

     vport_create:                                              Write_Only
       A "simple" create interface to instantiate a vport on an fc_host.
       A "<WWPN>:<WWNN>" string is written to the attribute. The transport
       then instantiates the vport object and calls the LLDD to create the
       vport with the role of FCP_Initiator.  Each WWN is specified as 16
       hex characters and may *not* contain any prefixes (e.g. 0x, x, etc).

     vport_delete:                                              Write_Only
        A "simple" delete interface to teardown a vport. A "<WWPN>:<WWNN>"
        string is written to the attribute. The transport will locate the
        vport on the fc_host with the same WWNs and tear it down.  Each WWN
        is specified as 16 hex characters and may *not* contain any prefixes
        (e.g. 0x, x, etc).

Vport States
------------

  Vport instantiation consists of two parts:

    - Creation with the kernel and LLDD. This means all transport and
      driver data structures are built up, and device objects created.
      This is equivalent to a driver "attach" on an adapter, which is
      independent of the adapter's link state.
    - Instantiation of the vport on the FC link via ELS traffic, etc.
      This is equivalent to a "link up" and successful link initialization.

  Further information can be found in the interfaces section below for
  Vport Creation.

  Once a vport has been instantiated with the kernel/LLDD, a vport state
  can be reported via the sysfs attribute. The following states exist:

    FC_VPORT_UNKNOWN            - Unknown
      An temporary state, typically set only while the vport is being
      instantiated with the kernel and LLDD.

    FC_VPORT_ACTIVE             - Active
      The vport has been successfully been created on the FC link.
      It is fully functional.

    FC_VPORT_DISABLED           - Disabled
      The vport instantiated, but "disabled". The vport is not instantiated
      on the FC link. This is equivalent to a physical port with the
      link "down".

    FC_VPORT_LINKDOWN           - Linkdown
      The vport is not operational as the physical link is not operational.

    FC_VPORT_INITIALIZING       - Initializing
      The vport is in the process of instantiating on the FC link.
      The LLDD will set this state just prior to starting the ELS traffic
      to create the vport. This state will persist until the vport is
      successfully created (state becomes FC_VPORT_ACTIVE) or it fails
      (state is one of the values below).  As this state is transitory,
      it will not be preserved in the "vport_last_state".

    FC_VPORT_NO_FABRIC_SUPP     - No Fabric Support
      The vport is not operational. One of the following conditions were
      encountered:

       - The FC topology is not Point-to-Point
       - The FC port is not connected to an F_Port
       - The F_Port has indicated that NPIV is not supported.

    FC_VPORT_NO_FABRIC_RSCS     - No Fabric Resources
      The vport is not operational. The Fabric failed FDISC with a status
      indicating that it does not have sufficient resources to complete
      the operation.

    FC_VPORT_FABRIC_LOGOUT      - Fabric Logout
      The vport is not operational. The Fabric has LOGO'd the N_Port_ID
      associated with the vport.

    FC_VPORT_FABRIC_REJ_WWN     - Fabric Rejected WWN
      The vport is not operational. The Fabric failed FDISC with a status
      indicating that the WWN's are not valid.

    FC_VPORT_FAILED             - VPort Failed
      The vport is not operational. This is a catchall for all other
      error conditions.

  The following state table indicates the different state transitions:

   +------------------+--------------------------------+---------------------+
   | State            | Event                          | New State           |
   +==================+================================+=====================+
   | n/a              | Initialization                 | Unknown             |
   +------------------+--------------------------------+---------------------+
   | Unknown:         | Link Down                      | Linkdown            |
   |                  +--------------------------------+---------------------+
   |                  | Link Up & Loop                 | No Fabric Support   |
   |                  +--------------------------------+---------------------+
   |                  | Link Up & no Fabric            | No Fabric Support   |
   |                  +--------------------------------+---------------------+
   |                  | Link Up & FLOGI response       | No Fabric Support   |
   |                  | indicates no NPIV support      |                     |
   |                  +--------------------------------+---------------------+
   |                  | Link Up & FDISC being sent     | Initializing        |
   |                  +--------------------------------+---------------------+
   |                  | Disable request                | Disable             |
   +------------------+--------------------------------+---------------------+
   | Linkdown:        | Link Up                        | Unknown             |
   +------------------+--------------------------------+---------------------+
   | Initializing:    | FDISC ACC                      | Active              |
   |                  +--------------------------------+---------------------+
   |                  | FDISC LS_RJT w/ no resources   | No Fabric Resources |
   |                  +--------------------------------+---------------------+
   |                  | FDISC LS_RJT w/ invalid        | Fabric Rejected WWN |
   |		      | pname or invalid nport_id      |                     |
   |                  +--------------------------------+---------------------+
   |                  | FDISC LS_RJT failed for        | Vport Failed        |
   |                  | other reasons                  |                     |
   |                  +--------------------------------+---------------------+
   |                  | Link Down                      | Linkdown            |
   |                  +--------------------------------+---------------------+
   |                  | Disable request                | Disable             |
   +------------------+--------------------------------+---------------------+
   | Disable:         | Enable request                 | Unknown             |
   +------------------+--------------------------------+---------------------+
   | Active:          | LOGO received from fabric      | Fabric Logout       |
   |                  +--------------------------------+---------------------+
   |                  | Link Down                      | Linkdown            |
   |                  +--------------------------------+---------------------+
   |                  | Disable request                | Disable             |
   +------------------+--------------------------------+---------------------+
   | Fabric Logout:   | Link still up                  | Unknown             |
   +------------------+--------------------------------+---------------------+

The following 4 error states all have the same transitions::

    No Fabric Support:
    No Fabric Resources:
    Fabric Rejected WWN:
    Vport Failed:
                        Disable request                 Disable
                        Link goes down                  Linkdown

Transport <-> LLDD Interfaces
-----------------------------

Vport support by LLDD:

  The LLDD indicates support for vports by supplying a vport_create()
  function in the transport template.  The presence of this function will
  cause the creation of the new attributes on the fc_host.  As part of
  the physical port completing its initialization relative to the
  transport, it should set the max_npiv_vports attribute to indicate the
  maximum number of vports the driver and/or adapter supports.

Vport Creation:

  The LLDD vport_create() syntax is::

      int vport_create(struct fc_vport *vport, bool disable)

  where:

      =======   ===========================================================
      vport     Is the newly allocated vport object
      disable   If "true", the vport is to be created in a disabled stated.
                If "false", the vport is to be enabled upon creation.
      =======   ===========================================================

  When a request is made to create a new vport (via sgio/netlink, or the
  vport_create fc_host attribute), the transport will validate that the LLDD
  can support another vport (e.g. max_npiv_vports > npiv_vports_inuse).
  If not, the create request will be failed.  If space remains, the transport
  will increment the vport count, create the vport object, and then call the
  LLDD's vport_create() function with the newly allocated vport object.

  As mentioned above, vport creation is divided into two parts:

    - Creation with the kernel and LLDD. This means all transport and
      driver data structures are built up, and device objects created.
      This is equivalent to a driver "attach" on an adapter, which is
      independent of the adapter's link state.
    - Instantiation of the vport on the FC link via ELS traffic, etc.
      This is equivalent to a "link up" and successful link initialization.

  The LLDD's vport_create() function will not synchronously wait for both
  parts to be fully completed before returning. It must validate that the
  infrastructure exists to support NPIV, and complete the first part of
  vport creation (data structure build up) before returning.  We do not
  hinge vport_create() on the link-side operation mainly because:

    - The link may be down. It is not a failure if it is. It simply
      means the vport is in an inoperable state until the link comes up.
      This is consistent with the link bouncing post vport creation.
    - The vport may be created in a disabled state.
    - This is consistent with a model where:  the vport equates to a
      FC adapter. The vport_create is synonymous with driver attachment
      to the adapter, which is independent of link state.

  .. Note::

      special error codes have been defined to delineate infrastructure
      failure cases for quicker resolution.

  The expected behavior for the LLDD's vport_create() function is:

    - Validate Infrastructure:

        - If the driver or adapter cannot support another vport, whether
            due to improper firmware, (a lie about) max_npiv, or a lack of
            some other resource - return VPCERR_UNSUPPORTED.
        - If the driver validates the WWN's against those already active on
            the adapter and detects an overlap - return VPCERR_BAD_WWN.
        - If the driver detects the topology is loop, non-fabric, or the
            FLOGI did not support NPIV - return VPCERR_NO_FABRIC_SUPP.

    - Allocate data structures. If errors are encountered, such as out
        of memory conditions, return the respective negative Exxx error code.
    - If the role is FCP Initiator, the LLDD is to :

        - Call scsi_host_alloc() to allocate a scsi_host for the vport.
        - Call scsi_add_host(new_shost, &vport->dev) to start the scsi_host
          and bind it as a child of the vport device.
        - Initializes the fc_host attribute values.

    - Kick of further vport state transitions based on the disable flag and
        link state - and return success (zero).

  LLDD Implementers Notes:

  - It is suggested that there be a different fc_function_templates for
    the physical port and the virtual port.  The physical port's template
    would have the vport_create, vport_delete, and vport_disable functions,
    while the vports would not.
  - It is suggested that there be different scsi_host_templates
    for the physical port and virtual port. Likely, there are driver
    attributes, embedded into the scsi_host_template, that are applicable
    for the physical port only (link speed, topology setting, etc). This
    ensures that the attributes are applicable to the respective scsi_host.

Vport Disable/Enable:

  The LLDD vport_disable() syntax is::

      int vport_disable(struct fc_vport *vport, bool disable)

  where:

      =======   =======================================
      vport     Is vport to be enabled or disabled
      disable   If "true", the vport is to be disabled.
                If "false", the vport is to be enabled.
      =======   =======================================

  When a request is made to change the disabled state on a vport, the
  transport will validate the request against the existing vport state.
  If the request is to disable and the vport is already disabled, the
  request will fail. Similarly, if the request is to enable, and the
  vport is not in a disabled state, the request will fail.  If the request
  is valid for the vport state, the transport will call the LLDD to
  change the vport's state.

  Within the LLDD, if a vport is disabled, it remains instantiated with
  the kernel and LLDD, but it is not active or visible on the FC link in
  any way. (see Vport Creation and the 2 part instantiation discussion).
  The vport will remain in this state until it is deleted or re-enabled.
  When enabling a vport, the LLDD reinstantiates the vport on the FC
  link - essentially restarting the LLDD statemachine (see Vport States
  above).

Vport Deletion:

  The LLDD vport_delete() syntax is::

      int vport_delete(struct fc_vport *vport)

  where:

      vport:    Is vport to delete

  When a request is made to delete a vport (via sgio/netlink, or via the
  fc_host or fc_vport vport_delete attributes), the transport will call
  the LLDD to terminate the vport on the FC link, and teardown all other
  datastructures and references.  If the LLDD completes successfully,
  the transport will teardown the vport objects and complete the vport
  removal.  If the LLDD delete request fails, the vport object will remain,
  but will be in an indeterminate state.

  Within the LLDD, the normal code paths for a scsi_host teardown should
  be followed. E.g. If the vport has a FCP Initiator role, the LLDD
  will call fc_remove_host() for the vports scsi_host, followed by
  scsi_remove_host() and scsi_host_put() for the vports scsi_host.

Other:
  fc_host port_type attribute:
    There is a new fc_host port_type value - FC_PORTTYPE_NPIV. This value
    must be set on all vport-based fc_hosts.  Normally, on a physical port,
    the port_type attribute would be set to NPORT, NLPORT, etc based on the
    topology type and existence of the fabric. As this is not applicable to
    a vport, it makes more sense to report the FC mechanism used to create
    the vport.

  Driver unload:
    FC drivers are required to call fc_remove_host() prior to calling
    scsi_remove_host().  This allows the fc_host to tear down all remote
    ports prior the scsi_host being torn down.  The fc_remove_host() call
    was updated to remove all vports for the fc_host as well.

Transport supplied functions
----------------------------

The following functions are supplied by the FC-transport for use by LLDs.

   ==================   =========================
   fc_vport_create      create a vport
   fc_vport_terminate   detach and remove a vport
   ==================   =========================

Details::

    /**
    * fc_vport_create - Admin App or LLDD requests creation of a vport
    * @shost:     scsi host the virtual port is connected to.
    * @ids:       The world wide names, FC4 port roles, etc for
    *              the virtual port.
    *
    * Notes:
    *     This routine assumes no locks are held on entry.
    */
    struct fc_vport *
    fc_vport_create(struct Scsi_Host *shost, struct fc_vport_identifiers *ids)

    /**
    * fc_vport_terminate - Admin App or LLDD requests termination of a vport
    * @vport:      fc_vport to be terminated
    *
    * Calls the LLDD vport_delete() function, then deallocates and removes
    * the vport from the shost and object tree.
    *
    * Notes:
    *      This routine assumes no locks are held on entry.
    */
    int
    fc_vport_terminate(struct fc_vport *vport)

FC BSG support (CT & ELS passthru, and more)
============================================

<< To Be Supplied >>

Credits
=======
The following people have contributed to this document:

James Smart
james.smart@emulex.com