aboutsummaryrefslogblamecommitdiff
path: root/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32F4/stm32f4xx_hal_tim.h
blob: b68bc97eb704d3ab626ec352d847af8a795c7517 (plain) (tree)
1
2
3
4
5
6



                                                                                

                            




























                                                                                    
     























                                                                                


                                                              





















                                                                                                                      
                                                                                                                  


                                                                                             

                                                                   






                                                                                                        
                                                                                                         







                                                                                                                
  











                                                                                                    
                       
 

                                                                   





                                                                                                        
                                                                                                         























                                                                                                                

                                                                                                           

 

                                                                  
















                                                                                                         

                                                            





                                                                                        
                                  










                                                                                                          
                                  












                                                                                                          


                                                             

              


                                                                                           
                                                                                            
                                                      
                                                                                             
                                                  


                                                                                                           


                                                                   
              





                                                                                                     
                                                                                                      
                                                                 
                                                                                                       
                                                             


                                                                                                                


                                                          
                


                                                                                          
                                                                                                
                                                           
                                                                                               
                                                            
                                                                                                

                                                                                                               


                        


                                             








                                                                                                


                                                      








                                                                                


                                                       






















































































                                                                                                                        
                                                           
















                                                                      
                                                                          














                                                                          
     







                                                                              
     








                                                             
                                 



      
                                                                     











                                                                            
                                                                                                              

















                                                                                                                                                
     















                                                                            
   





                                                                
     










                                                

                                                             
      
      



















                                                            
                                                 

      
                                                        




                                                        

                                                        


























                                                         

                                                      














                                                                   




                                                                                                                       

















                                                                                                                                                       
                                                              







                                                               

                                                                                                                            
















                                                                                                                                                                   
      




                                                     
  







                                                                                                              
  








                                                     
      

                                                                   
                             




                                                    

                                                     






                                                       
  






                                                               

      

                                                                 








                                                                                        

      

     


















                                                              

     













                                                             
      



                                                       




                                                                                                                                            






















                                                                                                                                                          
     

























                                                        
     
 
                                                         



































                                                                                                                                       
     









                                                           
     


      

       













































































































































                                                                                                                                                
                                                                              

















                                                                               

                                                                         





















                                                                                           
                                                                            





































                                                                                                   
    


                                                                            
                                                                          









                                                                              

                                                                            

















                                                                  
                                                    


                                                                              
                                                                                                    







































































































































































                                                                                                                                                             
                                                                                                                      












































                                                                                                                             
  


      
  



















                                                                                   
                              





























                                                                                
                                      




















                                                                                                       
                           




                                                                                                         
                           





















                                                                                          

                                                              
                                                                                       
                                                                                 








                                                                                                    

                                                               


















































                                                                                            
                                                                                                                   










                                                                                                  

                                                               






















                                                                                                 
                           
















                                                                                    
                                                                                                           
 
                                                                                  

      
     


                                                      
      






                                                                                                       
  













                                                                                                                    
                                                                                     

      

      

      
     


      

     






                                                                                
/**
  ******************************************************************************
  * @file    stm32f4xx_hal_tim.h
  * @author  MCD Application Team
  * @version V1.4.1
  * @date    09-October-2015
  * @brief   Header file of TIM HAL module.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2>
  *
  * 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.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.
  *
  ******************************************************************************
  */ 

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_TIM_H
#define __STM32F4xx_HAL_TIM_H

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal_def.h"

/** @addtogroup STM32F4xx_HAL_Driver
  * @{
  */

/** @addtogroup TIM
  * @{
  */

/* Exported types ------------------------------------------------------------*/
/** @defgroup TIM_Exported_Types TIM Exported Types
  * @{
  */
  
/** 
  * @brief  TIM Time base Configuration Structure definition  
  */
typedef struct
{
  uint32_t Prescaler;         /*!< Specifies the prescaler value used to divide the TIM clock.
                                   This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */

  uint32_t CounterMode;       /*!< Specifies the counter mode.
                                   This parameter can be a value of @ref TIM_Counter_Mode */

  uint32_t Period;            /*!< Specifies the period value to be loaded into the active
                                   Auto-Reload Register at the next update event.
                                   This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF.  */

  uint32_t ClockDivision;     /*!< Specifies the clock division.
                                   This parameter can be a value of @ref TIM_ClockDivision */

  uint32_t RepetitionCounter;  /*!< Specifies the repetition counter value. Each time the RCR downcounter
                                    reaches zero, an update event is generated and counting restarts
                                    from the RCR value (N).
                                    This means in PWM mode that (N+1) corresponds to:
                                        - the number of PWM periods in edge-aligned mode
                                        - the number of half PWM period in center-aligned mode
                                     This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. 
                                     @note This parameter is valid only for TIM1 and TIM8. */
} TIM_Base_InitTypeDef;

/** 
  * @brief  TIM Output Compare Configuration Structure definition  
  */

typedef struct
{
  uint32_t OCMode;        /*!< Specifies the TIM mode.
                               This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */

  uint32_t Pulse;         /*!< Specifies the pulse value to be loaded into the Capture Compare Register. 
                               This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */

  uint32_t OCPolarity;    /*!< Specifies the output polarity.
                               This parameter can be a value of @ref TIM_Output_Compare_Polarity */

  uint32_t OCNPolarity;   /*!< Specifies the complementary output polarity.
                               This parameter can be a value of @ref TIM_Output_Compare_N_Polarity
                               @note This parameter is valid only for TIM1 and TIM8. */
  
  uint32_t OCFastMode;   /*!< Specifies the Fast mode state.
                               This parameter can be a value of @ref TIM_Output_Fast_State
                               @note This parameter is valid only in PWM1 and PWM2 mode. */


  uint32_t OCIdleState;   /*!< Specifies the TIM Output Compare pin state during Idle state.
                               This parameter can be a value of @ref TIM_Output_Compare_Idle_State
                               @note This parameter is valid only for TIM1 and TIM8. */

  uint32_t OCNIdleState;  /*!< Specifies the TIM Output Compare pin state during Idle state.
                               This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State
                               @note This parameter is valid only for TIM1 and TIM8. */
} TIM_OC_InitTypeDef;  

/** 
  * @brief  TIM One Pulse Mode Configuration Structure definition  
  */
typedef struct
{
  uint32_t OCMode;        /*!< Specifies the TIM mode.
                               This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */

  uint32_t Pulse;         /*!< Specifies the pulse value to be loaded into the Capture Compare Register. 
                               This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */

  uint32_t OCPolarity;    /*!< Specifies the output polarity.
                               This parameter can be a value of @ref TIM_Output_Compare_Polarity */

  uint32_t OCNPolarity;   /*!< Specifies the complementary output polarity.
                               This parameter can be a value of @ref TIM_Output_Compare_N_Polarity
                               @note This parameter is valid only for TIM1 and TIM8. */

  uint32_t OCIdleState;   /*!< Specifies the TIM Output Compare pin state during Idle state.
                               This parameter can be a value of @ref TIM_Output_Compare_Idle_State
                               @note This parameter is valid only for TIM1 and TIM8. */

  uint32_t OCNIdleState;  /*!< Specifies the TIM Output Compare pin state during Idle state.
                               This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State
                               @note This parameter is valid only for TIM1 and TIM8. */

  uint32_t ICPolarity;    /*!< Specifies the active edge of the input signal.
                               This parameter can be a value of @ref TIM_Input_Capture_Polarity */

  uint32_t ICSelection;   /*!< Specifies the input.
                              This parameter can be a value of @ref TIM_Input_Capture_Selection */

  uint32_t ICFilter;      /*!< Specifies the input capture filter.
                              This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */  
} TIM_OnePulse_InitTypeDef;  


/** 
  * @brief  TIM Input Capture Configuration Structure definition  
  */

typedef struct
{
  uint32_t  ICPolarity;   /*!< Specifies the active edge of the input signal.
                               This parameter can be a value of @ref TIM_Input_Capture_Polarity */

  uint32_t ICSelection;  /*!< Specifies the input.
                              This parameter can be a value of @ref TIM_Input_Capture_Selection */

  uint32_t ICPrescaler;  /*!< Specifies the Input Capture Prescaler.
                              This parameter can be a value of @ref TIM_Input_Capture_Prescaler */

  uint32_t ICFilter;     /*!< Specifies the input capture filter.
                              This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */
} TIM_IC_InitTypeDef;

/** 
  * @brief  TIM Encoder Configuration Structure definition  
  */

typedef struct
{
  uint32_t EncoderMode;   /*!< Specifies the active edge of the input signal.
                               This parameter can be a value of @ref TIM_Encoder_Mode */
                                  
  uint32_t IC1Polarity;   /*!< Specifies the active edge of the input signal.
                               This parameter can be a value of @ref TIM_Input_Capture_Polarity */

  uint32_t IC1Selection;  /*!< Specifies the input.
                               This parameter can be a value of @ref TIM_Input_Capture_Selection */

  uint32_t IC1Prescaler;  /*!< Specifies the Input Capture Prescaler.
                               This parameter can be a value of @ref TIM_Input_Capture_Prescaler */

  uint32_t IC1Filter;     /*!< Specifies the input capture filter.
                               This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */
                                  
  uint32_t IC2Polarity;   /*!< Specifies the active edge of the input signal.
                               This parameter can be a value of @ref TIM_Input_Capture_Polarity */

  uint32_t IC2Selection;  /*!< Specifies the input.
                              This parameter can be a value of @ref TIM_Input_Capture_Selection */

  uint32_t IC2Prescaler;  /*!< Specifies the Input Capture Prescaler.
                               This parameter can be a value of @ref TIM_Input_Capture_Prescaler */

  uint32_t IC2Filter;     /*!< Specifies the input capture filter.
                               This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */
} TIM_Encoder_InitTypeDef;

/** 
  * @brief  Clock Configuration Handle Structure definition  
  */ 
typedef struct
{
  uint32_t ClockSource;     /*!< TIM clock sources. 
                                 This parameter can be a value of @ref TIM_Clock_Source */ 
  uint32_t ClockPolarity;   /*!< TIM clock polarity. 
                                 This parameter can be a value of @ref TIM_Clock_Polarity */
  uint32_t ClockPrescaler;  /*!< TIM clock prescaler. 
                                 This parameter can be a value of @ref TIM_Clock_Prescaler */
  uint32_t ClockFilter;    /*!< TIM clock filter. 
                                This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */
}TIM_ClockConfigTypeDef;

/** 
  * @brief  Clear Input Configuration Handle Structure definition  
  */ 
typedef struct
{ 
  uint32_t ClearInputState;      /*!< TIM clear Input state. 
                                      This parameter can be ENABLE or DISABLE */  
  uint32_t ClearInputSource;     /*!< TIM clear Input sources. 
                                      This parameter can be a value of @ref TIM_ClearInput_Source */ 
  uint32_t ClearInputPolarity;   /*!< TIM Clear Input polarity. 
                                      This parameter can be a value of @ref TIM_ClearInput_Polarity */
  uint32_t ClearInputPrescaler;  /*!< TIM Clear Input prescaler. 
                                      This parameter can be a value of @ref TIM_ClearInput_Prescaler */
  uint32_t ClearInputFilter;    /*!< TIM Clear Input filter. 
                                     This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */
}TIM_ClearInputConfigTypeDef;

/** 
  * @brief  TIM Slave configuration Structure definition  
  */ 
typedef struct {
  uint32_t  SlaveMode;         /*!< Slave mode selection 
                                  This parameter can be a value of @ref TIM_Slave_Mode */ 
  uint32_t  InputTrigger;      /*!< Input Trigger source 
                                  This parameter can be a value of @ref TIM_Trigger_Selection */
  uint32_t  TriggerPolarity;   /*!< Input Trigger polarity 
                                  This parameter can be a value of @ref TIM_Trigger_Polarity */
  uint32_t  TriggerPrescaler;  /*!< Input trigger prescaler 
                                  This parameter can be a value of @ref TIM_Trigger_Prescaler */
  uint32_t  TriggerFilter;     /*!< Input trigger filter 
                                  This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */  

}TIM_SlaveConfigTypeDef;

/** 
  * @brief  HAL State structures definition  
  */ 
typedef enum
{
  HAL_TIM_STATE_RESET             = 0x00,    /*!< Peripheral not yet initialized or disabled  */
  HAL_TIM_STATE_READY             = 0x01,    /*!< Peripheral Initialized and ready for use    */
  HAL_TIM_STATE_BUSY              = 0x02,    /*!< An internal process is ongoing              */
  HAL_TIM_STATE_TIMEOUT           = 0x03,    /*!< Timeout state                               */
  HAL_TIM_STATE_ERROR             = 0x04     /*!< Reception process is ongoing                */
}HAL_TIM_StateTypeDef;

/** 
  * @brief  HAL Active channel structures definition  
  */ 
typedef enum
{
  HAL_TIM_ACTIVE_CHANNEL_1        = 0x01,    /*!< The active channel is 1     */
  HAL_TIM_ACTIVE_CHANNEL_2        = 0x02,    /*!< The active channel is 2     */
  HAL_TIM_ACTIVE_CHANNEL_3        = 0x04,    /*!< The active channel is 3     */
  HAL_TIM_ACTIVE_CHANNEL_4        = 0x08,    /*!< The active channel is 4     */
  HAL_TIM_ACTIVE_CHANNEL_CLEARED  = 0x00     /*!< All active channels cleared */
}HAL_TIM_ActiveChannel;

/** 
  * @brief  TIM Time Base Handle Structure definition  
  */ 
typedef struct
{
  TIM_TypeDef                 *Instance;     /*!< Register base address             */
  TIM_Base_InitTypeDef        Init;          /*!< TIM Time Base required parameters */
  HAL_TIM_ActiveChannel       Channel;       /*!< Active channel                    */
  DMA_HandleTypeDef           *hdma[7];      /*!< DMA Handlers array
                                             This array is accessed by a @ref DMA_Handle_index */
  HAL_LockTypeDef             Lock;          /*!< Locking object                    */
  __IO HAL_TIM_StateTypeDef   State;         /*!< TIM operation state               */
}TIM_HandleTypeDef;
/**
  * @}
  */

/* Exported constants --------------------------------------------------------*/
/** @defgroup TIM_Exported_Constants  TIM Exported Constants
  * @{
  */

/** @defgroup TIM_Input_Channel_Polarity TIM Input Channel Polarity
  * @{
  */
#define  TIM_INPUTCHANNELPOLARITY_RISING      ((uint32_t)0x00000000)            /*!< Polarity for TIx source */
#define  TIM_INPUTCHANNELPOLARITY_FALLING     (TIM_CCER_CC1P)                   /*!< Polarity for TIx source */
#define  TIM_INPUTCHANNELPOLARITY_BOTHEDGE    (TIM_CCER_CC1P | TIM_CCER_CC1NP)  /*!< Polarity for TIx source */
/**
  * @}
  */

/** @defgroup TIM_ETR_Polarity  TIM ETR Polarity
  * @{
  */
#define TIM_ETRPOLARITY_INVERTED              (TIM_SMCR_ETP)                    /*!< Polarity for ETR source */
#define TIM_ETRPOLARITY_NONINVERTED           ((uint32_t)0x0000)                /*!< Polarity for ETR source */
/**
  * @}
  */

/** @defgroup TIM_ETR_Prescaler  TIM ETR Prescaler
  * @{
  */
#define TIM_ETRPRESCALER_DIV1                 ((uint32_t)0x0000)                /*!< No prescaler is used */
#define TIM_ETRPRESCALER_DIV2                 (TIM_SMCR_ETPS_0)                 /*!< ETR input source is divided by 2 */
#define TIM_ETRPRESCALER_DIV4                 (TIM_SMCR_ETPS_1)                 /*!< ETR input source is divided by 4 */
#define TIM_ETRPRESCALER_DIV8                 (TIM_SMCR_ETPS)                   /*!< ETR input source is divided by 8 */
/**
  * @}
  */

/** @defgroup TIM_Counter_Mode  TIM Counter Mode
  * @{
  */
#define TIM_COUNTERMODE_UP                 ((uint32_t)0x0000)
#define TIM_COUNTERMODE_DOWN               TIM_CR1_DIR
#define TIM_COUNTERMODE_CENTERALIGNED1     TIM_CR1_CMS_0
#define TIM_COUNTERMODE_CENTERALIGNED2     TIM_CR1_CMS_1
#define TIM_COUNTERMODE_CENTERALIGNED3     TIM_CR1_CMS
/**
  * @}
  */

/** @defgroup TIM_ClockDivision TIM Clock Division
  * @{
  */
#define TIM_CLOCKDIVISION_DIV1                       ((uint32_t)0x0000)
#define TIM_CLOCKDIVISION_DIV2                       (TIM_CR1_CKD_0)
#define TIM_CLOCKDIVISION_DIV4                       (TIM_CR1_CKD_1)
/**
  * @}
  */

/** @defgroup TIM_Output_Compare_and_PWM_modes  TIM Output Compare and PWM modes
  * @{
  */
#define TIM_OCMODE_TIMING                   ((uint32_t)0x0000)
#define TIM_OCMODE_ACTIVE                   (TIM_CCMR1_OC1M_0)
#define TIM_OCMODE_INACTIVE                 (TIM_CCMR1_OC1M_1)
#define TIM_OCMODE_TOGGLE                   (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1)
#define TIM_OCMODE_PWM1                     (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2)
#define TIM_OCMODE_PWM2                     (TIM_CCMR1_OC1M)
#define TIM_OCMODE_FORCED_ACTIVE            (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2)
#define TIM_OCMODE_FORCED_INACTIVE          (TIM_CCMR1_OC1M_2)

/**
  * @}
  */

/** @defgroup TIM_Output_Fast_State  TIM Output Fast State 
  * @{
  */
#define TIM_OCFAST_DISABLE                ((uint32_t)0x0000)
#define TIM_OCFAST_ENABLE                 (TIM_CCMR1_OC1FE)
/**
  * @}
  */

/** @defgroup TIM_Output_Compare_Polarity  TIM Output Compare Polarity
  * @{
  */
#define TIM_OCPOLARITY_HIGH                ((uint32_t)0x0000)
#define TIM_OCPOLARITY_LOW                 (TIM_CCER_CC1P)
/**
  * @}
  */

/** @defgroup TIM_Output_Compare_N_Polarity  TIM Output CompareN Polarity 
  * @{
  */
#define TIM_OCNPOLARITY_HIGH               ((uint32_t)0x0000)
#define TIM_OCNPOLARITY_LOW                (TIM_CCER_CC1NP)
/**
  * @}
  */

/** @defgroup TIM_Output_Compare_Idle_State  TIM Output Compare Idle State
  * @{
  */
#define TIM_OCIDLESTATE_SET                (TIM_CR2_OIS1)
#define TIM_OCIDLESTATE_RESET              ((uint32_t)0x0000)
/**
  * @}
  */ 

/** @defgroup TIM_Output_Compare_N_Idle_State  TIM Output Compare N Idle State
  * @{
  */
#define TIM_OCNIDLESTATE_SET               (TIM_CR2_OIS1N)
#define TIM_OCNIDLESTATE_RESET             ((uint32_t)0x0000)
/**
  * @}
  */ 

/** @defgroup TIM_Channel  TIM Channel
  * @{
  */
#define TIM_CHANNEL_1                      ((uint32_t)0x0000)
#define TIM_CHANNEL_2                      ((uint32_t)0x0004)
#define TIM_CHANNEL_3                      ((uint32_t)0x0008)
#define TIM_CHANNEL_4                      ((uint32_t)0x000C)
#define TIM_CHANNEL_ALL                    ((uint32_t)0x0018)
                                 
/**
  * @}
  */

/** @defgroup TIM_Input_Capture_Polarity  TIM Input Capture Polarity 
  * @{
  */
#define  TIM_ICPOLARITY_RISING             TIM_INPUTCHANNELPOLARITY_RISING
#define  TIM_ICPOLARITY_FALLING            TIM_INPUTCHANNELPOLARITY_FALLING
#define  TIM_ICPOLARITY_BOTHEDGE           TIM_INPUTCHANNELPOLARITY_BOTHEDGE
/**
  * @}
  */

/** @defgroup TIM_Input_Capture_Selection  TIM Input Capture Selection
  * @{
  */
#define TIM_ICSELECTION_DIRECTTI           (TIM_CCMR1_CC1S_0)   /*!< TIM Input 1, 2, 3 or 4 is selected to be 
                                                                     connected to IC1, IC2, IC3 or IC4, respectively */
#define TIM_ICSELECTION_INDIRECTTI         (TIM_CCMR1_CC1S_1)   /*!< TIM Input 1, 2, 3 or 4 is selected to be
                                                                     connected to IC2, IC1, IC4 or IC3, respectively */
#define TIM_ICSELECTION_TRC                (TIM_CCMR1_CC1S)     /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to TRC */

/**
  * @}
  */

/** @defgroup TIM_Input_Capture_Prescaler  TIM Input Capture Prescaler
  * @{
  */
#define TIM_ICPSC_DIV1                     ((uint32_t)0x0000)       /*!< Capture performed each time an edge is detected on the capture input */
#define TIM_ICPSC_DIV2                     (TIM_CCMR1_IC1PSC_0)     /*!< Capture performed once every 2 events */
#define TIM_ICPSC_DIV4                     (TIM_CCMR1_IC1PSC_1)     /*!< Capture performed once every 4 events */
#define TIM_ICPSC_DIV8                     (TIM_CCMR1_IC1PSC)       /*!< Capture performed once every 8 events */
/**
  * @}
  */ 

/** @defgroup TIM_One_Pulse_Mode TIM One Pulse Mode
  * @{
  */
#define TIM_OPMODE_SINGLE                  (TIM_CR1_OPM)
#define TIM_OPMODE_REPETITIVE              ((uint32_t)0x0000)
/**
  * @}
  */

/** @defgroup TIM_Encoder_Mode TIM Encoder Mode
  * @{
  */
#define TIM_ENCODERMODE_TI1                (TIM_SMCR_SMS_0)
#define TIM_ENCODERMODE_TI2                (TIM_SMCR_SMS_1)
#define TIM_ENCODERMODE_TI12               (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0)
   
/**
  * @}
  */

/** @defgroup TIM_Interrupt_definition  TIM Interrupt definition
  * @{
  */ 
#define TIM_IT_UPDATE           (TIM_DIER_UIE)
#define TIM_IT_CC1              (TIM_DIER_CC1IE)
#define TIM_IT_CC2              (TIM_DIER_CC2IE)
#define TIM_IT_CC3              (TIM_DIER_CC3IE)
#define TIM_IT_CC4              (TIM_DIER_CC4IE)
#define TIM_IT_COM              (TIM_DIER_COMIE)
#define TIM_IT_TRIGGER          (TIM_DIER_TIE)
#define TIM_IT_BREAK            (TIM_DIER_BIE)
/**
  * @}
  */
  
/** @defgroup TIM_Commutation_Source  TIM Commutation Source 
  * @{
  */  
#define TIM_COMMUTATION_TRGI              (TIM_CR2_CCUS)
#define TIM_COMMUTATION_SOFTWARE          ((uint32_t)0x0000)
/**
  * @}
  */

/** @defgroup TIM_DMA_sources  TIM DMA sources
  * @{
  */
#define TIM_DMA_UPDATE                     (TIM_DIER_UDE)
#define TIM_DMA_CC1                        (TIM_DIER_CC1DE)
#define TIM_DMA_CC2                        (TIM_DIER_CC2DE)
#define TIM_DMA_CC3                        (TIM_DIER_CC3DE)
#define TIM_DMA_CC4                        (TIM_DIER_CC4DE)
#define TIM_DMA_COM                        (TIM_DIER_COMDE)
#define TIM_DMA_TRIGGER                    (TIM_DIER_TDE)
/**
  * @}
  */

/** @defgroup TIM_Event_Source  TIM Event Source 
  * @{
  */
#define TIM_EVENTSOURCE_UPDATE              TIM_EGR_UG  
#define TIM_EVENTSOURCE_CC1                 TIM_EGR_CC1G
#define TIM_EVENTSOURCE_CC2                 TIM_EGR_CC2G
#define TIM_EVENTSOURCE_CC3                 TIM_EGR_CC3G
#define TIM_EVENTSOURCE_CC4                 TIM_EGR_CC4G
#define TIM_EVENTSOURCE_COM                 TIM_EGR_COMG
#define TIM_EVENTSOURCE_TRIGGER             TIM_EGR_TG  
#define TIM_EVENTSOURCE_BREAK               TIM_EGR_BG  

/**
  * @}
  */

/** @defgroup TIM_Flag_definition  TIM Flag definition
  * @{
  */
