code:
// The template and inlines for the -*- C++ -*- valarray class.

// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

/** @file valarray
 *  This is a Standard C++ Library header.
 */

// Written by Gabriel Dos Reis <Gabriel.Dos-Reis@DPTMaths.ENS-Cachan.Fr>

#ifndef _GLIBCXX_VALARRAY
#define _GLIBCXX_VALARRAY 1

#pragma GCC system_header

#include <bits/c++config.h>
#include <cstddef>
#include <cmath>
#include <cstdlib>
#include <numeric>
#include <algorithm>
#include <debug/debug.h>

_GLIBCXX_BEGIN_NAMESPACE(std)

  template<class _Clos, typename _Tp>
    class _Expr;

  template<typename _Tp1, typename _Tp2>
    class _ValArray;

  template<class _Oper, template<class, class> class _Meta, class _Dom>
    struct _UnClos;

  template<class _Oper,
        template<class, class> class _Meta1,
        template<class, class> class _Meta2,
        class _Dom1, class _Dom2>
    class _BinClos;

  template<template<class, class> class _Meta, class _Dom>
    class _SClos;

  template<template<class, class> class _Meta, class _Dom>
    class _GClos;

  template<template<class, class> class _Meta, class _Dom>
    class _IClos;

  template<template<class, class> class _Meta, class _Dom>
    class _ValFunClos;

  template<template<class, class> class _Meta, class _Dom>
    class _RefFunClos;

  template<class _Tp> class valarray;   // An array of type _Tp
  class slice;                          // BLAS-like slice out of an array
  template<class _Tp> class slice_array;
  class gslice;                         // generalized slice out of an array
  template<class _Tp> class gslice_array;
  template<class _Tp> class mask_array;     // masked array
  template<class _Tp> class indirect_array; // indirected array

_GLIBCXX_END_NAMESPACE

#include <bits/valarray_array.h>
#include <bits/valarray_before.h>

_GLIBCXX_BEGIN_NAMESPACE(std)

  /**
   *  @brief  Smart array designed to support numeric processing.
   *
   *  A valarray is an array that provides constraints intended to allow for
   *  effective optimization of numeric array processing by reducing the
   *  aliasing that can result from pointer representations.  It represents a
   *  one-dimensional array from which different multidimensional subsets can
   *  be accessed and modified.
   *
   *  @param  Tp  Type of object in the array.
   */
  template<class _Tp>
    class valarray
    {
      template<class _Op>
	struct _UnaryOp
	{
	  typedef typename __fun<_Op, _Tp>::result_type __rt;
	  typedef _Expr<_UnClos<_Op, _ValArray, _Tp>, __rt> _Rt;
	};
    public:
      typedef _Tp value_type;

	// _lib.valarray.cons_ construct/destroy:
      ///  Construct an empty array.
      valarray();

      ///  Construct an array with @a n elements.
      explicit valarray(size_t);

      ///  Construct an array with @a n elements initialized to @a t.
      valarray(const _Tp&, size_t);

      ///  Construct an array initialized to the first @a n elements of @a t.
      valarray(const _Tp* __restrict__, size_t);

      ///  Copy constructor.
      valarray(const valarray&);

      ///  Construct an array with the same size and values in @a sa.
      valarray(const slice_array<_Tp>&);

      ///  Construct an array with the same size and values in @a ga.
      valarray(const gslice_array<_Tp>&);

      ///  Construct an array with the same size and values in @a ma.
      valarray(const mask_array<_Tp>&);

      ///  Construct an array with the same size and values in @a ia.
      valarray(const indirect_array<_Tp>&);

      template<class _Dom>
	valarray(const _Expr<_Dom, _Tp>& __e);

      ~valarray();

      // _lib.valarray.assign_ assignment:
      /**
       *  @brief  Assign elements to an array.
       *
       *  Assign elements of array to values in @a v.  Results are undefined
       *  if @a v does not have the same size as this array.
       *
       *  @param  v  Valarray to get values from.
       */
      valarray<_Tp>& operator=(const valarray<_Tp>&);

      /**
       *  @brief  Assign elements to a value.
       *
       *  Assign all elements of array to @a t.
       *
       *  @param  t  Value for elements.
       */
      valarray<_Tp>& operator=(const _Tp&);

      /**
       *  @brief  Assign elements to an array subset.
       *
       *  Assign elements of array to values in @a sa.  Results are undefined
       *  if @a sa does not have the same size as this array.
       *
       *  @param  sa  Array slice to get values from.
       */
      valarray<_Tp>& operator=(const slice_array<_Tp>&);

      /**
       *  @brief  Assign elements to an array subset.
       *
       *  Assign elements of array to values in @a ga.  Results are undefined
       *  if @a ga does not have the same size as this array.
       *
       *  @param  ga  Array slice to get values from.
       */
      valarray<_Tp>& operator=(const gslice_array<_Tp>&);

      /**
       *  @brief  Assign elements to an array subset.
       *
       *  Assign elements of array to values in @a ma.  Results are undefined
       *  if @a ma does not have the same size as this array.
       *
       *  @param  ma  Array slice to get values from.
       */
      valarray<_Tp>& operator=(const mask_array<_Tp>&);

      /**
       *  @brief  Assign elements to an array subset.
       *
       *  Assign elements of array to values in @a ia.  Results are undefined
       *  if @a ia does not have the same size as this array.
       *
       *  @param  ia  Array slice to get values from.
       */
      valarray<_Tp>& operator=(const indirect_array<_Tp>&);

      template<class _Dom> valarray<_Tp>&
	operator= (const _Expr<_Dom, _Tp>&);

      // _lib.valarray.access_ element access:
      /**
       *  Return a reference to the i'th array element.
       *
       *  @param  i  Index of element to return.
       *  @return  Reference to the i'th element.
       */
      _Tp&                operator[](size_t);

      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 389. Const overload of valarray::operator[] returns by value.
      const _Tp&          operator[](size_t) const;

      // _lib.valarray.sub_ subset operations:
      /**
       *  @brief  Return an array subset.
       *
       *  Returns a new valarray containing the elements of the array
       *  indicated by the slice argument.  The new valarray has the same size
       *  as the input slice.  @see slice.
       *
       *  @param  s  The source slice.
       *  @return  New valarray containing elements in @a s.
       */
      _Expr<_SClos<_ValArray, _Tp>, _Tp> operator[](slice) const;

      /**
       *  @brief  Return a reference to an array subset.
       *
       *  Returns a new valarray containing the elements of the array
       *  indicated by the slice argument.  The new valarray has the same size
       *  as the input slice.  @see slice.
       *
       *  @param  s  The source slice.
       *  @return  New valarray containing elements in @a s.
       */
      slice_array<_Tp>    operator[](slice);

      /**
       *  @brief  Return an array subset.
       *
       *  Returns a slice_array referencing the elements of the array
       *  indicated by the slice argument.  @see gslice.
       *
       *  @param  s  The source slice.
       *  @return  Slice_array referencing elements indicated by @a s.
       */
      _Expr<_GClos<_ValArray, _Tp>, _Tp> operator[](const gslice&) const;

      /**
       *  @brief  Return a reference to an array subset.
       *
       *  Returns a new valarray containing the elements of the array
       *  indicated by the gslice argument.  The new valarray has
       *  the same size as the input gslice.  @see gslice.
       *
       *  @param  s  The source gslice.
       *  @return  New valarray containing elements in @a s.
       */
      gslice_array<_Tp>   operator[](const gslice&);

      /**
       *  @brief  Return an array subset.
       *
       *  Returns a new valarray containing the elements of the array
       *  indicated by the argument.  The input is a valarray of bool which
       *  represents a bitmask indicating which elements should be copied into
       *  the new valarray.  Each element of the array is added to the return
       *  valarray if the corresponding element of the argument is true.
       *
       *  @param  m  The valarray bitmask.
       *  @return  New valarray containing elements indicated by @a m.
       */
      valarray<_Tp>       operator[](const valarray<bool>&) const;

      /**
       *  @brief  Return a reference to an array subset.
       *
       *  Returns a new mask_array referencing the elements of the array
       *  indicated by the argument.  The input is a valarray of bool which
       *  represents a bitmask indicating which elements are part of the
       *  subset.  Elements of the array are part of the subset if the
       *  corresponding element of the argument is true.
       *
       *  @param  m  The valarray bitmask.
       *  @return  New valarray containing elements indicated by @a m.
       */
      mask_array<_Tp>     operator[](const valarray<bool>&);

      /**
       *  @brief  Return an array subset.
       *
       *  Returns a new valarray containing the elements of the array
       *  indicated by the argument.  The elements in the argument are
       *  interpreted as the indices of elements of this valarray to copy to
       *  the return valarray.
       *
       *  @param  i  The valarray element index list.
       *  @return  New valarray containing elements in @a s.
       */
      _Expr<_IClos<_ValArray, _Tp>, _Tp>
        operator[](const valarray<size_t>&) const;

      /**
       *  @brief  Return a reference to an array subset.
       *
       *  Returns an indirect_array referencing the elements of the array
       *  indicated by the argument.  The elements in the argument are
       *  interpreted as the indices of elements of this valarray to include
       *  in the subset.  The returned indirect_array refers to these
       *  elements.
       *
       *  @param  i  The valarray element index list.
       *  @return  Indirect_array referencing elements in @a i.
       */
      indirect_array<_Tp> operator[](const valarray<size_t>&);

      // _lib.valarray.unary_ unary operators:
      ///  Return a new valarray by applying unary + to each element.
      typename _UnaryOp<__unary_plus>::_Rt  operator+() const;

      ///  Return a new valarray by applying unary - to each element.
      typename _UnaryOp<__negate>::_Rt      operator-() const;

      ///  Return a new valarray by applying unary ~ to each element.
      typename _UnaryOp<__bitwise_not>::_Rt operator~() const;

      ///  Return a new valarray by applying unary ! to each element.
      typename _UnaryOp<__logical_not>::_Rt operator!() const;

      // _lib.valarray.cassign_ computed assignment:
      ///  Multiply each element of array by @a t.
      valarray<_Tp>& operator*=(const _Tp&);

      ///  Divide each element of array by @a t.
      valarray<_Tp>& operator/=(const _Tp&);

      ///  Set each element e of array to e % @a t.
      valarray<_Tp>& operator%=(const _Tp&);

      ///  Add @a t to each element of array.
      valarray<_Tp>& operator+=(const _Tp&);

      ///  Subtract @a t to each element of array.
      valarray<_Tp>& operator-=(const _Tp&);

      ///  Set each element e of array to e ^ @a t.
      valarray<_Tp>& operator^=(const _Tp&);

      ///  Set each element e of array to e & @a t.
      valarray<_Tp>& operator&=(const _Tp&);

      ///  Set each element e of array to e | @a t.
      valarray<_Tp>& operator|=(const _Tp&);

      ///  Left shift each element e of array by @a t bits.
      valarray<_Tp>& operator<<=(const _Tp&);

      ///  Right shift each element e of array by @a t bits.
      valarray<_Tp>& operator>>=(const _Tp&);

      ///  Multiply elements of array by corresponding elements of @a v.
      valarray<_Tp>& operator*=(const valarray<_Tp>&);

      ///  Divide elements of array by corresponding elements of @a v.
      valarray<_Tp>& operator/=(const valarray<_Tp>&);

      ///  Modulo elements of array by corresponding elements of @a v.
      valarray<_Tp>& operator%=(const valarray<_Tp>&);

      ///  Add corresponding elements of @a v to elements of array.
      valarray<_Tp>& operator+=(const valarray<_Tp>&);

      ///  Subtract corresponding elements of @a v from elements of array.
      valarray<_Tp>& operator-=(const valarray<_Tp>&);

      ///  Logical xor corresponding elements of @a v with elements of array.
      valarray<_Tp>& operator^=(const valarray<_Tp>&);

      ///  Logical or corresponding elements of @a v with elements of array.
      valarray<_Tp>& operator|=(const valarray<_Tp>&);

      ///  Logical and corresponding elements of @a v with elements of array.
      valarray<_Tp>& operator&=(const valarray<_Tp>&);

      ///  Left shift elements of array by corresponding elements of @a v.
      valarray<_Tp>& operator<<=(const valarray<_Tp>&);

      ///  Right shift elements of array by corresponding elements of @a v.
      valarray<_Tp>& operator>>=(const valarray<_Tp>&);

      template<class _Dom>
	valarray<_Tp>& operator*=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator/=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator%=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator+=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator-=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator^=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator|=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator&=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
        valarray<_Tp>& operator<<=(const _Expr<_Dom, _Tp>&);
      template<class _Dom>
	valarray<_Tp>& operator>>=(const _Expr<_Dom, _Tp>&);

      // _lib.valarray.members_ member functions:
      ///  Return the number of elements in array.
      size_t size() const;

      /**
       *  @brief  Return the sum of all elements in the array.
       *
       *  Accumulates the sum of all elements into a Tp using +=.  The order
       *  of adding the elements is unspecified.
       */
      _Tp    sum() const;

      ///  Return the minimum element using operator<().
      _Tp    min() const;

      ///  Return the maximum element using operator<().
      _Tp    max() const;

      /**
       *  @brief  Return a shifted array.
       *
       *  A new valarray is constructed as a copy of this array with elements
       *  in shifted positions.  For an element with index i, the new position
       *  is i - n.  The new valarray has the same size as the current one.
       *  New elements without a value are set to 0.  Elements whose new
       *  position is outside the bounds of the array are discarded.
       *
       *  Positive arguments shift toward index 0, discarding elements [0, n).
       *  Negative arguments discard elements from the top of the array.
       *
       *  @param  n  Number of element positions to shift.
       *  @return  New valarray with elements in shifted positions.
       */
      valarray<_Tp> shift (int) const;

      /**
       *  @brief  Return a rotated array.
       *
       *  A new valarray is constructed as a copy of this array with elements
       *  in shifted positions.  For an element with index i, the new position
       *  is (i - n) % size().  The new valarray has the same size as the
       *  current one.  Elements that are shifted beyond the array bounds are
       *  shifted into the other end of the array.  No elements are lost.
       *
       *  Positive arguments shift toward index 0, wrapping around the top.
       *  Negative arguments shift towards the top, wrapping around to 0.
       *
       *  @param  n  Number of element positions to rotate.
       *  @return  New valarray with elements in shifted positions.
       */
      valarray<_Tp> cshift(int) const;

      /**
       *  @brief  Apply a function to the array.
       *
       *  Returns a new valarray with elements assigned to the result of
       *  applying func to the corresponding element of this array.  The new
       *  array has the same size as this one.
       *
       *  @param  func  Function of Tp returning Tp to apply.
       *  @return  New valarray with transformed elements.
       */
      _Expr<_ValFunClos<_ValArray, _Tp>, _Tp> apply(_Tp func(_Tp)) const;

      /**
       *  @brief  Apply a function to the array.
       *
       *  Returns a new valarray with elements assigned to the result of
       *  applying func to the corresponding element of this array.  The new
       *  array has the same size as this one.
       *
       *  @param  func  Function of const Tp& returning Tp to apply.
       *  @return  New valarray with transformed elements.
       */
      _Expr<_RefFunClos<_ValArray, _Tp>, _Tp> apply(_Tp func(const _Tp&)) const;

      /**
       *  @brief  Resize array.
       *
       *  Resize this array to @a size and set all elements to @a c.  All
       *  references and iterators are invalidated.
       *
       *  @param  size  New array size.
       *  @param  c  New value for all elements.
       */
      void resize(size_t __size, _Tp __c = _Tp());

    private:
      size_t _M_size;
      _Tp* __restrict__ _M_data;

      friend class _Array<_Tp>;
    };

  template<typename _Tp>
    inline const _Tp&
    valarray<_Tp>::operator[](size_t __i) const
    {
      __glibcxx_requires_subscript(__i);
      return _M_data[__i];
    }

  template<typename _Tp>
    inline _Tp&
    valarray<_Tp>::operator[](size_t __i)
    {
      __glibcxx_requires_subscript(__i);
      return _M_data[__i];
    }

