f2fs/fscrypt: catch up to v4.12

Applied f2fs-related patches only, and tried to exclude other layers' changes.

- fs/f2fs

c6b1e36c8fa0 Merge branch 'for-4.13/block' of git://git.kernel.dk/linux-block
81e3e044897b Merge tag 'uuid-for-4.13' of git://git.infradead.org/users/hch/uuid
fdd050b5b3c9 Merge branch 'uuid-types' of bombadil.infradead.org:public_git/uuid into nvme-base
4e4cbee93d56 block: switch bios to blk_status_t
d41519a69b35 crypto: Work around deallocated stack frame reference gcc bug on sparc.
85787090a21e fs: switch ->s_uuid to uuid_t
bf5f89463f5b Merge branch 'akpm' (patches from Andrew)
48fbfe50f1d5 fs: f2fs: use ktime_get_real_seconds for sit_info times
a7c3e901a46f mm: introduce kv[mz]alloc helpers
70ef8f0d3757 Merge tag 'for-f2fs-4.12' of git://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs
...

- fs/crypto/

4e4cbee93d56 block: switch bios to blk_status_t
17159420a6c1 fscrypt: introduce helper function for filename matching
6b06cdee81d6 fscrypt: avoid collisions when presenting long encrypted filenames
272f98f68462 fscrypt: fix context consistency check when key(s) unavailable
9c8268def612 fscrypt: Move key structure and constants to uapi
cd39e4bac111 fscrypt: remove unnecessary checks for NULL operations
a643f9054c21 Merge tag 'fscrypt-for-linus_stable' of git://git.kernel.org/pub/scm/linux/kernel/git/tytso/fscrypt
...

- fs/ext4/
: Applied fscrypt-related changes only.

Signed-off-by: Jaegeuk Kim <jaegeuk@google.com>
diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c
index 170421e..2cec605 100644
--- a/fs/ext4/ialloc.c
+++ b/fs/ext4/ialloc.c
@@ -771,7 +771,7 @@
 		if (err)
 			return ERR_PTR(err);
 		if (!fscrypt_has_encryption_key(dir))
-			return ERR_PTR(-EPERM);
+			return ERR_PTR(-ENOKEY);
 		if (!handle)
 			nblocks += EXT4_DATA_TRANS_BLOCKS(dir->i_sb);
 		encrypt = 1;
@@ -1093,6 +1093,17 @@
 	if (err)
 		goto fail_drop;
 
+	/*
+	 * Since the encryption xattr will always be unique, create it first so
+	 * that it's less likely to end up in an external xattr block and
+	 * prevent its deduplication.
+	 */
+	if (encrypt) {
+		err = fscrypt_inherit_context(dir, inode, handle, true);
+		if (err)
+			goto fail_free_drop;
+	}
+
 	err = ext4_init_acl(handle, inode, dir);
 	if (err)
 		goto fail_free_drop;
@@ -1114,13 +1125,6 @@
 		ei->i_datasync_tid = handle->h_transaction->t_tid;
 	}
 
-	if (encrypt) {
-		/* give pointer to avoid set_context with journal ops. */
-		err = fscrypt_inherit_context(dir, inode, &encrypt, true);
-		if (err)
-			goto fail_free_drop;
-	}
-
 	err = ext4_mark_inode_dirty(handle, inode);
 	if (err) {
 		ext4_std_error(sb, err);