#define TIM_FLAG_UPDATE                    (TIM_SR_UIF)
#define TIM_FLAG_CC1                       (TIM_SR_CC1IF)
#define TIM_FLAG_CC2                       (TIM_SR_CC2IF)
#define TIM_FLAG_CC3                       (TIM_SR_CC3IF)
#define TIM_FLAG_CC4                       (TIM_SR_CC4IF)
#define TIM_FLAG_COM                       (TIM_SR_COMIF)
#define TIM_FLAG_TRIGGER                   (TIM_SR_TIF)
#define TIM_FLAG_BREAK                     (TIM_SR_BIF)
#define TIM_FLAG_CC1OF                     (TIM_SR_CC1OF)
#define TIM_FLAG_CC2OF                     (TIM_SR_CC2OF)
#define TIM_FLAG_CC3OF                     (TIM_SR_CC3OF)
#define TIM_FLAG_CC4OF                     (TIM_SR_CC4OF)
/**
  * @}
  */

/** @defgroup TIM_Clock_Source  TIM Clock Source
  * @{
  */
#define	TIM_CLOCKSOURCE_ETRMODE2    (TIM_SMCR_ETPS_1) 
#define	TIM_CLOCKSOURCE_INTERNAL    (TIM_SMCR_ETPS_0) 
#define	TIM_CLOCKSOURCE_ITR0        ((uint32_t)0x0000)
#define	TIM_CLOCKSOURCE_ITR1        (TIM_SMCR_TS_0)
#define	TIM_CLOCKSOURCE_ITR2        (TIM_SMCR_TS_1)
#define	TIM_CLOCKSOURCE_ITR3        (TIM_SMCR_TS_0 | TIM_SMCR_TS_1)
#define	TIM_CLOCKSOURCE_TI1ED       (TIM_SMCR_TS_2)
#define	TIM_CLOCKSOURCE_TI1         (TIM_SMCR_TS_0 | TIM_SMCR_TS_2)
#define	TIM_CLOCKSOURCE_TI2         (TIM_SMCR_TS_1 | TIM_SMCR_TS_2)
#define	TIM_CLOCKSOURCE_ETRMODE1    (TIM_SMCR_TS)
/**
  * @}
  */

/** @defgroup TIM_Clock_Polarity  TIM Clock Polarity
  * @{
  */
#define TIM_CLOCKPOLARITY_INVERTED           TIM_ETRPOLARITY_INVERTED          /*!< Polarity for ETRx clock sources */ 
#define TIM_CLOCKPOLARITY_NONINVERTED        TIM_ETRPOLARITY_NONINVERTED       /*!< Polarity for ETRx clock sources */ 
#define TIM_CLOCKPOLARITY_RISING             TIM_INPUTCHANNELPOLARITY_RISING   /*!< Polarity for TIx clock sources */ 
#define TIM_CLOCKPOLARITY_FALLING            TIM_INPUTCHANNELPOLARITY_FALLING   /*!< Polarity for TIx clock sources */ 
#define TIM_CLOCKPOLARITY_BOTHEDGE           TIM_INPUTCHANNELPOLARITY_BOTHEDGE  /*!< Polarity for TIx clock sources */ 
/**
  * @}
  */

/** @defgroup TIM_Clock_Prescaler  TIM Clock Prescaler
  * @{
  */
#define TIM_CLOCKPRESCALER_DIV1              TIM_ETRPRESCALER_DIV1     /*!< No prescaler is used */
#define TIM_CLOCKPRESCALER_DIV2              TIM_ETRPRESCALER_DIV2     /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */
#define TIM_CLOCKPRESCALER_DIV4              TIM_ETRPRESCALER_DIV4     /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */
#define TIM_CLOCKPRESCALER_DIV8              TIM_ETRPRESCALER_DIV8     /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */
/**
  * @}
  */

/** @defgroup TIM_ClearInput_Source TIM Clear Input Source
  * @{
  */
#define TIM_CLEARINPUTSOURCE_ETR           ((uint32_t)0x0001) 
#define TIM_CLEARINPUTSOURCE_NONE          ((uint32_t)0x0000)
/**
  * @}
  */

/** @defgroup TIM_ClearInput_Polarity  TIM Clear Input Polarity
  * @{
  */
#define TIM_CLEARINPUTPOLARITY_INVERTED           TIM_ETRPOLARITY_INVERTED                    /*!< Polarity for ETRx pin */ 
#define TIM_CLEARINPUTPOLARITY_NONINVERTED        TIM_ETRPOLARITY_NONINVERTED                 /*!< Polarity for ETRx pin */ 
/**
  * @}
  */

/** @defgroup TIM_ClearInput_Prescaler TIM Clear Input Prescaler
  * @{
  */
#define TIM_CLEARINPUTPRESCALER_DIV1                    TIM_ETRPRESCALER_DIV1      /*!< No prescaler is used */
#define TIM_CLEARINPUTPRESCALER_DIV2                    TIM_ETRPRESCALER_DIV2      /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */
#define TIM_CLEARINPUTPRESCALER_DIV4                    TIM_ETRPRESCALER_DIV4      /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */
#define TIM_CLEARINPUTPRESCALER_DIV8                    TIM_ETRPRESCALER_DIV8        /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */
/**
  * @}
  */

/** @defgroup TIM_OSSR_Off_State_Selection_for_Run_mode_state TIM OSSR OffState Selection for Run mode state
  * @{
  */  
#define TIM_OSSR_ENABLE 	      (TIM_BDTR_OSSR)
#define TIM_OSSR_DISABLE        ((uint32_t)0x0000)
/**
  * @}
  */
  
/** @defgroup TIM_OSSI_Off_State_Selection_for_Idle_mode_state TIM OSSI OffState Selection for Idle mode state
  * @{
  */
#define TIM_OSSI_ENABLE	 	    (TIM_BDTR_OSSI)
#define TIM_OSSI_DISABLE            ((uint32_t)0x0000)
/**
  * @}
  */
  
/** @defgroup TIM_Lock_level  TIM Lock level
  * @{
  */
#define TIM_LOCKLEVEL_OFF	   ((uint32_t)0x0000)
#define TIM_LOCKLEVEL_1            (TIM_BDTR_LOCK_0)
#define TIM_LOCKLEVEL_2            (TIM_BDTR_LOCK_1)
#define TIM_LOCKLEVEL_3            (TIM_BDTR_LOCK)
/**
  * @}
  */  
/** @defgroup TIM_Break_Input_enable_disable  TIM Break Input State
  * @{
  */                         
#define TIM_BREAK_ENABLE          (TIM_BDTR_BKE)
#define TIM_BREAK_DISABLE         ((uint32_t)0x0000)
/**
  * @}
  */
  
/** @defgroup TIM_Break_Polarity  TIM Break Polarity 
  * @{
  */
#define TIM_BREAKPOLARITY_LOW        ((uint32_t)0x0000)
#define TIM_BREAKPOLARITY_HIGH       (TIM_BDTR_BKP)
/**
  * @}
  */
  
/** @defgroup TIM_AOE_Bit_Set_Reset  TIM AOE Bit State
  * @{
  */
#define TIM_AUTOMATICOUTPUT_ENABLE           (TIM_BDTR_AOE)
#define	TIM_AUTOMATICOUTPUT_DISABLE          ((uint32_t)0x0000)
/**
  * @}
  */  
  
/** @defgroup TIM_Master_Mode_Selection TIM Master Mode Selection
  * @{
  */  
#define	TIM_TRGO_RESET            ((uint32_t)0x0000)             
#define	TIM_TRGO_ENABLE           (TIM_CR2_MMS_0)           
#define	TIM_TRGO_UPDATE           (TIM_CR2_MMS_1)             
#define	TIM_TRGO_OC1              ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0))    
#define	TIM_TRGO_OC1REF           (TIM_CR2_MMS_2)           
#define	TIM_TRGO_OC2REF           ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0))          
#define	TIM_TRGO_OC3REF           ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1))           
#define	TIM_TRGO_OC4REF           ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0))     
/**
  * @}
  */ 
  
/** @defgroup TIM_Slave_Mode TIM Slave Mode
  * @{
  */
#define TIM_SLAVEMODE_DISABLE              ((uint32_t)0x0000)
#define TIM_SLAVEMODE_RESET                ((uint32_t)0x0004)
#define TIM_SLAVEMODE_GATED                ((uint32_t)0x0005)
#define TIM_SLAVEMODE_TRIGGER              ((uint32_t)0x0006)
#define TIM_SLAVEMODE_EXTERNAL1            ((uint32_t)0x0007)
/**
  * @}
  */

/** @defgroup TIM_Master_Slave_Mode  TIM Master Slave Mode
  * @{
  */
#define TIM_MASTERSLAVEMODE_ENABLE          ((uint32_t)0x0080)
#define TIM_MASTERSLAVEMODE_DISABLE         ((uint32_t)0x0000)
/**
  * @}
  */ 
  
/** @defgroup TIM_Trigger_Selection  TIM Trigger Selection
  * @{
  */
#define TIM_TS_ITR0                        ((uint32_t)0x0000)
#define TIM_TS_ITR1                        ((uint32_t)0x0010)
#define TIM_TS_ITR2                        ((uint32_t)0x0020)
#define TIM_TS_ITR3                        ((uint32_t)0x0030)
#define TIM_TS_TI1F_ED                     ((uint32_t)0x0040)
#define TIM_TS_TI1FP1                      ((uint32_t)0x0050)
#define TIM_TS_TI2FP2                      ((uint32_t)0x0060)
#define TIM_TS_ETRF                        ((uint32_t)0x0070)
#define TIM_TS_NONE                        ((uint32_t)0xFFFF)
/**
  * @}
  */  

/** @defgroup TIM_Trigger_Polarity TIM Trigger Polarity
  * @{
  */
#define TIM_TRIGGERPOLARITY_INVERTED           TIM_ETRPOLARITY_INVERTED      /*!< Polarity for ETRx trigger sources */ 
#define TIM_TRIGGERPOLARITY_NONINVERTED        TIM_ETRPOLARITY_NONINVERTED   /*!< Polarity for ETRx trigger sources */ 
#define TIM_TRIGGERPOLARITY_RISING             TIM_INPUTCHANNELPOLARITY_RISING        /*!< Polarity for TIxFPx or TI1_ED trigger sources */ 
#define TIM_TRIGGERPOLARITY_FALLING            TIM_INPUTCHANNELPOLARITY_FALLING       /*!< Polarity for TIxFPx or TI1_ED trigger sources */ 
#define TIM_TRIGGERPOLARITY_BOTHEDGE           TIM_INPUTCHANNELPOLARITY_BOTHEDGE      /*!< Polarity for TIxFPx or TI1_ED trigger sources */ 
/**
  * @}
  */

/** @defgroup TIM_Trigger_Prescaler TIM Trigger Prescaler
  * @{
  */
#define TIM_TRIGGERPRESCALER_DIV1             TIM_ETRPRESCALER_DIV1     /*!< No prescaler is used */
#define TIM_TRIGGERPRESCALER_DIV2             TIM_ETRPRESCALER_DIV2     /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */
#define TIM_TRIGGERPRESCALER_DIV4             TIM_ETRPRESCALER_DIV4     /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */
#define TIM_TRIGGERPRESCALER_DIV8             TIM_ETRPRESCALER_DIV8     /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */
/**
  * @}
  */


/** @defgroup TIM_TI1_Selection TIM TI1 Selection
  * @{
  */
#define TIM_TI1SELECTION_CH1                ((uint32_t)0x0000)
#define TIM_TI1SELECTION_XORCOMBINATION     (TIM_CR2_TI1S)
/**
  * @}
  */ 

/** @defgroup TIM_DMA_Base_address  TIM DMA Base address
  * @{
  */
#define TIM_DMABASE_CR1                    (0x00000000)
#define TIM_DMABASE_CR2                    (0x00000001)
#define TIM_DMABASE_SMCR                   (0x00000002)
#define TIM_DMABASE_DIER                   (0x00000003)
#define TIM_DMABASE_SR                     (0x00000004)
#define TIM_DMABASE_EGR                    (0x00000005)
#define TIM_DMABASE_CCMR1                  (0x00000006)
#define TIM_DMABASE_CCMR2                  (0x00000007)
#define TIM_DMABASE_CCER                   (0x00000008)
#define TIM_DMABASE_CNT                    (0x00000009)
#define TIM_DMABASE_PSC                    (0x0000000A)
#define TIM_DMABASE_ARR                    (0x0000000B)
#define TIM_DMABASE_RCR                    (0x0000000C)
#define TIM_DMABASE_CCR1                   (0x0000000D)
#define TIM_DMABASE_CCR2                   (0x0000000E)
#define TIM_DMABASE_CCR3                   (0x0000000F)
#define TIM_DMABASE_CCR4                   (0x00000010)
#define TIM_DMABASE_BDTR                   (0x00000011)
#define TIM_DMABASE_DCR                    (0x00000012)
#define TIM_DMABASE_OR                     (0x00000013)
/**
  * @}
  */ 

/** @defgroup TIM_DMA_Burst_Length  TIM DMA Burst Length 
  * @{
  */
#define TIM_DMABURSTLENGTH_1TRANSFER           (0x00000000)
#define TIM_DMABURSTLENGTH_2TRANSFERS          (0x00000100)
#define TIM_DMABURSTLENGTH_3TRANSFERS          (0x00000200)
#define TIM_DMABURSTLENGTH_4TRANSFERS          (0x00000300)
#define TIM_DMABURSTLENGTH_5TRANSFERS          (0x00000400)
#define TIM_DMABURSTLENGTH_6TRANSFERS          (0x00000500)
#define TIM_DMABURSTLENGTH_7TRANSFERS          (0x00000600)
#define TIM_DMABURSTLENGTH_8TRANSFERS          (0x00000700)
#define TIM_DMABURSTLENGTH_9TRANSFERS          (0x00000800)
#define TIM_DMABURSTLENGTH_10TRANSFERS         (0x00000900)
#define TIM_DMABURSTLENGTH_11TRANSFERS         (0x00000A00)
#define TIM_DMABURSTLENGTH_12TRANSFERS         (0x00000B00)
#define TIM_DMABURSTLENGTH_13TRANSFERS         (0x00000C00)
#define TIM_DMABURSTLENGTH_14TRANSFERS         (0x00000D00)
#define TIM_DMABURSTLENGTH_15TRANSFERS         (0x00000E00)
#define TIM_DMABURSTLENGTH_16TRANSFERS         (0x00000F00)
#define TIM_DMABURSTLENGTH_17TRANSFERS         (0x00001000)
#define TIM_DMABURSTLENGTH_18TRANSFERS         (0x00001100)
/**
  * @}
  */

/** @defgroup DMA_Handle_index  DMA Handle index
  * @{
  */
#define TIM_DMA_ID_UPDATE                ((uint16_t) 0x0)       /*!< Index of the DMA handle used for Update DMA requests */
#define TIM_DMA_ID_CC1                   ((uint16_t) 0x1)       /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */
#define TIM_DMA_ID_CC2                   ((uint16_t) 0x2)       /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */
#define TIM_DMA_ID_CC3                   ((uint16_t) 0x3)       /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */
#define TIM_DMA_ID_CC4                   ((uint16_t) 0x4)       /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */
#define TIM_DMA_ID_COMMUTATION           ((uint16_t) 0x5)       /*!< Index of the DMA handle used for Commutation DMA requests */
#define TIM_DMA_ID_TRIGGER               ((uint16_t) 0x6)       /*!< Index of the DMA handle used for Trigger DMA requests */
/**
  * @}
  */ 

/** @defgroup Channel_CC_State  Channel CC State
  * @{
  */
#define TIM_CCx_ENABLE                   ((uint32_t)0x0001)
#define TIM_CCx_DISABLE                  ((uint32_t)0x0000)
#define TIM_CCxN_ENABLE                  ((uint32_t)0x0004)
#define TIM_CCxN_DISABLE                 ((uint32_t)0x0000)
/**
  * @}
  */ 

/**
  * @}
  */   
  
/* Exported macro ------------------------------------------------------------*/
/** @defgroup TIM_Exported_Macros TIM Exported Macros
  * @{
  */
/** @brief Reset TIM handle state
  * @param  __HANDLE__: TIM handle
  * @retval None
  */
#define __HAL_TIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TIM_STATE_RESET)

/**
  * @brief  Enable the TIM peripheral.
  * @param  __HANDLE__: TIM handle
  * @retval None
 */
#define __HAL_TIM_ENABLE(__HANDLE__)                 ((__HANDLE__)->Instance->CR1|=(TIM_CR1_CEN))

/**
  * @brief  Enable the TIM main Output.
  * @param  __HANDLE__: TIM handle
  * @retval None
  */
#define __HAL_TIM_MOE_ENABLE(__HANDLE__)             ((__HANDLE__)->Instance->BDTR|=(TIM_BDTR_MOE))


/**
  * @brief  Disable the TIM peripheral.
  * @param  __HANDLE__: TIM handle
  * @retval None
  */
#define __HAL_TIM_DISABLE(__HANDLE__) \
                        do { \
                          if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \
                          { \
                            if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \
                            { \
                              (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \
                            } \
                          } \
                        } while(0)

/* The Main Output of a timer instance is disabled only if all the CCx and CCxN
   channels have been disabled */
/**
  * @brief  Disable the TIM main Output.
  * @param  __HANDLE__: TIM handle
  * @retval None
  */
#define __HAL_TIM_MOE_DISABLE(__HANDLE__) \
                        do { \
                          if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \
                          { \
                            if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \
                            { \
                              (__HANDLE__)->Instance->BDTR &= ~(TIM_BDTR_MOE); \
                            } \
                          } \
                        } while(0)

#define __HAL_TIM_ENABLE_IT(__HANDLE__, __INTERRUPT__)    ((__HANDLE__)->Instance->DIER |= (__INTERRUPT__))
#define __HAL_TIM_ENABLE_DMA(__HANDLE__, __DMA__)         ((__HANDLE__)->Instance->DIER |= (__DMA__))
#define __HAL_TIM_DISABLE_IT(__HANDLE__, __INTERRUPT__)   ((__HANDLE__)->Instance->DIER &= ~(__INTERRUPT__))
#define __HAL_TIM_DISABLE_DMA(__HANDLE__, __DMA__)        ((__HANDLE__)->Instance->DIER &= ~(__DMA__))
#define __HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__)          (((__HANDLE__)->Instance->SR &(__FLAG__)) == (__FLAG__))
#define __HAL_TIM_CLEAR_FLAG(__HANDLE__, __FLAG__)        ((__HANDLE__)->Instance->SR = ~(__FLAG__))

#define __HAL_TIM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET)
#define __HAL_TIM_CLEAR_IT(__HANDLE__, __INTERRUPT__)     ((__HANDLE__)->Instance->SR = ~(__INTERRUPT__))

#define __HAL_TIM_IS_TIM_COUNTING_DOWN(__HANDLE__)            (((__HANDLE__)->Instance->CR1 &(TIM_CR1_DIR)) == (TIM_CR1_DIR))
#define __HAL_TIM_SET_PRESCALER(__HANDLE__, __PRESC__)       ((__HANDLE__)->Instance->PSC = (__PRESC__))

#define TIM_SET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__, __ICPSC__) \
(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\
 ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\
 ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\
 ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8)))

#define TIM_RESET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__) \
(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC1PSC) :\
 ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC2PSC) :\
 ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC3PSC) :\
 ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC4PSC))

#define TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \
(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER |= (__POLARITY__)) :\
 ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 4)) :\
 ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 8)) :\
 ((__HANDLE__)->Instance->CCER |= (((__POLARITY__) << 12) & TIM_CCER_CC4P)))

#define TIM_RESET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__) \
(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP)) :\
 ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC2P | TIM_CCER_CC2NP)) :\
 ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC3P | TIM_CCER_CC3NP)) :\
 ((__HANDLE__)->Instance->CCER &= (uint16_t)~TIM_CCER_CC4P))

/**
  * @brief  Sets the TIM Capture Compare Register value on runtime without
  *         calling another time ConfigChannel function.
  * @param  __HANDLE__: TIM handle.
  * @param  __CHANNEL__ : TIM Channels to be configured.
  *          This parameter can be one of the following values:
  *            @arg TIM_CHANNEL_1: TIM Channel 1 selected
  *            @arg TIM_CHANNEL_2: TIM Channel 2 selected
  *            @arg TIM_CHANNEL_3: TIM Channel 3 selected
  *            @arg TIM_CHANNEL_4: TIM Channel 4 selected
  * @param  __COMPARE__: specifies the Capture Compare register new value.
  * @retval None
  */
#define __HAL_TIM_SET_COMPARE(__HANDLE__, __CHANNEL__, __COMPARE__) \
(*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__))

/**
  * @brief  Gets the TIM Capture Compare Register value on runtime
  * @param  __HANDLE__: TIM handle.
  * @param  __CHANNEL__ : TIM Channel associated with the capture compare register
  *          This parameter can be one of the following values:
  *            @arg TIM_CHANNEL_1: get capture/compare 1 register value
  *            @arg TIM_CHANNEL_2: get capture/compare 2 register value
  *            @arg TIM_CHANNEL_3: get capture/compare 3 register value
  *            @arg TIM_CHANNEL_4: get capture/compare 4 register value
  * @retval None
  */
#define __HAL_TIM_GET_COMPARE(__HANDLE__, __CHANNEL__) \
  (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)))

/**
  * @brief  Sets the TIM Counter Register value on runtime.
  * @param  __HANDLE__: TIM handle.
  * @param  __COUNTER__: specifies the Counter register new value.
  * @retval None
  */
#define __HAL_TIM_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__))

/**
  * @brief  Gets the TIM Counter Register value on runtime.
  * @param  __HANDLE__: TIM handle.
  * @retval None
  */
#define __HAL_TIM_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->CNT)

/**
  * @brief  Sets the TIM Autoreload Register value on runtime without calling 
  *         another time any Init function.
  * @param  __HANDLE__: TIM handle.
  * @param  __AUTORELOAD__: specifies the Counter register new value.
  * @retval None
  */
#define __HAL_TIM_SET_AUTORELOAD(__HANDLE__, __AUTORELOAD__)                  \
                        do{                                                  \
                            (__HANDLE__)->Instance->ARR = (__AUTORELOAD__);  \
                            (__HANDLE__)->Init.Period = (__AUTORELOAD__);    \
                          } while(0)
/**
  * @brief  Gets the TIM Autoreload Register value on runtime
  * @param  __HANDLE__: TIM handle.
  * @retval None
  */
#define __HAL_TIM_GET_AUTORELOAD(__HANDLE__) ((__HANDLE__)->Instance->ARR)

/**
  * @brief  Sets the TIM Clock Division value on runtime without calling 
  *         another time any Init function. 
  * @param  __HANDLE__: TIM handle.
  * @param  __CKD__: specifies the clock division value.
  *          This parameter can be one of the following value:
  *            @arg TIM_CLOCKDIVISION_DIV1
  *            @arg TIM_CLOCKDIVISION_DIV2
  *            @arg TIM_CLOCKDIVISION_DIV4
  * @retval None
  */
#define __HAL_TIM_SET_CLOCKDIVISION(__HANDLE__, __CKD__) \
                        do{                                                             \
                              (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CKD);  \
                              (__HANDLE__)->Instance->CR1 |= (__CKD__);                 \
                              (__HANDLE__)->Init.ClockDivision = (__CKD__);             \
                          } while(0)
/**
  * @brief  Gets the TIM Clock Division value on runtime
  * @param  __HANDLE__: TIM handle.
  * @retval None
  */
#define __HAL_TIM_GET_CLOCKDIVISION(__HANDLE__) ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD)

/**
  * @brief  Sets the TIM Input Capture prescaler on runtime without calling 
  *         another time HAL_TIM_IC_ConfigChannel() function.
  * @param  __HANDLE__: TIM handle.
  * @param  __CHANNEL__ : TIM Channels to be configured.
  *          This parameter can be one of the following values:
  *            @arg TIM_CHANNEL_1: TIM Channel 1 selected
  *            @arg TIM_CHANNEL_2: TIM Channel 2 selected
  *            @arg TIM_CHANNEL_3: TIM Channel 3 selected
  *            @arg TIM_CHANNEL_4: TIM Channel 4 selected
  * @param  __ICPSC__: specifies the Input Capture4 prescaler new value.
  *          This parameter can be one of the following values:
  *            @arg TIM_ICPSC_DIV1: no prescaler
  *            @arg TIM_ICPSC_DIV2: capture is done once every 2 events
  *            @arg TIM_ICPSC_DIV4: capture is done once every 4 events
  *            @arg TIM_ICPSC_DIV8: capture is done once every 8 events
  * @retval None
  */
#define __HAL_TIM_SET_ICPRESCALER(__HANDLE__, __CHANNEL__, __ICPSC__) \
                        do{                                                    \
                              TIM_RESET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__));  \
                              TIM_SET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \
                          } while(0)