_GLIBCXX_END_NAMESPACE

#include <bits/valarray_after.h>
#include <bits/slice_array.h>
#include <bits/gslice.h>
#include <bits/gslice_array.h>
#include <bits/mask_array.h>
#include <bits/indirect_array.h>

_GLIBCXX_BEGIN_NAMESPACE(std)

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray() : _M_size(0), _M_data(0) {}

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(size_t __n)
    : _M_size(__n), _M_data(__valarray_get_storage<_Tp>(__n))
    { std::__valarray_default_construct(_M_data, _M_data + __n); }

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(const _Tp& __t, size_t __n)
    : _M_size(__n), _M_data(__valarray_get_storage<_Tp>(__n))
    { std::__valarray_fill_construct(_M_data, _M_data + __n, __t); }

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(const _Tp* __restrict__ __p, size_t __n)
    : _M_size(__n), _M_data(__valarray_get_storage<_Tp>(__n))
    {
      _GLIBCXX_DEBUG_ASSERT(__p != 0 || __n == 0);
      std::__valarray_copy_construct(__p, __p + __n, _M_data);
    }

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(const valarray<_Tp>& __v)
    : _M_size(__v._M_size), _M_data(__valarray_get_storage<_Tp>(__v._M_size))
    { std::__valarray_copy_construct(__v._M_data, __v._M_data + _M_size,
				     _M_data); }

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(const slice_array<_Tp>& __sa)
    : _M_size(__sa._M_sz), _M_data(__valarray_get_storage<_Tp>(__sa._M_sz))
    {
      std::__valarray_copy_construct
	(__sa._M_array, __sa._M_sz, __sa._M_stride, _Array<_Tp>(_M_data));
    }

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(const gslice_array<_Tp>& __ga)
    : _M_size(__ga._M_index.size()),
      _M_data(__valarray_get_storage<_Tp>(_M_size))
    {
      std::__valarray_copy_construct
	(__ga._M_array, _Array<size_t>(__ga._M_index),
	 _Array<_Tp>(_M_data), _M_size);
    }

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(const mask_array<_Tp>& __ma)
    : _M_size(__ma._M_sz), _M_data(__valarray_get_storage<_Tp>(__ma._M_sz))
    {
      std::__valarray_copy_construct
	(__ma._M_array, __ma._M_mask, _Array<_Tp>(_M_data), _M_size);
    }

  template<typename _Tp>
    inline
    valarray<_Tp>::valarray(const indirect_array<_Tp>& __ia)
    : _M_size(__ia._M_sz), _M_data(__valarray_get_storage<_Tp>(__ia._M_sz))
    {
      std::__valarray_copy_construct
	(__ia._M_array, __ia._M_index, _Array<_Tp>(_M_data), _M_size);
    }

  template<typename _Tp> template<class _Dom>
    inline
    valarray<_Tp>::valarray(const _Expr<_Dom, _Tp>& __e)
    : _M_size(__e.size()), _M_data(__valarray_get_storage<_Tp>(_M_size))
    { std::__valarray_copy_construct(__e, _M_size, _Array<_Tp>(_M_data)); }

  template<typename _Tp>
    inline
    valarray<_Tp>::~valarray()
    {
      std::__valarray_destroy_elements(_M_data, _M_data + _M_size);
      std::__valarray_release_memory(_M_data);
    }

  template<typename _Tp>
    inline valarray<_Tp>&
    valarray<_Tp>::operator=(const valarray<_Tp>& __v)
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size == __v._M_size);
      std::__valarray_copy(__v._M_data, _M_size, _M_data);
      return *this;
    }

  template<typename _Tp>
    inline valarray<_Tp>&
    valarray<_Tp>::operator=(const _Tp& __t)
    {
      std::__valarray_fill(_M_data, _M_size, __t);
      return *this;
    }

  template<typename _Tp>
    inline valarray<_Tp>&
    valarray<_Tp>::operator=(const slice_array<_Tp>& __sa)
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size == __sa._M_sz);
      std::__valarray_copy(__sa._M_array, __sa._M_sz,
			   __sa._M_stride, _Array<_Tp>(_M_data));
      return *this;
    }

  template<typename _Tp>
    inline valarray<_Tp>&
    valarray<_Tp>::operator=(const gslice_array<_Tp>& __ga)
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size == __ga._M_index.size());
      std::__valarray_copy(__ga._M_array, _Array<size_t>(__ga._M_index),
			   _Array<_Tp>(_M_data), _M_size);
      return *this;
    }

  template<typename _Tp>
    inline valarray<_Tp>&
    valarray<_Tp>::operator=(const mask_array<_Tp>& __ma)
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size == __ma._M_sz);
      std::__valarray_copy(__ma._M_array, __ma._M_mask,
			   _Array<_Tp>(_M_data), _M_size);
      return *this;
    }

  template<typename _Tp>
    inline valarray<_Tp>&
    valarray<_Tp>::operator=(const indirect_array<_Tp>& __ia)
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size == __ia._M_sz);
      std::__valarray_copy(__ia._M_array, __ia._M_index,
			   _Array<_Tp>(_M_data), _M_size);
      return *this;
    }

  template<typename _Tp> template<class _Dom>
    inline valarray<_Tp>&
    valarray<_Tp>::operator=(const _Expr<_Dom, _Tp>& __e)
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size == __e.size());
      std::__valarray_copy(__e, _M_size, _Array<_Tp>(_M_data));
      return *this;
    }

  template<typename _Tp>
    inline _Expr<_SClos<_ValArray,_Tp>, _Tp>
    valarray<_Tp>::operator[](slice __s) const
    {
      typedef _SClos<_ValArray,_Tp> _Closure;
      return _Expr<_Closure, _Tp>(_Closure (_Array<_Tp>(_M_data), __s));
    }

  template<typename _Tp>
    inline slice_array<_Tp>
    valarray<_Tp>::operator[](slice __s)
    { return slice_array<_Tp>(_Array<_Tp>(_M_data), __s); }

  template<typename _Tp>
    inline _Expr<_GClos<_ValArray,_Tp>, _Tp>
    valarray<_Tp>::operator[](const gslice& __gs) const
    {
      typedef _GClos<_ValArray,_Tp> _Closure;
      return _Expr<_Closure, _Tp>
	(_Closure(_Array<_Tp>(_M_data), __gs._M_index->_M_index));
    }

  template<typename _Tp>
    inline gslice_array<_Tp>
    valarray<_Tp>::operator[](const gslice& __gs)
    {
      return gslice_array<_Tp>
	(_Array<_Tp>(_M_data), __gs._M_index->_M_index);
    }

  template<typename _Tp>
    inline valarray<_Tp>
    valarray<_Tp>::operator[](const valarray<bool>& __m) const
    {
      size_t __s = 0;
      size_t __e = __m.size();
      for (size_t __i=0; __i<__e; ++__i)
	if (__m[__i]) ++__s;
      return valarray<_Tp>(mask_array<_Tp>(_Array<_Tp>(_M_data), __s,
					   _Array<bool> (__m)));
    }

  template<typename _Tp>
    inline mask_array<_Tp>
    valarray<_Tp>::operator[](const valarray<bool>& __m)
    {
      size_t __s = 0;
      size_t __e = __m.size();
      for (size_t __i=0; __i<__e; ++__i)
	if (__m[__i]) ++__s;
      return mask_array<_Tp>(_Array<_Tp>(_M_data), __s, _Array<bool>(__m));
    }

  template<typename _Tp>
    inline _Expr<_IClos<_ValArray,_Tp>, _Tp>
    valarray<_Tp>::operator[](const valarray<size_t>& __i) const
    {
      typedef _IClos<_ValArray,_Tp> _Closure;
      return _Expr<_Closure, _Tp>(_Closure(*this, __i));
    }

  template<typename _Tp>
    inline indirect_array<_Tp>
    valarray<_Tp>::operator[](const valarray<size_t>& __i)
    {
      return indirect_array<_Tp>(_Array<_Tp>(_M_data), __i.size(),
				 _Array<size_t>(__i));
    }

  template<class _Tp>
    inline size_t
    valarray<_Tp>::size() const
    { return _M_size; }

  template<class _Tp>
    inline _Tp
    valarray<_Tp>::sum() const
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size > 0);
      return std::__valarray_sum(_M_data, _M_data + _M_size);
    }

  template<class _Tp>
     inline valarray<_Tp>
     valarray<_Tp>::shift(int __n) const
     {
       valarray<_Tp> __ret;

       if (_M_size == 0)
	 return __ret;

       _Tp* __restrict__ __tmp_M_data =
	 std::__valarray_get_storage<_Tp>(_M_size);

       if (__n == 0)
	 std::__valarray_copy_construct(_M_data,
					_M_data + _M_size, __tmp_M_data);
       else if (__n > 0)      // shift left
	 {
	   if (size_t(__n) > _M_size)
	     __n = _M_size;

	   std::__valarray_copy_construct(_M_data + __n,
					  _M_data + _M_size, __tmp_M_data);
	   std::__valarray_default_construct(__tmp_M_data + _M_size - __n,
					     __tmp_M_data + _M_size);
	 }
       else                   // shift right
	 {
	   if (size_t(-__n) > _M_size)
	     __n = -_M_size;

	   std::__valarray_copy_construct(_M_data, _M_data + _M_size + __n,
					  __tmp_M_data - __n);
	   std::__valarray_default_construct(__tmp_M_data,
					     __tmp_M_data - __n);
	 }

       __ret._M_size = _M_size;
       __ret._M_data = __tmp_M_data;
       return __ret;
     }

  template<class _Tp>
     inline valarray<_Tp>
     valarray<_Tp>::cshift(int __n) const
     {
       valarray<_Tp> __ret;

       if (_M_size == 0)
	 return __ret;

       _Tp* __restrict__ __tmp_M_data =
	 std::__valarray_get_storage<_Tp>(_M_size);

       if (__n == 0)
	 std::__valarray_copy_construct(_M_data,
					_M_data + _M_size, __tmp_M_data);
       else if (__n > 0)      // cshift left
	 {
	   if (size_t(__n) > _M_size)
	     __n = __n % _M_size;

	   std::__valarray_copy_construct(_M_data, _M_data + __n,
					  __tmp_M_data + _M_size - __n);
	   std::__valarray_copy_construct(_M_data + __n, _M_data + _M_size,
					  __tmp_M_data);
	 }
       else                   // cshift right
	 {
	   if (size_t(-__n) > _M_size)
	     __n = -(size_t(-__n) % _M_size);

	   std::__valarray_copy_construct(_M_data + _M_size + __n,
					  _M_data + _M_size, __tmp_M_data);
	   std::__valarray_copy_construct(_M_data, _M_data + _M_size + __n,
					  __tmp_M_data - __n);
	 }

       __ret._M_size = _M_size;
       __ret._M_data = __tmp_M_data;
       return __ret;
     }

  template<class _Tp>
    inline void
    valarray<_Tp>::resize(size_t __n, _Tp __c)
    {
      // This complication is so to make valarray<valarray<T> > work
      // even though it is not required by the standard.  Nobody should
      // be saying valarray<valarray<T> > anyway.  See the specs.
      std::__valarray_destroy_elements(_M_data, _M_data + _M_size);
      if (_M_size != __n)
	{
	  std::__valarray_release_memory(_M_data);
	  _M_size = __n;
	  _M_data = __valarray_get_storage<_Tp>(__n);
	}
      std::__valarray_fill_construct(_M_data, _M_data + __n, __c);
    }

  template<typename _Tp>
    inline _Tp
    valarray<_Tp>::min() const
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size > 0);
      return *std::min_element(_M_data, _M_data+_M_size);
    }

  template<typename _Tp>
    inline _Tp
    valarray<_Tp>::max() const
    {
      _GLIBCXX_DEBUG_ASSERT(_M_size > 0);
      return *std::max_element(_M_data, _M_data+_M_size);
    }

  template<class _Tp>
    inline _Expr<_ValFunClos<_ValArray, _Tp>, _Tp>
    valarray<_Tp>::apply(_Tp func(_Tp)) const
    {
      typedef _ValFunClos<_ValArray, _Tp> _Closure;
      return _Expr<_Closure, _Tp>(_Closure(*this, func));
    }

  template<class _Tp>
    inline _Expr<_RefFunClos<_ValArray, _Tp>, _Tp>
    valarray<_Tp>::apply(_Tp func(const _Tp &)) const
    {
      typedef _RefFunClos<_ValArray, _Tp> _Closure;
      return _Expr<_Closure, _Tp>(_Closure(*this, func));
    }

