diff --git a/contrib/pg_upgrade/file.c b/contrib/pg_upgrade/file.c
index bf1f8a0991d21dfbe4b7516832b4f6fc1c3d0f9b..ba2ec73ead60e4644c114e53820ae9a36e94e548 100644
--- a/contrib/pg_upgrade/file.c
+++ b/contrib/pg_upgrade/file.c
@@ -136,16 +136,22 @@ copy_file(const char *srcfile, const char *dstfile, bool force)
 	int			save_errno = 0;
 
 	if ((srcfile == NULL) || (dstfile == NULL))
+	{
+		errno = EINVAL;
 		return -1;
+	}
 
 	if ((src_fd = open(srcfile, O_RDONLY, 0)) < 0)
 		return -1;
 
 	if ((dest_fd = open(dstfile, O_RDWR | O_CREAT | (force ? 0 : O_EXCL), S_IRUSR | S_IWUSR)) < 0)
 	{
+		save_errno = errno;
+
 		if (src_fd != 0)
 			close(src_fd);
 
+		errno = save_errno;
 		return -1;
 	}
 
@@ -170,6 +176,9 @@ copy_file(const char *srcfile, const char *dstfile, bool force)
 
 		if (write(dest_fd, buffer, nbytes) != nbytes)
 		{
+			/* if write didn't set errno, assume problem is no disk space */
+			if (errno == 0)
+				errno = ENOSPC;
 			save_errno = errno;
 			ret = -1;
 			break;