/**
  * @brief  Gets the TIM Input Capture prescaler on runtime
  * @param  __HANDLE__: TIM handle.
  * @param  __CHANNEL__ : TIM Channels to be configured.
  *          This parameter can be one of the following values:
  *            @arg TIM_CHANNEL_1: get input capture 1 prescaler value
  *            @arg TIM_CHANNEL_2: get input capture 2 prescaler value
  *            @arg TIM_CHANNEL_3: get input capture 3 prescaler value
  *            @arg TIM_CHANNEL_4: get input capture 4 prescaler value
  * @retval None
  */
#define __HAL_TIM_GET_ICPRESCALER(__HANDLE__, __CHANNEL__)  \
  (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\
   ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\
   ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\
   (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8)
    
/**
  * @brief  Set the Update Request Source (URS) bit of the TIMx_CR1 register
  * @param  __HANDLE__: TIM handle.
  * @note  When the USR bit of the TIMx_CR1 register is set, only counter 
  *        overflow/underflow generates an update interrupt or DMA request (if
  *        enabled)
  * @retval None
  */
#define __HAL_TIM_URS_ENABLE(__HANDLE__) \
    ((__HANDLE__)->Instance->CR1|= (TIM_CR1_URS))

/**
  * @brief  Reset the Update Request Source (URS) bit of the TIMx_CR1 register
  * @param  __HANDLE__: TIM handle.
  * @note  When the USR bit of the TIMx_CR1 register is reset, any of the 
  *        following events generate an update interrupt or DMA request (if 
  *        enabled):
  *          � Counter overflow/underflow
  *          � Setting the UG bit
  *          � Update generation through the slave mode controller
  * @retval None
  */
#define __HAL_TIM_URS_DISABLE(__HANDLE__) \
      ((__HANDLE__)->Instance->CR1&=~(TIM_CR1_URS))

/**
  * @brief  Sets the TIM Capture x input polarity on runtime.
  * @param  __HANDLE__: TIM handle.
  * @param  __CHANNEL__: TIM Channels to be configured.
  *          This parameter can be one of the following values:
  *            @arg TIM_CHANNEL_1: TIM Channel 1 selected
  *            @arg TIM_CHANNEL_2: TIM Channel 2 selected
  *            @arg TIM_CHANNEL_3: TIM Channel 3 selected
  *            @arg TIM_CHANNEL_4: TIM Channel 4 selected
  * @param  __POLARITY__: Polarity for TIx source   
  *            @arg TIM_INPUTCHANNELPOLARITY_RISING: Rising Edge
  *            @arg TIM_INPUTCHANNELPOLARITY_FALLING: Falling Edge
  *            @arg TIM_INPUTCHANNELPOLARITY_BOTHEDGE: Rising and Falling Edge
  * @note  The polarity TIM_INPUTCHANNELPOLARITY_BOTHEDGE is not authorized  for TIM Channel 4.     
  * @retval None
  */
#define __HAL_TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__)                          \
                       do{                                                                            \
                           TIM_RESET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__));               \
                           TIM_SET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__), (__POLARITY__)); \
                         }while(0)
/**
  * @}
  */

/* Include TIM HAL Extension module */
#include "stm32f4xx_hal_tim_ex.h"

/* Exported functions --------------------------------------------------------*/
/** @addtogroup TIM_Exported_Functions
  * @{
  */

/** @addtogroup TIM_Exported_Functions_Group1
  * @{
  */

/* Time Base functions ********************************************************/
HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim);
HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim);
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim);
void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim);
/* Blocking mode: Polling */
HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim);
HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim);
/* Non-Blocking mode: Interrupt */
HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim);
HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim);
/* Non-Blocking mode: DMA */
HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length);
HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim);
/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group2
  * @{
  */
/* Timer Output Compare functions **********************************************/
HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim);
HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim);
void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim);
void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim);
/* Blocking mode: Polling */
HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: Interrupt */
HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: DMA */
HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length);
HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group3
  * @{
  */
/* Timer PWM functions *********************************************************/
HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim);
HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim);
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim);
void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim);
/* Blocking mode: Polling */
HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: Interrupt */
HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: DMA */
HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length);
HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group4
  * @{
  */
/* Timer Input Capture functions ***********************************************/
HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim);
HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim);
void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim);
void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim);
/* Blocking mode: Polling */
HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: Interrupt */
HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: DMA */
HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length);
HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group5
  * @{
  */
/* Timer One Pulse functions ***************************************************/
HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode);
HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim);
void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim);
void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim);
/* Blocking mode: Polling */
HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel);
HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel);

/* Non-Blocking mode: Interrupt */
HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel);
HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group6
  * @{
  */
/* Timer Encoder functions *****************************************************/
HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim,  TIM_Encoder_InitTypeDef* sConfig);
HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim);
void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim);
void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim);
 /* Blocking mode: Polling */
HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: Interrupt */
HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel);
/* Non-Blocking mode: DMA */
HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length);
HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group7
  * @{
  */
/* Interrupt Handler functions  **********************************************/
void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group8
  * @{
  */
/* Control functions  *********************************************************/
HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel,  uint32_t InputChannel);
HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel);
HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig);    
HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection);
HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig);
HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig);
HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \
                                              uint32_t  *BurstBuffer, uint32_t  BurstLength);
HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc);
HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \
                                              uint32_t  *BurstBuffer, uint32_t  BurstLength);
HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc);
HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource);
uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group9
  * @{
  */
/* Callback in non blocking modes (Interrupt and DMA) *************************/
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim);
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim);
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim);
void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim);
void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim);

/**
  * @}
  */

/** @addtogroup TIM_Exported_Functions_Group10
  * @{
  */
/* Peripheral State functions  **************************************************/
HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim);
HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim);
HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim);
HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim);
HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim);
HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim);

/**
  * @}
  */
  
/**
  * @}
  */
  
/* Private macros ------------------------------------------------------------*/
/** @defgroup TIM_Private_Macros TIM Private Macros
  * @{
  */

/** @defgroup TIM_IS_TIM_Definitions TIM Private macros to check input parameters
  * @{
  */
#define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_COUNTERMODE_UP)              || \
                                   ((MODE) == TIM_COUNTERMODE_DOWN)            || \
                                   ((MODE) == TIM_COUNTERMODE_CENTERALIGNED1)  || \
                                   ((MODE) == TIM_COUNTERMODE_CENTERALIGNED2)  || \
                                   ((MODE) == TIM_COUNTERMODE_CENTERALIGNED3))

#define IS_TIM_CLOCKDIVISION_DIV(DIV) (((DIV) == TIM_CLOCKDIVISION_DIV1) || \
                                       ((DIV) == TIM_CLOCKDIVISION_DIV2) || \
                                       ((DIV) == TIM_CLOCKDIVISION_DIV4))

#define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \
                               ((MODE) == TIM_OCMODE_PWM2))
                              
#define IS_TIM_OC_MODE(MODE) (((MODE) == TIM_OCMODE_TIMING)       || \
                          ((MODE) == TIM_OCMODE_ACTIVE)           || \
                          ((MODE) == TIM_OCMODE_INACTIVE)         || \
                          ((MODE) == TIM_OCMODE_TOGGLE)           || \
                          ((MODE) == TIM_OCMODE_FORCED_ACTIVE)    || \
                          ((MODE) == TIM_OCMODE_FORCED_INACTIVE))

#define IS_TIM_FAST_STATE(STATE) (((STATE) == TIM_OCFAST_DISABLE) || \
                                  ((STATE) == TIM_OCFAST_ENABLE))

#define IS_TIM_OC_POLARITY(POLARITY) (((POLARITY) == TIM_OCPOLARITY_HIGH) || \
                                      ((POLARITY) == TIM_OCPOLARITY_LOW))

#define IS_TIM_OCN_POLARITY(POLARITY) (((POLARITY) == TIM_OCNPOLARITY_HIGH) || \
                                       ((POLARITY) == TIM_OCNPOLARITY_LOW))

#define IS_TIM_OCIDLE_STATE(STATE) (((STATE) == TIM_OCIDLESTATE_SET) || \
                                    ((STATE) == TIM_OCIDLESTATE_RESET))

#define IS_TIM_OCNIDLE_STATE(STATE) (((STATE) == TIM_OCNIDLESTATE_SET) || \
                                    ((STATE) == TIM_OCNIDLESTATE_RESET))

#define IS_TIM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \
                                  ((CHANNEL) == TIM_CHANNEL_2) || \
                                  ((CHANNEL) == TIM_CHANNEL_3) || \
                                  ((CHANNEL) == TIM_CHANNEL_4) || \
                                  ((CHANNEL) == TIM_CHANNEL_ALL))

#define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \
                                      ((CHANNEL) == TIM_CHANNEL_2))
                                      
#define IS_TIM_COMPLEMENTARY_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \
                                                ((CHANNEL) == TIM_CHANNEL_2) || \
                                                ((CHANNEL) == TIM_CHANNEL_3))

#define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING)   || \
                                      ((POLARITY) == TIM_ICPOLARITY_FALLING)  || \
                                      ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE))

#define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \
                                        ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \
                                        ((SELECTION) == TIM_ICSELECTION_TRC))

#define IS_TIM_IC_PRESCALER(PRESCALER) (((PRESCALER) == TIM_ICPSC_DIV1) || \
                                        ((PRESCALER) == TIM_ICPSC_DIV2) || \
                                        ((PRESCALER) == TIM_ICPSC_DIV4) || \
                                        ((PRESCALER) == TIM_ICPSC_DIV8))

#define IS_TIM_OPM_MODE(MODE) (((MODE) == TIM_OPMODE_SINGLE) || \
                               ((MODE) == TIM_OPMODE_REPETITIVE))

#define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FF) == 0x00000000) && ((SOURCE) != 0x00000000))
                           
#define IS_TIM_ENCODER_MODE(MODE) (((MODE) == TIM_ENCODERMODE_TI1) || \
                                   ((MODE) == TIM_ENCODERMODE_TI2) || \
                                   ((MODE) == TIM_ENCODERMODE_TI12))

#define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00) == 0x00000000) && ((SOURCE) != 0x00000000))
                           
#define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_ITR0)     || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_ITR1)     || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_ITR2)     || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_ITR3)     || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_TI1ED)    || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_TI1)      || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_TI2)      || \
                                   ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE1))

#define IS_TIM_CLOCKPOLARITY(POLARITY) (((POLARITY) == TIM_CLOCKPOLARITY_INVERTED)    || \
                                        ((POLARITY) == TIM_CLOCKPOLARITY_NONINVERTED) || \
                                        ((POLARITY) == TIM_CLOCKPOLARITY_RISING)      || \
                                        ((POLARITY) == TIM_CLOCKPOLARITY_FALLING)     || \
                                        ((POLARITY) == TIM_CLOCKPOLARITY_BOTHEDGE))

#define IS_TIM_CLOCKPRESCALER(PRESCALER) (((PRESCALER) == TIM_CLOCKPRESCALER_DIV1) || \
                                          ((PRESCALER) == TIM_CLOCKPRESCALER_DIV2) || \
                                          ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \
                                          ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8))

#define IS_TIM_CLOCKFILTER(ICFILTER)      ((ICFILTER) <= 0xF) 
                           
#define IS_TIM_CLEARINPUT_SOURCE(SOURCE)  (((SOURCE) == TIM_CLEARINPUTSOURCE_NONE) || \
                                         ((SOURCE) == TIM_CLEARINPUTSOURCE_ETR)) 

#define IS_TIM_CLEARINPUT_POLARITY(POLARITY)   (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \
                                               ((POLARITY) == TIM_CLEARINPUTPOLARITY_NONINVERTED))

#define IS_TIM_CLEARINPUT_PRESCALER(PRESCALER)   (((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV1) || \
                                                 ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV2) || \
                                                 ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \
                                                 ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8))

#define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) 
                          
#define IS_TIM_OSSR_STATE(STATE) (((STATE) == TIM_OSSR_ENABLE) || \
                                  ((STATE) == TIM_OSSR_DISABLE))

#define IS_TIM_OSSI_STATE(STATE) (((STATE) == TIM_OSSI_ENABLE) || \
                                  ((STATE) == TIM_OSSI_DISABLE))

#define IS_TIM_LOCK_LEVEL(LEVEL) (((LEVEL) == TIM_LOCKLEVEL_OFF) || \
                                  ((LEVEL) == TIM_LOCKLEVEL_1) || \
                                  ((LEVEL) == TIM_LOCKLEVEL_2) || \
                                  ((LEVEL) == TIM_LOCKLEVEL_3))

#define IS_TIM_BREAK_STATE(STATE) (((STATE) == TIM_BREAK_ENABLE) || \
                                   ((STATE) == TIM_BREAK_DISABLE))

#define IS_TIM_BREAK_POLARITY(POLARITY) (((POLARITY) == TIM_BREAKPOLARITY_LOW) || \
                                         ((POLARITY) == TIM_BREAKPOLARITY_HIGH))

#define IS_TIM_AUTOMATIC_OUTPUT_STATE(STATE) (((STATE) == TIM_AUTOMATICOUTPUT_ENABLE) || \
                                              ((STATE) == TIM_AUTOMATICOUTPUT_DISABLE))

#define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \
                                    ((SOURCE) == TIM_TRGO_ENABLE) || \
                                    ((SOURCE) == TIM_TRGO_UPDATE) || \
                                    ((SOURCE) == TIM_TRGO_OC1) || \
                                    ((SOURCE) == TIM_TRGO_OC1REF) || \
                                    ((SOURCE) == TIM_TRGO_OC2REF) || \
                                    ((SOURCE) == TIM_TRGO_OC3REF) || \
                                    ((SOURCE) == TIM_TRGO_OC4REF))

#define IS_TIM_SLAVE_MODE(MODE) (((MODE) == TIM_SLAVEMODE_DISABLE) || \
                                 ((MODE) == TIM_SLAVEMODE_GATED) || \
                                 ((MODE) == TIM_SLAVEMODE_RESET) || \
                                 ((MODE) == TIM_SLAVEMODE_TRIGGER) || \
                                 ((MODE) == TIM_SLAVEMODE_EXTERNAL1))

#define IS_TIM_MSM_STATE(STATE) (((STATE) == TIM_MASTERSLAVEMODE_ENABLE) || \
                                 ((STATE) == TIM_MASTERSLAVEMODE_DISABLE))

#define IS_TIM_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \
                                             ((SELECTION) == TIM_TS_ITR1) || \
                                             ((SELECTION) == TIM_TS_ITR2) || \
                                             ((SELECTION) == TIM_TS_ITR3) || \
                                             ((SELECTION) == TIM_TS_TI1F_ED) || \
                                             ((SELECTION) == TIM_TS_TI1FP1) || \
                                             ((SELECTION) == TIM_TS_TI2FP2) || \
                                             ((SELECTION) == TIM_TS_ETRF))

#define IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \
                                                           ((SELECTION) == TIM_TS_ITR1) || \
                                                           ((SELECTION) == TIM_TS_ITR2) || \
                                                           ((SELECTION) == TIM_TS_ITR3) || \
                                                           ((SELECTION) == TIM_TS_NONE))                           
#define IS_TIM_TRIGGERPOLARITY(POLARITY)     (((POLARITY) == TIM_TRIGGERPOLARITY_INVERTED   ) || \
                                              ((POLARITY) == TIM_TRIGGERPOLARITY_NONINVERTED) || \
                                              ((POLARITY) == TIM_TRIGGERPOLARITY_RISING     ) || \
                                              ((POLARITY) == TIM_TRIGGERPOLARITY_FALLING    ) || \
                                              ((POLARITY) == TIM_TRIGGERPOLARITY_BOTHEDGE   ))

#define IS_TIM_TRIGGERPRESCALER(PRESCALER)  (((PRESCALER) == TIM_TRIGGERPRESCALER_DIV1) || \
                                             ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV2) || \
                                             ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \
                                             ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8))

#define IS_TIM_TRIGGERFILTER(ICFILTER)     ((ICFILTER) <= 0xF) 
                          
#define IS_TIM_TI1SELECTION(TI1SELECTION)   (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \
                                             ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION))

#define IS_TIM_DMA_BASE(BASE) (((BASE) == TIM_DMABASE_CR1) || \
                               ((BASE) == TIM_DMABASE_CR2) || \
                               ((BASE) == TIM_DMABASE_SMCR) || \
                               ((BASE) == TIM_DMABASE_DIER) || \
                               ((BASE) == TIM_DMABASE_SR) || \
                               ((BASE) == TIM_DMABASE_EGR) || \
                               ((BASE) == TIM_DMABASE_CCMR1) || \
                               ((BASE) == TIM_DMABASE_CCMR2) || \
                               ((BASE) == TIM_DMABASE_CCER) || \
                               ((BASE) == TIM_DMABASE_CNT) || \
                               ((BASE) == TIM_DMABASE_PSC) || \
                               ((BASE) == TIM_DMABASE_ARR) || \
                               ((BASE) == TIM_DMABASE_RCR) || \
                               ((BASE) == TIM_DMABASE_CCR1) || \
                               ((BASE) == TIM_DMABASE_CCR2) || \
                               ((BASE) == TIM_DMABASE_CCR3) || \
                               ((BASE) == TIM_DMABASE_CCR4) || \
                               ((BASE) == TIM_DMABASE_BDTR) || \
                               ((BASE) == TIM_DMABASE_DCR) || \
                               ((BASE) == TIM_DMABASE_OR))
                           
#define IS_TIM_DMA_LENGTH(LENGTH) (((LENGTH) == TIM_DMABURSTLENGTH_1TRANSFER) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_2TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_3TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_4TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_5TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_6TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_7TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_8TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_9TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_10TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_11TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_12TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_13TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_14TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_15TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_16TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_17TRANSFERS) || \
                                   ((LENGTH) == TIM_DMABURSTLENGTH_18TRANSFERS))                           

#define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF)                            
/**
  * @}
  */ 

/** @defgroup TIM_Mask_Definitions TIM Mask Definition
  * @{
  */  
/* The counter of a timer instance is disabled only if all the CCx and CCxN
   channels have been disabled */
#define TIM_CCER_CCxE_MASK  ((uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E))
#define TIM_CCER_CCxNE_MASK ((uint32_t)(TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE))
/**
  * @}
  */
  
/**
  * @}
  */

/* Private functions ---------------------------------------------------------*/
/** @defgroup TIM_Private_Functions TIM Private Functions
  * @{
  */
void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure);
void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter);
void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma);
void TIM_DMAError(DMA_HandleTypeDef *hdma);
void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma);
void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState);  
/**
  * @}
  */ 
      
/**
  * @}
  */ 

/**
  * @}
  */ 
  
#ifdef __cplusplus
}
#endif

#endif /* __STM32F4xx_HAL_TIM_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
6'>1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
  


           

                                                                      


                            


















                                                                       
                                                                   



                                                                   





                                             
                   

                   
                
















                                                                           
 
                       
                       









                                                                     
                                          











                                                               


                     
                 
                         


                    
                         

      
  






                                              











                                                    

                   


                  



                    






                    




                                                                      
  





                                                                     
  



                                                                      

   







                                                                           
                             





                                                                  








































                                                                               








                                                                      






















                                                                     



                                                                  






                                                                     

   

                






                                                                         


















                                                                         
                                                    






                                     
  
                                   

   
             
 
                                                                                                                   


                    
                                                                                      
           

 
                                                                             
 
                      
 


                                              



  































                                                                                       




                                                 

             





                                                 




                                            
                






















                                                        
   





















































































                                                               
                         



  



                                                                      
  



                                                                      

   
                         
 

                                      
 

                                  
 
                         
 

                                                                  
 

                                       
 






                                                                  
 
                                      

   

                      




































































































































































                                                                                   
 













                                                        

     









                                                                                                                            

      









































                                                                                                                       


                                                                 

   



                                                








                                                                                                                 
                                     


                                                                     
                                     


                                                                                 
                                    


















































































                                                                                                             



                                                            




















                                                                                       
                                                                 










                                                                                                      









                                                                  



                                                                        

                                                                  


























                                                                  






                                                                                                  
             




































































                                                                                    

                                                







                                                                          

                                                                          

                                                                          


                                                                          









                                                                          

                                                                          


                                                                          


                                                                          



















































                                                                                            
 






















                                                                                                                  
                            
  




                                                                      

   

                                                                               
 

                                  

                                     

                                                                                       
 
                                                                                  
                                                                            
                                                


                         


                                                                                  

                                                                                  

                                                            
                                                                                  

                                                                                  
                                                                                  

                                                                                  

              


         
                                      




                      
                            
  


                                                                  
  
                                                         

   


                                                                                   
 

                                                                                                   
 




                                                                            

    
                                               

     





                                                                  
 









                                                           

                                   
 










                                                                                              

 







































                                                                                                         















                                                    











                                                    
                                               
































































                                                                              





                                                                       





                                                            


                                      


















                                                                  

   

                                                 

                                         


                                           

                         










                                     





































































































                                                                                                                          




                                                                                                   




















































                                                                                                               


                                                                


















                                                                      
  
                                                        
  

                                                                      










                                                                                            





























                                                                                                          










                                                                                                           










                                                                     








                                                                                                   
                                                                              

































                                                                                                 



                                          

                               
                               
                       













                                                                                                                      
                                                               

                                                              






                                                                
     
                                                                    
      








                                                                   
                                                                                  










                                                                 
     
                                                                     
      








                                                                    



     

                                                                    
     
                                                                    


                                   
                                                          

     










                                                                                                  
                                                                         
                                                                                                  



                                                                                                  

                              
                         
















                                                  
                                    






                            
  
















































































                                                                                             

                                                                 








                                                           














                                                                                           
                                                                           

                             









                                                                                           







































                                                                                             
 







                                         

                                      
                                         
                          

           



































                                                                      
                  




                                                               


                                 
                                                                    





                                                              



                                                                     

       







                                                   
                




                                             

                          
     


    












                                                                     








                                                                
                  
                            
 



                             



                







                                       

                                    

                    


                             
                                                 
 










                                  
                            

    











                                                                   



                                                                

                                           


                                                                      

                                                                




















                                                       

                                       

                                               
                                                    


















                                             

                                        



                                                                        









                                                                    















































































                                                                      

                                       




                                                                 
                                                 
 


























                                                                                       
   








                                         


                                                      




                               
                                        




                                                

                                        

           
                                                 
 
                                    
 
                                                    



                                           

                                            


                                      
                                                 
 

                           
                                        






                                         

                                 
                                        
                                                                 
 
                         

                         
                    
 
                                                 
 
                   
                            







                                                                      
                                     

    




                                                                    
                                     

    
                                         
                                                  
    



                                                                     




                      

                                                                          
                                           






                                        

    



                                                                       

     





















                                                                             
 
   















                                                                              
                              
   

    

                                                                     






















                                                                                        
      
                      
                                                    



                                          

                                  
                         
                    
 
                                                 
 






                                                                      
                                     
 

                                    




























                                                                          
      
                                                    




                                                 

                                         



                                                  


                                                                                            
 
                         
                         

                    
                                                 

                                       



                                                                                          

                                                                  


                                                                  

                              

                                                                  




                                       
                                                    






                                                     

                                             





                                                                      
                         





                                            
           

             
                                                 
 


                            

                                       



























                                                                                         

              

































                                                                                        
                                                    





                                                   

                                           





























                                                                                        
                         



                                      
                                                 

                                                     































                                                                                            






                                                                      


                                                                  


                                                                  



                                                                  


                              


                                                                    


                                          




                                                                  

























                                                                                
                              




                               
                                                    






                                                  

                                       
                         


                         
                                                 

                                                     





































                                                                                           
                                                    



                                                    

                                            


                                            
                         

                         
 
                                                 

                                                     








                                               

                                                                          




                                       
                                                    




                                               

                                      
                         
                    
 
                                                 


                                                     

                         
                            
 
                                         
                               

                                  



                                                                            
                                                    

   



                                                                      
 
                                        

      
                                                    







                                          

                                  

                         
 
                                                 


                                                     

                                            
                            
 
                                         
                                        
 
                                                                                                 
 
                                                            
 

                                          
 
                                 

                               


                                                                    
 





                                                                                  



                                                  

                                      
                                                    





                                             

                                    
                         
                    
 
                                                 


                                                     

                         
                            
 
                                                                                               
                               



                                                                                      






                                                                   
                                  




                                                                                              


                                                             
                                        

      


                                                 
   
                                                    







                                          

                                

                                     
                         
                       

           
                                                 


                                                     

                                               
                            
 
                                                    
                                        
 



                                                                
 


                                                                    
 



                                                                 
 

                                                                        
 
                                                                        
 
                                   
 


                                          

   

                                 
 
                                                





                                                                                        
 






                                                                                         






























                                                                                         
 

                            
 

                                                                                                   
 

                                                                                      
 






















































                                                                                              

                                                                   


                                                  




                                                                                        
                                
 
                                                                                            





                                                
                                                                                            
                

   



                                                  
                        

                                                   
   
 
                         
 
                                                    


  





                                                                    








                                                             

                                           

                         
 
                                                 


                                                     



                                                            
                            

                                  
 
                                 





                                                                                   
          
                                
   

      
                                                    





                                                  

                                          
                         

                    
                                                 


                                                     

                         
                            
 
                                                          


                              
                                                    

 


                                                                   
                                                        











                                                                      

                                            


                                    










                                             
 

































                                                        
                                 

                                      



                                                  















                                                  

          









                                                                           






                                 
 


  











                                                                      




                                                



                                       
 
                                  



                                    


                                           



                                       



                                                              



                                            
 



                                         



                                     



                                           



                                    





                                          



                                    


                                                  



                                          



                                                            



                                             





                                                              



                                             




                                                   



                                        





                                                    



                                      



                                                 



                                         




                                                     



                                             



                                                



                                       





                                                 



                                    





                                                       



                                         



                                                          



                                        



                                                



                                       





                                            



                                    





                                                  



                                         



                                                 



                                        



                                                



                                        


                                             



                                     



                                               



                                       



                                              



                                      



                                               



                                     



                                                    



                                           





                                                 



                                       



                                                



                                        



                                               



                                       



                                                      



                                             





                                                 



                                         





                                                             



                                               





                                                        



                                               





                                                           



                                             





                                                        



                                               






                                              



                                    








                                                  



                                     






                                              



                                     



                                              



                                      

                                                     



                                             

                                                  



                                          



                                              



                                            











                                                                            
/*
 * pkcs11.c
 * --------
 *
 * This is a partial implementation of PKCS #11 on top of the Cryptech
 * libhal library connecting to the Cryptech FPGA cores.
 *
 * Author: Rob Austein
 * Copyright (c) 2015, SUNET
 *
 * 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 COPYRIGHT HOLDERS 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
 * COPYRIGHT OWNER 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.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>

#include <hal.h>

/*
 * Magic PKCS #11 macros that must be defined before including
 * pkcs11.h.  For now these are only the Unix versions, add others
 * later (which may require minor refactoring).
 */