#define _DEFINE_VALARRAY_UNARY_OPERATOR(_Op, _Name)                     \
  template<typename _Tp>						\
    inline typename valarray<_Tp>::template _UnaryOp<_Name>::_Rt      	\
    valarray<_Tp>::operator _Op() const					\
    {									\
      typedef _UnClos<_Name, _ValArray, _Tp> _Closure;	                \
      typedef typename __fun<_Name, _Tp>::result_type _Rt;              \
      return _Expr<_Closure, _Rt>(_Closure(*this));			\
    }

    _DEFINE_VALARRAY_UNARY_OPERATOR(+, __unary_plus)
    _DEFINE_VALARRAY_UNARY_OPERATOR(-, __negate)
    _DEFINE_VALARRAY_UNARY_OPERATOR(~, __bitwise_not)
    _DEFINE_VALARRAY_UNARY_OPERATOR (!, __logical_not)

#undef _DEFINE_VALARRAY_UNARY_OPERATOR

#define _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(_Op, _Name)               \
  template<class _Tp>							\
    inline valarray<_Tp>&						\
    valarray<_Tp>::operator _Op##=(const _Tp &__t)			\
    {									\
      _Array_augmented_##_Name(_Array<_Tp>(_M_data), _M_size, __t);	\
      return *this;							\
    }									\
									\
  template<class _Tp>							\
    inline valarray<_Tp>&						\
    valarray<_Tp>::operator _Op##=(const valarray<_Tp> &__v)		\
    {									\
      _GLIBCXX_DEBUG_ASSERT(_M_size == __v._M_size);                    \
      _Array_augmented_##_Name(_Array<_Tp>(_M_data), _M_size, 		\
			       _Array<_Tp>(__v._M_data));		\
      return *this;							\
    }

_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(+, __plus)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(-, __minus)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(*, __multiplies)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(/, __divides)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(%, __modulus)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(^, __bitwise_xor)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(&, __bitwise_and)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(|, __bitwise_or)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(<<, __shift_left)
_DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(>>, __shift_right)

#undef _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT

#define _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(_Op, _Name)          \
  template<class _Tp> template<class _Dom>				\
    inline valarray<_Tp>&						\
    valarray<_Tp>::operator _Op##=(const _Expr<_Dom, _Tp>& __e)		\
    {									\
      _Array_augmented_##_Name(_Array<_Tp>(_M_data), __e, _M_size);	\
      return *this;							\
    }

_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(+, __plus)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(-, __minus)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(*, __multiplies)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(/, __divides)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(%, __modulus)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(^, __bitwise_xor)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(&, __bitwise_and)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(|, __bitwise_or)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(<<, __shift_left)
_DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(>>, __shift_right)

#undef _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT

#define _DEFINE_BINARY_OPERATOR(_Op, _Name)				\
  template<typename _Tp>						\
    inline _Expr<_BinClos<_Name, _ValArray, _ValArray, _Tp, _Tp>,       \
                 typename __fun<_Name, _Tp>::result_type>               \
    operator _Op(const valarray<_Tp>& __v, const valarray<_Tp>& __w)	\
    {									\
      _GLIBCXX_DEBUG_ASSERT(__v.size() == __w.size());                  \
      typedef _BinClos<_Name, _ValArray, _ValArray, _Tp, _Tp> _Closure; \
      typedef typename __fun<_Name, _Tp>::result_type _Rt;              \
      return _Expr<_Closure, _Rt>(_Closure(__v, __w));                  \
    }									\
									\
  template<typename _Tp>						\
    inline _Expr<_BinClos<_Name, _ValArray,_Constant, _Tp, _Tp>,        \
                 typename __fun<_Name, _Tp>::result_type>               \
    operator _Op(const valarray<_Tp>& __v, const _Tp& __t)		\
    {									\
      typedef _BinClos<_Name, _ValArray, _Constant, _Tp, _Tp> _Closure;	\
      typedef typename __fun<_Name, _Tp>::result_type _Rt;              \
      return _Expr<_Closure, _Rt>(_Closure(__v, __t));	                \
    }									\
									\
  template<typename _Tp>						\
    inline _Expr<_BinClos<_Name, _Constant, _ValArray, _Tp, _Tp>,       \
                 typename __fun<_Name, _Tp>::result_type>               \
    operator _Op(const _Tp& __t, const valarray<_Tp>& __v)		\
    {									\
      typedef _BinClos<_Name, _Constant, _ValArray, _Tp, _Tp> _Closure; \
      typedef typename __fun<_Name, _Tp>::result_type _Rt;              \
      return _Expr<_Closure, _Rt>(_Closure(__t, __v));        	        \
    }

_DEFINE_BINARY_OPERATOR(+, __plus)
_DEFINE_BINARY_OPERATOR(-, __minus)
_DEFINE_BINARY_OPERATOR(*, __multiplies)
_DEFINE_BINARY_OPERATOR(/, __divides)
_DEFINE_BINARY_OPERATOR(%, __modulus)
_DEFINE_BINARY_OPERATOR(^, __bitwise_xor)
_DEFINE_BINARY_OPERATOR(&, __bitwise_and)
_DEFINE_BINARY_OPERATOR(|, __bitwise_or)
_DEFINE_BINARY_OPERATOR(<<, __shift_left)
_DEFINE_BINARY_OPERATOR(>>, __shift_right)
_DEFINE_BINARY_OPERATOR(&&, __logical_and)
_DEFINE_BINARY_OPERATOR(||, __logical_or)
_DEFINE_BINARY_OPERATOR(==, __equal_to)
_DEFINE_BINARY_OPERATOR(!=, __not_equal_to)
_DEFINE_BINARY_OPERATOR(<, __less)
_DEFINE_BINARY_OPERATOR(>, __greater)
_DEFINE_BINARY_OPERATOR(<=, __less_equal)
_DEFINE_BINARY_OPERATOR(>=, __greater_equal)

#undef _DEFINE_BINARY_OPERATOR

_GLIBCXX_END_NAMESPACE

#endif /* _GLIBCXX_VALARRAY */


code:
// <vector> -*- C++ -*-

// Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

/*
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Hewlett-Packard Company makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 *
 * Copyright (c) 1996
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 */

/** @file include/vector
 *  This is a Standard C++ Library header.
 */

#ifndef _GLIBCXX_VECTOR
#define _GLIBCXX_VECTOR 1

#pragma GCC system_header

#include <bits/functexcept.h>
#include <bits/stl_algobase.h>
#include <bits/allocator.h>
#include <bits/stl_construct.h>
#include <bits/stl_uninitialized.h>
#include <bits/stl_vector.h>
#include <bits/stl_bvector.h>

#ifndef _GLIBCXX_EXPORT_TEMPLATE
# include <bits/vector.tcc>
#endif

#ifdef _GLIBCXX_DEBUG
# include <debug/vector>
#endif

#endif /* _GLIBCXX_VECTOR */

repo_name: veiledmerc/mira

license: mit


code:
/*-
 * Copyright (c) 1997 Wolfgang Helbig
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: release/9.0.0/lib/libcalendar/calendar.h 50476 1999-08-28 00:22:10Z peter $
 */
struct date {
	int y;	/* year */
	int m;	/* month */
	int d;	/* day */
};

struct date	*easterg(int _year, struct date *_dt);
struct date	*easterog(int _year, struct date *_dt);
struct date	*easteroj(int _year, struct date *_dt);
struct date	*gdate(int _nd, struct date *_dt);
struct date	*jdate(int _nd, struct date *_dt);
int		 ndaysg(struct date *_dt);
int		 ndaysj(struct date *_dt);
int		 week(int _nd, int *_year);
int		 weekday(int _nd);


code:
/*-
 * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer,
 *    without modification, immediately at the beginning of the file.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $FreeBSD: release/9.0.0/sys/cam/ata/ata_all.h 220886 2011-04-20 13:27:50Z mav $
 */

#ifndef	CAM_ATA_ALL_H
#define CAM_ATA_ALL_H 1

#include <sys/ata.h>

struct ccb_ataio;
struct cam_periph;
union  ccb;

#define	SID_DMA		0x10	/* Abuse inq_flags bit to track enabled DMA. */

struct ata_cmd {
	u_int8_t	flags;		/* ATA command flags */
#define		CAM_ATAIO_48BIT		0x01	/* Command has 48-bit format */
#define		CAM_ATAIO_FPDMA		0x02	/* FPDMA command */
#define		CAM_ATAIO_CONTROL	0x04	/* Control, not a command */
#define		CAM_ATAIO_NEEDRESULT	0x08	/* Request requires result. */
#define		CAM_ATAIO_DMA		0x10	/* DMA command */

	u_int8_t	command;
	u_int8_t	features;

	u_int8_t	lba_low;
	u_int8_t	lba_mid;
	u_int8_t	lba_high;
	u_int8_t	device;

	u_int8_t	lba_low_exp;
	u_int8_t	lba_mid_exp;
	u_int8_t	lba_high_exp;
	u_int8_t	features_exp;

	u_int8_t	sector_count;
	u_int8_t	sector_count_exp;
	u_int8_t	control;
};

struct ata_res {
	u_int8_t	flags;		/* ATA command flags */
#define		CAM_ATAIO_48BIT		0x01	/* Command has 48-bit format */

	u_int8_t	status;
	u_int8_t	error;

	u_int8_t	lba_low;
	u_int8_t	lba_mid;
	u_int8_t	lba_high;
	u_int8_t	device;

	u_int8_t	lba_low_exp;
	u_int8_t	lba_mid_exp;
	u_int8_t	lba_high_exp;

	u_int8_t	sector_count;
	u_int8_t	sector_count_exp;
};

int	ata_version(int ver);

char *	ata_op_string(struct ata_cmd *cmd);
char *	ata_cmd_string(struct ata_cmd *cmd, char *cmd_string, size_t len);
char *	ata_res_string(struct ata_res *res, char *res_string, size_t len);
int	ata_command_sbuf(struct ccb_ataio *ataio, struct sbuf *sb);
int	ata_status_sbuf(struct ccb_ataio *ataio, struct sbuf *sb);
int	ata_res_sbuf(struct ccb_ataio *ataio, struct sbuf *sb);

void	ata_print_ident(struct ata_params *ident_data);

uint32_t	ata_logical_sector_size(struct ata_params *ident_data);
uint64_t	ata_physical_sector_size(struct ata_params *ident_data);
uint64_t	ata_logical_sector_offset(struct ata_params *ident_data);

void	ata_28bit_cmd(struct ccb_ataio *ataio, uint8_t cmd, uint8_t features,
    uint32_t lba, uint8_t sector_count);
void	ata_48bit_cmd(struct ccb_ataio *ataio, uint8_t cmd, uint16_t features,
    uint64_t lba, uint16_t sector_count);
void	ata_ncq_cmd(struct ccb_ataio *ataio, uint8_t cmd,
    uint64_t lba, uint16_t sector_count);
void	ata_reset_cmd(struct ccb_ataio *ataio);
void	ata_pm_read_cmd(struct ccb_ataio *ataio, int reg, int port);
void	ata_pm_write_cmd(struct ccb_ataio *ataio, int reg, int port, uint32_t val);

void	ata_bswap(int8_t *buf, int len);
void	ata_btrim(int8_t *buf, int len);
void	ata_bpack(int8_t *src, int8_t *dst, int len);

int	ata_max_pmode(struct ata_params *ap);
int	ata_max_wmode(struct ata_params *ap);
int	ata_max_umode(struct ata_params *ap);
int	ata_max_mode(struct ata_params *ap, int maxmode);

char *	ata_mode2string(int mode);
int	ata_string2mode(char *str);
u_int	ata_mode2speed(int mode);
u_int	ata_revision2speed(int revision);
int	ata_speed2revision(u_int speed);

int	ata_identify_match(caddr_t identbuffer, caddr_t table_entry);
int	ata_static_identify_match(caddr_t identbuffer, caddr_t table_entry);

#endif


code:
/*-
 * Data structures and definitions for the CAM system.
 *
 * Copyright (c) 1997 Justin T. Gibbs.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification, immediately at the beginning of the file.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: release/9.0.0/sys/cam/cam.h 216088 2010-11-30 22:39:46Z ken $
 */

