#include <stdint.h>
#include <stdio.h>

typedef uint32_t uint32;
typedef uint32 MultiXactOffset;

#define MaxMultiXactOffset	((MultiXactOffset) 0xFFFFFFFF)

#define MULTIXACT_MEMBER_SAFE_THRESHOLD		(MaxMultiXactOffset / 2)
#define MULTIXACT_MEMBER_DANGER_THRESHOLD	\
	(MaxMultiXactOffset - MaxMultiXactOffset / 4)

#define autovacuum_multixact_freeze_max_age 200000000

static int
test_MultiXactMemberFreezeThreshold(uint32 multixacts, MultiXactOffset members)
{
	uint32		victim_multixacts;
	double		fraction;

	/* If member space utilization is low, no special action is required. */
	if (members <= MULTIXACT_MEMBER_SAFE_THRESHOLD)
		return autovacuum_multixact_freeze_max_age;

	/*
	 * Compute a target for relminmxid advancement.  The number of multixacts
	 * we try to eliminate from the system is based on how far we are past
	 * MULTIXACT_MEMBER_SAFE_THRESHOLD.
	 */
	fraction = (double) (members - MULTIXACT_MEMBER_SAFE_THRESHOLD) /
		(MULTIXACT_MEMBER_DANGER_THRESHOLD - MULTIXACT_MEMBER_SAFE_THRESHOLD);
	victim_multixacts = multixacts * fraction;

	/* fraction could be > 1.0, but lowest possible freeze age is zero */
	if (victim_multixacts > multixacts)
		return 0;
	return multixacts - victim_multixacts;
}

static int
testit(uint32 multixacts, MultiXactOffset members)
{
  int result = test_MultiXactMemberFreezeThreshold(multixacts, members);

  printf("multixacts: %10u, members %10u -> %10d\n", multixacts, members, result);

  return result;
}


int main(int argc, char **argv)
{
  testit(   1000000UL, 1000000000UL);
  testit(   1000000UL, 2000000000UL);
  testit(   1000000UL, 2100000000UL);
  testit(   1000000UL, 2200000000UL);
  testit(   1000000UL, 2300000000UL);
  testit(   1000000UL, 2500000000UL);
  testit(   1000000UL, 3000000000UL);
  testit(   1000000UL, 3100000000UL);
  testit(   1000000UL, 3500000000UL);
  testit(   1000000UL, 4000000000UL);

  testit(1000000000UL, 2200000000UL);
}