#define CK_PTR                                          *
#define CK_DEFINE_FUNCTION(returnType, name)            returnType name
#define CK_DECLARE_FUNCTION(returnType, name)           returnType name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name)   returnType (* name)
#define CK_CALLBACK_FUNCTION(returnType, name)          returnType (* name)
#ifndef NULL_PTR
#define NULL_PTR                                        NULL
#endif

#include "pkcs11.h"

#include "attributes.h"
#include "sql_common.h"

/*
 * This PKCS #11 implementation is hardwired with one slot, the token
 * for which is always present (so we return the same answer
 * regardless of the value of tokenPresent).
 */

#define P11_ONE_AND_ONLY_SLOT   0

/*
 * Version numbers.  Placeholders for now.
 *
 * Software version number is just the version of this PKCS #11
 * implementation.  Probably.
 */

#warning Figure out hardware and software version numbers
#define P11_VERSION_SW_MAJOR    0
#define P11_VERSION_SW_MINOR    0
#define P11_VERSION_HW_MAJOR    0
#define P11_VERSION_HW_MINOR    0

/*
 * Debugging control.
 */

#ifndef DEBUG_HAL
#define DEBUG_HAL       1
#endif

#ifndef DEBUG_PKCS11
#define DEBUG_PKCS11    1
#endif

/*
 * Whether to include POSIX-specific features.
 */

#ifndef USE_POSIX
#define USE_POSIX 1
#endif

/*
 * Whether to use POSIX threads.
 */

#ifndef USE_PTHREADS
#define USE_PTHREADS USE_POSIX
#endif

#if USE_PTHREADS && !USE_POSIX
#error Can not use POSIX threads without using POSIX
#endif

#if USE_POSIX
#include <unistd.h>
#include <errno.h>
#endif

#if USE_PTHREADS
#include <pthread.h>
#endif



/*
 * PKCS #11 session.
 */

/*
 * At present we have no concept of encryption or signature algorithms
 * in libhal, as we only support RSA and AES.  For PKCS #11 purposes
 * we can figure out what kind of key we're looking at from attributes
 * like CKA_KEY_TYPE, so it's just something we look up given the key
 * object handle.
 *
 * At the moment we don't need to keep any signature or digest state
 * in the session structure, which is good since the current hash
 * cores don't allow us to extract state anyway.  This makes it
 * impossible to implement the incremental operations
 * (C_DigestUpdate(), C_SignUpdate()) but also simplifies our current
 * task.
 *
 * General idea is that we have separate descriptors/handles/state for
 * each operation that we're allowed to do in parallel, so sign,
 * verify, digest, encrypt, decrypt, wrapkey, and unwrapkey all need
 * separate slots in the session structure.  Add these as we go.
 */

typedef struct p11_session {
  CK_SESSION_HANDLE handle;             /* Session handle */
  struct p11_session *link;             /* Next session in list */
  CK_STATE state;                       /* State (CKS_*) of this session */
  CK_NOTIFY notify;                     /* Notification callback */
  CK_VOID_PTR application;              /* Application data */
  sqlite3_stmt *find_query;             /* FindObject*() query state */
  int find_query_done;                  /* find_query has terminated */
  const hal_hash_descriptor_t
    *digest_descriptor,                 /* Hash for C_Digest*() */
    *sign_digest_descriptor,            /* Hash for C_Sign*() */
    *verify_digest_descriptor;          /* Hash for C_Verify*() */
  CK_OBJECT_HANDLE
    sign_key_handle,                    /* Key  for C_Sign*() */
    verify_key_handle;                  /* Key  for C_Verify() */
} p11_session_t;

/*
 * PKCS #11 handle management.  PKCS #11 has two kinds of handles:
 * session handles and object handles.  We subdivide object handles
 * into token object handles (handles for objects that live on the
 * token) and session object handles (handles for objects that live
 * only as long as the session does), and we steal a bit of the object
 * handle as a flag to distinguish between our two kinds of object
 * handles, considerably simplifing the objected-related SQL code.
 */

typedef enum {
  handle_flavor_session,
  handle_flavor_token_object,
  handle_flavor_session_object
} handle_flavor_t;

#define FLAG_HANDLE_TOKEN               0x80000000

#define is_token_handle(_handle_)       (((_handle_) & FLAG_HANDLE_TOKEN) != 0)



/*
 * Current logged-in user.
 */

static enum {
  not_logged_in,
  logged_in_as_user,
  logged_in_as_so
} logged_in_as = not_logged_in;

/*
 * PKCS #11 sessions for this application.
 */

static p11_session_t *p11_sessions;

/*
 * Next PKCS #11 handle to allocate.  We use a single handle space for
 * both session and object handles, and we just keep incrementing
 * until it wraps, to reduce the amount of time we have to spend
 * on SQL probes to avoid handle conflicts.
 */

static CK_ULONG next_handle;

/*
 * Mutex callbacks.
 */

static CK_CREATEMUTEX  mutex_cb_create;
static CK_DESTROYMUTEX mutex_cb_destroy;
static CK_LOCKMUTEX    mutex_cb_lock;
static CK_UNLOCKMUTEX  mutex_cb_unlock;

/*
 * Global mutex.  We may want something finer grained later, but this
 * will suffice to comply with the API requirements.
 */

static CK_VOID_PTR p11_global_mutex;

/*
 * (POSIX-specific) process which last called C_Initialize().
 */

#if USE_POSIX
static pid_t initialized_pid;
#endif



/*
 * Syntactic sugar for functions returning CK_RV complex enough to
 * need cleanup actions on failure.  Also does very basic logging for
 * debug-by-printf().
 *
 * NB: This uses a variable ("rv") and a goto target ("fail") which
 * must be defined in the calling environment.  We could make these
 * arguments to the macro, but doing so would make the code less
 * readable without significantly reducing the voodoo factor.
 */

#if DEBUG_PKCS11

#define lose(_ck_rv_code_)                                              \
  do {                                                                  \
    rv = (_ck_rv_code_);                                                \
    fprintf(stderr, "%s:%u: %s\n", __FILE__, __LINE__, #_ck_rv_code_);  \
    goto fail;                                                          \
  } while (0)

#else  /* DEBUG_PKCS11 */

#define lose(_ck_rv_code_)                                              \
  do {                                                                  \
    rv = (_ck_rv_code_);                                                \
    goto fail;                                                          \
  } while (0)

#endif  /* DEBUG_PKCS11 */

/*
 * More debug-by-printf() support.  One would like to consider this a
 * relic of the previous millenium, but, sadly, broken debugging
 * environments are still all too common.
 */

#if DEBUG_PKCS11 > 1

#define ENTER_PUBLIC_FUNCTION(_name_) \
  fprintf(stderr, "Entering function %s\n", #_name_)

#else  /* DEBUG_PKCS11 > 1 */

#define ENTER_PUBLIC_FUNCTION(_name_)

#endif  /* DEBUG_PKCS11 > 1 */

/*
 * Error checking for libhal calls.
 */

#if DEBUG_HAL

static int _hal_check(const hal_error_t err, const char * const expr, const char * const file, const unsigned line)
{
  if (err == HAL_OK)
    return 1;
  fprintf(stderr, "%s:%u: %s returned %s\n", file, line, expr, hal_error_string(err));
  return 0;
}

#define hal_check(_expr_) (_hal_check((_expr_), #_expr_, __FILE__, __LINE__))

#else  /* DEBUG_HAL */

#define hal_check(_expr_) ((_expr_) == HAL_OK)

#endif  /* DEBUG_HAL */



/*
 * Thread mutex utilities.  We need to handle three separate cases:
 *
 * 1) User doesn't care about mutexes;
 * 2) User wants us to use "OS" mutexes;
 * 3) User wants us to use user-specified mutexs.
 *
 * For "OS" mutexes, read POSIX Threads mutexes, at least for now.
 *
 * PKCS #11 sort of has a fourth case, but it's really just license
 * for us to pick either the second or third case at whim.
 *
 * To simplify the rest of the API, we provide a POSIX-based
 * implementation which uses the same API an user-provided mutex
 * implementation would be required to use, use null function pointers
 * to represent the case where the user doesn't need mutexes at all,
 * and wrap the whole thing in trivial macros to insulate the rest of
 * the code from the grotty details.
 */

/*
 * Basic macros.
 */

#define mutex_create(_m_)   (mutex_cb_create  == NULL ? CKR_OK : mutex_cb_create(_m_))
#define mutex_destroy(_m_)  (mutex_cb_destroy == NULL ? CKR_OK : mutex_cb_destroy(_m_))
#define mutex_lock(_m_)     (mutex_cb_lock    == NULL ? CKR_OK : mutex_cb_lock(_m_))
#define mutex_unlock(_m_)   (mutex_cb_unlock  == NULL ? CKR_OK : mutex_cb_unlock(_m_))

/*
 * Slightly higher-level macros for common operations.
 */

#define mutex_lock_or_return_failure(_m_)       \
  do {                                          \
    CK_RV _rv = mutex_lock(_m_);                \
    if (_rv != CKR_OK)                          \
      return _rv;                               \
  } while (0)

#define mutex_unlock_return_with_rv(_rv_, _m_)  \
  do {                                          \
    CK_RV _rv1 = _rv_;                          \
    CK_RV _rv2 = mutex_unlock(_m_);             \
    return _rv1 == CKR_OK ? _rv2 : _rv1;        \
  } while (0)

/*
 * Mutex implementation using POSIX mutexes.
 */

#if USE_PTHREADS

static CK_RV posix_mutex_create(CK_VOID_PTR_PTR ppMutex)
{
  pthread_mutex_t *m = NULL;
  CK_RV rv;

  if (ppMutex == NULL)
    lose(CKR_GENERAL_ERROR);

  if ((m = malloc(sizeof(*m))) == NULL)
    lose(CKR_HOST_MEMORY);

  switch (pthread_mutex_init(m, NULL)) {

  case 0:
    *ppMutex = m;
    return CKR_OK;

  case ENOMEM:
    lose(CKR_HOST_MEMORY);

  default:
    lose(CKR_GENERAL_ERROR);
  }

 fail:
  if (m != NULL)
    free(m);
  return rv;
}

static CK_RV posix_mutex_destroy(CK_VOID_PTR pMutex)
{
  CK_RV rv;

  if (pMutex == NULL)
    lose(CKR_MUTEX_BAD);

  switch (pthread_mutex_destroy(pMutex)) {

  case 0:
    free(pMutex);
    return CKR_OK;

  case EINVAL:
    lose(CKR_MUTEX_BAD);

  case EBUSY:
    /*
     * PKCS #11 mutex semantics are a bad match for POSIX here,
     * leaving us only the nuclear option.  Feh.  Fall through.
     */

  default:
    lose(CKR_GENERAL_ERROR);
  }

 fail:
  return rv;
}

static CK_RV posix_mutex_lock(CK_VOID_PTR pMutex)
{
  CK_RV rv;

  if (pMutex == NULL)
    lose(CKR_MUTEX_BAD);

  switch (pthread_mutex_lock(pMutex)) {

  case 0:
    return CKR_OK;

  case EINVAL:
    lose(CKR_MUTEX_BAD);

  default:
    lose(CKR_GENERAL_ERROR);
  }

 fail:
  return rv;
}

static CK_RV posix_mutex_unlock(CK_VOID_PTR pMutex)
{
  CK_RV rv;

  if (pMutex == NULL)
    lose(CKR_MUTEX_BAD);

  switch (pthread_mutex_unlock(pMutex)) {

  case 0:
    return CKR_OK;

  case EINVAL:
    lose(CKR_MUTEX_BAD);

  case EPERM:
    lose(CKR_MUTEX_NOT_LOCKED);

  default:
    lose(CKR_GENERAL_ERROR);
  }

 fail:
  return rv;
}

#endif /* USE_PTHREADS */



/*
 * Initialize KEK.  If we had proper hardware support the KEK would be
 * living in special RAM where we could wipe it if anything triggered
 * our tamper circuitry.  But we have no such at the moment, so we
 * have no good place to store the KEK.
 *
 * So we store it in the SQL database, which kind of defeats the point
 * of wrapping private keys that live in the same database -- except
 * that we're trying to get all the other bits right so that we can
 * just move the KEK to secure memory once we have it.
 */

static int kek_init(void)
{
  static const char test_kek[] =
    " SELECT kek IS NULL FROM global";

  static const char set_kek[] =
    " UPDATE global SET kek = ?1";

  sqlite3_stmt *q = NULL;

  int ok = (sql_check_ok(sql_prepare(&q, test_kek))             &&
            sql_check_row(sqlite3_step(q)));

  if (ok && sqlite3_column_int(q, 0)) {
    uint8_t kekbuf[bitsToBytes(256)];

    ok = (hal_check(hal_get_random(kekbuf, sizeof(kekbuf)))	&&
          sql_check_ok(sql_finalize_and_clear(&q))              &&
          sql_check_ok(sql_prepare(&q, set_kek))		&&
          sql_check_ok(sqlite3_bind_blob(q, 1, kekbuf,
                                         sizeof(kekbuf),
                                         NULL))                 &&
          sql_check_done(sqlite3_step(q)));

    memset(kekbuf, 0, sizeof(kekbuf));
  }

  sqlite3_finalize(q);
  return ok;
}



/*
 * Find an unused handle.
 *
 * Note that zero is an excluded value (CK_INVALID_HANDLE), hence the
 * slightly odd arithmetic.
 *
 * For object handles, we steal the high-order bit to flag whether the
 * handle represents a session object or token object.
 */

static CK_ULONG p11_allocate_unused_handle(const handle_flavor_t flavor)
{
  static const char select_format[] =
    " SELECT %s_id FROM %s WHERE %s_handle = ?";

  const char *table = flavor == handle_flavor_session ? "session" : "object";
  sqlite3_stmt *q = NULL;
  CK_ULONG handle;
  int ret;

  if (!sql_check_ok(sql_prepare(&q, select_format, table, table, table)))
    goto fail;

  for (;;) {

    handle = ++next_handle;
    next_handle %= 0xFFFFFFFF;

    switch (flavor) {
    case handle_flavor_session:
      break;
    case handle_flavor_token_object:
      handle |= FLAG_HANDLE_TOKEN;
      break;
    case handle_flavor_session_object:
      handle &= ~FLAG_HANDLE_TOKEN;
      break;
    }

    assert(handle != CK_INVALID_HANDLE);

    if (!sql_check_ok(sqlite3_reset(q)) ||
        !sql_check_ok(sqlite3_bind_int64(q, 1, handle)))
      goto fail;

    if ((ret = sqlite3_step(q)) == SQLITE_ROW)
      continue;

    if (ret == SQLITE_DONE)
      break;

    sql_whine_step();
    goto fail;

  }

  sqlite3_finalize(q);
  return handle;

 fail:
  sqlite3_finalize(q);
  return CK_INVALID_HANDLE;
}

/*
 * Translate CKA_TOKEN value to handle flavor.
 */

static handle_flavor_t p11_handle_flavor_from_cka_token(const CK_BBOOL *bbool)
{
  assert(bbool != NULL);
  return  *bbool ? handle_flavor_token_object : handle_flavor_session_object;
}



/*
 * Attribute methods.
 */

/*
 * Set an attribute for a given object.
 *
 * It would be trivial to generalize this to take a CK_ATTRIBUTE_PTR
 * template instead of a single attribute, at the cost of losing the
 * const specifiers (CK_ATTRIBUTE_PTR has an internal non-const void*).
 */

static int p11_attribute_set(const CK_OBJECT_HANDLE object_handle,
                             const CK_ATTRIBUTE_TYPE type,
                             const void * const value,
                             const CK_ULONG length)
{
  static const char insert_format[] =
    " INSERT OR REPLACE INTO %s_attribute (%s_object_id, type, value)"
    " VALUES ((SELECT %s_object_id FROM object WHERE object_handle = ?1), ?2, ?3)";

  const char *flavor = is_token_handle(object_handle) ? "token" : "session";

  sqlite3_stmt *q = NULL;
  int ok = 0;

  if (!sql_check_ok(sql_prepare(&q, insert_format, flavor, flavor, flavor))     ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, object_handle))                    ||
      !sql_check_ok(sqlite3_bind_int64(q, 2, type))                             ||
      !sql_check_ok(sqlite3_bind_blob( q, 3, value, length, NULL))              ||
      !sql_check_done(sqlite3_step(q)))
    goto fail;

  ok = 1;

 fail:
  sqlite3_finalize(q);
  return ok;
}

/*
 * Get a single attribute from a given object.
 *
 * This could easily be generalized to take a CK_ATTRIBUTE_PTR, at the
 * cost of more complicated error semantics.
 */

static int p11_attribute_get(const CK_OBJECT_HANDLE object_handle,
                             const CK_ATTRIBUTE_TYPE type,
                             void *value,
                             CK_ULONG *length,
                             const CK_ULONG maxlength)
{
  static const char select_format[] =
    " SELECT value FROM %s_attribute NATURAL JOIN object"
    " WHERE object_handle = ?1 AND type = ?2";

  const char *flavor = is_token_handle(object_handle) ? "token" : "session";

  sqlite3_stmt *q = NULL;
  int ret, ok = 0;
  CK_ULONG len;

  if (!sql_check_ok(sql_prepare(&q, select_format, flavor))     ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, object_handle))    ||
      !sql_check_ok(sqlite3_bind_int64(q, 2, type)))
    goto fail;

  ret = sqlite3_step(q);

  if (ret == SQLITE_DONE)
    goto fail;

  if (ret != SQLITE_ROW) {
    sql_whine_step();
    goto fail;
  }

  len = sqlite3_column_bytes(q, 0);

  if (length != NULL)
    *length = len;

  if (value != NULL && maxlength < len)
    goto fail;

  if (value != NULL)
    memcpy(value, sqlite3_column_blob(q, 0), len);

  ok = 1;

 fail:
  sqlite3_finalize(q);
  return ok;
}

/*
 * Wrappers to set and get CK_BBOOL and CK_ULONG values.
 */

#if 0

static int p11_attribute_set_bbool(const CK_OBJECT_HANDLE object_handle, const CK_ATTRIBUTE_TYPE type, const CK_BBOOL value)
{
  return p11_attribute_set(object_handle, type, &value, sizeof(value));
}

static int p11_attribute_set_ulong(const CK_OBJECT_HANDLE object_handle, const CK_ATTRIBUTE_TYPE type, const CK_ULONG value)
{
  return p11_attribute_set(object_handle, type, &value, sizeof(value));
}

#endif

static int p11_attribute_get_bbool(const CK_OBJECT_HANDLE object_handle, const CK_ATTRIBUTE_TYPE type, CK_BBOOL *value)
{
  CK_ULONG length;
  return p11_attribute_get(object_handle, type, value, &length, sizeof(*value)) && length == sizeof(*value);
}

static int p11_attribute_get_ulong(const CK_OBJECT_HANDLE object_handle, const CK_ATTRIBUTE_TYPE type, CK_ULONG *value)
{
  CK_ULONG length;
  return p11_attribute_get(object_handle, type, value, &length, sizeof(*value)) && length == sizeof(*value);
}

/*
 * Find an attribute in a CK_ATTRIBUTE_PTR template.  Returns index
 * into template, or -1 if not found.
 */

static int p11_attribute_find_in_template(const CK_ATTRIBUTE_TYPE type,
                                          const CK_ATTRIBUTE_PTR template,
                                          const CK_ULONG length)
{
  int i;

  if (template != NULL)
    for (i = 0; i < length; i++)
      if (template[i].type == type)
        return i;

  return -1;
}

/*
 * Map a keyusage-related attribute to a keyusage bit flag.
 *
 * Assumes that calling code has already checked whether this
 * attribute is legal for this object class, that attribute which
 * should be CK_BBOOLs are of the correct length, etcetera.
 *
 * To handle all the possible permutations of specified and default
 * values, it may be necessary to defer calling this method until
 * after the default and mandatory values have been merged into the
 * values supplied by the application-supplied template.
 *
 * Semantics of the flags follow RFC 5280 4.2.1.3, numeric values
 * don't matter particularly as we only use them internally.
 */

#define KEYUSAGE_DIGITALSIGNATURE	(1 << 0)
#define KEYUSAGE_KEYENCIPHERMENT	(1 << 1)
#define KEYUSAGE_DATAENCIPHERMENT	(1 << 2)

static void p11_attribute_apply_keyusage(unsigned *keyusage, const CK_ATTRIBUTE_TYPE type, const CK_BBOOL *value)
{
  unsigned flag;

  assert(keyusage != NULL && value != NULL);

  switch (type) {
  case CKA_SIGN:                /* Generate signature */
  case CKA_VERIFY:              /* Verify signature */
    flag = KEYUSAGE_DIGITALSIGNATURE;
    break;
  case CKA_ENCRYPT:             /* Encrypt bulk data (seldom used) */
  case CKA_DECRYPT:             /* Bulk decryption (seldom used) */
    flag = KEYUSAGE_DATAENCIPHERMENT;
    break;
  case CKA_WRAP:                /* Wrap key (normal way of doing encryption) */
  case CKA_UNWRAP:              /* Unwrap key (normal way of doing decryption) */
    flag = KEYUSAGE_KEYENCIPHERMENT;
    break;
  default:
    return;                     /* Attribute not related to key usage */
  }

  if (*value)
    *keyusage |=  flag;
  else
    *keyusage &= ~flag;
}



/*
 * Descriptor methods.  Descriptors are generated at compile time by
 * an auxiliary Python script, see attributes.* for details.
 */

/*
 * Return the descriptor associated with a particular object class and
 * key type.
 */

static const p11_descriptor_t *p11_descriptor_from_key_type(const CK_OBJECT_CLASS object_class,
                                                            const CK_KEY_TYPE key_type)
{
  int i;

  for (i = 0; i < sizeof(p11_descriptor_keyclass_map)/sizeof(*p11_descriptor_keyclass_map); i++) {
    const p11_descriptor_keyclass_map_t * const m = &p11_descriptor_keyclass_map[i];
    if (m->object_class == object_class && m->key_type == key_type)
      return m->descriptor;
  }

  return NULL;
}

/*
 * Find the entry for a particular attribute in a descriptor.
 */

static const p11_attribute_descriptor_t *p11_find_attribute_in_descriptor(const p11_descriptor_t *descriptor,
                                                                          const CK_ATTRIBUTE_TYPE type)
{
  int i;

  if (descriptor != NULL && descriptor->attributes != NULL)
    for (i = 0; i < descriptor->n_attributes; i++)
      if (descriptor->attributes[i].type == type)
        return &descriptor->attributes[i];

  return NULL;
}

/*
 * Check whether an attribute is marked as sensitive.  If we don't
 * recognize the attribute, report it as sensitive (safer than the
 * alternative).
 */

static int p11_attribute_is_sensitive(const p11_descriptor_t *descriptor,
                                      const CK_ATTRIBUTE_TYPE type)
{
  const p11_attribute_descriptor_t *a = p11_find_attribute_in_descriptor(descriptor, type);
  return a == NULL || (a->flags & P11_DESCRIPTOR_SENSITIVE) != 0;
}



/*
 * Object methods.
 */