#ifndef _CAM_CAM_H
#define _CAM_CAM_H 1

#ifdef _KERNEL
#include <opt_cam.h>
#endif

#include <sys/cdefs.h>

typedef u_int path_id_t;
typedef u_int target_id_t;
typedef u_int lun_id_t;

#define	CAM_XPT_PATH_ID	((path_id_t)~0)
#define	CAM_BUS_WILDCARD ((path_id_t)~0)
#define	CAM_TARGET_WILDCARD ((target_id_t)~0)
#define	CAM_LUN_WILDCARD ((lun_id_t)~0)

/*
 * Maximum length for a CAM CDB.
 */
#define CAM_MAX_CDBLEN 16

/*
 * Definition of a CAM peripheral driver entry.  Peripheral drivers instantiate
 * one of these for each device they wish to communicate with and pass it into
 * the xpt layer when they wish to schedule work on that device via the
 * xpt_schedule API.
 */
struct cam_periph;

/*
 * Priority information for a CAM structure.
 */
typedef enum {
    CAM_RL_HOST,
    CAM_RL_BUS,
    CAM_RL_XPT,
    CAM_RL_DEV,
    CAM_RL_NORMAL,
    CAM_RL_VALUES
} cam_rl;
/*
 * The generation number is incremented everytime a new entry is entered into
 * the queue giving round robin per priority level scheduling.
 */
typedef struct {
	u_int32_t priority;
#define CAM_PRIORITY_HOST	((CAM_RL_HOST << 8) + 0x80)
#define CAM_PRIORITY_BUS	((CAM_RL_BUS << 8) + 0x80)
#define CAM_PRIORITY_XPT	((CAM_RL_XPT << 8) + 0x80)
#define CAM_PRIORITY_DEV	((CAM_RL_DEV << 8) + 0x80)
#define CAM_PRIORITY_NORMAL	((CAM_RL_NORMAL << 8) + 0x80)
#define CAM_PRIORITY_NONE	(u_int32_t)-1
#define CAM_PRIORITY_TO_RL(x)	((x) >> 8)
	u_int32_t generation;
	int       index;
#define CAM_UNQUEUED_INDEX	-1
#define CAM_ACTIVE_INDEX	-2
#define CAM_DONEQ_INDEX		-3
} cam_pinfo;

/*
 * Macro to compare two generation numbers.  It is used like this:
 *
 *	if (GENERATIONCMP(a, >=, b))
 *		...;
 *
 * GERERATIONCMP uses modular arithmetic to guard against wraps
 * wraps in the generation number.
 */
#define GENERATIONCMP(x, op, y) ((int32_t)((x) - (y)) op 0)

/* CAM flags XXX Move to cam_periph.h ??? */
typedef enum {
	CAM_FLAG_NONE		= 0x00,
	CAM_EXPECT_INQ_CHANGE	= 0x01,
	CAM_RETRY_SELTO		= 0x02 /* Retry Selection Timeouts */
} cam_flags;

/* CAM  Status field values */
typedef enum {
	CAM_REQ_INPROG,		/* CCB request is in progress */
	CAM_REQ_CMP,		/* CCB request completed without error */
	CAM_REQ_ABORTED,	/* CCB request aborted by the host */
	CAM_UA_ABORT,		/* Unable to abort CCB request */
	CAM_REQ_CMP_ERR,	/* CCB request completed with an error */
	CAM_BUSY,		/* CAM subsystem is busy */
	CAM_REQ_INVALID,	/* CCB request was invalid */
	CAM_PATH_INVALID,	/* Supplied Path ID is invalid */
	CAM_DEV_NOT_THERE,	/* SCSI Device Not Installed/there */
	CAM_UA_TERMIO,		/* Unable to terminate I/O CCB request */
	CAM_SEL_TIMEOUT,	/* Target Selection Timeout */
	CAM_CMD_TIMEOUT,	/* Command timeout */
	CAM_SCSI_STATUS_ERROR,	/* SCSI error, look at error code in CCB */
	CAM_MSG_REJECT_REC,	/* Message Reject Received */
	CAM_SCSI_BUS_RESET,	/* SCSI Bus Reset Sent/Received */
	CAM_UNCOR_PARITY,	/* Uncorrectable parity error occurred */
	CAM_AUTOSENSE_FAIL = 0x10,/* Autosense: request sense cmd fail */
	CAM_NO_HBA,		/* No HBA Detected error */
	CAM_DATA_RUN_ERR,	/* Data Overrun error */
	CAM_UNEXP_BUSFREE,	/* Unexpected Bus Free */
	CAM_SEQUENCE_FAIL,	/* Target Bus Phase Sequence Failure */
	CAM_CCB_LEN_ERR,	/* CCB length supplied is inadequate */
	CAM_PROVIDE_FAIL,	/* Unable to provide requested capability */
	CAM_BDR_SENT,		/* A SCSI BDR msg was sent to target */
	CAM_REQ_TERMIO,		/* CCB request terminated by the host */
	CAM_UNREC_HBA_ERROR,	/* Unrecoverable Host Bus Adapter Error */
	CAM_REQ_TOO_BIG,	/* The request was too large for this host */
	CAM_REQUEUE_REQ,	/*
				 * This request should be requeued to preserve
				 * transaction ordering.  This typically occurs
				 * when the SIM recognizes an error that should
				 * freeze the queue and must place additional
				 * requests for the target at the sim level
				 * back into the XPT queue.
				 */
	CAM_ATA_STATUS_ERROR,	/* ATA error, look at error code in CCB */
	CAM_SCSI_IT_NEXUS_LOST,	/* Initiator/Target Nexus lost. */
	CAM_SMP_STATUS_ERROR,	/* SMP error, look at error code in CCB */
	CAM_IDE = 0x33,		/* Initiator Detected Error */
	CAM_RESRC_UNAVAIL,	/* Resource Unavailable */
	CAM_UNACKED_EVENT,	/* Unacknowledged Event by Host */
	CAM_MESSAGE_RECV,	/* Message Received in Host Target Mode */
	CAM_INVALID_CDB,	/* Invalid CDB received in Host Target Mode */
	CAM_LUN_INVALID,	/* Lun supplied is invalid */
	CAM_TID_INVALID,	/* Target ID supplied is invalid */
	CAM_FUNC_NOTAVAIL,	/* The requested function is not available */
	CAM_NO_NEXUS,		/* Nexus is not established */
	CAM_IID_INVALID,	/* The initiator ID is invalid */
	CAM_CDB_RECVD,		/* The SCSI CDB has been received */
	CAM_LUN_ALRDY_ENA,	/* The LUN is already enabled for target mode */
	CAM_SCSI_BUSY,		/* SCSI Bus Busy */

	CAM_DEV_QFRZN = 0x40,	/* The DEV queue is frozen w/this err */

				/* Autosense data valid for target */
	CAM_AUTOSNS_VALID = 0x80,
	CAM_RELEASE_SIMQ = 0x100,/* SIM ready to take more commands */
	CAM_SIM_QUEUED   = 0x200,/* SIM has this command in it's queue */

	CAM_STATUS_MASK = 0x3F,	/* Mask bits for just the status # */

				/* Target Specific Adjunct Status */
	CAM_SENT_SENSE = 0x40000000	/* sent sense with status */
} cam_status;

typedef enum {
	CAM_ESF_NONE		= 0x00,
	CAM_ESF_COMMAND		= 0x01,
	CAM_ESF_CAM_STATUS	= 0x02,
	CAM_ESF_PROTO_STATUS	= 0x04,
	CAM_ESF_ALL		= 0xff
} cam_error_string_flags;

typedef enum {
	CAM_EPF_NONE		= 0x00,
	CAM_EPF_MINIMAL		= 0x01,
	CAM_EPF_NORMAL		= 0x02,
	CAM_EPF_ALL		= 0x03,
	CAM_EPF_LEVEL_MASK	= 0x0f
	/* All bits above bit 3 are protocol-specific */
} cam_error_proto_flags;

typedef enum {
	CAM_ESF_PRINT_NONE	= 0x00,
	CAM_ESF_PRINT_STATUS	= 0x10,
	CAM_ESF_PRINT_SENSE	= 0x20
} cam_error_scsi_flags;

typedef enum {
	CAM_ESMF_PRINT_NONE	= 0x00,
	CAM_ESMF_PRINT_STATUS	= 0x10,
	CAM_ESMF_PRINT_FULL_CMD	= 0x20,
} cam_error_smp_flags;

typedef enum {
	CAM_EAF_PRINT_NONE	= 0x00,
	CAM_EAF_PRINT_STATUS	= 0x10,
	CAM_EAF_PRINT_RESULT	= 0x20
} cam_error_ata_flags;

struct cam_status_entry
{
	cam_status  status_code;
	const char *status_text;
};

extern const struct cam_status_entry cam_status_table[];
extern const int num_cam_status_entries;
union ccb;

#ifdef SYSCTL_DECL	/* from sysctl.h */
SYSCTL_DECL(_kern_cam);
#endif

__BEGIN_DECLS
typedef int (cam_quirkmatch_t)(caddr_t, caddr_t);

caddr_t	cam_quirkmatch(caddr_t target, caddr_t quirk_table, int num_entries,
		       int entry_size, cam_quirkmatch_t *comp_func);

void	cam_strvis(u_int8_t *dst, const u_int8_t *src, int srclen, int dstlen);

int	cam_strmatch(const u_int8_t *str, const u_int8_t *pattern, int str_len);
const struct cam_status_entry*
	cam_fetch_status_entry(cam_status status);
#ifdef _KERNEL
char *	cam_error_string(union ccb *ccb, char *str, int str_len,
			 cam_error_string_flags flags,
			 cam_error_proto_flags proto_flags);
void	cam_error_print(union ccb *ccb, cam_error_string_flags flags,
			cam_error_proto_flags proto_flags);
#else /* _KERNEL */
struct cam_device;

char *	cam_error_string(struct cam_device *device, union ccb *ccb, char *str,
			 int str_len, cam_error_string_flags flags,
			 cam_error_proto_flags proto_flags);
void	cam_error_print(struct cam_device *device, union ccb *ccb,
			cam_error_string_flags flags,
			cam_error_proto_flags proto_flags, FILE *ofile);
#endif /* _KERNEL */
__END_DECLS

#ifdef _KERNEL
static __inline void cam_init_pinfo(cam_pinfo *pinfo);

static __inline void cam_init_pinfo(cam_pinfo *pinfo)
{
	pinfo->priority = CAM_PRIORITY_NONE;
	pinfo->index = CAM_UNQUEUED_INDEX;
}
#endif

#endif /* _CAM_CAM_H */


code:
/*-
 * Data structures and definitions for CAM Control Blocks (CCBs).
 *
 * Copyright (c) 1997, 1998 Justin T. Gibbs.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification, immediately at the beginning of the file.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: release/9.0.0/sys/cam/cam_ccb.h 226067 2011-10-06 19:15:51Z ken $
 */

#ifndef _CAM_CAM_CCB_H
#define _CAM_CAM_CCB_H 1

#include <sys/queue.h>
#include <sys/cdefs.h>
#include <sys/time.h>
#include <sys/limits.h>
#ifndef _KERNEL
#include <sys/callout.h>
#endif
#include <cam/cam_debug.h>
#include <cam/scsi/scsi_all.h>
#include <cam/ata/ata_all.h>

/* General allocation length definitions for CCB structures */
#define	IOCDBLEN	CAM_MAX_CDBLEN	/* Space for CDB bytes/pointer */
#define	VUHBALEN	14		/* Vendor Unique HBA length */
#define	SIM_IDLEN	16		/* ASCII string len for SIM ID */
#define	HBA_IDLEN	16		/* ASCII string len for HBA ID */
#define	DEV_IDLEN	16		/* ASCII string len for device names */
#define CCB_PERIPH_PRIV_SIZE 	2	/* size of peripheral private area */
#define CCB_SIM_PRIV_SIZE 	2	/* size of sim private area */

/* Struct definitions for CAM control blocks */

