static int reencrypt_context_update(struct crypt_device *cd,
	struct luks2_reencrypt *rh)
{
	if (rh->read < 0)
		return -EINVAL;

	if (rh->direction == CRYPT_REENCRYPT_BACKWARD) {
		if (rh->data_shift && rh->mode == CRYPT_REENCRYPT_ENCRYPT) {
			if (rh->offset)
				rh->offset -= rh->data_shift;
			if (rh->offset && (rh->offset < rh->data_shift)) {
				rh->length = rh->offset;
				rh->offset = rh->data_shift;
			}
			if (!rh->offset)
				rh->length = rh->data_shift;
		} else {
			if (rh->offset < rh->length)
				rh->length = rh->offset;
			rh->offset -= rh->length;
		}
	} else if (rh->direction == CRYPT_REENCRYPT_FORWARD) {
		rh->offset += (uint64_t)rh->read;
		/* it fails in-case of device_size < rh->offset later */
		if (rh->device_size - rh->offset < rh->length)
			rh->length = rh->device_size - rh->offset;
	} else
		return -EINVAL;

	if (rh->device_size < rh->offset) {
		log_dbg(cd, "Calculated reencryption offset %" PRIu64 " is beyond device size %" PRIu64 ".", rh->offset, rh->device_size);
		return -EINVAL;
	}

	rh->progress += (uint64_t)rh->read;

	return 0;
}
static int reencrypt_context_update(struct crypt_device *cd,
	struct luks2_reencrypt *rh)
{
	if (rh->read < 0)
		return -EINVAL;

	if (rh->direction == CRYPT_REENCRYPT_BACKWARD) {
		if (rh->data_shift && rh->mode == CRYPT_REENCRYPT_ENCRYPT) {
			if (rh->offset)
				rh->offset -= rh->data_shift;
			if (rh->offset && (rh->offset < rh->data_shift)) {
				rh->length = rh->offset;
				rh->offset = rh->data_shift;
			}
			if (!rh->offset)
				rh->length = rh->data_shift;
		} else {
			if (rh->offset < rh->length)
				rh->length = rh->offset;
			rh->offset -= rh->length;
		}
	} else if (rh->direction == CRYPT_REENCRYPT_FORWARD) {
		rh->offset += (uint64_t)rh->read;
		 
		if (rh->device_size - rh->offset < rh->length)
			rh->length = rh->device_size - rh->offset;
	} else
		return -EINVAL;

	if (rh->device_size < rh->offset) {
		log_dbg(cd, "Calculated reencryption offset %" PRIu64 " is beyond device size %" PRIu64 ".", rh->offset, rh->device_size);
		return -EINVAL;
	}

	rh->progress += (uint64_t)rh->read;

	return 0;
}