/*
 * Check access rights for an object.
 */

typedef enum { p11_object_access_read, p11_object_access_write } p11_object_access_t;

static CK_RV p11_object_check_rights(const p11_session_t *session,
                                     const CK_OBJECT_HANDLE object_handle,
                                     const p11_object_access_t rights)
{
  static const char object_exists_query[] =
    " SELECT count(*) FROM object WHERE object_handle = ?1";

  static const char session_object_query[] =
    " SELECT session_handle FROM session NATURAL JOIN object WHERE object_handle = ?1";

  CK_BBOOL object_is_private;
  sqlite3_stmt *q = NULL;
  CK_RV rv;

  if (session == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  /*
   * Read-only sessions are, um, read-only.
   */

  switch (session->state) {
  case CKS_RO_PUBLIC_SESSION:
  case CKS_RO_USER_FUNCTIONS:
    if (rights == p11_object_access_write)
      lose(CKR_SESSION_READ_ONLY);
  }

  /*
   * Private objects don't exist for sessions in the wrong state.
   */

  switch (session->state) {
  case CKS_RO_PUBLIC_SESSION:
  case CKS_RW_PUBLIC_SESSION:
  case CKS_RW_SO_FUNCTIONS:
    if (!p11_attribute_get_bbool(object_handle, CKA_PRIVATE, &object_is_private) || object_is_private)
      lose(CKR_OBJECT_HANDLE_INVALID);
  }

  /*
   * Does the object even exist?
   */

  if (!sql_check_ok(sql_prepare(&q, object_exists_query))       ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, object_handle))    ||
      !sql_check_row(sqlite3_step(q))                           ||
      !sqlite3_column_int(q, 0))
    lose(CKR_OBJECT_HANDLE_INVALID);

  /*
   * Session objects are only visible to the session which created them.
   */

  if (!is_token_handle(object_handle)                           &&
      (!sql_check_ok(sql_finalize_and_clear(&q))                ||
       !sql_check_ok(sql_prepare(&q, session_object_query))     ||
       !sql_check_ok(sqlite3_bind_int64(q, 1, object_handle))   ||
       !sql_check_row(sqlite3_step(q))                          ||
       sqlite3_column_int64(q, 0) != session->handle))
    lose(CKR_OBJECT_HANDLE_INVALID);

  /*
   * Ran out of reasons to reject, guess we should allow it.
   */

  rv = CKR_OK;

 fail:
  sqlite3_finalize(q);
  return rv;
}

/*
 * Delete all private objects, probably because user logged out.
 *
 * In the case of token objects, the object itself remains in the
 * token, we're just deleting our handle for the object.
 *
 * In the case of session objects, the object itself goes away.
 */

static int p11_object_delete_all_private(void)
{
  static const char delete_format[] =
    " WITH"
    "  s AS (SELECT session_object_id FROM session_attribute WHERE type = %u AND value <> X'00'),"
    "  t AS (SELECT token_object_id   FROM token_attribute   WHERE type = %u AND value <> X'00')"
    " DELETE FROM object WHERE token_object_id IN t OR session_object_id IN s";

  sqlite3_stmt *q = NULL;
  int ok = 0;

  if (!sql_check_ok(sql_prepare(&q, delete_format, CKA_PRIVATE, CKA_PRIVATE))   ||
      !sql_check_done(sqlite3_step(q)))
    goto fail;

  ok = 1;

 fail:
  sqlite3_finalize(q);
  return ok;
}

/*
 * Create a new object.
 *
 * This is a bit nasty due to the SQL foreign key constraints and the
 * different handling required for session and token objects.
 */

static CK_OBJECT_HANDLE p11_object_create(const p11_session_t *session,
                                          const handle_flavor_t flavor,
                                          const CK_ATTRIBUTE_PTR template,
                                          const CK_ULONG template_length,
                                          const p11_descriptor_t * const descriptor,
                                          const CK_MECHANISM_PTR mechanism)
{
  static const char insert_object[] =
    " INSERT INTO object (object_handle)"
    " VALUES (?)";

  static const char insert_token_object[] =
    " INSERT INTO token_object DEFAULT VALUES";

  static const char insert_session_object[] =
    " INSERT INTO session_object (object_id) VALUES (?)";

  static const char update_object_session_object[] =
    " UPDATE object SET"
    "   session_id = (SELECT session_id FROM session WHERE session_handle = ?1),"
    "   session_object_id = ?2"
    " WHERE object_id = ?3";

  static const char update_object_token_object[] =
    " UPDATE object SET token_object_id = ?1 WHERE object_id = ?2";

  static const char insert_token_attribute[] =
    " INSERT OR REPLACE INTO token_attribute (token_object_id, type, value)"
    " VALUES (?1, ?2, ?3)";

  static const char insert_session_attribute[] =
    " INSERT OR REPLACE INTO session_attribute (session_object_id, type, value)"
    " VALUES (?1, ?2, ?3)";

  CK_OBJECT_HANDLE object_handle = p11_allocate_unused_handle(flavor);;
  sqlite3_int64 object_id, session_object_id, token_object_id;
  sqlite3_stmt *q = NULL;
  int i, ok = 0;

  assert(session != NULL && template != NULL && descriptor != NULL &&
         (flavor == handle_flavor_token_object ||
          flavor == handle_flavor_session_object));

  if (!sql_check_ok(sql_prepare(&q, insert_object))             ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, object_handle))    ||
      !sql_check_done(sqlite3_step(q)))
    goto fail;

  object_id = sqlite3_last_insert_rowid(sqldb);

  if (!sql_check_ok(sql_finalize_and_clear(&q)))
    goto fail;

  switch (flavor) {

  case handle_flavor_token_object:
    if (!sql_check_ok(sql_prepare(&q, insert_token_object))             ||
        !sql_check_done(sqlite3_step(q)))
      goto fail;
    token_object_id = sqlite3_last_insert_rowid(sqldb);
    if (!sql_check_ok(sql_finalize_and_clear(&q))                       ||
        !sql_check_ok(sql_prepare(&q, update_object_token_object))      ||
        !sql_check_ok(sqlite3_bind_int64(q, 1, token_object_id))        ||
        !sql_check_ok(sqlite3_bind_int64(q, 2, object_id))              ||
        !sql_check_done(sqlite3_step(q))                                ||
        !sql_check_ok(sql_finalize_and_clear(&q))                       ||
        !sql_check_ok(sql_prepare(&q, insert_token_attribute))          ||
        !sql_check_ok(sqlite3_bind_int64(q, 1, token_object_id)))
      goto fail;
    break;

  case handle_flavor_session_object:
    if (!sql_check_ok(sql_prepare(&q, insert_session_object))           ||
        !sql_check_ok(sqlite3_bind_int64(q, 1, object_id))              ||
        !sql_check_done(sqlite3_step(q)))
      goto fail;
    session_object_id = sqlite3_last_insert_rowid(sqldb);
    if (!sql_check_ok(sql_finalize_and_clear(&q))                       ||
        !sql_check_ok(sql_prepare(&q, update_object_session_object))    ||
        !sql_check_ok(sqlite3_bind_int64(q, 1, session->handle))        ||
        !sql_check_ok(sqlite3_bind_int64(q, 2, session_object_id))      ||
        !sql_check_ok(sqlite3_bind_int64(q, 3, object_id))              ||
        !sql_check_done(sqlite3_step(q))                                ||
        !sql_check_ok(sql_finalize_and_clear(&q))                       ||
        !sql_check_ok(sql_prepare(&q, insert_session_attribute))        ||
        !sql_check_ok(sqlite3_bind_int64(q, 1, session_object_id)))
      goto fail;
    break;

  default:                      /* Suppress GCC warning */
    goto fail;
  }

  /*
   * Now populate attributes, starting with the application's
   * template, which we assume has already been blessed by the API
   * function that called this method.
   */

  for (i = 0; i < template_length; i++) {
    const CK_ATTRIBUTE_TYPE type = template[i].type;
    const void *             val = template[i].pValue;
    const int                len = template[i].ulValueLen;

    if (!sql_check_ok(sqlite3_reset(q))                         ||
        !sql_check_ok(sqlite3_bind_int64(q, 2, type))           ||
        !sql_check_ok(sqlite3_bind_blob( q, 3, val, len, NULL)) ||
        !sql_check_done(sqlite3_step(q)))
      goto fail;
  }

  /*
   * Next, add defaults from the descriptor.
   */

  for (i = 0; i < descriptor->n_attributes; i++) {
    const CK_ATTRIBUTE_TYPE type = descriptor->attributes[i].type;
    const void *             val = descriptor->attributes[i].value;
    const int                len = descriptor->attributes[i].length;
    const unsigned         flags = descriptor->attributes[i].flags;

    if (val == NULL && (flags & P11_DESCRIPTOR_DEFAULT_VALUE) != 0)
      val = "";

    if (val == NULL || p11_attribute_find_in_template(type, template, template_length) >= 0)
      continue;

    if (!sql_check_ok(sqlite3_reset(q))                         ||
        !sql_check_ok(sqlite3_bind_int64(q, 2, type))           ||
        !sql_check_ok(sqlite3_bind_blob( q, 3, val, len, NULL)) ||
        !sql_check_done(sqlite3_step(q)))
      goto fail;
  }

  /*
   * Finally, add generation mechanism attributes as needed.
   */

  if (mechanism != NULL &&
      (!sql_check_ok(sqlite3_reset(q))                                                                          ||
       !sql_check_ok(sqlite3_bind_int64(q, 2, CKA_LOCAL))                                                       ||
       !sql_check_ok(sqlite3_bind_blob( q, 3, &const_CK_TRUE, sizeof(const_CK_TRUE), NULL))                     ||
       !sql_check_done(sqlite3_step(q))                                                                         ||
       !sql_check_ok(sqlite3_reset(q))                                                                          ||
       !sql_check_ok(sqlite3_bind_int64(q, 2, CKA_KEY_GEN_MECHANISM))                                           ||
       !sql_check_ok(sqlite3_bind_blob( q, 3, &mechanism->mechanism, sizeof(mechanism->mechanism), NULL))       ||
       !sql_check_done(sqlite3_step(q))))
    goto fail;

  /*
   * If we made it past all that, we're happy.
   */

  ok = 1;

 fail:
  sqlite3_finalize(q);
  return ok ? object_handle : CK_INVALID_HANDLE;
}

/*
 * Store an RSA private key.
 *
 * Write the key as PKCS #1.5 RSAPrivateKey DER, encrypt that using
 * AES key wrap, and store the result as an SQL blob.
 *
 * We jump through a few minor hoops to let us do all the encoding and
 * wrapping in place in a single buffer.
 */

static int p11_object_set_rsa_private_key(const CK_OBJECT_HANDLE object_handle,
                                          const hal_rsa_key_t key)
{
  static const char select_kek[] =
    " SELECT kek FROM global";

  static const char update_format[] =
    " UPDATE %s_object SET private_key = ?1"
    " WHERE %s_object_id = (SELECT %s_object_id FROM object WHERE object_handle = ?2)";

  uint8_t wrapbuf[hal_aes_keywrap_ciphertext_length(hal_rsa_key_to_der_len(key))];
  const char *flavor = is_token_handle(object_handle) ? "token" : "session";
  size_t der_len, wrapbuf_len = sizeof(wrapbuf);
  sqlite3_stmt *q = NULL;
  int ok = 0;

  if (!sql_check_ok(sql_prepare(&q, select_kek))                                ||
      !sql_check_row(sqlite3_step(q))                                           ||
      sqlite3_column_type(q, 0) == SQLITE_NULL                                  ||
      !hal_check(hal_rsa_key_to_der(key, wrapbuf+8, &der_len,
                                    sizeof(wrapbuf)-8))                         ||
      !hal_check(hal_aes_keywrap(sqlite3_column_blob(q, 0),
                                 sqlite3_column_bytes(q, 0),
                                 wrapbuf+8, der_len, wrapbuf, &wrapbuf_len))	||
      !sql_check_ok(sql_finalize_and_clear(&q))                                 ||
      !sql_check_ok(sql_prepare(&q, update_format, flavor, flavor, flavor))     ||
      !sql_check_ok(sqlite3_bind_blob( q, 1, wrapbuf, wrapbuf_len, NULL))       ||
      !sql_check_ok(sqlite3_bind_int64(q, 2, object_handle))                    ||
      !sql_check_done(sqlite3_step(q)))
    goto fail;

  ok = 1;

 fail:
  memset(wrapbuf, 0, sizeof(wrapbuf));
  sqlite3_finalize(q);
  return ok;
}

/*
 * Fetch an RSA private key.
 *
 * Retrieve SQL blob from the object, unwrap that to get the DER
 * encoding of a PKCS #1.5 RSAPrivateKey object, load the key from
 * that.
 *
 * If the key isn't set, we return success with null key.
 */

static int p11_object_get_rsa_private_key(const CK_OBJECT_HANDLE object_handle,
                                          hal_rsa_key_t *key,
                                          uint8_t *keybuf, const size_t keybuf_len)
{
  static const char select_format[] =
    " SELECT kek, private_key FROM global, %s_object NATURAL JOIN object WHERE object_handle = ?1";

  const char *flavor = is_token_handle(object_handle) ? "token" : "session";
  sqlite3_stmt *q = NULL;
  int ok;

  assert(key != NULL && keybuf != NULL);

  /*
   * Pull everything we need from the database.
   */

  if (!sql_check_ok(sql_prepare(&q, select_format, flavor))     ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, object_handle))    ||
      !sql_check_row(sqlite3_step(q))                           ||
      sqlite3_column_type(q, 0) == SQLITE_NULL) {
    ok = 0;
  }

  else if (sqlite3_column_type(q, 1) == SQLITE_NULL) {
    key->key = NULL;
    ok = 1;
  }

  else {
    const uint8_t * const kek  = sqlite3_column_blob(q, 0);
    const uint8_t * const pkey = sqlite3_column_blob(q, 1);
    const size_t kek_len  = sqlite3_column_bytes(q, 0);
    const size_t pkey_len = sqlite3_column_bytes(q, 1);
    size_t  wrapbuf_len = pkey_len;
    uint8_t wrapbuf[pkey_len];

    ok = (hal_check(hal_aes_keyunwrap(kek, kek_len, pkey, pkey_len, wrapbuf, &wrapbuf_len)) &&
          hal_check(hal_rsa_key_from_der(key, keybuf, keybuf_len, wrapbuf, wrapbuf_len)));

    memset(wrapbuf, 0, sizeof(wrapbuf));
  }

  if (!ok || key->key == NULL)
    memset(keybuf, 0, keybuf_len);

  sqlite3_finalize(q);
  return ok;
}

#warning Revisit return semantics of p11_object_get_rsa_private_key() and p11_object_get_rsa_public_key()

/*
 * Fetch an RSA public key.
 *
 * Public keys aren't stored separately the way that private keys are,
 * so we're looking for the public components so we can load them into
 * a key objet.
 */

static int p11_object_get_rsa_public_key(const CK_OBJECT_HANDLE object_handle,
                                         hal_rsa_key_t *key,
                                         uint8_t *keybuf, const size_t keybuf_len)
{
  static const char select_format[] =
    " WITH a (type, value) "
    "   AS (SELECT type, value FROM %s_attribute NATURAL JOIN object WHERE object_handle = ?1)"
    " SELECT a1.value, a2.value FROM a AS a1, a AS a2 WHERE a1.type = %u AND a2.type = %u";

  const char *flavor = is_token_handle(object_handle) ? "token" : "session";
  sqlite3_stmt *q = NULL;

  assert(key != NULL && keybuf != NULL);

  const int ok = (sql_check_ok(sql_prepare(&q, select_format, flavor,
                                           CKA_MODULUS, CKA_PUBLIC_EXPONENT))     &&
                  sql_check_ok(sqlite3_bind_int64(q, 1, object_handle))           &&
                  sql_check_row(sqlite3_step(q))                                  &&
                  sqlite3_column_type(q, 0) == SQLITE_BLOB                        &&
                  sqlite3_column_type(q, 1) == SQLITE_BLOB                        &&
                  hal_check(hal_rsa_key_load_public(key, keybuf, keybuf_len,
                                                    sqlite3_column_blob( q, 0),
                                                    sqlite3_column_bytes(q, 0),
                                                    sqlite3_column_blob( q, 1),
                                                    sqlite3_column_bytes(q, 1))));

  sqlite3_finalize(q);
  return ok;
}



/*
 * Session methods.
 */

/*
 * Create a new session.
 */

static p11_session_t *p11_session_new(void)
{
  p11_session_t *session = malloc(sizeof(*session));
  if (session == NULL)
    return NULL;
  memset(session, 0, sizeof(*session));
  return session;
}

/*
 * Free a session.
 */

static void p11_session_free(p11_session_t *session)
{
  if (session == NULL)
    return;

  sql_finalize_and_clear(&session->find_query);

  free(session);
}

/*
 * Assign a handle to a session and add the session to SQL.
 */

static int p11_session_add(p11_session_t *session)
{
  static const char insert_session[] =
    " INSERT INTO session (session_handle) VALUES (?)";

  sqlite3_stmt *q = NULL;
  int ok = 0;

  assert(session != NULL);

  session->handle = p11_allocate_unused_handle(handle_flavor_session);

  if (!sql_check_ok(sql_prepare(&q, insert_session))            ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, session->handle))  ||
      !sql_check_done(sqlite3_step(q)))
    goto fail;

  session->link = p11_sessions;
  p11_sessions = session;
  ok = 1;

 fail:
  sqlite3_finalize(q);
  return ok;
}

/*
 * Find a session.
 *
 * Since we don't expect the total number of sessions to be all that
 * high, we use a linked list with a move-to-the-front search.  Some
 * of the other session methods assume this behavior, so be careful if
 * you decide to change it.
 */

static p11_session_t *p11_session_find(const CK_SESSION_HANDLE session_handle)
{
  p11_session_t **link, *session;

  for (link = &p11_sessions;
       (session = *link) != NULL && session->handle != session_handle;
       link = &session->link)
    ;

  if (session != NULL && link != &p11_sessions) {
    *link = session->link;
    session->link = p11_sessions;
    p11_sessions = session;
  }

  return session;
}

/*
 * Delete a session: remove it from SQL and free the session data
 * structure.
 *
 * This method assumes the move-to-the-front behavior of
 * p11_session_find().
 */

static CK_RV p11_session_delete(const CK_SESSION_HANDLE session_handle)
{
  static const char delete_session[] =
    " DELETE FROM session WHERE session_handle = ?";

  p11_session_t *session = p11_session_find(session_handle);
  sqlite3_stmt *q = NULL;
  CK_RV rv = CKR_OK;

  if (session == NULL)
    return CKR_SESSION_HANDLE_INVALID;

  if (!sql_check_ok(sql_prepare(&q, delete_session))            ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, session_handle))   ||
      !sql_check_done(sqlite3_step(q)))
    lose(CKR_FUNCTION_FAILED);

  /* Check that move-to-the-front behaved as expected */
  assert(p11_sessions == session);

  p11_sessions = session->link;
  p11_session_free(session);

 fail:
  sqlite3_finalize(q);
  return rv;
}

/*
 * Delete all sessions.
 */

#warning Should this also clear the object table?

static CK_RV p11_session_delete_all(void)
{
  static const char delete_all_sessions[] =
    " DELETE FROM session";

  p11_session_t *session;
  CK_RV rv = CKR_OK;

  if (!sql_exec(delete_all_sessions))
    lose(CKR_FUNCTION_FAILED);

  while (p11_sessions != NULL) {
    session = p11_sessions;
    p11_sessions = session->link;
    p11_session_free(session);
  }

 fail:
  return rv;
}

/*
 * Check session database against login state for consistency.
 *
 * This is mostly useful in assertions.
 */

static int p11_session_consistent_login(void)
{
  p11_session_t *session;

  switch (logged_in_as) {

  case not_logged_in:
    for (session = p11_sessions; session != NULL; session = session->link)
      if (session->state != CKS_RO_PUBLIC_SESSION && session->state != CKS_RW_PUBLIC_SESSION)
        return 0;
    return 1;

  case logged_in_as_user:
    for (session = p11_sessions; session != NULL; session = session->link)
      if (session->state != CKS_RO_USER_FUNCTIONS && session->state != CKS_RW_USER_FUNCTIONS)
        return 0;
    return 1;

  case logged_in_as_so:
    for (session = p11_sessions; session != NULL; session = session->link)
      if (session->state != CKS_RW_SO_FUNCTIONS)
        return 0;
    return 1;

  default:
    return 0;
  }
}



/*
 * PKCS #11 likes space-padded rather than null-terminated strings.
 */

static int psnprintf(void *buffer_, size_t size, const char *format, ...)
{
  char *buffer = buffer_;
  size_t i, n;
  va_list ap;

  va_start(ap, format);
  i = n = vsnprintf(buffer, size, format, ap);
  va_end(ap);

  while (i < size)
    buffer[i++] = ' ';

  return n;
}



/*
 * Template checking and key generation.
 *
 * This may need refactoring at some point, eg, when we add support
 * for C_CreateObject().
 */

/*
 * First pass: called once per template entry during initial pass over
 * template to handle generic checks that apply regardless of
 * attribute type.
 */

static CK_RV p11_check_keypair_attributes_check_template_1(const CK_ATTRIBUTE_TYPE type,
                                                           const void * const val,
                                                           const size_t len,
                                                           const p11_descriptor_t * const descriptor)
{
  const p11_attribute_descriptor_t * const atd = p11_find_attribute_in_descriptor(descriptor, type);
  CK_RV rv;

  /* Attribute not allowed or not allowed for key generation */
  if (atd == NULL || (atd->flags & P11_DESCRIPTOR_FORBIDDEN_BY_GENERATE) != 0)
    lose(CKR_ATTRIBUTE_TYPE_INVALID);

  /* NULL or wrong-sized attribute values */
  if (val == NULL || (atd->size != 0 && len != atd->size))
    lose(CKR_ATTRIBUTE_VALUE_INVALID);

  /* Attributes which only the SO user is allowed to set to CK_TRUE */
  if ((atd->flags & P11_DESCRIPTOR_ONLY_SO_USER_CAN_SET) != 0 && logged_in_as != logged_in_as_so && *(CK_BBOOL *) val)
      lose(CKR_ATTRIBUTE_VALUE_INVALID);

  /* Attributes which don't match mandatory values */
  if (atd->value != NULL && (atd->flags & P11_DESCRIPTOR_DEFAULT_VALUE) == 0 && memcmp(val, atd->value, atd->length) != 0)
    lose(CKR_TEMPLATE_INCONSISTENT);

  rv = CKR_OK;

 fail:
#if DEBUG_PKCS11
  if (rv != CKR_OK)
    fprintf(stderr, "p11_check_keypair_attributes_check_template_1() rejected attribute 0x%08lx\n",
            (unsigned long) type);
#endif
  return rv;
}

/*
 * Second pass: called once per template to check that each attribute
 * required for that template has been specified exactly once.
 */

static CK_RV p11_check_keypair_attributes_check_template_2(const p11_session_t *session,
                                                           const p11_descriptor_t * const descriptor,
                                                           const CK_ATTRIBUTE_PTR template,
                                                           const CK_ULONG template_length)
{
  const CK_BBOOL *object_is_private;
  CK_RV rv;
  int i, j;

  /*
   * Some session states aren't allowed to play with private objects.
   */

  switch (session->state) {
  case CKS_RO_PUBLIC_SESSION:
  case CKS_RW_PUBLIC_SESSION:
  case CKS_RW_SO_FUNCTIONS:
    if ((i = p11_attribute_find_in_template(CKA_PRIVATE, template, template_length)) >= 0) {
      assert(template[i].pValue != NULL);
      object_is_private = template[i].pValue;
    }
    else {
      const p11_attribute_descriptor_t * const atd = p11_find_attribute_in_descriptor(descriptor, CKA_PRIVATE);
      assert(atd != NULL && atd->value != NULL);
      object_is_private = atd->value;
    }
    if (*object_is_private)
      lose(CKR_TEMPLATE_INCONSISTENT);
  }

  for (i = 0; i < descriptor->n_attributes; i++) {
    const p11_attribute_descriptor_t * const atd = &descriptor->attributes[i];
    const int required_by_api  = (atd->flags & P11_DESCRIPTOR_REQUIRED_BY_GENERATE) != 0;
    const int forbidden_by_api = (atd->flags & P11_DESCRIPTOR_FORBIDDEN_BY_GENERATE) != 0;
    const int in_descriptor    = (atd->flags & P11_DESCRIPTOR_DEFAULT_VALUE) != 0 || atd->value != NULL;
    const int pos_in_template  = p11_attribute_find_in_template(atd->type, template, template_length);

    /* Multiple entries for same attribute */
    if (pos_in_template >= 0)
      for (j = pos_in_template + 1; j < template_length; j++)
        if (template[j].type == atd->type)
          lose(CKR_TEMPLATE_INCONSISTENT);

    /* Required attribute missing from template */
    if (!forbidden_by_api && (required_by_api || !in_descriptor) && pos_in_template < 0) {
#if DEBUG_PKCS11
      fprintf(stderr, "[Missing attribute 0x%lx]\n", atd->type);
#endif
      lose(CKR_TEMPLATE_INCOMPLETE);
    }
  }

  rv = CKR_OK;

 fail:
  return rv;
}