/* Common CCB header */
/* CAM CCB flags */
typedef enum {
	CAM_CDB_POINTER		= 0x00000001,/* The CDB field is a pointer    */
	CAM_QUEUE_ENABLE	= 0x00000002,/* SIM queue actions are enabled */
	CAM_CDB_LINKED		= 0x00000004,/* CCB contains a linked CDB     */
	CAM_NEGOTIATE		= 0x00000008,/*
					      * Perform transport negotiation
					      * with this command.
					      */
	CAM_SCATTER_VALID	= 0x00000010,/* Scatter/gather list is valid  */
	CAM_DIS_AUTOSENSE	= 0x00000020,/* Disable autosense feature     */
	CAM_DIR_BOTH		= 0x00000000,/* Data direction (00:IN/OUT)    */
	CAM_DIR_IN		= 0x00000040,/* Data direction (01:DATA IN)   */
	CAM_DIR_OUT		= 0x00000080,/* Data direction (10:DATA OUT)  */
	CAM_DIR_NONE		= 0x000000C0,/* Data direction (11:no data)   */
	CAM_DIR_MASK		= 0x000000C0,/* Data direction Mask	      */
	CAM_SOFT_RST_OP		= 0x00000100,/* Use Soft reset alternative    */
	CAM_ENG_SYNC		= 0x00000200,/* Flush resid bytes on complete */
	CAM_DEV_QFRZDIS		= 0x00000400,/* Disable DEV Q freezing	      */
	CAM_DEV_QFREEZE		= 0x00000800,/* Freeze DEV Q on execution     */
	CAM_HIGH_POWER		= 0x00001000,/* Command takes a lot of power  */
	CAM_SENSE_PTR		= 0x00002000,/* Sense data is a pointer	      */
	CAM_SENSE_PHYS		= 0x00004000,/* Sense pointer is physical addr*/
	CAM_TAG_ACTION_VALID	= 0x00008000,/* Use the tag action in this ccb*/
	CAM_PASS_ERR_RECOVER	= 0x00010000,/* Pass driver does err. recovery*/
	CAM_DIS_DISCONNECT	= 0x00020000,/* Disable disconnect	      */
	CAM_SG_LIST_PHYS	= 0x00040000,/* SG list has physical addrs.   */
	CAM_MSG_BUF_PHYS	= 0x00080000,/* Message buffer ptr is physical*/
	CAM_SNS_BUF_PHYS	= 0x00100000,/* Autosense data ptr is physical*/
	CAM_DATA_PHYS		= 0x00200000,/* SG/Buffer data ptrs are phys. */
	CAM_CDB_PHYS		= 0x00400000,/* CDB poiner is physical	      */
	CAM_ENG_SGLIST		= 0x00800000,/* SG list is for the HBA engine */

/* Phase cognizant mode flags */
	CAM_DIS_AUTOSRP		= 0x01000000,/* Disable autosave/restore ptrs */
	CAM_DIS_AUTODISC	= 0x02000000,/* Disable auto disconnect	      */
	CAM_TGT_CCB_AVAIL	= 0x04000000,/* Target CCB available	      */
	CAM_TGT_PHASE_MODE	= 0x08000000,/* The SIM runs in phase mode    */
	CAM_MSGB_VALID		= 0x10000000,/* Message buffer valid	      */
	CAM_STATUS_VALID	= 0x20000000,/* Status buffer valid	      */
	CAM_DATAB_VALID		= 0x40000000,/* Data buffer valid	      */

/* Host target Mode flags */
	CAM_SEND_SENSE		= 0x08000000,/* Send sense data with status   */
	CAM_TERM_IO		= 0x10000000,/* Terminate I/O Message sup.    */
	CAM_DISCONNECT		= 0x20000000,/* Disconnects are mandatory     */
	CAM_SEND_STATUS		= 0x40000000 /* Send status after data phase  */
} ccb_flags;

/* XPT Opcodes for xpt_action */
typedef enum {
/* Function code flags are bits greater than 0xff */
	XPT_FC_QUEUED		= 0x100,
				/* Non-immediate function code */
	XPT_FC_USER_CCB		= 0x200,
	XPT_FC_XPT_ONLY		= 0x400,
				/* Only for the transport layer device */
	XPT_FC_DEV_QUEUED	= 0x800 | XPT_FC_QUEUED,
				/* Passes through the device queues */
/* Common function commands: 0x00->0x0F */
	XPT_NOOP 		= 0x00,
				/* Execute Nothing */
	XPT_SCSI_IO		= 0x01 | XPT_FC_DEV_QUEUED,
				/* Execute the requested I/O operation */
	XPT_GDEV_TYPE		= 0x02,
				/* Get type information for specified device */
	XPT_GDEVLIST		= 0x03,
				/* Get a list of peripheral devices */
	XPT_PATH_INQ		= 0x04,
				/* Path routing inquiry */
	XPT_REL_SIMQ		= 0x05,
				/* Release a frozen device queue */
	XPT_SASYNC_CB		= 0x06,
				/* Set Asynchronous Callback Parameters */
	XPT_SDEV_TYPE		= 0x07,
				/* Set device type information */
	XPT_SCAN_BUS		= 0x08 | XPT_FC_QUEUED | XPT_FC_USER_CCB
				       | XPT_FC_XPT_ONLY,
				/* (Re)Scan the SCSI Bus */
	XPT_DEV_MATCH		= 0x09 | XPT_FC_XPT_ONLY,
				/* Get EDT entries matching the given pattern */
	XPT_DEBUG		= 0x0a,
				/* Turn on debugging for a bus, target or lun */
	XPT_PATH_STATS		= 0x0b,
				/* Path statistics (error counts, etc.) */
	XPT_GDEV_STATS		= 0x0c,
				/* Device statistics (error counts, etc.) */
	XPT_FREEZE_QUEUE	= 0x0d,
				/* Freeze device queue */
	XPT_DEV_ADVINFO		= 0x0e,
				/* Get/Set Device advanced information */
/* SCSI Control Functions: 0x10->0x1F */
	XPT_ABORT		= 0x10,
				/* Abort the specified CCB */
	XPT_RESET_BUS		= 0x11 | XPT_FC_XPT_ONLY,
				/* Reset the specified SCSI bus */
	XPT_RESET_DEV		= 0x12 | XPT_FC_DEV_QUEUED,
				/* Bus Device Reset the specified SCSI device */
	XPT_TERM_IO		= 0x13,
				/* Terminate the I/O process */
	XPT_SCAN_LUN		= 0x14 | XPT_FC_QUEUED | XPT_FC_USER_CCB
				       | XPT_FC_XPT_ONLY,
				/* Scan Logical Unit */
	XPT_GET_TRAN_SETTINGS	= 0x15,
				/*
				 * Get default/user transfer settings
				 * for the target
				 */
	XPT_SET_TRAN_SETTINGS	= 0x16,
				/*
				 * Set transfer rate/width
				 * negotiation settings
				 */
	XPT_CALC_GEOMETRY	= 0x17,
				/*
				 * Calculate the geometry parameters for
				 * a device give the sector size and
				 * volume size.
				 */
	XPT_ATA_IO		= 0x18 | XPT_FC_DEV_QUEUED,
				/* Execute the requested ATA I/O operation */

	XPT_GET_SIM_KNOB	= 0x18,
				/*
				 * Get SIM specific knob values.
				 */

	XPT_SET_SIM_KNOB	= 0x19,
				/*
				 * Set SIM specific knob values.
				 */

	XPT_SMP_IO		= 0x1b | XPT_FC_DEV_QUEUED,
				/* Serial Management Protocol */

	XPT_SCAN_TGT		= 0x1E | XPT_FC_QUEUED | XPT_FC_USER_CCB
				       | XPT_FC_XPT_ONLY,
				/* Scan Target */

/* HBA engine commands 0x20->0x2F */
	XPT_ENG_INQ		= 0x20 | XPT_FC_XPT_ONLY,
				/* HBA engine feature inquiry */
	XPT_ENG_EXEC		= 0x21 | XPT_FC_DEV_QUEUED,
				/* HBA execute engine request */

/* Target mode commands: 0x30->0x3F */
	XPT_EN_LUN		= 0x30,
				/* Enable LUN as a target */
	XPT_TARGET_IO		= 0x31 | XPT_FC_DEV_QUEUED,
				/* Execute target I/O request */
	XPT_ACCEPT_TARGET_IO	= 0x32 | XPT_FC_QUEUED | XPT_FC_USER_CCB,
				/* Accept Host Target Mode CDB */
	XPT_CONT_TARGET_IO	= 0x33 | XPT_FC_DEV_QUEUED,
				/* Continue Host Target I/O Connection */
	XPT_IMMED_NOTIFY	= 0x34 | XPT_FC_QUEUED | XPT_FC_USER_CCB,
				/* Notify Host Target driver of event (obsolete) */
	XPT_NOTIFY_ACK		= 0x35,
				/* Acknowledgement of event (obsolete) */
	XPT_IMMEDIATE_NOTIFY	= 0x36 | XPT_FC_QUEUED | XPT_FC_USER_CCB,
				/* Notify Host Target driver of event */
	XPT_NOTIFY_ACKNOWLEDGE	= 0x37 | XPT_FC_QUEUED | XPT_FC_USER_CCB,
				/* Acknowledgement of event */

/* Vendor Unique codes: 0x80->0x8F */
	XPT_VUNIQUE		= 0x80
} xpt_opcode;

#define XPT_FC_GROUP_MASK		0xF0
#define XPT_FC_GROUP(op) ((op) & XPT_FC_GROUP_MASK)
#define XPT_FC_GROUP_COMMON		0x00
#define XPT_FC_GROUP_SCSI_CONTROL	0x10
#define XPT_FC_GROUP_HBA_ENGINE		0x20
#define XPT_FC_GROUP_TMODE		0x30
#define XPT_FC_GROUP_VENDOR_UNIQUE	0x80

#define XPT_FC_IS_DEV_QUEUED(ccb) 	\
    (((ccb)->ccb_h.func_code & XPT_FC_DEV_QUEUED) == XPT_FC_DEV_QUEUED)
#define XPT_FC_IS_QUEUED(ccb) 	\
    (((ccb)->ccb_h.func_code & XPT_FC_QUEUED) != 0)

typedef enum {
	PROTO_UNKNOWN,
	PROTO_UNSPECIFIED,
	PROTO_SCSI,	/* Small Computer System Interface */
	PROTO_ATA,	/* AT Attachment */
	PROTO_ATAPI,	/* AT Attachment Packetized Interface */
	PROTO_SATAPM,	/* SATA Port Multiplier */
} cam_proto;

typedef enum {
	XPORT_UNKNOWN,
	XPORT_UNSPECIFIED,
	XPORT_SPI,	/* SCSI Parallel Interface */
	XPORT_FC,	/* Fiber Channel */
	XPORT_SSA,	/* Serial Storage Architecture */
	XPORT_USB,	/* Universal Serial Bus */
	XPORT_PPB,	/* Parallel Port Bus */
	XPORT_ATA,	/* AT Attachment */
	XPORT_SAS,	/* Serial Attached SCSI */
	XPORT_SATA,	/* Serial AT Attachment */
	XPORT_ISCSI,	/* iSCSI */
} cam_xport;

#define XPORT_IS_ATA(t)		((t) == XPORT_ATA || (t) == XPORT_SATA)
#define XPORT_IS_SCSI(t)	((t) != XPORT_UNKNOWN && \
				 (t) != XPORT_UNSPECIFIED && \
				 !XPORT_IS_ATA(t))
#define XPORT_DEVSTAT_TYPE(t)	(XPORT_IS_ATA(t) ? DEVSTAT_TYPE_IF_IDE : \
				 XPORT_IS_SCSI(t) ? DEVSTAT_TYPE_IF_SCSI : \
				 DEVSTAT_TYPE_IF_OTHER)

#define PROTO_VERSION_UNKNOWN (UINT_MAX - 1)
#define PROTO_VERSION_UNSPECIFIED UINT_MAX
#define XPORT_VERSION_UNKNOWN (UINT_MAX - 1)
#define XPORT_VERSION_UNSPECIFIED UINT_MAX

typedef union {
	LIST_ENTRY(ccb_hdr) le;
	SLIST_ENTRY(ccb_hdr) sle;
	TAILQ_ENTRY(ccb_hdr) tqe;
	STAILQ_ENTRY(ccb_hdr) stqe;
} camq_entry;

typedef union {
	void		*ptr;
	u_long		field;
	u_int8_t	bytes[sizeof(uintptr_t)];
} ccb_priv_entry;

typedef union {
	ccb_priv_entry	entries[CCB_PERIPH_PRIV_SIZE];
	u_int8_t	bytes[CCB_PERIPH_PRIV_SIZE * sizeof(ccb_priv_entry)];
} ccb_ppriv_area;

typedef union {
	ccb_priv_entry	entries[CCB_SIM_PRIV_SIZE];
	u_int8_t	bytes[CCB_SIM_PRIV_SIZE * sizeof(ccb_priv_entry)];
} ccb_spriv_area;

struct ccb_hdr {
	cam_pinfo	pinfo;		/* Info for priority scheduling */
	camq_entry	xpt_links;	/* For chaining in the XPT layer */
	camq_entry	sim_links;	/* For chaining in the SIM layer */
	camq_entry	periph_links;	/* For chaining in the type driver */
	u_int32_t	retry_count;
	void		(*cbfcnp)(struct cam_periph *, union ccb *);
					/* Callback on completion function */
	xpt_opcode	func_code;	/* XPT function code */
	u_int32_t	status;		/* Status returned by CAM subsystem */
	struct		cam_path *path;	/* Compiled path for this ccb */
	path_id_t	path_id;	/* Path ID for the request */
	target_id_t	target_id;	/* Target device ID */
	lun_id_t	target_lun;	/* Target LUN number */
	u_int32_t	flags;		/* ccb_flags */
	ccb_ppriv_area	periph_priv;
	ccb_spriv_area	sim_priv;
	u_int32_t	timeout;	/* Timeout value */

	/*
	 * Deprecated, only for use by non-MPSAFE SIMs.  All others must
	 * allocate and initialize their own callout storage.
	 */
	struct		callout_handle timeout_ch;
};

/* Get Device Information CCB */
struct ccb_getdev {
	struct	  ccb_hdr ccb_h;
	cam_proto protocol;
	struct scsi_inquiry_data inq_data;
	struct ata_params ident_data;
	u_int8_t  serial_num[252];
	u_int8_t  inq_flags;
	u_int8_t  serial_num_len;
};

/* Device Statistics CCB */
struct ccb_getdevstats {
	struct	ccb_hdr	ccb_h;
	int	dev_openings;	/* Space left for more work on device*/
	int	dev_active;	/* Transactions running on the device */
	int	devq_openings;	/* Space left for more queued work */
	int	devq_queued;	/* Transactions queued to be sent */
	int	held;		/*
				 * CCBs held by peripheral drivers
				 * for this device
				 */
	int	maxtags;	/*
				 * Boundary conditions for number of
				 * tagged operations
				 */
	int	mintags;
	struct	timeval last_reset;	/* Time of last bus reset/loop init */
};

