/ src / common / psw.c
psw.c
  1  /*
  2   * psw.c
  3   *
  4   * Copyright (C) 2013 Hugo Villeneuve <hugo@hugovil.com>
  5   *
  6   * This file is released under the GPLv2
  7   */
  8  
  9  #include "common.h"
 10  #include "reg8051.h"
 11  #include "memory.h"
 12  
 13  /* Returns 0 or 1 */
 14  int
 15  psw_read_bit(unsigned int bit)
 16  {
 17  	return (mem_read8(INT_MEM_ID, _PSW_) >> bit) & 0x01;
 18  }
 19  
 20  void
 21  psw_write_bit(unsigned int bit, int val)
 22  {
 23  	uint8_t psw = mem_read8(INT_MEM_ID, _PSW_);
 24  
 25  	if (val)
 26  		psw |= (1 << bit);  /* Set */
 27  	else
 28  		psw &= ~(1 << bit); /* Clear */
 29  
 30  	mem_write8(INT_MEM_ID, _PSW_, psw); /* Save updated value */
 31  }
 32  
 33  /* Returns 0 or 1 */
 34  int
 35  psw_read_cy(void)
 36  {
 37  	return psw_read_bit(PSW_BIT_CY);
 38  }
 39  
 40  void
 41  psw_write_cy(int cy)
 42  {
 43  	psw_write_bit(PSW_BIT_CY, cy);
 44  }
 45  
 46  void
 47  psw_set_cy(void)
 48  {
 49  	psw_write_bit(PSW_BIT_CY, 1);
 50  }
 51  
 52  void
 53  psw_clr_cy(void)
 54  {
 55  	psw_write_bit(PSW_BIT_CY, 0);
 56  }
 57  
 58  /* Returns 0 or 1 */
 59  int
 60  psw_read_ac(void)
 61  {
 62  	return psw_read_bit(PSW_BIT_AC);
 63  }
 64  
 65  void
 66  psw_write_ac(int ac)
 67  {
 68  	psw_write_bit(PSW_BIT_AC, ac);
 69  }
 70  
 71  void
 72  psw_set_ac(void)
 73  {
 74  	psw_write_bit(PSW_BIT_AC, 1);
 75  }
 76  
 77  void
 78  psw_clr_ac(void)
 79  {
 80  	psw_write_bit(PSW_BIT_AC, 0);
 81  }
 82  
 83  /* Returns 0 or 1 */
 84  int
 85  psw_read_ov(void)
 86  {
 87  	return psw_read_bit(PSW_BIT_OV);
 88  }
 89  
 90  void
 91  psw_write_ov(int ov)
 92  {
 93  	psw_write_bit(PSW_BIT_OV, ov);
 94  }
 95  
 96  void
 97  psw_set_ov(void)
 98  {
 99  	psw_write_bit(PSW_BIT_OV, 1);
100  }
101  
102  void
103  psw_clr_ov(void)
104  {
105  	psw_write_bit(PSW_BIT_OV, 0);
106  }
107  
108  /*
109   * Compute parity of bits in accumulator:
110   *   parity = 0: even number of ones in accumulator
111   *   parity = 1: odd  number of ones in accumulator
112   */
113  void
114  psw_compute_parity_bit(void)
115  {
116  	int parity = 0;
117  	uint8_t acc = mem_read8(INT_MEM_ID, _ACC_);
118  
119  	while (acc) {
120  		parity = !parity;
121  		acc = acc & (acc - 1);
122  	}
123  
124  	psw_write_bit(PSW_BIT_P, parity);
125  }