/*
 * Mechanism-independent checks for templates and descriptors when
 * generating new keypairs.
 *
 * PKCS #11 gives the application far too much rope (including but not
 * limited to the ability to supply completely unrelated templates for
 * public and private keys in a keypair), so we need to do a fair
 * amount of checking.  We automate as much of the dumb stuff as
 * possible through the object descriptor.
 *
 * Key usage handling here is based on RFC 5280 4.2.1.3.
 *
 * PKCS #11 suggests but does not require CKA_ID values for public and
 * private key to match.
 */

static CK_RV p11_check_keypair_attributes(const p11_session_t *session,
                                          const CK_ATTRIBUTE_PTR pPublicKeyTemplate,
                                          const CK_ULONG ulPublicKeyAttributeCount,
                                          const p11_descriptor_t * const public_descriptor,
                                          const CK_ATTRIBUTE_PTR pPrivateKeyTemplate,
                                          const CK_ULONG ulPrivateKeyAttributeCount,
                                          const p11_descriptor_t * const private_descriptor)
{
  unsigned public_keyusage = 0, private_keyusage = 0;
  CK_RV rv = CKR_OK;
  int i;

  assert(session             != NULL &&
         pPublicKeyTemplate  != NULL && public_descriptor  != NULL &&
         pPrivateKeyTemplate != NULL && private_descriptor != NULL);

  /*
   * Read-only sessions can't create keys, doh.
   */

  switch (session->state) {
  case CKS_RO_PUBLIC_SESSION:
  case CKS_RO_USER_FUNCTIONS:
    lose(CKR_SESSION_READ_ONLY);
  }

  /*
   * Check values provided in the public and private templates.
   */

  for (i = 0; i < ulPublicKeyAttributeCount; i++) {
    const CK_ATTRIBUTE_TYPE type = pPublicKeyTemplate[i].type;
    const void * const       val = pPublicKeyTemplate[i].pValue;
    const size_t             len = pPublicKeyTemplate[i].ulValueLen;

    if ((rv = p11_check_keypair_attributes_check_template_1(type, val, len, public_descriptor)) != CKR_OK)
      goto fail;

    p11_attribute_apply_keyusage(&public_keyusage, type, val);
  }

  for (i = 0; i < ulPrivateKeyAttributeCount; i++) {
    const CK_ATTRIBUTE_TYPE type = pPrivateKeyTemplate[i].type;
    const void * const       val = pPrivateKeyTemplate[i].pValue;
    const size_t             len = pPrivateKeyTemplate[i].ulValueLen;

    if ((rv = p11_check_keypair_attributes_check_template_1(type, val, len, private_descriptor)) != CKR_OK)
      goto fail;

    p11_attribute_apply_keyusage(&private_keyusage, type, val);
  }

  /*
   * We insist that keyusage be specified for both public and private
   * key, and that they match.  May not need to be this strict.
   */

  if (public_keyusage != private_keyusage || public_keyusage == 0)
    lose(CKR_TEMPLATE_INCONSISTENT);

  /*
   * Check that all required attributes have been specified.
   */

  if ((rv = p11_check_keypair_attributes_check_template_2(session,
                                                          public_descriptor,
                                                          pPublicKeyTemplate,
                                                          ulPublicKeyAttributeCount))  != CKR_OK ||
      (rv = p11_check_keypair_attributes_check_template_2(session,
                                                          private_descriptor,
                                                          pPrivateKeyTemplate,
                                                          ulPrivateKeyAttributeCount)) != CKR_OK)
    goto fail;

  /*
   * If we get this far, we're happy.  Maybe.
   */

  rv = CKR_OK;

 fail:
  return rv;
}

/*
 * CKM_RSA_PKCS_KEY_PAIR_GEN key pair generation implemetation.
 *
 * Much mechanism-independent code has already been factored out of
 * this function, no doubt much remains that will require further
 * refactoring once we implement other mechanisms.
 */

static CK_RV generate_keypair_rsa_pkcs(p11_session_t *session,
                                       const CK_MECHANISM_PTR pMechanism,
                                       const CK_ATTRIBUTE_PTR pPublicKeyTemplate,
                                       const CK_ULONG ulPublicKeyAttributeCount,
                                       const CK_ATTRIBUTE_PTR pPrivateKeyTemplate,
                                       const CK_ULONG ulPrivateKeyAttributeCount,
                                       CK_OBJECT_HANDLE_PTR phPublicKey,
                                       CK_OBJECT_HANDLE_PTR phPrivateKey)
{
  CK_OBJECT_HANDLE private_handle = CK_INVALID_HANDLE;
  CK_OBJECT_HANDLE public_handle = CK_INVALID_HANDLE;
  handle_flavor_t public_handle_flavor = handle_flavor_session_object;
  handle_flavor_t private_handle_flavor = handle_flavor_session_object;
  uint8_t
    keybuf[hal_rsa_key_t_size],
    modulus[hal_rsa_key_t_size/8],
    public_exponent[hal_rsa_key_t_size/8];
  size_t modulus_len;
  CK_ULONG public_exponent_len;
  hal_rsa_key_t key = { NULL };
  CK_ULONG keysize = 0;
  CK_RV rv;
  int i;

  /*
   * Do mechanism-independent checks before anything else.
   */

  rv = p11_check_keypair_attributes(session,
                                    pPublicKeyTemplate,  ulPublicKeyAttributeCount,  &p11_descriptor_rsa_public_key,
                                    pPrivateKeyTemplate, ulPrivateKeyAttributeCount, &p11_descriptor_rsa_private_key);
  if (rv != CKR_OK)
    return rv;

  assert(session             != NULL && pMechanism   != NULL &&
         pPublicKeyTemplate  != NULL && phPublicKey  != NULL &&
         pPrivateKeyTemplate != NULL && phPrivateKey != NULL);

  /*
   * Grab values and perform mechanism-specific checks.
   */

  for (i = 0; i < ulPublicKeyAttributeCount; i++) {
    const CK_ATTRIBUTE_TYPE type = pPublicKeyTemplate[i].type;
    const void * const       val = pPublicKeyTemplate[i].pValue;
#if 0
    const size_t             len = pPublicKeyTemplate[i].ulValueLen;
#endif

    assert(val != NULL);

    switch (type) {

    case CKA_TOKEN:             /* Object stored on token */
      public_handle_flavor = p11_handle_flavor_from_cka_token(val);
      continue;

    case CKA_MODULUS_BITS:      /* Keysize in bits -- only allow multiples of 8 */
      keysize = *(CK_ULONG *) val;
      if ((keysize & 7) != 0)
        return CKR_ATTRIBUTE_VALUE_INVALID;
      continue;

    }
  }

  for (i = 0; i < ulPrivateKeyAttributeCount; i++) {
    const CK_ATTRIBUTE_TYPE type = pPrivateKeyTemplate[i].type;
    const void * const       val = pPrivateKeyTemplate[i].pValue;
#if 0
    const size_t             len = pPrivateKeyTemplate[i].ulValueLen;
#endif

    assert (val != NULL);

    switch (type) {

    case CKA_TOKEN:             /* Object stored on token */
      private_handle_flavor = p11_handle_flavor_from_cka_token(val);
      continue;

    }
  }

  /*
   * We require a key size, and if either key is a token object, the
   * other must be too.
   */
  if (keysize == 0 || public_handle_flavor != private_handle_flavor)
    return CKR_TEMPLATE_INCOMPLETE;

  /*
   * Create the PKCS #11 objects and generate the keypair.
   */

  if (!sql_exec("BEGIN")                                                                        ||
      (public_handle = p11_object_create(session, public_handle_flavor,
                                         pPublicKeyTemplate, ulPublicKeyAttributeCount,
                                         &p11_descriptor_rsa_public_key,
                                         pMechanism)) == CK_INVALID_HANDLE                      ||
      (private_handle = p11_object_create(session, private_handle_flavor,
                                          pPrivateKeyTemplate,  ulPrivateKeyAttributeCount,
                                          &p11_descriptor_rsa_private_key,
                                          pMechanism)) == CK_INVALID_HANDLE			||
      !p11_attribute_get(public_handle, CKA_PUBLIC_EXPONENT,
                         public_exponent, &public_exponent_len, sizeof(public_exponent))	||
      !hal_check(hal_rsa_key_gen(&key, keybuf, sizeof(keybuf), keysize/8,
                                 public_exponent, (size_t) public_exponent_len))                ||
      !p11_object_set_rsa_private_key(private_handle, key)                                      ||
      !hal_check(hal_rsa_key_get_modulus(key, modulus, &modulus_len, sizeof(modulus)))          ||
      !p11_attribute_set(public_handle,  CKA_MODULUS, modulus, modulus_len)                     ||
      !p11_attribute_set(private_handle, CKA_MODULUS, modulus, modulus_len))
    lose(CKR_FUNCTION_FAILED);

  hal_rsa_key_clear(key);

  /*
   * Commit the SQL transaction.
   */

  if (!sql_exec("COMMIT"))
    lose(CKR_FUNCTION_FAILED);

  /*
   * All went well, return handles and we're done.
   */
  *phPublicKey  = public_handle;
  *phPrivateKey = private_handle;
  return CKR_OK;

 fail:

  memset(keybuf, 0, sizeof(keybuf));

  if (!sql_exec("ROLLBACK"))
    rv = CKR_GENERAL_ERROR;

  return rv;
}

/*
 * Construct a PKCS #1 DigestInfo object.  This requires some (very
 * basic) ASN.1 encoding, which we perform inline.
 */

static int pkcs1_construct_digestinfo(const hal_hash_descriptor_t * const desc,
                                      const uint8_t * const data, const size_t data_len,
                                      uint8_t *digest_info, const size_t digest_info_len)
{
  uint8_t statebuf[desc->hash_state_length];
  hal_hash_state_t state = { NULL };
  uint8_t *d = digest_info;

  /*
   * Make sure size of output buffer is right.  Caller is responsible
   * for supplying the right length, the check here is just paranoia.
   *
   * This encoder will fail if the DigestInfo object is more than
   * 129 octets long.  Rewrite if and when we need to support
   * digests or OIDs long enough for that to be an issue.
   */

  assert(digest_info_len == desc->digest_length + desc->digest_algorithm_id_length + 4);
  assert(digest_info_len < 130);

  *d++ = 0x30;                /* SEQUENCE */
  *d++ = (uint8_t) (digest_info_len - 2);

  memcpy(d, desc->digest_algorithm_id, desc->digest_algorithm_id_length);
  d += desc->digest_algorithm_id_length;

  *d++ = 0x04;                /* OCTET STRING */
  *d++ = (uint8_t) desc->digest_length;

  assert(digest_info + digest_info_len == d + desc->digest_length);

  const int ok = (hal_check(hal_hash_initialize(desc, &state, statebuf, sizeof(statebuf))) &&
                  hal_check(hal_hash_update(state, data, data_len))                        &&
                  hal_check(hal_hash_finalize(state, d, desc->digest_length)));

  memset(statebuf, 0, sizeof(statebuf));
  if (!ok)
    memset(digest_info, 0, digest_info_len);
  return ok;
}

/*
 * Pad an octet string with PKCS #1.5 padding for use with RSA.
 *
 * For the moment, this only handles type 01 encryption blocks, thus
 * is only suitable for use with signature and verification.  If and
 * when we add support for encryption and decryption, this function
 * should be extended to take an argument specifying the block type
 * and include support for generating type 02 encryption blocks.
 * Other than the block type code, the only difference is the padding
 * value: for type 01 it's constant (0xFF), for type 02 it should be
 * non-zero random bytes from the CSPRNG.
 */

static int pkcs1_5_pad(const uint8_t * const data, const size_t data_len,
                       uint8_t *block, const size_t block_len)
{
  assert(data != NULL && block != NULL);

  /*
   * Congregation will now please turn to RFC 2313 8.1 as we
   * construct a PKCS #1.5 type 01 encryption block.
   */

  if (data_len > block_len - 11)
    return 0;

  block[0] = 0x00;
  block[1] = 0x01;

  /* This is where we'd use non-zero random bytes if constructing a type 02 block. */
  memset(block + 2, 0xFF, block_len - 3 - data_len);

  block[block_len - data_len - 1] = 0x00;
  memcpy(block + block_len - data_len, data, data_len);

#if DEBUG_PKCS11 > 1
  fprintf(stderr, "[PKCS #1.5 block_len %lu data_len %lu block ",
          (unsigned long) block_len, (unsigned long) data_len);
  for (int i = 0; i < block_len; i++)
    fprintf(stderr, "%s%02x", i == 0 ? "" : ":", block[i]);
  fprintf(stderr, "]\n");
#endif

  return 1;
}

/*
 * Sign a PKCS #1 DigestInfo using an RSA key and PKCS #1.5 padding.
 *
 * As explained in RFC 3447, the RSASP1 (signature generation)
 * operation is the same mathematical operation as the RSADP
 * (decryption) operation (both use the private key as exponent).
 */

static CK_RV sign_rsa_pkcs(hal_rsa_key_t key,
                           const uint8_t * const digest_info, const size_t digest_info_len,
                           uint8_t *signature, const size_t signature_len)
{
  CK_RV rv;

  assert(digest_info != NULL && signature != NULL);

  if (!pkcs1_5_pad(digest_info, digest_info_len, signature, signature_len))
    lose(CKR_DATA_LEN_RANGE);

  if (!hal_check(hal_rsa_decrypt(key, signature, signature_len, signature, signature_len)))
    lose(CKR_FUNCTION_FAILED);

  return CKR_OK;

 fail:
  memset(signature, 0, signature_len);
  return rv;
}

/*
 * Verify a PKCS #1.5 padded RSA signature.
 *
 * We don't bother decoding the ASN.1, we just generate the type 01
 * encryption block we expect and compare it with what we got.
 *
 * Using constant-time comparision code for this is probably
 * unnecessary, but it's also harmless.
 */

static CK_RV verify_rsa_pkcs(hal_rsa_key_t key,
                             const uint8_t * const digest_info, const size_t digest_info_len,
                             const uint8_t * const signature, const size_t signature_len)
{
  assert(digest_info != NULL && signature != NULL);

  uint8_t expected[signature_len], received[signature_len];
  unsigned diff = 0;
  CK_RV rv;

  if (!pkcs1_5_pad(digest_info, digest_info_len, expected, sizeof(expected)))
    lose(CKR_DATA_LEN_RANGE);

  if (!hal_check(hal_rsa_encrypt(key, signature, signature_len, received, sizeof(received))))
    lose(CKR_FUNCTION_FAILED);

  for (int i = 0; i < signature_len; i++)
    diff |= expected[i] ^ received[i];

  if (diff != 0)
    lose(CKR_SIGNATURE_INVALID);

  rv = CKR_OK;

 fail:
  memset(expected, 0, sizeof(expected));
  memset(received, 0, sizeof(received));
  return rv;
}




/*
 * PKCS #11 API functions.
 */

CK_RV C_Initialize(CK_VOID_PTR pInitArgs)
{
  ENTER_PUBLIC_FUNCTION(C_Initialize);

  CK_C_INITIALIZE_ARGS_PTR a = pInitArgs;
  int initialized_sql = 0;
  CK_RV rv;

  /*
   * We'd like to detect the error of calling this method more than
   * once in a single process without an intervening call to
   * C_Finalize(), but there's no completely portable way to do that
   * when faced with things like the POSIX fork() system call.  For
   * the moment, we use a POSIX-specific check, but may need to
   * generalize this for other platforms.
   */

#if USE_POSIX
  if (initialized_pid == getpid())
    lose(CKR_CRYPTOKI_ALREADY_INITIALIZED);
#endif

  /*
   * Sort out what the user wants to do about mutexes.  Default is not
   * to use mutexes at all.
   *
   * There's a chicken and egg problem here: setting up the global
   * mutex and mutex function pointers creates a race condition, and
   * there's no obvious action we can take which is robust in the face
   * of pathological behavior by the caller such as simultaneous calls
   * to this method with incompatible mutex primitives.
   *
   * Given that (a) it's an error to call this method more than once
   * in the same process without an intervening F_Finalize() call, and
   * given that (b) we haven't actually promised to do any kind of
   * locking at all until this method returns CKR_OK, we punt
   * responsibility for this pathological case back to the caller.
   */

  mutex_cb_create  = NULL;
  mutex_cb_destroy = NULL;
  mutex_cb_lock    = NULL;
  mutex_cb_unlock  = NULL;

  if (a != NULL) {

    const int functions_provided = ((a->CreateMutex  != NULL) +
                                    (a->DestroyMutex != NULL) +
                                    (a->LockMutex    != NULL) +
                                    (a->UnlockMutex  != NULL));

    /*
     * Reserved is, um, reserved.
     * Mutex parameters must either all be present or all be absent.
     */

    if (a->pReserved != NULL || (functions_provided & 3) != 0)
      lose(CKR_ARGUMENTS_BAD);

    /*
     * If the user provided mutex functions, use them.  Otherwise, if
     * the user wants locking, use POSIX mutexes or return an error
     * depending on whether we have POSIX mutexes available.
     * Otherwise, we don't need to use mutexes.
     */

    if (functions_provided) {
      mutex_cb_create  = a->CreateMutex;
      mutex_cb_destroy = a->DestroyMutex;
      mutex_cb_lock    = a->LockMutex;
      mutex_cb_unlock  = a->UnlockMutex;
    }

    else if ((a->flags & CKF_OS_LOCKING_OK) != 0) {
#if USE_PTHREADS
      mutex_cb_create  = posix_mutex_create;
      mutex_cb_destroy = posix_mutex_destroy;
      mutex_cb_lock    = posix_mutex_lock;
      mutex_cb_unlock  = posix_mutex_unlock;
#else
      lose(CKR_CANT_LOCK);
#endif
    }
  }

  /*
   * Now that we know which mutex implementation to use, set up a
   * global mutex.  We may want something finer grained later, but
   * this is enough to preserve the basic API semantics.
   *
   * Open question whether we should lock at this point, given that
   * until we return we haven't promised to do locking.  Skip for now
   * as it's simpler, fix later if it turns out to be a problem.
   */

  if ((rv = mutex_create(&p11_global_mutex)) != CKR_OK)
    goto fail;

  /*
   * Initialize SQLite3, opening the database(s) and loading the
   * schema and views.
   */

  if (!sql_init())
    lose(CKR_GENERAL_ERROR);

  initialized_sql = 1;

  if (!kek_init())
    lose(CKR_GENERAL_ERROR);

#if USE_POSIX
  initialized_pid = getpid();
#endif

  return CKR_OK;

 fail:

  if (initialized_sql)
    sql_fini();

  return rv;
}

CK_RV C_Finalize(CK_VOID_PTR pReserved)
{
  ENTER_PUBLIC_FUNCTION(C_Finalize);

  CK_RV rv = CKR_OK;

  if (pReserved != NULL)
    return CKR_ARGUMENTS_BAD;

  mutex_lock_or_return_failure(p11_global_mutex);

  /*
   * Destroy all current sessions.
   */

  p11_session_delete_all();

  /*
   * Shut down SQLite3.
   */

  if (!sql_fini())
    lose(CKR_GENERAL_ERROR);

  /*
   * By this point we're pretty well committed to shutting down, so
   * there's not much to be done if these mutex operations fail.
   */

  rv =  mutex_unlock(p11_global_mutex);
  (void) mutex_destroy(p11_global_mutex);
  p11_global_mutex = NULL;
  return rv;

 fail:
  (void) mutex_unlock(p11_global_mutex);
  return rv;
}

CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList)
{
  ENTER_PUBLIC_FUNCTION(C_GetFunctionList);

  /*
   * Use pkcs11f.h to build dispatch vector for C_GetFunctionList().
   * This should be const, but that's not what PKCS #11 says, oh well.
   *
   * This doesn't touch anything requiring locks, nor should it.
   */

  static CK_FUNCTION_LIST ck_function_list = {
    { CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR },
#define CK_PKCS11_FUNCTION_INFO(name) name,
#include "pkcs11f.h"
#undef  CK_PKCS11_FUNCTION_INFO
  };

  if (ppFunctionList == NULL)
    return CKR_ARGUMENTS_BAD;

  *ppFunctionList = &ck_function_list;

  return CKR_OK;
}

CK_RV C_GetSlotList(CK_BBOOL tokenPresent,
                    CK_SLOT_ID_PTR pSlotList,
                    CK_ULONG_PTR pulCount)
{
  ENTER_PUBLIC_FUNCTION(C_GetSlotList);

  /*
   * We only have one slot, and it's hardwired.
   * No locking required here as long as this holds.
   */

  if (pulCount == NULL)
    return CKR_ARGUMENTS_BAD;

  if (pSlotList != NULL && *pulCount < 1)
    return CKR_BUFFER_TOO_SMALL;

  *pulCount = 1;

  if (pSlotList != NULL)
    pSlotList[0] = P11_ONE_AND_ONLY_SLOT;

  return CKR_OK;
}

CK_RV C_GetTokenInfo(CK_SLOT_ID slotID,
                     CK_TOKEN_INFO_PTR pInfo)
{
  ENTER_PUBLIC_FUNCTION(C_GetTokenInfo);

  /*
   * No locking required here as long as we're just returning constants.
   */

  if (pInfo == NULL)
    return CKR_ARGUMENTS_BAD;

  if (slotID != P11_ONE_AND_ONLY_SLOT)
    return CKR_SLOT_ID_INVALID;

  memset(pInfo, 0, sizeof(*pInfo));

  /*
   * No real idea (yet) how we get many of the following parameters.
   *
   * pInfo->label is supposed to be set when the token is initialized.
   * Not yet sure what that means in our context, but need something
   * here or the libhsm test programs will bomb trying to find the
   * right token, so hard-wire something for now.
   */

  psnprintf(pInfo->label, sizeof(pInfo->label),
            "Cryptech Token");

  psnprintf(pInfo->manufacturerID, sizeof(pInfo->manufacturerID),
            "Cryptech Project");

  psnprintf(pInfo->model, sizeof(pInfo->model),
            "%04x%04x%04x%04x",
            P11_VERSION_HW_MAJOR, P11_VERSION_HW_MINOR,
            P11_VERSION_SW_MAJOR, P11_VERSION_SW_MINOR);

  psnprintf(pInfo->serialNumber, sizeof(pInfo->serialNumber),
            "007");

  pInfo->flags = CKF_RNG | CKF_LOGIN_REQUIRED;

#warning Have not yet sorted out token flags
#if 0
    CKF_RNG
    CKF_WRITE_PROTECTED
    CKF_LOGIN_REQUIRED
    CKF_USER_PIN_INITIALIZED
    CKF_RESTORE_KEY_NOT_NEEDED
    CKF_CLOCK_ON_TOKEN
    CKF_PROTECTED_AUTHENTICATION_PATH
    CKF_DUAL_CRYPTO_OPERATIONS
    CKF_TOKEN_INITIALIZED
    CKF_SECONDARY_AUTHENTICATION
    CKF_USER_PIN_COUNT_LOW
    CKF_USER_PIN_FINAL_TRY
    CKF_USER_PIN_LOCKED
    CKF_USER_PIN_TO_BE_CHANGED
    CKF_SO_PIN_COUNT_LOW
    CKF_SO_PIN_FINAL_TRY
    CKF_SO_PIN_LOCKED
    CKF_SO_PIN_TO_BE_CHANGED
    CKF_ERROR_STATE
#endif

#warning Much of the TOKEN_INFO we return is nonsense
  pInfo->ulMaxSessionCount      = CK_EFFECTIVELY_INFINITE;
  pInfo->ulSessionCount         = CK_UNAVAILABLE_INFORMATION;
  pInfo->ulMaxRwSessionCount    = CK_EFFECTIVELY_INFINITE;
  pInfo->ulRwSessionCount       = CK_UNAVAILABLE_INFORMATION;
  pInfo->ulMaxPinLen            = P11_MAX_PIN_LENGTH;
  pInfo->ulMinPinLen            = P11_MIN_PIN_LENGTH;
  pInfo->ulTotalPublicMemory    = CK_UNAVAILABLE_INFORMATION;
  pInfo->ulFreePublicMemory     = CK_UNAVAILABLE_INFORMATION;
  pInfo->ulTotalPrivateMemory   = CK_UNAVAILABLE_INFORMATION;
  pInfo->ulFreePrivateMemory    = CK_UNAVAILABLE_INFORMATION;
  pInfo->hardwareVersion.major  = P11_VERSION_HW_MAJOR;
  pInfo->hardwareVersion.minor  = P11_VERSION_HW_MINOR;
  pInfo->firmwareVersion.major  = P11_VERSION_SW_MAJOR;
  pInfo->firmwareVersion.minor  = P11_VERSION_SW_MINOR;

#warning Need to sort out hardware clock
#if 0
  /*
   * Eventually we expect cryptech devices to have their own hardware
   * clocks.  Not implemented yet.
   */
  pInfo->utcTime;
#endif

  return CKR_OK;
}