typedef enum {
	CAM_GDEVLIST_LAST_DEVICE,
	CAM_GDEVLIST_LIST_CHANGED,
	CAM_GDEVLIST_MORE_DEVS,
	CAM_GDEVLIST_ERROR
} ccb_getdevlist_status_e;

struct ccb_getdevlist {
	struct ccb_hdr		ccb_h;
	char 			periph_name[DEV_IDLEN];
	u_int32_t		unit_number;
	unsigned int		generation;
	u_int32_t		index;
	ccb_getdevlist_status_e	status;
};

typedef enum {
	PERIPH_MATCH_NONE	= 0x000,
	PERIPH_MATCH_PATH	= 0x001,
	PERIPH_MATCH_TARGET	= 0x002,
	PERIPH_MATCH_LUN	= 0x004,
	PERIPH_MATCH_NAME	= 0x008,
	PERIPH_MATCH_UNIT	= 0x010,
	PERIPH_MATCH_ANY	= 0x01f
} periph_pattern_flags;

struct periph_match_pattern {
	char			periph_name[DEV_IDLEN];
	u_int32_t		unit_number;
	path_id_t		path_id;
	target_id_t		target_id;
	lun_id_t		target_lun;
	periph_pattern_flags	flags;
};

typedef enum {
	DEV_MATCH_NONE		= 0x000,
	DEV_MATCH_PATH		= 0x001,
	DEV_MATCH_TARGET	= 0x002,
	DEV_MATCH_LUN		= 0x004,
	DEV_MATCH_INQUIRY	= 0x008,
	DEV_MATCH_DEVID		= 0x010,
	DEV_MATCH_ANY		= 0x00f
} dev_pattern_flags;

struct device_id_match_pattern {
	uint8_t id_len;
	uint8_t id[256];
};

struct device_match_pattern {
	path_id_t					path_id;
	target_id_t					target_id;
	lun_id_t					target_lun;
	dev_pattern_flags				flags;
	union {
		struct scsi_static_inquiry_pattern	inq_pat;
		struct device_id_match_pattern		devid_pat;
	} data;
};

typedef enum {
	BUS_MATCH_NONE		= 0x000,
	BUS_MATCH_PATH		= 0x001,
	BUS_MATCH_NAME		= 0x002,
	BUS_MATCH_UNIT		= 0x004,
	BUS_MATCH_BUS_ID	= 0x008,
	BUS_MATCH_ANY		= 0x00f
} bus_pattern_flags;

struct bus_match_pattern {
	path_id_t		path_id;
	char			dev_name[DEV_IDLEN];
	u_int32_t		unit_number;
	u_int32_t		bus_id;
	bus_pattern_flags	flags;
};

union match_pattern {
	struct periph_match_pattern	periph_pattern;
	struct device_match_pattern	device_pattern;
	struct bus_match_pattern	bus_pattern;
};

typedef enum {
	DEV_MATCH_PERIPH,
	DEV_MATCH_DEVICE,
	DEV_MATCH_BUS
} dev_match_type;

struct dev_match_pattern {
	dev_match_type		type;
	union match_pattern	pattern;
};

struct periph_match_result {
	char			periph_name[DEV_IDLEN];
	u_int32_t		unit_number;
	path_id_t		path_id;
	target_id_t		target_id;
	lun_id_t		target_lun;
};

typedef enum {
	DEV_RESULT_NOFLAG		= 0x00,
	DEV_RESULT_UNCONFIGURED		= 0x01
} dev_result_flags;

struct device_match_result {
	path_id_t			path_id;
	target_id_t			target_id;
	lun_id_t			target_lun;
	cam_proto			protocol;
	struct scsi_inquiry_data	inq_data;
	struct ata_params		ident_data;
	dev_result_flags		flags;
};

struct bus_match_result {
	path_id_t	path_id;
	char		dev_name[DEV_IDLEN];
	u_int32_t	unit_number;
	u_int32_t	bus_id;
};

union match_result {
	struct periph_match_result	periph_result;
	struct device_match_result	device_result;
	struct bus_match_result		bus_result;
};

struct dev_match_result {
	dev_match_type		type;
	union match_result	result;
};

typedef enum {
	CAM_DEV_MATCH_LAST,
	CAM_DEV_MATCH_MORE,
	CAM_DEV_MATCH_LIST_CHANGED,
	CAM_DEV_MATCH_SIZE_ERROR,
	CAM_DEV_MATCH_ERROR
} ccb_dev_match_status;

typedef enum {
	CAM_DEV_POS_NONE	= 0x000,
	CAM_DEV_POS_BUS		= 0x001,
	CAM_DEV_POS_TARGET	= 0x002,
	CAM_DEV_POS_DEVICE	= 0x004,
	CAM_DEV_POS_PERIPH	= 0x008,
	CAM_DEV_POS_PDPTR	= 0x010,
	CAM_DEV_POS_TYPEMASK	= 0xf00,
	CAM_DEV_POS_EDT		= 0x100,
	CAM_DEV_POS_PDRV	= 0x200
} dev_pos_type;

struct ccb_dm_cookie {
	void 	*bus;
	void	*target;
	void	*device;
	void	*periph;
	void	*pdrv;
};

struct ccb_dev_position {
	u_int			generations[4];
#define	CAM_BUS_GENERATION	0x00
#define CAM_TARGET_GENERATION	0x01
#define CAM_DEV_GENERATION	0x02
#define CAM_PERIPH_GENERATION	0x03
	dev_pos_type		position_type;
	struct ccb_dm_cookie	cookie;
};

struct ccb_dev_match {
	struct ccb_hdr			ccb_h;
	ccb_dev_match_status		status;
	u_int32_t			num_patterns;
	u_int32_t			pattern_buf_len;
	struct dev_match_pattern	*patterns;
	u_int32_t			num_matches;
	u_int32_t			match_buf_len;
	struct dev_match_result		*matches;
	struct ccb_dev_position		pos;
};

/*
 * Definitions for the path inquiry CCB fields.
 */
#define CAM_VERSION	0x16	/* Hex value for current version */

typedef enum {
	PI_MDP_ABLE	= 0x80,	/* Supports MDP message */
	PI_WIDE_32	= 0x40,	/* Supports 32 bit wide SCSI */
	PI_WIDE_16	= 0x20, /* Supports 16 bit wide SCSI */
	PI_SDTR_ABLE	= 0x10,	/* Supports SDTR message */
	PI_LINKED_CDB	= 0x08, /* Supports linked CDBs */
	PI_SATAPM	= 0x04,	/* Supports SATA PM */
	PI_TAG_ABLE	= 0x02,	/* Supports tag queue messages */
	PI_SOFT_RST	= 0x01	/* Supports soft reset alternative */
} pi_inqflag;

typedef enum {
	PIT_PROCESSOR	= 0x80,	/* Target mode processor mode */
	PIT_PHASE	= 0x40,	/* Target mode phase cog. mode */
	PIT_DISCONNECT	= 0x20,	/* Disconnects supported in target mode */
	PIT_TERM_IO	= 0x10,	/* Terminate I/O message supported in TM */
	PIT_GRP_6	= 0x08,	/* Group 6 commands supported */
	PIT_GRP_7	= 0x04	/* Group 7 commands supported */
} pi_tmflag;

typedef enum {
	PIM_SCANHILO	= 0x80,	/* Bus scans from high ID to low ID */
	PIM_NOREMOVE	= 0x40,	/* Removeable devices not included in scan */
	PIM_NOINITIATOR	= 0x20,	/* Initiator role not supported. */
	PIM_NOBUSRESET	= 0x10,	/* User has disabled initial BUS RESET */
	PIM_NO_6_BYTE	= 0x08,	/* Do not send 6-byte commands */
	PIM_SEQSCAN	= 0x04	/* Do bus scans sequentially, not in parallel */
} pi_miscflag;

/* Path Inquiry CCB */
struct ccb_pathinq_settings_spi {
	u_int8_t ppr_options;
};

struct ccb_pathinq_settings_fc {
	u_int64_t wwnn;		/* world wide node name */
	u_int64_t wwpn;		/* world wide port name */
	u_int32_t port;		/* 24 bit port id, if known */
	u_int32_t bitrate;	/* Mbps */
};

struct ccb_pathinq_settings_sas {
	u_int32_t bitrate;	/* Mbps */
};
#define	PATHINQ_SETTINGS_SIZE	128

struct ccb_pathinq {
	struct 	    ccb_hdr ccb_h;
	u_int8_t    version_num;	/* Version number for the SIM/HBA */
	u_int8_t    hba_inquiry;	/* Mimic of INQ byte 7 for the HBA */
	u_int8_t    target_sprt;	/* Flags for target mode support */
	u_int8_t    hba_misc;		/* Misc HBA features */
	u_int16_t   hba_eng_cnt;	/* HBA engine count */
					/* Vendor Unique capabilities */
	u_int8_t    vuhba_flags[VUHBALEN];
	u_int32_t   max_target;		/* Maximum supported Target */
	u_int32_t   max_lun;		/* Maximum supported Lun */
	u_int32_t   async_flags;	/* Installed Async handlers */
	path_id_t   hpath_id;		/* Highest Path ID in the subsystem */
	target_id_t initiator_id;	/* ID of the HBA on the SCSI bus */
	char	    sim_vid[SIM_IDLEN];	/* Vendor ID of the SIM */
	char	    hba_vid[HBA_IDLEN];	/* Vendor ID of the HBA */
	char 	    dev_name[DEV_IDLEN];/* Device name for SIM */
	u_int32_t   unit_number;	/* Unit number for SIM */
	u_int32_t   bus_id;		/* Bus ID for SIM */
	u_int32_t   base_transfer_speed;/* Base bus speed in KB/sec */
	cam_proto   protocol;
	u_int	    protocol_version;
	cam_xport   transport;
	u_int	    transport_version;
	union {
		struct ccb_pathinq_settings_spi spi;
		struct ccb_pathinq_settings_fc fc;
		struct ccb_pathinq_settings_sas sas;
		char ccb_pathinq_settings_opaque[PATHINQ_SETTINGS_SIZE];
	} xport_specific;
	u_int		maxio;		/* Max supported I/O size, in bytes. */
	u_int16_t	hba_vendor;	/* HBA vendor ID */
	u_int16_t	hba_device;	/* HBA device ID */
	u_int16_t	hba_subvendor;	/* HBA subvendor ID */
	u_int16_t	hba_subdevice;	/* HBA subdevice ID */
};

/* Path Statistics CCB */
struct ccb_pathstats {
	struct	ccb_hdr	ccb_h;
	struct	timeval last_reset;	/* Time of last bus reset/loop init */
};

typedef enum {
	SMP_FLAG_NONE		= 0x00,
	SMP_FLAG_REQ_SG		= 0x01,
	SMP_FLAG_RSP_SG		= 0x02
} ccb_smp_pass_flags;

/*
 * Serial Management Protocol CCB
 * XXX Currently the semantics for this CCB are that it is executed either
 * by the addressed device, or that device's parent (i.e. an expander for
 * any device on an expander) if the addressed device doesn't support SMP.
 * Later, once we have the ability to probe SMP-only devices and put them
 * in CAM's topology, the CCB will only be executed by the addressed device
 * if possible.
 */
struct ccb_smpio {
	struct ccb_hdr		ccb_h;
	uint8_t			*smp_request;
	int			smp_request_len;
	uint16_t		smp_request_sglist_cnt;
	uint8_t			*smp_response;
	int			smp_response_len;
	uint16_t		smp_response_sglist_cnt;
	ccb_smp_pass_flags	flags;
};

typedef union {
	u_int8_t *sense_ptr;		/*
					 * Pointer to storage
					 * for sense information
					 */
	                                /* Storage Area for sense information */
	struct	 scsi_sense_data sense_buf;
} sense_t;

typedef union {
	u_int8_t  *cdb_ptr;		/* Pointer to the CDB bytes to send */
					/* Area for the CDB send */
	u_int8_t  cdb_bytes[IOCDBLEN];
} cdb_t;

/*
 * SCSI I/O Request CCB used for the XPT_SCSI_IO and XPT_CONT_TARGET_IO
 * function codes.
 */
struct ccb_scsiio {
	struct	   ccb_hdr ccb_h;
	union	   ccb *next_ccb;	/* Ptr for next CCB for action */
	u_int8_t   *req_map;		/* Ptr to mapping info */
	u_int8_t   *data_ptr;		/* Ptr to the data buf/SG list */
	u_int32_t  dxfer_len;		/* Data transfer length */
					/* Autosense storage */
	struct     scsi_sense_data sense_data;
	u_int8_t   sense_len;		/* Number of bytes to autosense */
	u_int8_t   cdb_len;		/* Number of bytes for the CDB */
	u_int16_t  sglist_cnt;		/* Number of SG list entries */
	u_int8_t   scsi_status;		/* Returned SCSI status */
	u_int8_t   sense_resid;		/* Autosense resid length: 2's comp */
	u_int32_t  resid;		/* Transfer residual length: 2's comp */
	cdb_t	   cdb_io;		/* Union for CDB bytes/pointer */
	u_int8_t   *msg_ptr;		/* Pointer to the message buffer */
	u_int16_t  msg_len;		/* Number of bytes for the Message */
	u_int8_t   tag_action;		/* What to do for tag queueing */
	/*
	 * The tag action should be either the define below (to send a
	 * non-tagged transaction) or one of the defined scsi tag messages
	 * from scsi_message.h.
	 */
#define		CAM_TAG_ACTION_NONE	0x00
	u_int	   tag_id;		/* tag id from initator (target mode) */
	u_int	   init_id;		/* initiator id of who selected */
};

/*
 * ATA I/O Request CCB used for the XPT_ATA_IO function code.
 */
struct ccb_ataio {
	struct	   ccb_hdr ccb_h;
	union	   ccb *next_ccb;	/* Ptr for next CCB for action */
	struct ata_cmd	cmd;		/* ATA command register set */
	struct ata_res	res;		/* ATA result register set */
	u_int8_t   *data_ptr;		/* Ptr to the data buf/SG list */
	u_int32_t  dxfer_len;		/* Data transfer length */
	u_int32_t  resid;		/* Transfer residual length: 2's comp */
	u_int8_t   tag_action;		/* What to do for tag queueing */
	/*
	 * The tag action should be either the define below (to send a
	 * non-tagged transaction) or one of the defined scsi tag messages
	 * from scsi_message.h.
	 */
#define		CAM_TAG_ACTION_NONE	0x00
	u_int	   tag_id;		/* tag id from initator (target mode) */
	u_int	   init_id;		/* initiator id of who selected */
};

struct ccb_accept_tio {
	struct	   ccb_hdr ccb_h;
	cdb_t	   cdb_io;		/* Union for CDB bytes/pointer */
	u_int8_t   cdb_len;		/* Number of bytes for the CDB */
	u_int8_t   tag_action;		/* What to do for tag queueing */
	u_int8_t   sense_len;		/* Number of bytes of Sense Data */
	u_int      tag_id;		/* tag id from initator (target mode) */
	u_int      init_id;		/* initiator id of who selected */
	struct     scsi_sense_data sense_data;
};

/* Release SIM Queue */
struct ccb_relsim {
	struct ccb_hdr ccb_h;
	u_int32_t      release_flags;
#define RELSIM_ADJUST_OPENINGS		0x01
#define RELSIM_RELEASE_AFTER_TIMEOUT	0x02
#define RELSIM_RELEASE_AFTER_CMDCMPLT	0x04
#define RELSIM_RELEASE_AFTER_QEMPTY	0x08
#define RELSIM_RELEASE_RUNLEVEL		0x10
	u_int32_t      openings;
	u_int32_t      release_timeout;	/* Abstract argument. */
	u_int32_t      qfrozen_cnt;
};

/*
 * Definitions for the asynchronous callback CCB fields.
 */
typedef enum {
	AC_ADVINFO_CHANGED	= 0x2000,/* Advance info might have changes */
	AC_CONTRACT		= 0x1000,/* A contractual callback */
	AC_GETDEV_CHANGED	= 0x800,/* Getdev info might have changed */
	AC_INQ_CHANGED		= 0x400,/* Inquiry info might have changed */
	AC_TRANSFER_NEG		= 0x200,/* New transfer settings in effect */
	AC_LOST_DEVICE		= 0x100,/* A device went away */
	AC_FOUND_DEVICE		= 0x080,/* A new device was found */
	AC_PATH_DEREGISTERED	= 0x040,/* A path has de-registered */
	AC_PATH_REGISTERED	= 0x020,/* A new path has been registered */
	AC_SENT_BDR		= 0x010,/* A BDR message was sent to target */
	AC_SCSI_AEN		= 0x008,/* A SCSI AEN has been received */
	AC_UNSOL_RESEL		= 0x002,/* Unsolicited reselection occurred */
	AC_BUS_RESET		= 0x001	/* A SCSI bus reset occurred */
} ac_code;

typedef void ac_callback_t (void *softc, u_int32_t code,
			    struct cam_path *path, void *args);

/*
 * Generic Asynchronous callbacks.
 *
 * Generic arguments passed bac which are then interpreted between a per-system
 * contract number.
 */
#define	AC_CONTRACT_DATA_MAX (128 - sizeof (u_int64_t))
struct ac_contract {
	u_int64_t	contract_number;
	u_int8_t	contract_data[AC_CONTRACT_DATA_MAX];
};

#define	AC_CONTRACT_DEV_CHG	1
struct ac_device_changed {
	u_int64_t	wwpn;
	u_int32_t	port;
	target_id_t	target;
	u_int8_t	arrived;
};

/* Set Asynchronous Callback CCB */
struct ccb_setasync {
	struct ccb_hdr	 ccb_h;
	u_int32_t	 event_enable;	/* Async Event enables */
	ac_callback_t	*callback;
	void		*callback_arg;
};

/* Set Device Type CCB */
struct ccb_setdev {
	struct	   ccb_hdr ccb_h;
	u_int8_t   dev_type;	/* Value for dev type field in EDT */
};

/* SCSI Control Functions */

/* Abort XPT request CCB */
struct ccb_abort {
	struct 	ccb_hdr ccb_h;
	union	ccb *abort_ccb;	/* Pointer to CCB to abort */
};

/* Reset SCSI Bus CCB */
struct ccb_resetbus {
	struct	ccb_hdr ccb_h;
};

/* Reset SCSI Device CCB */
struct ccb_resetdev {
	struct	ccb_hdr ccb_h;
};

/* Terminate I/O Process Request CCB */
struct ccb_termio {
	struct	ccb_hdr ccb_h;
	union	ccb *termio_ccb;	/* Pointer to CCB to terminate */
};

typedef enum {
	CTS_TYPE_CURRENT_SETTINGS,
	CTS_TYPE_USER_SETTINGS
} cts_type;

struct ccb_trans_settings_scsi
{
	u_int	valid;	/* Which fields to honor */
#define	CTS_SCSI_VALID_TQ		0x01
	u_int	flags;
#define	CTS_SCSI_FLAGS_TAG_ENB		0x01
};

struct ccb_trans_settings_spi
{
	u_int	  valid;	/* Which fields to honor */
#define	CTS_SPI_VALID_SYNC_RATE		0x01
#define	CTS_SPI_VALID_SYNC_OFFSET	0x02
#define	CTS_SPI_VALID_BUS_WIDTH		0x04
#define	CTS_SPI_VALID_DISC		0x08
#define CTS_SPI_VALID_PPR_OPTIONS	0x10
	u_int	flags;
#define	CTS_SPI_FLAGS_DISC_ENB		0x01
	u_int	sync_period;
	u_int	sync_offset;
	u_int	bus_width;
	u_int	ppr_options;
};

struct ccb_trans_settings_fc {
	u_int     	valid;		/* Which fields to honor */
#define	CTS_FC_VALID_WWNN		0x8000
#define	CTS_FC_VALID_WWPN		0x4000
#define	CTS_FC_VALID_PORT		0x2000
#define	CTS_FC_VALID_SPEED		0x1000
	u_int64_t	wwnn;		/* world wide node name */
	u_int64_t 	wwpn;		/* world wide port name */
	u_int32_t 	port;		/* 24 bit port id, if known */
	u_int32_t 	bitrate;	/* Mbps */
};

struct ccb_trans_settings_sas {
	u_int     	valid;		/* Which fields to honor */
#define	CTS_SAS_VALID_SPEED		0x1000
	u_int32_t 	bitrate;	/* Mbps */
};

struct ccb_trans_settings_ata {
	u_int     	valid;		/* Which fields to honor */
#define	CTS_ATA_VALID_MODE		0x01
#define	CTS_ATA_VALID_BYTECOUNT		0x02
#define	CTS_ATA_VALID_ATAPI		0x20
	int		mode;		/* Mode */
	u_int 		bytecount;	/* Length of PIO transaction */
	u_int 		atapi;		/* Length of ATAPI CDB */
};

struct ccb_trans_settings_sata {
	u_int     	valid;		/* Which fields to honor */
#define	CTS_SATA_VALID_MODE		0x01
#define	CTS_SATA_VALID_BYTECOUNT	0x02
#define	CTS_SATA_VALID_REVISION		0x04
#define	CTS_SATA_VALID_PM		0x08
#define	CTS_SATA_VALID_TAGS		0x10
#define	CTS_SATA_VALID_ATAPI		0x20
#define	CTS_SATA_VALID_CAPS		0x40
	int		mode;		/* Legacy PATA mode */
	u_int 		bytecount;	/* Length of PIO transaction */
	int		revision;	/* SATA revision */
	u_int 		pm_present;	/* PM is present (XPT->SIM) */
	u_int 		tags;		/* Number of allowed tags */
	u_int 		atapi;		/* Length of ATAPI CDB */
	u_int 		caps;		/* Device and host SATA caps. */
#define	CTS_SATA_CAPS_H			0x0000ffff
#define	CTS_SATA_CAPS_H_PMREQ		0x00000001
#define	CTS_SATA_CAPS_H_APST		0x00000002
#define	CTS_SATA_CAPS_H_DMAAA		0x00000010 /* Auto-activation */
#define	CTS_SATA_CAPS_H_AN		0x00000020 /* Async. notification */
#define	CTS_SATA_CAPS_D			0xffff0000
#define	CTS_SATA_CAPS_D_PMREQ		0x00010000
#define	CTS_SATA_CAPS_D_APST		0x00020000
};

/* Get/Set transfer rate/width/disconnection/tag queueing settings */
struct ccb_trans_settings {
	struct	  ccb_hdr ccb_h;
	cts_type  type;		/* Current or User settings */
	cam_proto protocol;
	u_int	  protocol_version;
	cam_xport transport;
	u_int	  transport_version;
	union {
		u_int  valid;	/* Which fields to honor */
		struct ccb_trans_settings_scsi scsi;
	} proto_specific;
	union {
		u_int  valid;	/* Which fields to honor */
		struct ccb_trans_settings_spi spi;
		struct ccb_trans_settings_fc fc;
		struct ccb_trans_settings_sas sas;
		struct ccb_trans_settings_ata ata;
		struct ccb_trans_settings_sata sata;
	} xport_specific;
};

/*
 * Calculate the geometry parameters for a device
 * give the block size and volume size in blocks.
 */
struct ccb_calc_geometry {
	struct	  ccb_hdr ccb_h;
	u_int32_t block_size;
	u_int64_t volume_size;
	u_int32_t cylinders;
	u_int8_t  heads;
	u_int8_t  secs_per_track;
};

/*
 * Set or get SIM (and transport) specific knobs
 */

#define	KNOB_VALID_ADDRESS	0x1
#define	KNOB_VALID_ROLE		0x2

#define	KNOB_ROLE_NONE		0x0
#define	KNOB_ROLE_INITIATOR	0x1
#define	KNOB_ROLE_TARGET	0x2
#define	KNOB_ROLE_BOTH		0x3

struct ccb_sim_knob_settings_spi {
	u_int		valid;
	u_int		initiator_id;
	u_int		role;
};

struct ccb_sim_knob_settings_fc {
	u_int		valid;
	u_int64_t	wwnn;		/* world wide node name */
	u_int64_t 	wwpn;		/* world wide port name */
	u_int		role;
};

struct ccb_sim_knob_settings_sas {
	u_int		valid;
	u_int64_t	wwnn;		/* world wide node name */
	u_int		role;
};
#define	KNOB_SETTINGS_SIZE	128

struct ccb_sim_knob {
	struct	  ccb_hdr ccb_h;
	union {
		u_int  valid;	/* Which fields to honor */
		struct ccb_sim_knob_settings_spi spi;
		struct ccb_sim_knob_settings_fc fc;
		struct ccb_sim_knob_settings_sas sas;
		char pad[KNOB_SETTINGS_SIZE];
	} xport_specific;
};

/*
 * Rescan the given bus, or bus/target/lun
 */
struct ccb_rescan {
	struct	ccb_hdr ccb_h;
	cam_flags	flags;
};

/*
 * Turn on debugging for the given bus, bus/target, or bus/target/lun.
 */
struct ccb_debug {
	struct	ccb_hdr ccb_h;
	cam_debug_flags flags;
};

/* Target mode structures. */

struct ccb_en_lun {
	struct	  ccb_hdr ccb_h;
	u_int16_t grp6_len;		/* Group 6 VU CDB length */
	u_int16_t grp7_len;		/* Group 7 VU CDB length */
	u_int8_t  enable;
};

/* old, barely used immediate notify, binary compatibility */
struct ccb_immed_notify {
	struct	  ccb_hdr ccb_h;
	struct    scsi_sense_data sense_data;
	u_int8_t  sense_len;		/* Number of bytes in sense buffer */
	u_int8_t  initiator_id;		/* Id of initiator that selected */
	u_int8_t  message_args[7];	/* Message Arguments */
};

struct ccb_notify_ack {
	struct	  ccb_hdr ccb_h;
	u_int16_t seq_id;		/* Sequence identifier */
	u_int8_t  event;		/* Event flags */
};

struct ccb_immediate_notify {
	struct    ccb_hdr ccb_h;
	u_int     tag_id;		/* Tag for immediate notify */
	u_int     seq_id;		/* Tag for target of notify */
	u_int     initiator_id;		/* Initiator Identifier */
	u_int     arg;			/* Function specific */
};

struct ccb_notify_acknowledge {
	struct    ccb_hdr ccb_h;
	u_int     tag_id;		/* Tag for immediate notify */
	u_int     seq_id;		/* Tar for target of notify */
	u_int     initiator_id;		/* Initiator Identifier */
	u_int     arg;			/* Function specific */
};

/* HBA engine structures. */

typedef enum {
	EIT_BUFFER,	/* Engine type: buffer memory */
	EIT_LOSSLESS,	/* Engine type: lossless compression */
	EIT_LOSSY,	/* Engine type: lossy compression */
	EIT_ENCRYPT	/* Engine type: encryption */
} ei_type;