CK_RV C_OpenSession(CK_SLOT_ID slotID,
                    CK_FLAGS flags,
                    CK_VOID_PTR pApplication,
                    CK_NOTIFY Notify,
                    CK_SESSION_HANDLE_PTR phSession)
{
  ENTER_PUBLIC_FUNCTION(C_OpenSession);

  const int parallel_session = (flags & CKF_SERIAL_SESSION) == 0;
  const int read_only_session = (flags & CKF_RW_SESSION) == 0;
  p11_session_t *session = NULL;
  CK_RV rv;

  mutex_lock_or_return_failure(p11_global_mutex);

  if (slotID != P11_ONE_AND_ONLY_SLOT)
    lose(CKR_SLOT_ID_INVALID);

  if (phSession == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (parallel_session)
    lose(CKR_SESSION_PARALLEL_NOT_SUPPORTED);

  if ((session = p11_session_new()) == NULL)
    lose(CKR_HOST_MEMORY);

  switch (logged_in_as) {

  case not_logged_in:
    session->state = read_only_session ? CKS_RO_PUBLIC_SESSION : CKS_RW_PUBLIC_SESSION;
    break;

  case logged_in_as_user:
    session->state = read_only_session ? CKS_RO_USER_FUNCTIONS : CKS_RW_USER_FUNCTIONS;
    break;

  case logged_in_as_so:
    if (read_only_session)
      lose(CKR_SESSION_READ_WRITE_SO_EXISTS);
    session->state = CKS_RW_SO_FUNCTIONS;
    break;
  }

  session->notify = Notify;
  session->application = pApplication;

  if (!p11_session_add(session))
    lose(CKR_FUNCTION_FAILED);

  assert(p11_session_consistent_login());

  if ((rv = mutex_unlock(p11_global_mutex)) != CKR_OK)
    goto fail;

  *phSession = session->handle;
  return CKR_OK;

 fail:
  p11_session_free(session);
  (void) mutex_unlock(p11_global_mutex);
  return rv;
}

CK_RV C_CloseSession(CK_SESSION_HANDLE hSession)
{
  ENTER_PUBLIC_FUNCTION(C_CloseSession);

  CK_RV rv;

  mutex_lock_or_return_failure(p11_global_mutex);

  rv = p11_session_delete(hSession);

  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_CloseAllSessions(CK_SLOT_ID slotID)
{
  ENTER_PUBLIC_FUNCTION(C_CloseAllSessions);

  if (slotID != P11_ONE_AND_ONLY_SLOT)
    return CKR_SLOT_ID_INVALID;

  mutex_lock_or_return_failure(p11_global_mutex);

  p11_session_delete_all();

  return mutex_unlock(p11_global_mutex);
}

CK_RV C_Login(CK_SESSION_HANDLE hSession,
              CK_USER_TYPE userType,
              CK_UTF8CHAR_PTR pPin,
              CK_ULONG ulPinLen)
{
  ENTER_PUBLIC_FUNCTION(C_Login);

  static const char pin_query_format[] =
    " SELECT pbkdf2_iterations, %s_pin, %s_pin_salt FROM global";

  p11_session_t *session;
  sqlite3_stmt *q = NULL;
  const char *pin_type;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if (pPin == NULL)
    lose(CKR_ARGUMENTS_BAD);

  /*
   * Mind, I don't really know why this function takes a session
   * handle, given that the semantics don't seem to call upon us to do
   * anything special for "this" session.
   */

  if (p11_session_find(hSession) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  /*
   * We don't currently support re-login without an intervening
   * logout, so reject the login attempt if we're already logged in.
   */

  if (logged_in_as != not_logged_in)
    lose(CKR_USER_ALREADY_LOGGED_IN);

  /*
   * Figure out which PIN we're checking.
   * We don't (yet?) support CKU_CONTEXT_SPECIFIC.
   *
   * Read-only SO is an illegal state, so reject the login attempt if
   * we have any read-only sessions and we're trying to log in as SO.
   */

  switch (userType) {
  case CKU_USER:
    pin_type = "user";
    break;
  case CKU_SO:
    for (session = p11_sessions; session != NULL; session = session->link)
      if (session->state == CKS_RO_PUBLIC_SESSION)
        lose(CKR_SESSION_READ_ONLY_EXISTS);
    pin_type = "so";
    break;
  case CKU_CONTEXT_SPECIFIC:
    lose(CKR_OPERATION_NOT_INITIALIZED);
  default:
    lose(CKR_USER_TYPE_INVALID);
  }

  /*
   * Look up the PIN and make sure it's set.
   *
   * Not obvious what error we should return if SO PIN isn't set, for
   * now consider this state "locked" (because it hasn't been set yet).
   */

  if (!sql_check_ok(sql_prepare(&q, pin_query_format, pin_type, pin_type)) ||
      !sql_check_row(sqlite3_step(q)))
    lose(CKR_FUNCTION_FAILED);

  if (sqlite3_column_type(q, 1) == SQLITE_NULL ||
      sqlite3_column_type(q, 2) == SQLITE_NULL) {
    switch (userType) {
    case CKU_USER:
      lose(CKR_USER_PIN_NOT_INITIALIZED);
    case CKU_SO:
      lose(CKR_PIN_LOCKED);
    default:
      lose(CKR_USER_TYPE_INVALID);
    }
  }

  /*
   * Run PBKDF2 over the supplied PIN and compare results.
   *
   * Probably not really necessary to use constant-time string
   * comparison, but it's harmless and cheap, so we might as well.
   */

  {
    const unsigned iterations = sqlite3_column_int(q, 0);
    const uint8_t * const pin  = sqlite3_column_blob(q, 1);
    const uint8_t * const salt = sqlite3_column_blob(q, 2);
    const size_t pin_len  = sqlite3_column_bytes(q, 1);
    const size_t salt_len = sqlite3_column_bytes(q, 2);
    uint8_t pinbuf[pin_len];
    unsigned diff = 0;

    if (!hal_check(hal_pbkdf2(hal_hash_sha256, pPin, ulPinLen, salt, salt_len,
                              pinbuf, sizeof(pinbuf), iterations)))
      lose(CKR_FUNCTION_FAILED);

    for (int i = 0; i < pin_len; i++)
      diff |= pin[i] ^ pinbuf[i];

    if (diff != 0)
      lose(CKR_PIN_INCORRECT);
  }

  /*
   * If we get here, the PIN was OK.  Update global login state, then
   * whack every session into the correct new state.
   */

  assert(p11_session_consistent_login());

  logged_in_as = userType == CKU_SO ? logged_in_as_so : logged_in_as_user;

  for (session = p11_sessions; session != NULL; session = session->link) {
    switch (session->state) {

    case CKS_RO_PUBLIC_SESSION:
      assert(userType == CKU_USER);
      session->state = CKS_RO_USER_FUNCTIONS;
      continue;

    case CKS_RW_PUBLIC_SESSION:
      session->state = userType == CKU_SO ? CKS_RW_SO_FUNCTIONS : CKS_RW_USER_FUNCTIONS;
      continue;

    }
  }

  assert(p11_session_consistent_login());

 fail:
  sqlite3_finalize(q);
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_Logout(CK_SESSION_HANDLE hSession)
{
  ENTER_PUBLIC_FUNCTION(C_Logout);

  p11_session_t *session;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  /*
   * Mind, I don't really know why this function takes a session
   * handle, given that the semantics don't seem to call upon us to do
   * anything special for "this" session.
   */

  if (p11_session_find(hSession) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (logged_in_as == not_logged_in)
    lose(CKR_USER_NOT_LOGGED_IN);

  /*
   * Update global login state, then delete any private objects and
   * whack every existing session into the right state.
   */

  assert(p11_session_consistent_login());

  logged_in_as = not_logged_in;

  p11_object_delete_all_private();

  for (session = p11_sessions; session != NULL; session = session->link) {
    switch (session->state) {

    case CKS_RO_USER_FUNCTIONS:
      session->state = CKS_RO_PUBLIC_SESSION;
      continue;

    case CKS_RW_USER_FUNCTIONS:
    case CKS_RW_SO_FUNCTIONS:
      session->state = CKS_RW_PUBLIC_SESSION;
      continue;

    }
  }

  assert(p11_session_consistent_login());

 fail:
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_DestroyObject(CK_SESSION_HANDLE hSession,
                      CK_OBJECT_HANDLE hObject)
{
  ENTER_PUBLIC_FUNCTION(C_DestroyObject);

  static const char delete_object[] =
    " DELETE FROM object WHERE object_handle = ?";

  static const char delete_token_object[] =
    " DELETE FROM token_object"
    " WHERE token_object_id = (SELECT token_object_id FROM object WHERE object_handle = ?)";


  p11_session_t *session;
  sqlite3_stmt *q = NULL;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  session = p11_session_find(hSession);

  if ((rv = p11_object_check_rights(session, hObject, p11_object_access_write)) != CKR_OK)
    goto fail;

  if (is_token_handle(hObject)                                  &&
      (!sql_check_ok(sql_prepare(&q, delete_token_object))      ||
       !sql_check_ok(sqlite3_bind_int64(q, 1, hObject))         ||
       !sql_check_done(sqlite3_step(q))                         ||
       !sql_check_ok(sql_finalize_and_clear(&q))))
    lose(CKR_FUNCTION_FAILED);

  if (!sql_check_ok(sql_prepare(&q, delete_object))             ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, hObject))          ||
      !sql_check_done(sqlite3_step(q)))
    lose(CKR_FUNCTION_FAILED);

 fail:
  sqlite3_finalize(q);
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_GetAttributeValue(CK_SESSION_HANDLE hSession,
                          CK_OBJECT_HANDLE hObject,
                          CK_ATTRIBUTE_PTR pTemplate,
                          CK_ULONG ulCount)
{
  ENTER_PUBLIC_FUNCTION(C_GetAttributeValue);

  static const char select_format[] =
    " SELECT value FROM %s_attribute NATURAL JOIN object"
    " WHERE object_handle = ?1 AND type = ?2";

  const char *flavor = is_token_handle(hObject) ? "token" : "session";

  p11_session_t *session;
  const p11_descriptor_t *descriptor = NULL;
  CK_BBOOL cka_sensitive, cka_extractable;
  CK_OBJECT_CLASS cka_class;
  CK_KEY_TYPE cka_key_type;
  int sensitive_object = 0;
  sqlite3_stmt *q = NULL;
  CK_RV rv;
  int ret, i;

  mutex_lock_or_return_failure(p11_global_mutex);

  if (pTemplate == NULL)
    lose(CKR_ARGUMENTS_BAD);

  session = p11_session_find(hSession);

  if ((rv = p11_object_check_rights(session, hObject, p11_object_access_read)) != CKR_OK)
    goto fail;

  if (!p11_attribute_get_ulong(hObject, CKA_CLASS, &cka_class))
    lose(CKR_OBJECT_HANDLE_INVALID);

  switch (cka_class) {

  case CKO_PRIVATE_KEY:
  case CKO_SECRET_KEY:
    if (!p11_attribute_get_bbool(hObject, CKA_EXTRACTABLE, &cka_extractable) ||
        !p11_attribute_get_bbool(hObject, CKA_SENSITIVE,   &cka_sensitive))
      lose(CKR_OBJECT_HANDLE_INVALID);

    sensitive_object = cka_sensitive || !cka_extractable;

    /* Fall through */

  case CKO_PUBLIC_KEY:
    if (!p11_attribute_get_ulong(hObject, CKA_KEY_TYPE, &cka_key_type))
      lose(CKR_OBJECT_HANDLE_INVALID);
    descriptor = p11_descriptor_from_key_type(cka_class, cka_key_type);
  }

  if (!sql_check_ok(sql_prepare(&q, select_format, flavor)) ||
      !sql_check_ok(sqlite3_bind_int64(q, 1, hObject)))
    lose(CKR_FUNCTION_FAILED);

  rv = CKR_OK;

  for (i = 0; i < ulCount; i++) {

    if (sensitive_object && p11_attribute_is_sensitive(descriptor, pTemplate[i].type)) {
      pTemplate[i].ulValueLen = -1;
      rv = CKR_ATTRIBUTE_SENSITIVE;
    }

    else if (!sql_check_ok(sqlite3_reset(q)) ||
             !sql_check_ok(sqlite3_bind_int64(q, 2, pTemplate[i].type)) ||
             (ret = sqlite3_step(q)) != SQLITE_ROW) {
      if (ret != SQLITE_DONE)
        sql_whine_step();
      pTemplate[i].ulValueLen = -1;
      rv = CKR_ATTRIBUTE_TYPE_INVALID;
    }

    else if (pTemplate[i].pValue == NULL) {
      pTemplate[i].ulValueLen = sqlite3_column_bytes(q, 0);
    }

    else if (pTemplate[i].ulValueLen >= sqlite3_column_bytes(q, 0)) {
      pTemplate[i].ulValueLen = sqlite3_column_bytes(q, 0);
      memcpy(pTemplate[i].pValue, sqlite3_column_blob(q, 0), pTemplate[i].ulValueLen);
    }

    else {
      pTemplate[i].ulValueLen = -1;
      rv = CKR_BUFFER_TOO_SMALL;
    }

  }

 fail:
  sqlite3_finalize(q);
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_FindObjectsInit(CK_SESSION_HANDLE hSession,
                        CK_ATTRIBUTE_PTR pTemplate,
                        CK_ULONG ulCount)
{
  ENTER_PUBLIC_FUNCTION(C_FindObjectsInit);

  static const char select_missing[] =
    " WITH"
    "   known AS (SELECT token_object_id FROM object WHERE token_object_id IS NOT NULL)"
    " SELECT token_object_id FROM token_object WHERE token_object_id NOT IN known";

  static const char insert_missing[] =
    " INSERT INTO object (object_handle, token_object_id) VALUES (?1, ?2)";

  static const char create_format[] =
    " CREATE TEMPORARY TABLE findobjects_%lu AS"
    " SELECT object_id FROM object NATURAL LEFT JOIN session"
    " WHERE session_handle IS NULL OR session_handle = ?1";

  static const char drop_format[] =
    " DROP TABLE IF EXISTS findobjects_%lu";

  static const char delete_format[] =
    " WITH"
    "   matches AS (SELECT object_id"
    "                 FROM object NATURAL JOIN session_attribute"
    "                 WHERE type = ?1 AND value = ?2"
    "               UNION"
    "               SELECT object_id"
    "                 FROM object NATURAL JOIN token_attribute"
    "                 WHERE type = ?1 AND value = ?2)"
    " DELETE FROM findobjects_%lu WHERE object_id NOT IN matches";

  static const char select_format[] =
    " SELECT object_handle FROM findobjects_%lu NATURAL JOIN object ORDER BY object_id";

  p11_session_t *session;
  sqlite3_stmt *q1 = NULL, *q2 = NULL;
  CK_RV rv = CKR_OK;
  int i, ret;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (ulCount > 0  && pTemplate == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (session->find_query != NULL)
    lose(CKR_OPERATION_ACTIVE);

  /*
   * Assign handles to any token objects that don't have them yet.
   */

  if (!sql_check_ok(sql_prepare(&q1, select_missing))   ||
      !sql_check_ok(sql_prepare(&q2, insert_missing)))
    lose(CKR_FUNCTION_FAILED);

  while ((ret = sqlite3_step(q1)) == SQLITE_ROW) {
    sqlite3_int64 token_object_id = sqlite3_column_int64(q1, 0);
    CK_OBJECT_HANDLE object_handle = p11_allocate_unused_handle(handle_flavor_token_object);

    if (!sql_check_ok(sqlite3_reset(q2))                                ||
        !sql_check_ok(sqlite3_bind_int64(q2, 1, object_handle))         ||
        !sql_check_ok(sqlite3_bind_int64(q2, 2, token_object_id))       ||
        !sql_check_done(sqlite3_step(q2)))
      lose(CKR_FUNCTION_FAILED);
  }

  if (ret != SQLITE_DONE) {
    sql_whine_step();
    lose(CKR_FUNCTION_FAILED);
  }

  /*
   * Create a temporary table to hold this session's FindObjects
   * state.  Populate this with every object this session knows about,
   * then prune based on login status and whatever filter attributes
   * the caller supplied.
   */

  if (!sql_check_ok(sql_finalize_and_clear(&q1))                ||
      !sql_check_ok(sql_finalize_and_clear(&q2))                ||
      !sql_check_ok(sql_prepare(&q1, drop_format, hSession))    ||
      !sql_check_done(sqlite3_step(q1))                         ||
      !sql_check_ok(sql_prepare(&q2, create_format, hSession))  ||
      !sql_check_ok(sqlite3_bind_int64(q2, 1, hSession))        ||
      !sql_check_done(sqlite3_step(q2))                         ||
      !sql_check_ok(sql_finalize_and_clear(&q1))                ||
      !sql_check_ok(sql_finalize_and_clear(&q2))                ||
      !sql_check_ok(sql_prepare(&q1, delete_format, hSession)))
    lose(CKR_FUNCTION_FAILED);

  /*
   * If we're not logged in as the regular user, run an extra filter
   * cycle to remove all private objects before we get to the
   * caller-supplied template.
   */

  if (logged_in_as != logged_in_as_user) {
    if (!sql_check_ok(sqlite3_bind_int64(q1, 1, CKA_PRIVATE))   ||
        !sql_check_ok(sqlite3_bind_blob( q1, 2,
                                         &const_CK_FALSE,
                                         sizeof(const_CK_FALSE),
                                         NULL))                 ||
        !sql_check_done(sqlite3_step(q1)))
      lose(CKR_FUNCTION_FAILED);
  }

  /*
   * Filter through the caller-supplied template.
   *
   * NB: This doesn't support some of the more obscure searches, such
   * as searches for sessions or hardware features.  Too much rope
   * already, worry about those if we ever really need them.
   */

  for (i = 0; i < ulCount; i++)
    if (!sql_check_ok(sqlite3_reset(q1))                                ||
        !sql_check_ok(sqlite3_bind_int64(q1, 1, pTemplate[i].type))     ||
        !sql_check_ok(sqlite3_bind_blob( q1, 2, pTemplate[i].pValue,
                                        pTemplate[i].ulValueLen, NULL)) ||
        !sql_check_done(sqlite3_step(q1)))
      lose(CKR_FUNCTION_FAILED);

  /*
   * Stash a prepared query in the session object which will return
   * whatever object handles survived all that filtering.
   */

  if (!sql_check_ok(sql_prepare(&session->find_query, select_format, hSession)))
    lose(CKR_FUNCTION_FAILED);
  session->find_query_done = 0;

 fail:
  sqlite3_finalize(q1);
  sqlite3_finalize(q2);
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_FindObjects(CK_SESSION_HANDLE hSession,
                    CK_OBJECT_HANDLE_PTR phObject,
                    CK_ULONG ulMaxObjectCount,
                    CK_ULONG_PTR pulObjectCount)
{
  ENTER_PUBLIC_FUNCTION(C_FindObjects);

  p11_session_t *session;
  int i, ret = SQLITE_OK;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (session->find_query == NULL)
    lose(CKR_OPERATION_NOT_INITIALIZED);

  if (phObject == NULL || pulObjectCount == NULL)
    lose(CKR_ARGUMENTS_BAD);

  /*
   * C_FindObjectsInit() did all the heavy lifting, we just have to
   * return the resulting handles.
   */

  i = 0;

  if (!session->find_query_done)
    while (i < ulMaxObjectCount && (ret = sqlite3_step(session->find_query)) == SQLITE_ROW)
      phObject[i++] = (CK_OBJECT_HANDLE) sqlite3_column_int64(session->find_query, 0);

  switch (ret) {

  case SQLITE_DONE:
    session->find_query_done = 1;
    break;

  case SQLITE_OK:
  case SQLITE_ROW:
    break;

  default:
    sql_whine_step();
    lose(CKR_FUNCTION_FAILED);

  }

  *pulObjectCount = i;

 fail:
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE hSession)
{
  ENTER_PUBLIC_FUNCTION(C_FindObjectsFinal);

  static const char drop_format[] =
    " DROP TABLE IF EXISTS findobjects_%lu";

  p11_session_t *session;
  sqlite3_stmt *q = NULL;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (session->find_query == NULL)
    lose(CKR_OPERATION_NOT_INITIALIZED);

  /*
   * Clean up result query and temporary table.
   */

  if (!sql_check_ok(sql_finalize_and_clear(&session->find_query))       ||
      !sql_check_ok(sql_prepare(&q, drop_format, hSession))             ||
      !sql_check_done(sqlite3_step(q)))
    lose(CKR_FUNCTION_FAILED);

 fail:
  sqlite3_finalize(q);
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_DigestInit(CK_SESSION_HANDLE hSession,
                   CK_MECHANISM_PTR pMechanism)
{
  ENTER_PUBLIC_FUNCTION(C_DigestInit);

  p11_session_t *session;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (pMechanism == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (session->digest_descriptor != NULL)
    lose(CKR_OPERATION_ACTIVE);

  switch (pMechanism->mechanism) {
  case CKM_SHA_1:       session->digest_descriptor = hal_hash_sha1;   break;
  case CKM_SHA256:      session->digest_descriptor = hal_hash_sha256; break;
  case CKM_SHA384:      session->digest_descriptor = hal_hash_sha384; break;
  case CKM_SHA512:      session->digest_descriptor = hal_hash_sha512; break;
  default:              lose(CKR_MECHANISM_INVALID);
  }

  if (!hal_check(hal_hash_core_present(session->digest_descriptor))) {
    session->digest_descriptor = NULL;
    lose(CKR_MECHANISM_INVALID);
  }

  return mutex_unlock(p11_global_mutex);

 fail:
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_Digest(CK_SESSION_HANDLE hSession,
               CK_BYTE_PTR pData,
               CK_ULONG ulDataLen,
               CK_BYTE_PTR pDigest,
               CK_ULONG_PTR pulDigestLen)
{
  ENTER_PUBLIC_FUNCTION(C_Digest);

  p11_session_t *session;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (pData == NULL || pulDigestLen == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (session->digest_descriptor == NULL)
    lose(CKR_OPERATION_NOT_INITIALIZED);

  rv = *pulDigestLen < session->digest_descriptor->digest_length ? CKR_BUFFER_TOO_SMALL : CKR_OK;

  *pulDigestLen = session->digest_descriptor->digest_length;

  if (pDigest == NULL)
    return mutex_unlock(p11_global_mutex);

  if (rv == CKR_BUFFER_TOO_SMALL)
    lose(CKR_BUFFER_TOO_SMALL);

  {
    uint8_t statebuf[session->digest_descriptor->hash_state_length];
    hal_hash_state_t state = { NULL };

    if (!hal_check(hal_hash_initialize(session->digest_descriptor,
                                       &state, statebuf, sizeof(statebuf)))     ||
        !hal_check(hal_hash_update(state, pData, ulDataLen))                    ||
        !hal_check(hal_hash_finalize(state, pDigest, *pulDigestLen)))
      lose(CKR_FUNCTION_FAILED);
  }

  rv = CKR_OK;                  /* Fall through */

 fail:
  if (session != NULL)
    session->digest_descriptor = NULL;
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_SignInit(CK_SESSION_HANDLE hSession,
                 CK_MECHANISM_PTR pMechanism,
                 CK_OBJECT_HANDLE hKey)
{
  ENTER_PUBLIC_FUNCTION(C_SignInit);

  p11_session_t *session;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (pMechanism == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (session->sign_key_handle != CK_INVALID_HANDLE || session->sign_digest_descriptor != NULL)
    lose(CKR_OPERATION_ACTIVE);

  if ((rv = p11_object_check_rights(session, hKey, p11_object_access_read)) != CKR_OK)
    goto fail;

  /*
   * Will need to check key algorithm type here once we add support
   * for signature algorithms other than RSA.
   */

  session->sign_key_handle = hKey;

  switch (pMechanism->mechanism) {
  case CKM_RSA_PKCS:            session->sign_digest_descriptor = NULL;                 break;
  case CKM_SHA1_RSA_PKCS:       session->sign_digest_descriptor = hal_hash_sha1;        break;
  case CKM_SHA256_RSA_PKCS:     session->sign_digest_descriptor = hal_hash_sha256;      break;
  case CKM_SHA384_RSA_PKCS:     session->sign_digest_descriptor = hal_hash_sha384;      break;
  case CKM_SHA512_RSA_PKCS:     session->sign_digest_descriptor = hal_hash_sha512;      break;
  default:                      return CKR_MECHANISM_INVALID;
  }

  return mutex_unlock(p11_global_mutex);

 fail:
  if (session != NULL) {
    session->sign_key_handle = CK_INVALID_HANDLE;
    session->sign_digest_descriptor = NULL;
  }
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_Sign(CK_SESSION_HANDLE hSession,
             CK_BYTE_PTR pData,
             CK_ULONG ulDataLen,
             CK_BYTE_PTR pSignature,
             CK_ULONG_PTR pulSignatureLen)
{
  ENTER_PUBLIC_FUNCTION(C_Sign);

  uint8_t keybuf[hal_rsa_key_t_size];
  hal_rsa_key_t key = { NULL };
  p11_session_t *session;
  size_t signature_len;
  CK_RV rv;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (pData == NULL || pulSignatureLen == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (session->sign_key_handle == CK_INVALID_HANDLE)
    lose(CKR_OPERATION_NOT_INITIALIZED);

  /*
   * From here down this function is RSA-specific, and will need
   * rewriting when we add support for other algorithms.
   */

  if (!p11_object_get_rsa_private_key(session->sign_key_handle,
                                      &key, keybuf, sizeof(keybuf)))
    lose(CKR_FUNCTION_FAILED);

  /*
   * Retrieve signature length.  For RSA this is just the modulus
   * length, other algorithms will need a more generic solution.
   */

  if (!hal_check(hal_rsa_key_get_modulus(key, NULL, &signature_len, 0)))
    lose(CKR_FUNCTION_FAILED);

  rv = signature_len > *pulSignatureLen ? CKR_BUFFER_TOO_SMALL : CKR_OK;

  *pulSignatureLen = signature_len;

  if (pSignature == NULL) {
    hal_rsa_key_clear(key);
    return mutex_unlock(p11_global_mutex);
  }

  if (rv == CKR_BUFFER_TOO_SMALL)
    lose(CKR_BUFFER_TOO_SMALL);

  if (session->sign_digest_descriptor != NULL) {
    uint8_t digest_info[session->sign_digest_descriptor->digest_length + 4 +
                        session->sign_digest_descriptor->digest_algorithm_id_length];

    if (!pkcs1_construct_digestinfo(session->sign_digest_descriptor,
                                    pData, ulDataLen, digest_info, sizeof(digest_info)))
      lose(CKR_FUNCTION_FAILED);

    rv = sign_rsa_pkcs(key, digest_info, sizeof(digest_info), pSignature, signature_len);
    memset(digest_info, 0, sizeof(digest_info));
    if (rv != CKR_OK)
      goto fail;
  }

  else {
    if ((rv = sign_rsa_pkcs(key, pData, ulDataLen, pSignature, signature_len)) != CKR_OK)
      goto fail;
  }

  rv = CKR_OK;                  /* Fall through */

 fail:

  if (session != NULL) {
    session->sign_key_handle = CK_INVALID_HANDLE;
    session->sign_digest_descriptor = NULL;
  }

  hal_rsa_key_clear(key);

  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_VerifyInit(CK_SESSION_HANDLE hSession,
                   CK_MECHANISM_PTR pMechanism,
                   CK_OBJECT_HANDLE hKey )
{
  ENTER_PUBLIC_FUNCTION(C_VerifyInit);

  p11_session_t *session;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (pMechanism == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (session->verify_key_handle != CK_INVALID_HANDLE || session->verify_digest_descriptor != NULL)
    lose(CKR_OPERATION_ACTIVE);

  if ((rv = p11_object_check_rights(session, hKey, p11_object_access_read)) != CKR_OK)
    goto fail;

  /*
   * Will need to check key algorithm type here once we add support
   * for signature algorithms other than RSA.
   */

  session->verify_key_handle = hKey;

  switch (pMechanism->mechanism) {
  case CKM_RSA_PKCS:            session->verify_digest_descriptor = NULL;               break;
  case CKM_SHA1_RSA_PKCS:       session->verify_digest_descriptor = hal_hash_sha1;      break;
  case CKM_SHA256_RSA_PKCS:     session->verify_digest_descriptor = hal_hash_sha256;    break;
  case CKM_SHA384_RSA_PKCS:     session->verify_digest_descriptor = hal_hash_sha384;    break;
  case CKM_SHA512_RSA_PKCS:     session->verify_digest_descriptor = hal_hash_sha512;	break;
  default:                      return CKR_MECHANISM_INVALID;
  }

  return mutex_unlock(p11_global_mutex);

 fail:
  if (session != NULL) {
    session->verify_key_handle = CK_INVALID_HANDLE;
    session->verify_digest_descriptor = NULL;
  }
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_Verify(CK_SESSION_HANDLE hSession,
               CK_BYTE_PTR pData,
               CK_ULONG ulDataLen,
               CK_BYTE_PTR pSignature,
               CK_ULONG ulSignatureLen)
{
  ENTER_PUBLIC_FUNCTION(C_Verify);

  uint8_t keybuf[hal_rsa_key_t_size];
  hal_rsa_key_t key = { NULL };
  p11_session_t *session;
  CK_RV rv;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (pData == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (session->verify_key_handle == CK_INVALID_HANDLE)
    lose(CKR_OPERATION_NOT_INITIALIZED);

  /*
   * From here down this function is RSA-specific, and will need
   * rewriting when we add support for other algorithms.
   */

  if (!p11_object_get_rsa_public_key(session->verify_key_handle,
                                     &key, keybuf, sizeof(keybuf)))
    lose(CKR_FUNCTION_FAILED);

  if (session->verify_digest_descriptor != NULL) {
    uint8_t digest_info[session->verify_digest_descriptor->digest_length + 4 +
                        session->verify_digest_descriptor->digest_algorithm_id_length];

    if (!pkcs1_construct_digestinfo(session->verify_digest_descriptor,
                                    pData, ulDataLen, digest_info, sizeof(digest_info)))
      lose(CKR_FUNCTION_FAILED);

    rv = verify_rsa_pkcs(key, digest_info, sizeof(digest_info), pSignature, ulSignatureLen);
    memset(digest_info, 0, sizeof(digest_info));
    if (rv != CKR_OK)
      goto fail;
  }

  else {
    if ((rv = verify_rsa_pkcs(key, pData, ulDataLen, pSignature, ulSignatureLen)) != CKR_OK)
      goto fail;
  }

  rv = CKR_OK;                  /* Fall through */

 fail:

  if (session != NULL) {
    session->verify_key_handle = CK_INVALID_HANDLE;
    session->verify_digest_descriptor = NULL;
  }

  hal_rsa_key_clear(key);

  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

/*
 * If there's any method in this entire package which really needs a
 * more complex mutex structure than the single global mutex, it's
 * probably this one.  Key generation can take a looooong time.
 * Drive off that bridge when we get to it.
 */

CK_RV C_GenerateKeyPair(CK_SESSION_HANDLE hSession,
                        CK_MECHANISM_PTR pMechanism,
                        CK_ATTRIBUTE_PTR pPublicKeyTemplate,
                        CK_ULONG ulPublicKeyAttributeCount,
                        CK_ATTRIBUTE_PTR pPrivateKeyTemplate,
                        CK_ULONG ulPrivateKeyAttributeCount,
                        CK_OBJECT_HANDLE_PTR phPublicKey,
                        CK_OBJECT_HANDLE_PTR phPrivateKey)
{
  ENTER_PUBLIC_FUNCTION(C_GenerateKeyPair);

  p11_session_t *session;
  CK_RV rv;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (pMechanism          == NULL ||
      pPublicKeyTemplate  == NULL || phPublicKey  == NULL ||
      pPrivateKeyTemplate == NULL || phPrivateKey == NULL)
    lose(CKR_ARGUMENTS_BAD);

  switch (pMechanism->mechanism) {

  case CKM_RSA_PKCS_KEY_PAIR_GEN:
    rv = generate_keypair_rsa_pkcs(session, pMechanism,
                                   pPublicKeyTemplate, ulPublicKeyAttributeCount,
                                   pPrivateKeyTemplate, ulPrivateKeyAttributeCount,
                                   phPublicKey, phPrivateKey);
    break;

  default:
    lose(CKR_MECHANISM_INVALID);
  }

 fail:
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

CK_RV C_GenerateRandom(CK_SESSION_HANDLE hSession,
                       CK_BYTE_PTR RandomData,
                       CK_ULONG ulRandomLen)
{
  ENTER_PUBLIC_FUNCTION(C_GenerateRandom);

  p11_session_t *session;
  CK_RV rv = CKR_OK;

  mutex_lock_or_return_failure(p11_global_mutex);

  if ((session = p11_session_find(hSession)) == NULL)
    lose(CKR_SESSION_HANDLE_INVALID);

  if (RandomData == NULL)
    lose(CKR_ARGUMENTS_BAD);

  if (!hal_check(hal_get_random(RandomData, ulRandomLen)))
    lose(CKR_FUNCTION_FAILED);

 fail:
  mutex_unlock_return_with_rv(rv, p11_global_mutex);
}

/*
 * Supply information about a particular mechanism.  We may want a
 * more generic structure for this, for the moment, just answer the
 * questions that applications we care about are asking.
 *
 * Not really sure whether I should be setting CKF_HW here or not, RSA
 * is a mix of hardware and software at the moment, but I'm also a
 * little unclear on what "the device" means in this context, so let's
 * just say that if it's implemented by libhal or the Verilog hiding
 * behind libhal, it's implemented in hardware.
 */

CK_RV C_GetMechanismInfo(CK_SLOT_ID slotID,
                         CK_MECHANISM_TYPE type,
                         CK_MECHANISM_INFO_PTR pInfo)
{
  ENTER_PUBLIC_FUNCTION(C_GetMechanismInfo);

  const CK_ULONG rsa_key_min = 1024;
  const CK_ULONG rsa_key_max = 8192;

  /*
   * No locking here, no obvious need for it.
   */

  if (pInfo == NULL)
    return CKR_ARGUMENTS_BAD;

  if (slotID != P11_ONE_AND_ONLY_SLOT)
    return CKR_SLOT_ID_INVALID;

  switch (type) {

  case CKM_SHA_1:
  case CKM_SHA1_RSA_PKCS:
  case CKM_SHA_1_HMAC:
    if (hal_has_core_present(hal_hash_sha1) != HAL_OK)
      return CKR_MECHANISM_INVALID;
    break;

  case CKM_SHA256:
  case CKM_SHA256_RSA_PKCS:
  case CKM_SHA256_HMAC:
    if (hal_has_core_present(hal_hash_sha256) != HAL_OK)
      return CKR_MECHANISM_INVALID;
    break;

  case CKM_SHA384:
  case CKM_SHA384_RSA_PKCS:
  case CKM_SHA384_HMAC:
    if (hal_has_core_present(hal_hash_sha384) != HAL_OK)
      return CKR_MECHANISM_INVALID;
    break;

  case CKM_SHA512:
  case CKM_SHA512_RSA_PKCS:
  case CKM_SHA512_HMAC:
    if (hal_has_core_present(hal_hash_sha512) != HAL_OK)
      return CKR_MECHANISM_INVALID;
    break;

  default:
    break;
  }

  switch (type) {

  case CKM_RSA_PKCS_KEY_PAIR_GEN:
    pInfo->ulMinKeySize = rsa_key_min;
    pInfo->ulMaxKeySize = rsa_key_max;
    pInfo->flags = CKF_HW | CKF_GENERATE_KEY_PAIR;
    break;

  case CKM_RSA_PKCS:
  case CKM_SHA1_RSA_PKCS:
  case CKM_SHA256_RSA_PKCS:
  case CKM_SHA384_RSA_PKCS:
  case CKM_SHA512_RSA_PKCS:
    pInfo->ulMinKeySize = rsa_key_min;
    pInfo->ulMaxKeySize = rsa_key_max;
    pInfo->flags = CKF_HW | CKF_SIGN | CKF_VERIFY;
    break;

  case CKM_SHA_1:
  case CKM_SHA256:
  case CKM_SHA384:
  case CKM_SHA512:
    pInfo->ulMinKeySize = 0;
    pInfo->ulMaxKeySize = 0;
    pInfo->flags = CKF_HW | CKF_DIGEST;
    break;

#if 0
    /*
     * We have Verilog and libhal for these, but no PKCS #11 support (yet).
     */
  case CKM_SHA_1_HMAC:
  case CKM_SHA256_HMAC:
  case CKM_SHA384_HMAC:
  case CKM_SHA512_HMAC:
#endif

  default:
    return CKR_MECHANISM_INVALID;
  }

  return CKR_OK;
}




/*
 * Stubs for unsupported functions below here.  Per the PKCS #11
 * specification, it's OK to skip implementing almost any function in
 * the API, but if one does so, one must provide a stub which returns
 * CKR_FUNCTION_NOT_SUPPORTED, because every slot in the dispatch
 * vector must be populated.  We could reuse a single stub for all the
 * unimplemented slots, but the type signatures wouldn't match, which
 * would require some nasty casts I'd rather avoid.
 *
 * Many of these functions would be straightforward to implement, but
 * there are enough bald yaks in this saga already.
 */

CK_RV C_GenerateKey(CK_SESSION_HANDLE hSession,
                    CK_MECHANISM_PTR pMechanism,
                    CK_ATTRIBUTE_PTR pTemplate,
                    CK_ULONG ulCount,
                    CK_OBJECT_HANDLE_PTR phKey)
{
  ENTER_PUBLIC_FUNCTION(C_GenerateKey);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetInfo(CK_INFO_PTR pInfo)
{
  ENTER_PUBLIC_FUNCTION(C_GetInfo);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetSlotInfo(CK_SLOT_ID slotID,
                    CK_SLOT_INFO_PTR pInfo)
{
  ENTER_PUBLIC_FUNCTION(C_GetSlotInfo);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetMechanismList(CK_SLOT_ID slotID,
                         CK_MECHANISM_TYPE_PTR pMechanismList,
                         CK_ULONG_PTR pulCount)
{
  ENTER_PUBLIC_FUNCTION(C_GetMechanismList);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_InitToken(CK_SLOT_ID slotID,
                  CK_UTF8CHAR_PTR pPin,
                  CK_ULONG ulPinLen,
                  CK_UTF8CHAR_PTR pLabel)
{
  ENTER_PUBLIC_FUNCTION(C_InitToken);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_InitPIN(CK_SESSION_HANDLE hSession,
                CK_UTF8CHAR_PTR pPin,
                CK_ULONG ulPinLen)
{
  ENTER_PUBLIC_FUNCTION(C_InitPIN);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SetPIN(CK_SESSION_HANDLE hSession,
               CK_UTF8CHAR_PTR pOldPin,
               CK_ULONG ulOldLen,
               CK_UTF8CHAR_PTR pNewPin,
               CK_ULONG ulNewLen)
{
  ENTER_PUBLIC_FUNCTION(C_SetPIN);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetSessionInfo(CK_SESSION_HANDLE hSession,
                       CK_SESSION_INFO_PTR pInfo)
{
  ENTER_PUBLIC_FUNCTION(C_GetSessionInfo);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetOperationState(CK_SESSION_HANDLE hSession,
                          CK_BYTE_PTR pOperationState,
                          CK_ULONG_PTR pulOperationStateLen)
{
  ENTER_PUBLIC_FUNCTION(C_GetOperationState);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SetOperationState(CK_SESSION_HANDLE hSession,
                          CK_BYTE_PTR pOperationState,
                          CK_ULONG ulOperationStateLen,
                          CK_OBJECT_HANDLE hEncryptionKey,
                          CK_OBJECT_HANDLE hAuthenticationKey)
{
  ENTER_PUBLIC_FUNCTION(C_SetOperationState);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_CreateObject(CK_SESSION_HANDLE hSession,
                     CK_ATTRIBUTE_PTR pTemplate,
                     CK_ULONG ulCount,
                     CK_OBJECT_HANDLE_PTR phObject)
{
  ENTER_PUBLIC_FUNCTION(C_CreateObject);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_CopyObject(CK_SESSION_HANDLE hSession,
                   CK_OBJECT_HANDLE hObject,
                   CK_ATTRIBUTE_PTR pTemplate,
                   CK_ULONG ulCount,
                   CK_OBJECT_HANDLE_PTR phNewObject)
{
  ENTER_PUBLIC_FUNCTION(C_CopyObject);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetObjectSize(CK_SESSION_HANDLE hSession,
                      CK_OBJECT_HANDLE hObject,
                      CK_ULONG_PTR pulSize)
{
  ENTER_PUBLIC_FUNCTION(C_GetObjectSize);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SetAttributeValue(CK_SESSION_HANDLE hSession,
                          CK_OBJECT_HANDLE hObject,
                          CK_ATTRIBUTE_PTR pTemplate,
                          CK_ULONG ulCount)
{
  ENTER_PUBLIC_FUNCTION(C_SetAttributeValue);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_EncryptInit(CK_SESSION_HANDLE hSession,
                    CK_MECHANISM_PTR pMechanism,
                    CK_OBJECT_HANDLE hKey)
{
  ENTER_PUBLIC_FUNCTION(C_EncryptInit);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_Encrypt(CK_SESSION_HANDLE hSession,
                CK_BYTE_PTR pData,
                CK_ULONG ulDataLen,
                CK_BYTE_PTR pEncryptedData,
                CK_ULONG_PTR pulEncryptedDataLen)
{
  ENTER_PUBLIC_FUNCTION(C_Encrypt);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_EncryptUpdate(CK_SESSION_HANDLE hSession,
                      CK_BYTE_PTR pPart,
                      CK_ULONG ulPartLen,
                      CK_BYTE_PTR pEncryptedPart,
                      CK_ULONG_PTR pulEncryptedPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_EncryptUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_EncryptFinal(CK_SESSION_HANDLE hSession,
                     CK_BYTE_PTR pLastEncryptedPart,
                     CK_ULONG_PTR pulLastEncryptedPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_EncryptFinal);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptInit(CK_SESSION_HANDLE hSession,
                    CK_MECHANISM_PTR pMechanism,
                    CK_OBJECT_HANDLE hKey)
{
  ENTER_PUBLIC_FUNCTION(C_DecryptInit);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_Decrypt(CK_SESSION_HANDLE hSession,
                CK_BYTE_PTR pEncryptedData,
                CK_ULONG ulEncryptedDataLen,
                CK_BYTE_PTR pData,
                CK_ULONG_PTR pulDataLen)
{
  ENTER_PUBLIC_FUNCTION(C_Decrypt);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptUpdate(CK_SESSION_HANDLE hSession,
                      CK_BYTE_PTR pEncryptedPart,
                      CK_ULONG ulEncryptedPartLen,
                      CK_BYTE_PTR pPart,
                      CK_ULONG_PTR pulPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_DecryptUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptFinal(CK_SESSION_HANDLE hSession,
                     CK_BYTE_PTR pLastPart,
                     CK_ULONG_PTR pulLastPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_DecryptFinal);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestUpdate(CK_SESSION_HANDLE hSession,
                     CK_BYTE_PTR pPart,
                     CK_ULONG ulPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_DigestUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestKey(CK_SESSION_HANDLE hSession,
                  CK_OBJECT_HANDLE hKey)
{
  ENTER_PUBLIC_FUNCTION(C_DigestKey);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestFinal(CK_SESSION_HANDLE hSession,
                    CK_BYTE_PTR pDigest,
                    CK_ULONG_PTR pulDigestLen)
{
  ENTER_PUBLIC_FUNCTION(C_DigestFinal);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignUpdate(CK_SESSION_HANDLE hSession,
                   CK_BYTE_PTR pPart,
                   CK_ULONG ulPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_SignUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignFinal(CK_SESSION_HANDLE hSession,
                  CK_BYTE_PTR pSignature,
                  CK_ULONG_PTR pulSignatureLen)
{
  ENTER_PUBLIC_FUNCTION(C_SignFinal);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignRecoverInit(CK_SESSION_HANDLE hSession,
                        CK_MECHANISM_PTR pMechanism,
                        CK_OBJECT_HANDLE hKey)
{
  ENTER_PUBLIC_FUNCTION(C_SignRecoverInit);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignRecover(CK_SESSION_HANDLE hSession,
                    CK_BYTE_PTR pData,
                    CK_ULONG ulDataLen,
                    CK_BYTE_PTR pSignature,
                    CK_ULONG_PTR pulSignatureLen)
{
  ENTER_PUBLIC_FUNCTION(C_SignRecover);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyUpdate(CK_SESSION_HANDLE hSession,
                     CK_BYTE_PTR pPart,
                     CK_ULONG ulPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_VerifyUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyFinal(CK_SESSION_HANDLE hSession,
                    CK_BYTE_PTR pSignature,
                    CK_ULONG ulSignatureLen)
{
  ENTER_PUBLIC_FUNCTION(C_VerifyFinal);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyRecoverInit(CK_SESSION_HANDLE hSession,
                          CK_MECHANISM_PTR pMechanism,
                          CK_OBJECT_HANDLE hKey)
{
  ENTER_PUBLIC_FUNCTION(C_VerifyRecoverInit);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyRecover(CK_SESSION_HANDLE hSession,
                      CK_BYTE_PTR pSignature,
                      CK_ULONG ulSignatureLen,
                      CK_BYTE_PTR pData,
                      CK_ULONG_PTR pulDataLen)
{
  ENTER_PUBLIC_FUNCTION(C_VerifyRecover);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestEncryptUpdate(CK_SESSION_HANDLE hSession,
                            CK_BYTE_PTR pPart,
                            CK_ULONG ulPartLen,
                            CK_BYTE_PTR pEncryptedPart,
                            CK_ULONG_PTR pulEncryptedPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_DigestEncryptUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptDigestUpdate(CK_SESSION_HANDLE hSession,
                            CK_BYTE_PTR pEncryptedPart,
                            CK_ULONG ulEncryptedPartLen,
                            CK_BYTE_PTR pPart,
                            CK_ULONG_PTR pulPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_DecryptDigestUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignEncryptUpdate(CK_SESSION_HANDLE hSession,
                          CK_BYTE_PTR pPart,
                          CK_ULONG ulPartLen,
                          CK_BYTE_PTR pEncryptedPart,
                          CK_ULONG_PTR pulEncryptedPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_SignEncryptUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession,
                            CK_BYTE_PTR pEncryptedPart,
                            CK_ULONG ulEncryptedPartLen,
                            CK_BYTE_PTR pPart,
                            CK_ULONG_PTR pulPartLen)
{
  ENTER_PUBLIC_FUNCTION(C_DecryptVerifyUpdate);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_WrapKey(CK_SESSION_HANDLE hSession,
                CK_MECHANISM_PTR pMechanism,
                CK_OBJECT_HANDLE hWrappingKey,
                CK_OBJECT_HANDLE hKey,
                CK_BYTE_PTR pWrappedKey,
                CK_ULONG_PTR pulWrappedKeyLen)
{
  ENTER_PUBLIC_FUNCTION(C_WrapKey);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_UnwrapKey(CK_SESSION_HANDLE hSession,
                  CK_MECHANISM_PTR pMechanism,
                  CK_OBJECT_HANDLE hUnwrappingKey,
                  CK_BYTE_PTR pWrappedKey,
                  CK_ULONG ulWrappedKeyLen,
                  CK_ATTRIBUTE_PTR pTemplate,
                  CK_ULONG ulAttributeCount,
                  CK_OBJECT_HANDLE_PTR phKey)
{
  ENTER_PUBLIC_FUNCTION(C_UnwrapKey);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DeriveKey(CK_SESSION_HANDLE hSession,
                  CK_MECHANISM_PTR pMechanism,
                  CK_OBJECT_HANDLE hBaseKey,
                  CK_ATTRIBUTE_PTR pTemplate,
                  CK_ULONG ulAttributeCount,
                  CK_OBJECT_HANDLE_PTR phKey)
{
  ENTER_PUBLIC_FUNCTION(C_DeriveKey);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SeedRandom(CK_SESSION_HANDLE hSession,
                   CK_BYTE_PTR pSeed,
                   CK_ULONG ulSeedLen)
{
  ENTER_PUBLIC_FUNCTION(C_SeedRandom);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetFunctionStatus(CK_SESSION_HANDLE hSession)
{
  ENTER_PUBLIC_FUNCTION(C_GetFunctionStatus);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_CancelFunction(CK_SESSION_HANDLE hSession)
{
  ENTER_PUBLIC_FUNCTION(C_CancelFunction);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_WaitForSlotEvent(CK_FLAGS flags,
                         CK_SLOT_ID_PTR pSlot,
                         CK_VOID_PTR pRserved)
{
  ENTER_PUBLIC_FUNCTION(C_WaitForSlotEvent);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

/*
 * "Any programmer who fails to comply with the standard naming, formatting,
 *  or commenting conventions should be shot.  If it so happens that it is
 *  inconvenient to shoot him, then he is to be politely requested to recode
 *  his program in adherence to the above standard."
 *                      -- Michael Spier, Digital Equipment Corporation
 *
 * Local variables:
 * indent-tabs-mode: nil
 * End:
 */