typedef enum {
	EAD_VUNIQUE,	/* Engine algorithm ID: vendor unique */
	EAD_LZ1V1,	/* Engine algorithm ID: LZ1 var.1 */
	EAD_LZ2V1,	/* Engine algorithm ID: LZ2 var.1 */
	EAD_LZ2V2	/* Engine algorithm ID: LZ2 var.2 */
} ei_algo;

struct ccb_eng_inq {
	struct	  ccb_hdr ccb_h;
	u_int16_t eng_num;	/* The engine number for this inquiry */
	ei_type   eng_type;	/* Returned engine type */
	ei_algo   eng_algo;	/* Returned engine algorithm type */
	u_int32_t eng_memeory;	/* Returned engine memory size */
};

struct ccb_eng_exec {	/* This structure must match SCSIIO size */
	struct	  ccb_hdr ccb_h;
	u_int8_t  *pdrv_ptr;	/* Ptr used by the peripheral driver */
	u_int8_t  *req_map;	/* Ptr for mapping info on the req. */
	u_int8_t  *data_ptr;	/* Pointer to the data buf/SG list */
	u_int32_t dxfer_len;	/* Data transfer length */
	u_int8_t  *engdata_ptr;	/* Pointer to the engine buffer data */
	u_int16_t sglist_cnt;	/* Num of scatter gather list entries */
	u_int32_t dmax_len;	/* Destination data maximum length */
	u_int32_t dest_len;	/* Destination data length */
	int32_t	  src_resid;	/* Source residual length: 2's comp */
	u_int32_t timeout;	/* Timeout value */
	u_int16_t eng_num;	/* Engine number for this request */
	u_int16_t vu_flags;	/* Vendor Unique flags */
};

/*
 * Definitions for the timeout field in the SCSI I/O CCB.
 */
#define	CAM_TIME_DEFAULT	0x00000000	/* Use SIM default value */
#define	CAM_TIME_INFINITY	0xFFFFFFFF	/* Infinite timeout */

#define	CAM_SUCCESS	0	/* For signaling general success */
#define	CAM_FAILURE	1	/* For signaling general failure */

#define CAM_FALSE	0
#define CAM_TRUE	1

#define XPT_CCB_INVALID	-1	/* for signaling a bad CCB to free */

/*
 * CCB for working with advanced device information.  This operates in a fashion
 * similar to XPT_GDEV_TYPE.  Specify the target in ccb_h, the buffer
 * type requested, and provide a buffer size/buffer to write to.  If the
 * buffer is too small, provsiz will be larger than bufsiz.
 */
struct ccb_dev_advinfo {
	struct ccb_hdr ccb_h;
	uint32_t flags;
#define	CDAI_FLAG_STORE		0x1	/* If set, action becomes store */
	uint32_t buftype;		/* IN: Type of data being requested */
	/* NB: buftype is interpreted on a per-transport basis */
#define	CDAI_TYPE_SCSI_DEVID	1
#define	CDAI_TYPE_SERIAL_NUM	2
#define	CDAI_TYPE_PHYS_PATH	3
	off_t bufsiz;			/* IN: Size of external buffer */
#define	CAM_SCSI_DEVID_MAXLEN	65536	/* length in buffer is an uint16_t */
	off_t provsiz;			/* OUT: Size required/used */
	uint8_t *buf;			/* IN/OUT: Buffer for requested data */
};

/*
 * Union of all CCB types for kernel space allocation.  This union should
 * never be used for manipulating CCBs - its only use is for the allocation
 * and deallocation of raw CCB space and is the return type of xpt_ccb_alloc
 * and the argument to xpt_ccb_free.
 */
union ccb {
	struct	ccb_hdr			ccb_h;	/* For convenience */
	struct	ccb_scsiio		csio;
	struct	ccb_getdev		cgd;
	struct	ccb_getdevlist		cgdl;
	struct	ccb_pathinq		cpi;
	struct	ccb_relsim		crs;
	struct	ccb_setasync		csa;
	struct	ccb_setdev		csd;
	struct	ccb_pathstats		cpis;
	struct	ccb_getdevstats		cgds;
	struct	ccb_dev_match		cdm;
	struct	ccb_trans_settings	cts;
	struct	ccb_calc_geometry	ccg;
	struct	ccb_sim_knob		knob;
	struct	ccb_abort		cab;
	struct	ccb_resetbus		crb;
	struct	ccb_resetdev		crd;
	struct	ccb_termio		tio;
	struct	ccb_accept_tio		atio;
	struct	ccb_scsiio		ctio;
	struct	ccb_en_lun		cel;
	struct	ccb_immed_notify	cin;
	struct	ccb_notify_ack		cna;
	struct	ccb_immediate_notify	cin1;
	struct	ccb_notify_acknowledge	cna2;
	struct	ccb_eng_inq		cei;
	struct	ccb_eng_exec		cee;
	struct	ccb_smpio		smpio;
	struct 	ccb_rescan		crcn;
	struct  ccb_debug		cdbg;
	struct	ccb_ataio		ataio;
	struct	ccb_dev_advinfo		cdai;
};

__BEGIN_DECLS
static __inline void
cam_fill_csio(struct ccb_scsiio *csio, u_int32_t retries,
	      void (*cbfcnp)(struct cam_periph *, union ccb *),
	      u_int32_t flags, u_int8_t tag_action,
	      u_int8_t *data_ptr, u_int32_t dxfer_len,
	      u_int8_t sense_len, u_int8_t cdb_len,
	      u_int32_t timeout);

static __inline void
cam_fill_ctio(struct ccb_scsiio *csio, u_int32_t retries,
	      void (*cbfcnp)(struct cam_periph *, union ccb *),
	      u_int32_t flags, u_int tag_action, u_int tag_id,
	      u_int init_id, u_int scsi_status, u_int8_t *data_ptr,
	      u_int32_t dxfer_len, u_int32_t timeout);

static __inline void
cam_fill_ataio(struct ccb_ataio *ataio, u_int32_t retries,
	      void (*cbfcnp)(struct cam_periph *, union ccb *),
	      u_int32_t flags, u_int tag_action,
	      u_int8_t *data_ptr, u_int32_t dxfer_len,
	      u_int32_t timeout);

static __inline void
cam_fill_smpio(struct ccb_smpio *smpio, uint32_t retries,
	       void (*cbfcnp)(struct cam_periph *, union ccb *), uint32_t flags,
	       uint8_t *smp_request, int smp_request_len,
	       uint8_t *smp_response, int smp_response_len,
	       uint32_t timeout);

static __inline void
cam_fill_csio(struct ccb_scsiio *csio, u_int32_t retries,
	      void (*cbfcnp)(struct cam_periph *, union ccb *),
	      u_int32_t flags, u_int8_t tag_action,
	      u_int8_t *data_ptr, u_int32_t dxfer_len,
	      u_int8_t sense_len, u_int8_t cdb_len,
	      u_int32_t timeout)
{
	csio->ccb_h.func_code = XPT_SCSI_IO;
	csio->ccb_h.flags = flags;
	csio->ccb_h.retry_count = retries;
	csio->ccb_h.cbfcnp = cbfcnp;
	csio->ccb_h.timeout = timeout;
	csio->data_ptr = data_ptr;
	csio->dxfer_len = dxfer_len;
	csio->sense_len = sense_len;
	csio->cdb_len = cdb_len;
	csio->tag_action = tag_action;
}

static __inline void
cam_fill_ctio(struct ccb_scsiio *csio, u_int32_t retries,
	      void (*cbfcnp)(struct cam_periph *, union ccb *),
	      u_int32_t flags, u_int tag_action, u_int tag_id,
	      u_int init_id, u_int scsi_status, u_int8_t *data_ptr,
	      u_int32_t dxfer_len, u_int32_t timeout)
{
	csio->ccb_h.func_code = XPT_CONT_TARGET_IO;
	csio->ccb_h.flags = flags;
	csio->ccb_h.retry_count = retries;
	csio->ccb_h.cbfcnp = cbfcnp;
	csio->ccb_h.timeout = timeout;
	csio->data_ptr = data_ptr;
	csio->dxfer_len = dxfer_len;
	csio->scsi_status = scsi_status;
	csio->tag_action = tag_action;
	csio->tag_id = tag_id;
	csio->init_id = init_id;
}

static __inline void
cam_fill_ataio(struct ccb_ataio *ataio, u_int32_t retries,
	      void (*cbfcnp)(struct cam_periph *, union ccb *),
	      u_int32_t flags, u_int tag_action,
	      u_int8_t *data_ptr, u_int32_t dxfer_len,
	      u_int32_t timeout)
{
	ataio->ccb_h.func_code = XPT_ATA_IO;
	ataio->ccb_h.flags = flags;
	ataio->ccb_h.retry_count = retries;
	ataio->ccb_h.cbfcnp = cbfcnp;
	ataio->ccb_h.timeout = timeout;
	ataio->data_ptr = data_ptr;
	ataio->dxfer_len = dxfer_len;
	ataio->tag_action = tag_action;
}

static __inline void
cam_fill_smpio(struct ccb_smpio *smpio, uint32_t retries,
	       void (*cbfcnp)(struct cam_periph *, union ccb *), uint32_t flags,
	       uint8_t *smp_request, int smp_request_len,
	       uint8_t *smp_response, int smp_response_len,
	       uint32_t timeout)
{
#ifdef _KERNEL
	KASSERT((flags & CAM_DIR_MASK) == CAM_DIR_BOTH,
		("direction != CAM_DIR_BOTH"));
	KASSERT((smp_request != NULL) && (smp_response != NULL),
		("need valid request and response buffers"));
	KASSERT((smp_request_len != 0) && (smp_response_len != 0),
		("need non-zero request and response lengths"));
#endif /*_KERNEL*/
	smpio->ccb_h.func_code = XPT_SMP_IO;
	smpio->ccb_h.flags = flags;
	smpio->ccb_h.retry_count = retries;
	smpio->ccb_h.cbfcnp = cbfcnp;
	smpio->ccb_h.timeout = timeout;
	smpio->smp_request = smp_request;
	smpio->smp_request_len = smp_request_len;
	smpio->smp_response = smp_response;
	smpio->smp_response_len = smp_response_len;
}

void cam_calc_geometry(struct ccb_calc_geometry *ccg, int extended);

__END_DECLS

#endif /* _CAM_CAM_CCB_H */


code:
/*-
 * Macros for tracing/loging information in the CAM layer
 *
 * Copyright (c) 1997 Justin T. Gibbs.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification, immediately at the beginning of the file.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: release/9.0.0/sys/cam/cam_debug.h 208911 2010-06-08 16:17:25Z mjacob $
 */
#ifndef	_CAM_CAM_DEBUG_H
#define _CAM_CAM_DEBUG_H 1

/*
 * Debugging flags.
 */
typedef enum {
	CAM_DEBUG_NONE		= 0x00, /* no debugging */
	CAM_DEBUG_INFO		= 0x01,	/* scsi commands, errors, data */
	CAM_DEBUG_TRACE		= 0x02,	/* routine flow tracking */
	CAM_DEBUG_SUBTRACE	= 0x04,	/* internal to routine flows */
	CAM_DEBUG_CDB		= 0x08, /* print out SCSI CDBs only */
	CAM_DEBUG_XPT		= 0x10,	/* print out xpt scheduling */
	CAM_DEBUG_PERIPH	= 0x20, /* print out peripheral calls */
	CAM_DEBUG_PROBE		= 0x40  /* print out probe actions */
} cam_debug_flags;

#if defined(CAMDEBUG) && defined(_KERNEL)

/* Path we want to debug */
extern struct cam_path *cam_dpath;
/* Current debug levels set */
extern u_int32_t cam_dflags;
/* Printf delay value (to prevent scrolling) */
extern u_int32_t cam_debug_delay;

/* Debugging macros. */
#define	CAM_DEBUGGED(path, flag)			\
	((cam_dflags & (flag))				\
	 && (cam_dpath != NULL)				\
	 && (xpt_path_comp(cam_dpath, path) >= 0)	\
	 && (xpt_path_comp(cam_dpath, path) < 2))

#define	CAM_DEBUG(path, flag, printfargs)		\
	if ((cam_dflags & (flag))			\
	 && (cam_dpath != NULL)				\
	 && (xpt_path_comp(cam_dpath, path) >= 0)	\
	 && (xpt_path_comp(cam_dpath, path) < 2)) {	\
		xpt_print_path(path);			\
 		printf printfargs;			\
		if (cam_debug_delay != 0)		\
			DELAY(cam_debug_delay);		\
	}

#define	CAM_DEBUG_PRINT(flag, printfargs)		\
	if (cam_dflags & (flag)) {			\
		printf("cam_debug: ");			\
 		printf printfargs;			\
		if (cam_debug_delay != 0)		\
			DELAY(cam_debug_delay);		\
	}

#define	CAM_DEBUG_PATH_PRINT(flag, path, printfargs)	\
	if (cam_dflags & (flag)) {			\
		xpt_print(path, "cam_debug: ");		\
 		printf printfargs;			\
		if (cam_debug_delay != 0)		\
			DELAY(cam_debug_delay);		\
	}

#else /* !CAMDEBUG || !_KERNEL */

#define	CAM_DEBUGGED(A, B)	0
#define	CAM_DEBUG(A, B, C)
#define	CAM_DEBUG_PRINT(A, B)
#define	CAM_DEBUG_PATH_PRINT(A, B, C)

#endif /* CAMDEBUG && _KERNEL */

#endif /* _CAM_CAM_DEBUG_H */