1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * linux/fs/ext4/inode.c
4 *
5 * Copyright (C) 1992, 1993, 1994, 1995
6 * Remy Card (card@masi.ibp.fr)
7 * Laboratoire MASI - Institut Blaise Pascal
8 * Universite Pierre et Marie Curie (Paris VI)
9 *
10 * from
11 *
12 * linux/fs/minix/inode.c
13 *
14 * Copyright (C) 1991, 1992 Linus Torvalds
15 *
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
18 *
19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
20 */
21
22 #include <linux/fs.h>
23 #include <linux/mount.h>
24 #include <linux/time.h>
25 #include <linux/highuid.h>
26 #include <linux/pagemap.h>
27 #include <linux/dax.h>
28 #include <linux/quotaops.h>
29 #include <linux/string.h>
30 #include <linux/buffer_head.h>
31 #include <linux/writeback.h>
32 #include <linux/pagevec.h>
33 #include <linux/mpage.h>
34 #include <linux/namei.h>
35 #include <linux/uio.h>
36 #include <linux/bio.h>
37 #include <linux/workqueue.h>
38 #include <linux/kernel.h>
39 #include <linux/printk.h>
40 #include <linux/slab.h>
41 #include <linux/bitops.h>
42 #include <linux/iomap.h>
43 #include <linux/iversion.h>
44
45 #include "ext4_jbd2.h"
46 #include "xattr.h"
47 #include "acl.h"
48 #include "truncate.h"
49
50 #include <trace/events/ext4.h>
51
ext4_inode_csum(struct inode * inode,struct ext4_inode * raw,struct ext4_inode_info * ei)52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 struct ext4_inode_info *ei)
54 {
55 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56 __u32 csum;
57 __u16 dummy_csum = 0;
58 int offset = offsetof(struct ext4_inode, i_checksum_lo);
59 unsigned int csum_size = sizeof(dummy_csum);
60
61 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63 offset += csum_size;
64 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65 EXT4_GOOD_OLD_INODE_SIZE - offset);
66
67 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68 offset = offsetof(struct ext4_inode, i_checksum_hi);
69 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70 EXT4_GOOD_OLD_INODE_SIZE,
71 offset - EXT4_GOOD_OLD_INODE_SIZE);
72 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
74 csum_size);
75 offset += csum_size;
76 }
77 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
78 EXT4_INODE_SIZE(inode->i_sb) - offset);
79 }
80
81 return csum;
82 }
83
ext4_inode_csum_verify(struct inode * inode,struct ext4_inode * raw,struct ext4_inode_info * ei)84 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85 struct ext4_inode_info *ei)
86 {
87 __u32 provided, calculated;
88
89 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90 cpu_to_le32(EXT4_OS_LINUX) ||
91 !ext4_has_metadata_csum(inode->i_sb))
92 return 1;
93
94 provided = le16_to_cpu(raw->i_checksum_lo);
95 calculated = ext4_inode_csum(inode, raw, ei);
96 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
99 else
100 calculated &= 0xFFFF;
101
102 return provided == calculated;
103 }
104
ext4_inode_csum_set(struct inode * inode,struct ext4_inode * raw,struct ext4_inode_info * ei)105 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106 struct ext4_inode_info *ei)
107 {
108 __u32 csum;
109
110 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111 cpu_to_le32(EXT4_OS_LINUX) ||
112 !ext4_has_metadata_csum(inode->i_sb))
113 return;
114
115 csum = ext4_inode_csum(inode, raw, ei);
116 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
120 }
121
ext4_begin_ordered_truncate(struct inode * inode,loff_t new_size)122 static inline int ext4_begin_ordered_truncate(struct inode *inode,
123 loff_t new_size)
124 {
125 trace_ext4_begin_ordered_truncate(inode, new_size);
126 /*
127 * If jinode is zero, then we never opened the file for
128 * writing, so there's no need to call
129 * jbd2_journal_begin_ordered_truncate() since there's no
130 * outstanding writes we need to flush.
131 */
132 if (!EXT4_I(inode)->jinode)
133 return 0;
134 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
135 EXT4_I(inode)->jinode,
136 new_size);
137 }
138
139 static void ext4_invalidatepage(struct page *page, unsigned int offset,
140 unsigned int length);
141 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
142 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
143 int pextents);
144
145 /*
146 * Test whether an inode is a fast symlink.
147 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
148 */
ext4_inode_is_fast_symlink(struct inode * inode)149 int ext4_inode_is_fast_symlink(struct inode *inode)
150 {
151 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
152 int ea_blocks = EXT4_I(inode)->i_file_acl ?
153 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
154
155 if (ext4_has_inline_data(inode))
156 return 0;
157
158 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
159 }
160 return S_ISLNK(inode->i_mode) && inode->i_size &&
161 (inode->i_size < EXT4_N_BLOCKS * 4);
162 }
163
164 /*
165 * Called at the last iput() if i_nlink is zero.
166 */
ext4_evict_inode(struct inode * inode)167 void ext4_evict_inode(struct inode *inode)
168 {
169 handle_t *handle;
170 int err;
171 /*
172 * Credits for final inode cleanup and freeing:
173 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
174 * (xattr block freeing), bitmap, group descriptor (inode freeing)
175 */
176 int extra_credits = 6;
177 struct ext4_xattr_inode_array *ea_inode_array = NULL;
178 bool freeze_protected = false;
179
180 trace_ext4_evict_inode(inode);
181
182 if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
183 ext4_evict_ea_inode(inode);
184 if (inode->i_nlink) {
185 /*
186 * When journalling data dirty buffers are tracked only in the
187 * journal. So although mm thinks everything is clean and
188 * ready for reaping the inode might still have some pages to
189 * write in the running transaction or waiting to be
190 * checkpointed. Thus calling jbd2_journal_invalidatepage()
191 * (via truncate_inode_pages()) to discard these buffers can
192 * cause data loss. Also even if we did not discard these
193 * buffers, we would have no way to find them after the inode
194 * is reaped and thus user could see stale data if he tries to
195 * read them before the transaction is checkpointed. So be
196 * careful and force everything to disk here... We use
197 * ei->i_datasync_tid to store the newest transaction
198 * containing inode's data.
199 *
200 * Note that directories do not have this problem because they
201 * don't use page cache.
202 */
203 if (inode->i_ino != EXT4_JOURNAL_INO &&
204 ext4_should_journal_data(inode) &&
205 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
206 inode->i_data.nrpages) {
207 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
208 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
209
210 jbd2_complete_transaction(journal, commit_tid);
211 filemap_write_and_wait(&inode->i_data);
212 }
213 truncate_inode_pages_final(&inode->i_data);
214
215 goto no_delete;
216 }
217
218 if (is_bad_inode(inode))
219 goto no_delete;
220 dquot_initialize(inode);
221
222 if (ext4_should_order_data(inode))
223 ext4_begin_ordered_truncate(inode, 0);
224 truncate_inode_pages_final(&inode->i_data);
225
226 /*
227 * For inodes with journalled data, transaction commit could have
228 * dirtied the inode. And for inodes with dioread_nolock, unwritten
229 * extents converting worker could merge extents and also have dirtied
230 * the inode. Flush worker is ignoring it because of I_FREEING flag but
231 * we still need to remove the inode from the writeback lists.
232 */
233 if (!list_empty_careful(&inode->i_io_list))
234 inode_io_list_del(inode);
235
236 /*
237 * Protect us against freezing - iput() caller didn't have to have any
238 * protection against it. When we are in a running transaction though,
239 * we are already protected against freezing and we cannot grab further
240 * protection due to lock ordering constraints.
241 */
242 if (!ext4_journal_current_handle()) {
243 sb_start_intwrite(inode->i_sb);
244 freeze_protected = true;
245 }
246
247 if (!IS_NOQUOTA(inode))
248 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
249
250 /*
251 * Block bitmap, group descriptor, and inode are accounted in both
252 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
253 */
254 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
255 ext4_blocks_for_truncate(inode) + extra_credits - 3);
256 if (IS_ERR(handle)) {
257 ext4_std_error(inode->i_sb, PTR_ERR(handle));
258 /*
259 * If we're going to skip the normal cleanup, we still need to
260 * make sure that the in-core orphan linked list is properly
261 * cleaned up.
262 */
263 ext4_orphan_del(NULL, inode);
264 if (freeze_protected)
265 sb_end_intwrite(inode->i_sb);
266 goto no_delete;
267 }
268
269 if (IS_SYNC(inode))
270 ext4_handle_sync(handle);
271
272 /*
273 * Set inode->i_size to 0 before calling ext4_truncate(). We need
274 * special handling of symlinks here because i_size is used to
275 * determine whether ext4_inode_info->i_data contains symlink data or
276 * block mappings. Setting i_size to 0 will remove its fast symlink
277 * status. Erase i_data so that it becomes a valid empty block map.
278 */
279 if (ext4_inode_is_fast_symlink(inode))
280 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
281 inode->i_size = 0;
282 err = ext4_mark_inode_dirty(handle, inode);
283 if (err) {
284 ext4_warning(inode->i_sb,
285 "couldn't mark inode dirty (err %d)", err);
286 goto stop_handle;
287 }
288 if (inode->i_blocks) {
289 err = ext4_truncate(inode);
290 if (err) {
291 ext4_error_err(inode->i_sb, -err,
292 "couldn't truncate inode %lu (err %d)",
293 inode->i_ino, err);
294 goto stop_handle;
295 }
296 }
297
298 /* Remove xattr references. */
299 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
300 extra_credits);
301 if (err) {
302 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
303 stop_handle:
304 ext4_journal_stop(handle);
305 ext4_orphan_del(NULL, inode);
306 if (freeze_protected)
307 sb_end_intwrite(inode->i_sb);
308 ext4_xattr_inode_array_free(ea_inode_array);
309 goto no_delete;
310 }
311
312 /*
313 * Kill off the orphan record which ext4_truncate created.
314 * AKPM: I think this can be inside the above `if'.
315 * Note that ext4_orphan_del() has to be able to cope with the
316 * deletion of a non-existent orphan - this is because we don't
317 * know if ext4_truncate() actually created an orphan record.
318 * (Well, we could do this if we need to, but heck - it works)
319 */
320 ext4_orphan_del(handle, inode);
321 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
322
323 /*
324 * One subtle ordering requirement: if anything has gone wrong
325 * (transaction abort, IO errors, whatever), then we can still
326 * do these next steps (the fs will already have been marked as
327 * having errors), but we can't free the inode if the mark_dirty
328 * fails.
329 */
330 if (ext4_mark_inode_dirty(handle, inode))
331 /* If that failed, just do the required in-core inode clear. */
332 ext4_clear_inode(inode);
333 else
334 ext4_free_inode(handle, inode);
335 ext4_journal_stop(handle);
336 if (freeze_protected)
337 sb_end_intwrite(inode->i_sb);
338 ext4_xattr_inode_array_free(ea_inode_array);
339 return;
340 no_delete:
341 /*
342 * Check out some where else accidentally dirty the evicting inode,
343 * which may probably cause inode use-after-free issues later.
344 */
345 WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
346
347 if (!list_empty(&EXT4_I(inode)->i_fc_list))
348 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
349 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
350 }
351
352 #ifdef CONFIG_QUOTA
ext4_get_reserved_space(struct inode * inode)353 qsize_t *ext4_get_reserved_space(struct inode *inode)
354 {
355 return &EXT4_I(inode)->i_reserved_quota;
356 }
357 #endif
358
359 /*
360 * Called with i_data_sem down, which is important since we can call
361 * ext4_discard_preallocations() from here.
362 */
ext4_da_update_reserve_space(struct inode * inode,int used,int quota_claim)363 void ext4_da_update_reserve_space(struct inode *inode,
364 int used, int quota_claim)
365 {
366 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
367 struct ext4_inode_info *ei = EXT4_I(inode);
368
369 spin_lock(&ei->i_block_reservation_lock);
370 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
371 if (unlikely(used > ei->i_reserved_data_blocks)) {
372 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
373 "with only %d reserved data blocks",
374 __func__, inode->i_ino, used,
375 ei->i_reserved_data_blocks);
376 WARN_ON(1);
377 used = ei->i_reserved_data_blocks;
378 }
379
380 /* Update per-inode reservations */
381 ei->i_reserved_data_blocks -= used;
382 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
383
384 spin_unlock(&ei->i_block_reservation_lock);
385
386 /* Update quota subsystem for data blocks */
387 if (quota_claim)
388 dquot_claim_block(inode, EXT4_C2B(sbi, used));
389 else {
390 /*
391 * We did fallocate with an offset that is already delayed
392 * allocated. So on delayed allocated writeback we should
393 * not re-claim the quota for fallocated blocks.
394 */
395 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
396 }
397
398 /*
399 * If we have done all the pending block allocations and if
400 * there aren't any writers on the inode, we can discard the
401 * inode's preallocations.
402 */
403 if ((ei->i_reserved_data_blocks == 0) &&
404 !inode_is_open_for_write(inode))
405 ext4_discard_preallocations(inode, 0);
406 }
407
__check_block_validity(struct inode * inode,const char * func,unsigned int line,struct ext4_map_blocks * map)408 static int __check_block_validity(struct inode *inode, const char *func,
409 unsigned int line,
410 struct ext4_map_blocks *map)
411 {
412 if (ext4_has_feature_journal(inode->i_sb) &&
413 (inode->i_ino ==
414 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
415 return 0;
416 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
417 ext4_error_inode(inode, func, line, map->m_pblk,
418 "lblock %lu mapped to illegal pblock %llu "
419 "(length %d)", (unsigned long) map->m_lblk,
420 map->m_pblk, map->m_len);
421 return -EFSCORRUPTED;
422 }
423 return 0;
424 }
425
ext4_issue_zeroout(struct inode * inode,ext4_lblk_t lblk,ext4_fsblk_t pblk,ext4_lblk_t len)426 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
427 ext4_lblk_t len)
428 {
429 int ret;
430
431 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
432 return fscrypt_zeroout_range(inode, lblk, pblk, len);
433
434 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
435 if (ret > 0)
436 ret = 0;
437
438 return ret;
439 }
440
441 #define check_block_validity(inode, map) \
442 __check_block_validity((inode), __func__, __LINE__, (map))
443
444 #ifdef ES_AGGRESSIVE_TEST
ext4_map_blocks_es_recheck(handle_t * handle,struct inode * inode,struct ext4_map_blocks * es_map,struct ext4_map_blocks * map,int flags)445 static void ext4_map_blocks_es_recheck(handle_t *handle,
446 struct inode *inode,
447 struct ext4_map_blocks *es_map,
448 struct ext4_map_blocks *map,
449 int flags)
450 {
451 int retval;
452
453 map->m_flags = 0;
454 /*
455 * There is a race window that the result is not the same.
456 * e.g. xfstests #223 when dioread_nolock enables. The reason
457 * is that we lookup a block mapping in extent status tree with
458 * out taking i_data_sem. So at the time the unwritten extent
459 * could be converted.
460 */
461 down_read(&EXT4_I(inode)->i_data_sem);
462 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
463 retval = ext4_ext_map_blocks(handle, inode, map, 0);
464 } else {
465 retval = ext4_ind_map_blocks(handle, inode, map, 0);
466 }
467 up_read((&EXT4_I(inode)->i_data_sem));
468
469 /*
470 * We don't check m_len because extent will be collpased in status
471 * tree. So the m_len might not equal.
472 */
473 if (es_map->m_lblk != map->m_lblk ||
474 es_map->m_flags != map->m_flags ||
475 es_map->m_pblk != map->m_pblk) {
476 printk("ES cache assertion failed for inode: %lu "
477 "es_cached ex [%d/%d/%llu/%x] != "
478 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
479 inode->i_ino, es_map->m_lblk, es_map->m_len,
480 es_map->m_pblk, es_map->m_flags, map->m_lblk,
481 map->m_len, map->m_pblk, map->m_flags,
482 retval, flags);
483 }
484 }
485 #endif /* ES_AGGRESSIVE_TEST */
486
487 /*
488 * The ext4_map_blocks() function tries to look up the requested blocks,
489 * and returns if the blocks are already mapped.
490 *
491 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
492 * and store the allocated blocks in the result buffer head and mark it
493 * mapped.
494 *
495 * If file type is extents based, it will call ext4_ext_map_blocks(),
496 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
497 * based files
498 *
499 * On success, it returns the number of blocks being mapped or allocated. if
500 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
501 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
502 *
503 * It returns 0 if plain look up failed (blocks have not been allocated), in
504 * that case, @map is returned as unmapped but we still do fill map->m_len to
505 * indicate the length of a hole starting at map->m_lblk.
506 *
507 * It returns the error in case of allocation failure.
508 */
ext4_map_blocks(handle_t * handle,struct inode * inode,struct ext4_map_blocks * map,int flags)509 int ext4_map_blocks(handle_t *handle, struct inode *inode,
510 struct ext4_map_blocks *map, int flags)
511 {
512 struct extent_status es;
513 int retval;
514 int ret = 0;
515 #ifdef ES_AGGRESSIVE_TEST
516 struct ext4_map_blocks orig_map;
517
518 memcpy(&orig_map, map, sizeof(*map));
519 #endif
520
521 map->m_flags = 0;
522 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
523 flags, map->m_len, (unsigned long) map->m_lblk);
524
525 /*
526 * ext4_map_blocks returns an int, and m_len is an unsigned int
527 */
528 if (unlikely(map->m_len > INT_MAX))
529 map->m_len = INT_MAX;
530
531 /* We can handle the block number less than EXT_MAX_BLOCKS */
532 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
533 return -EFSCORRUPTED;
534
535 /* Lookup extent status tree firstly */
536 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
537 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
538 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
539 map->m_pblk = ext4_es_pblock(&es) +
540 map->m_lblk - es.es_lblk;
541 map->m_flags |= ext4_es_is_written(&es) ?
542 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
543 retval = es.es_len - (map->m_lblk - es.es_lblk);
544 if (retval > map->m_len)
545 retval = map->m_len;
546 map->m_len = retval;
547 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
548 map->m_pblk = 0;
549 retval = es.es_len - (map->m_lblk - es.es_lblk);
550 if (retval > map->m_len)
551 retval = map->m_len;
552 map->m_len = retval;
553 retval = 0;
554 } else {
555 BUG();
556 }
557 #ifdef ES_AGGRESSIVE_TEST
558 ext4_map_blocks_es_recheck(handle, inode, map,
559 &orig_map, flags);
560 #endif
561 goto found;
562 }
563
564 /*
565 * Try to see if we can get the block without requesting a new
566 * file system block.
567 */
568 down_read(&EXT4_I(inode)->i_data_sem);
569 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
570 retval = ext4_ext_map_blocks(handle, inode, map, 0);
571 } else {
572 retval = ext4_ind_map_blocks(handle, inode, map, 0);
573 }
574 if (retval > 0) {
575 unsigned int status;
576
577 if (unlikely(retval != map->m_len)) {
578 ext4_warning(inode->i_sb,
579 "ES len assertion failed for inode "
580 "%lu: retval %d != map->m_len %d",
581 inode->i_ino, retval, map->m_len);
582 WARN_ON(1);
583 }
584
585 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
586 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
587 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
588 !(status & EXTENT_STATUS_WRITTEN) &&
589 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
590 map->m_lblk + map->m_len - 1))
591 status |= EXTENT_STATUS_DELAYED;
592 ret = ext4_es_insert_extent(inode, map->m_lblk,
593 map->m_len, map->m_pblk, status);
594 if (ret < 0)
595 retval = ret;
596 }
597 up_read((&EXT4_I(inode)->i_data_sem));
598
599 found:
600 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
601 ret = check_block_validity(inode, map);
602 if (ret != 0)
603 return ret;
604 }
605
606 /* If it is only a block(s) look up */
607 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
608 return retval;
609
610 /*
611 * Returns if the blocks have already allocated
612 *
613 * Note that if blocks have been preallocated
614 * ext4_ext_get_block() returns the create = 0
615 * with buffer head unmapped.
616 */
617 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
618 /*
619 * If we need to convert extent to unwritten
620 * we continue and do the actual work in
621 * ext4_ext_map_blocks()
622 */
623 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
624 return retval;
625
626 /*
627 * Here we clear m_flags because after allocating an new extent,
628 * it will be set again.
629 */
630 map->m_flags &= ~EXT4_MAP_FLAGS;
631
632 /*
633 * New blocks allocate and/or writing to unwritten extent
634 * will possibly result in updating i_data, so we take
635 * the write lock of i_data_sem, and call get_block()
636 * with create == 1 flag.
637 */
638 down_write(&EXT4_I(inode)->i_data_sem);
639
640 /*
641 * We need to check for EXT4 here because migrate
642 * could have changed the inode type in between
643 */
644 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
645 retval = ext4_ext_map_blocks(handle, inode, map, flags);
646 } else {
647 retval = ext4_ind_map_blocks(handle, inode, map, flags);
648
649 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
650 /*
651 * We allocated new blocks which will result in
652 * i_data's format changing. Force the migrate
653 * to fail by clearing migrate flags
654 */
655 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
656 }
657 }
658
659 if (retval > 0) {
660 unsigned int status;
661
662 if (unlikely(retval != map->m_len)) {
663 ext4_warning(inode->i_sb,
664 "ES len assertion failed for inode "
665 "%lu: retval %d != map->m_len %d",
666 inode->i_ino, retval, map->m_len);
667 WARN_ON(1);
668 }
669
670 /*
671 * We have to zeroout blocks before inserting them into extent
672 * status tree. Otherwise someone could look them up there and
673 * use them before they are really zeroed. We also have to
674 * unmap metadata before zeroing as otherwise writeback can
675 * overwrite zeros with stale data from block device.
676 */
677 if (flags & EXT4_GET_BLOCKS_ZERO &&
678 map->m_flags & EXT4_MAP_MAPPED &&
679 map->m_flags & EXT4_MAP_NEW) {
680 ret = ext4_issue_zeroout(inode, map->m_lblk,
681 map->m_pblk, map->m_len);
682 if (ret) {
683 retval = ret;
684 goto out_sem;
685 }
686 }
687
688 /*
689 * If the extent has been zeroed out, we don't need to update
690 * extent status tree.
691 */
692 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
693 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
694 if (ext4_es_is_written(&es))
695 goto out_sem;
696 }
697 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
698 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
699 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
700 !(status & EXTENT_STATUS_WRITTEN) &&
701 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
702 map->m_lblk + map->m_len - 1))
703 status |= EXTENT_STATUS_DELAYED;
704 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
705 map->m_pblk, status);
706 if (ret < 0) {
707 retval = ret;
708 goto out_sem;
709 }
710 }
711
712 out_sem:
713 up_write((&EXT4_I(inode)->i_data_sem));
714 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
715 ret = check_block_validity(inode, map);
716 if (ret != 0)
717 return ret;
718
719 /*
720 * Inodes with freshly allocated blocks where contents will be
721 * visible after transaction commit must be on transaction's
722 * ordered data list.
723 */
724 if (map->m_flags & EXT4_MAP_NEW &&
725 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
726 !(flags & EXT4_GET_BLOCKS_ZERO) &&
727 !ext4_is_quota_file(inode) &&
728 ext4_should_order_data(inode)) {
729 loff_t start_byte =
730 (loff_t)map->m_lblk << inode->i_blkbits;
731 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
732
733 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
734 ret = ext4_jbd2_inode_add_wait(handle, inode,
735 start_byte, length);
736 else
737 ret = ext4_jbd2_inode_add_write(handle, inode,
738 start_byte, length);
739 if (ret)
740 return ret;
741 }
742 }
743 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
744 map->m_flags & EXT4_MAP_MAPPED))
745 ext4_fc_track_range(handle, inode, map->m_lblk,
746 map->m_lblk + map->m_len - 1);
747 if (retval < 0)
748 ext_debug(inode, "failed with err %d\n", retval);
749 return retval;
750 }
751
752 /*
753 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
754 * we have to be careful as someone else may be manipulating b_state as well.
755 */
ext4_update_bh_state(struct buffer_head * bh,unsigned long flags)756 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
757 {
758 unsigned long old_state;
759 unsigned long new_state;
760
761 flags &= EXT4_MAP_FLAGS;
762
763 /* Dummy buffer_head? Set non-atomically. */
764 if (!bh->b_page) {
765 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
766 return;
767 }
768 /*
769 * Someone else may be modifying b_state. Be careful! This is ugly but
770 * once we get rid of using bh as a container for mapping information
771 * to pass to / from get_block functions, this can go away.
772 */
773 do {
774 old_state = READ_ONCE(bh->b_state);
775 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
776 } while (unlikely(
777 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
778 }
779
_ext4_get_block(struct inode * inode,sector_t iblock,struct buffer_head * bh,int flags)780 static int _ext4_get_block(struct inode *inode, sector_t iblock,
781 struct buffer_head *bh, int flags)
782 {
783 struct ext4_map_blocks map;
784 int ret = 0;
785
786 if (ext4_has_inline_data(inode))
787 return -ERANGE;
788
789 map.m_lblk = iblock;
790 map.m_len = bh->b_size >> inode->i_blkbits;
791
792 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
793 flags);
794 if (ret > 0) {
795 map_bh(bh, inode->i_sb, map.m_pblk);
796 ext4_update_bh_state(bh, map.m_flags);
797 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
798 ret = 0;
799 } else if (ret == 0) {
800 /* hole case, need to fill in bh->b_size */
801 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
802 }
803 return ret;
804 }
805
ext4_get_block(struct inode * inode,sector_t iblock,struct buffer_head * bh,int create)806 int ext4_get_block(struct inode *inode, sector_t iblock,
807 struct buffer_head *bh, int create)
808 {
809 return _ext4_get_block(inode, iblock, bh,
810 create ? EXT4_GET_BLOCKS_CREATE : 0);
811 }
812
813 /*
814 * Get block function used when preparing for buffered write if we require
815 * creating an unwritten extent if blocks haven't been allocated. The extent
816 * will be converted to written after the IO is complete.
817 */
ext4_get_block_unwritten(struct inode * inode,sector_t iblock,struct buffer_head * bh_result,int create)818 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
819 struct buffer_head *bh_result, int create)
820 {
821 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
822 inode->i_ino, create);
823 return _ext4_get_block(inode, iblock, bh_result,
824 EXT4_GET_BLOCKS_IO_CREATE_EXT);
825 }
826
827 /* Maximum number of blocks we map for direct IO at once. */
828 #define DIO_MAX_BLOCKS 4096
829
830 /*
831 * `handle' can be NULL if create is zero
832 */
ext4_getblk(handle_t * handle,struct inode * inode,ext4_lblk_t block,int map_flags)833 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
834 ext4_lblk_t block, int map_flags)
835 {
836 struct ext4_map_blocks map;
837 struct buffer_head *bh;
838 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
839 int err;
840
841 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
842 || handle != NULL || create == 0);
843
844 map.m_lblk = block;
845 map.m_len = 1;
846 err = ext4_map_blocks(handle, inode, &map, map_flags);
847
848 if (err == 0)
849 return create ? ERR_PTR(-ENOSPC) : NULL;
850 if (err < 0)
851 return ERR_PTR(err);
852
853 bh = sb_getblk(inode->i_sb, map.m_pblk);
854 if (unlikely(!bh))
855 return ERR_PTR(-ENOMEM);
856 if (map.m_flags & EXT4_MAP_NEW) {
857 ASSERT(create != 0);
858 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
859 || (handle != NULL));
860
861 /*
862 * Now that we do not always journal data, we should
863 * keep in mind whether this should always journal the
864 * new buffer as metadata. For now, regular file
865 * writes use ext4_get_block instead, so it's not a
866 * problem.
867 */
868 lock_buffer(bh);
869 BUFFER_TRACE(bh, "call get_create_access");
870 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
871 EXT4_JTR_NONE);
872 if (unlikely(err)) {
873 unlock_buffer(bh);
874 goto errout;
875 }
876 if (!buffer_uptodate(bh)) {
877 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
878 set_buffer_uptodate(bh);
879 }
880 unlock_buffer(bh);
881 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
882 err = ext4_handle_dirty_metadata(handle, inode, bh);
883 if (unlikely(err))
884 goto errout;
885 } else
886 BUFFER_TRACE(bh, "not a new buffer");
887 return bh;
888 errout:
889 brelse(bh);
890 return ERR_PTR(err);
891 }
892
ext4_bread(handle_t * handle,struct inode * inode,ext4_lblk_t block,int map_flags)893 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
894 ext4_lblk_t block, int map_flags)
895 {
896 struct buffer_head *bh;
897 int ret;
898
899 bh = ext4_getblk(handle, inode, block, map_flags);
900 if (IS_ERR(bh))
901 return bh;
902 if (!bh || ext4_buffer_uptodate(bh))
903 return bh;
904
905 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
906 if (ret) {
907 put_bh(bh);
908 return ERR_PTR(ret);
909 }
910 return bh;
911 }
912
913 /* Read a contiguous batch of blocks. */
ext4_bread_batch(struct inode * inode,ext4_lblk_t block,int bh_count,bool wait,struct buffer_head ** bhs)914 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
915 bool wait, struct buffer_head **bhs)
916 {
917 int i, err;
918
919 for (i = 0; i < bh_count; i++) {
920 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
921 if (IS_ERR(bhs[i])) {
922 err = PTR_ERR(bhs[i]);
923 bh_count = i;
924 goto out_brelse;
925 }
926 }
927
928 for (i = 0; i < bh_count; i++)
929 /* Note that NULL bhs[i] is valid because of holes. */
930 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
931 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
932
933 if (!wait)
934 return 0;
935
936 for (i = 0; i < bh_count; i++)
937 if (bhs[i])
938 wait_on_buffer(bhs[i]);
939
940 for (i = 0; i < bh_count; i++) {
941 if (bhs[i] && !buffer_uptodate(bhs[i])) {
942 err = -EIO;
943 goto out_brelse;
944 }
945 }
946 return 0;
947
948 out_brelse:
949 for (i = 0; i < bh_count; i++) {
950 brelse(bhs[i]);
951 bhs[i] = NULL;
952 }
953 return err;
954 }
955
ext4_walk_page_buffers(handle_t * handle,struct inode * inode,struct buffer_head * head,unsigned from,unsigned to,int * partial,int (* fn)(handle_t * handle,struct inode * inode,struct buffer_head * bh))956 int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
957 struct buffer_head *head,
958 unsigned from,
959 unsigned to,
960 int *partial,
961 int (*fn)(handle_t *handle, struct inode *inode,
962 struct buffer_head *bh))
963 {
964 struct buffer_head *bh;
965 unsigned block_start, block_end;
966 unsigned blocksize = head->b_size;
967 int err, ret = 0;
968 struct buffer_head *next;
969
970 for (bh = head, block_start = 0;
971 ret == 0 && (bh != head || !block_start);
972 block_start = block_end, bh = next) {
973 next = bh->b_this_page;
974 block_end = block_start + blocksize;
975 if (block_end <= from || block_start >= to) {
976 if (partial && !buffer_uptodate(bh))
977 *partial = 1;
978 continue;
979 }
980 err = (*fn)(handle, inode, bh);
981 if (!ret)
982 ret = err;
983 }
984 return ret;
985 }
986
987 /*
988 * To preserve ordering, it is essential that the hole instantiation and
989 * the data write be encapsulated in a single transaction. We cannot
990 * close off a transaction and start a new one between the ext4_get_block()
991 * and the commit_write(). So doing the jbd2_journal_start at the start of
992 * prepare_write() is the right place.
993 *
994 * Also, this function can nest inside ext4_writepage(). In that case, we
995 * *know* that ext4_writepage() has generated enough buffer credits to do the
996 * whole page. So we won't block on the journal in that case, which is good,
997 * because the caller may be PF_MEMALLOC.
998 *
999 * By accident, ext4 can be reentered when a transaction is open via
1000 * quota file writes. If we were to commit the transaction while thus
1001 * reentered, there can be a deadlock - we would be holding a quota
1002 * lock, and the commit would never complete if another thread had a
1003 * transaction open and was blocking on the quota lock - a ranking
1004 * violation.
1005 *
1006 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1007 * will _not_ run commit under these circumstances because handle->h_ref
1008 * is elevated. We'll still have enough credits for the tiny quotafile
1009 * write.
1010 */
do_journal_get_write_access(handle_t * handle,struct inode * inode,struct buffer_head * bh)1011 int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1012 struct buffer_head *bh)
1013 {
1014 int dirty = buffer_dirty(bh);
1015 int ret;
1016
1017 if (!buffer_mapped(bh) || buffer_freed(bh))
1018 return 0;
1019 /*
1020 * __block_write_begin() could have dirtied some buffers. Clean
1021 * the dirty bit as jbd2_journal_get_write_access() could complain
1022 * otherwise about fs integrity issues. Setting of the dirty bit
1023 * by __block_write_begin() isn't a real problem here as we clear
1024 * the bit before releasing a page lock and thus writeback cannot
1025 * ever write the buffer.
1026 */
1027 if (dirty)
1028 clear_buffer_dirty(bh);
1029 BUFFER_TRACE(bh, "get write access");
1030 ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1031 EXT4_JTR_NONE);
1032 if (!ret && dirty)
1033 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1034 return ret;
1035 }
1036
1037 #ifdef CONFIG_FS_ENCRYPTION
ext4_block_write_begin(struct page * page,loff_t pos,unsigned len,get_block_t * get_block)1038 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1039 get_block_t *get_block)
1040 {
1041 unsigned from = pos & (PAGE_SIZE - 1);
1042 unsigned to = from + len;
1043 struct inode *inode = page->mapping->host;
1044 unsigned block_start, block_end;
1045 sector_t block;
1046 int err = 0;
1047 unsigned blocksize = inode->i_sb->s_blocksize;
1048 unsigned bbits;
1049 struct buffer_head *bh, *head, *wait[2];
1050 int nr_wait = 0;
1051 int i;
1052
1053 BUG_ON(!PageLocked(page));
1054 BUG_ON(from > PAGE_SIZE);
1055 BUG_ON(to > PAGE_SIZE);
1056 BUG_ON(from > to);
1057
1058 if (!page_has_buffers(page))
1059 create_empty_buffers(page, blocksize, 0);
1060 head = page_buffers(page);
1061 bbits = ilog2(blocksize);
1062 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1063
1064 for (bh = head, block_start = 0; bh != head || !block_start;
1065 block++, block_start = block_end, bh = bh->b_this_page) {
1066 block_end = block_start + blocksize;
1067 if (block_end <= from || block_start >= to) {
1068 if (PageUptodate(page)) {
1069 set_buffer_uptodate(bh);
1070 }
1071 continue;
1072 }
1073 if (buffer_new(bh))
1074 clear_buffer_new(bh);
1075 if (!buffer_mapped(bh)) {
1076 WARN_ON(bh->b_size != blocksize);
1077 err = get_block(inode, block, bh, 1);
1078 if (err)
1079 break;
1080 if (buffer_new(bh)) {
1081 if (PageUptodate(page)) {
1082 clear_buffer_new(bh);
1083 set_buffer_uptodate(bh);
1084 mark_buffer_dirty(bh);
1085 continue;
1086 }
1087 if (block_end > to || block_start < from)
1088 zero_user_segments(page, to, block_end,
1089 block_start, from);
1090 continue;
1091 }
1092 }
1093 if (PageUptodate(page)) {
1094 set_buffer_uptodate(bh);
1095 continue;
1096 }
1097 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1098 !buffer_unwritten(bh) &&
1099 (block_start < from || block_end > to)) {
1100 ext4_read_bh_lock(bh, 0, false);
1101 wait[nr_wait++] = bh;
1102 }
1103 }
1104 /*
1105 * If we issued read requests, let them complete.
1106 */
1107 for (i = 0; i < nr_wait; i++) {
1108 wait_on_buffer(wait[i]);
1109 if (!buffer_uptodate(wait[i]))
1110 err = -EIO;
1111 }
1112 if (unlikely(err)) {
1113 page_zero_new_buffers(page, from, to);
1114 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1115 for (i = 0; i < nr_wait; i++) {
1116 int err2;
1117
1118 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1119 bh_offset(wait[i]));
1120 if (err2) {
1121 clear_buffer_uptodate(wait[i]);
1122 err = err2;
1123 }
1124 }
1125 }
1126
1127 return err;
1128 }
1129 #endif
1130
ext4_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned flags,struct page ** pagep,void ** fsdata)1131 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1132 loff_t pos, unsigned len, unsigned flags,
1133 struct page **pagep, void **fsdata)
1134 {
1135 struct inode *inode = mapping->host;
1136 int ret, needed_blocks;
1137 handle_t *handle;
1138 int retries = 0;
1139 struct page *page;
1140 pgoff_t index;
1141 unsigned from, to;
1142
1143 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1144 return -EIO;
1145
1146 trace_ext4_write_begin(inode, pos, len, flags);
1147 /*
1148 * Reserve one block more for addition to orphan list in case
1149 * we allocate blocks but write fails for some reason
1150 */
1151 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1152 index = pos >> PAGE_SHIFT;
1153 from = pos & (PAGE_SIZE - 1);
1154 to = from + len;
1155
1156 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1157 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1158 flags, pagep);
1159 if (ret < 0)
1160 return ret;
1161 if (ret == 1)
1162 return 0;
1163 }
1164
1165 /*
1166 * grab_cache_page_write_begin() can take a long time if the
1167 * system is thrashing due to memory pressure, or if the page
1168 * is being written back. So grab it first before we start
1169 * the transaction handle. This also allows us to allocate
1170 * the page (if needed) without using GFP_NOFS.
1171 */
1172 retry_grab:
1173 page = grab_cache_page_write_begin(mapping, index, flags);
1174 if (!page)
1175 return -ENOMEM;
1176 /*
1177 * The same as page allocation, we prealloc buffer heads before
1178 * starting the handle.
1179 */
1180 if (!page_has_buffers(page))
1181 create_empty_buffers(page, inode->i_sb->s_blocksize, 0);
1182
1183 unlock_page(page);
1184
1185 retry_journal:
1186 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1187 if (IS_ERR(handle)) {
1188 put_page(page);
1189 return PTR_ERR(handle);
1190 }
1191
1192 lock_page(page);
1193 if (page->mapping != mapping) {
1194 /* The page got truncated from under us */
1195 unlock_page(page);
1196 put_page(page);
1197 ext4_journal_stop(handle);
1198 goto retry_grab;
1199 }
1200 /* In case writeback began while the page was unlocked */
1201 wait_for_stable_page(page);
1202
1203 #ifdef CONFIG_FS_ENCRYPTION
1204 if (ext4_should_dioread_nolock(inode))
1205 ret = ext4_block_write_begin(page, pos, len,
1206 ext4_get_block_unwritten);
1207 else
1208 ret = ext4_block_write_begin(page, pos, len,
1209 ext4_get_block);
1210 #else
1211 if (ext4_should_dioread_nolock(inode))
1212 ret = __block_write_begin(page, pos, len,
1213 ext4_get_block_unwritten);
1214 else
1215 ret = __block_write_begin(page, pos, len, ext4_get_block);
1216 #endif
1217 if (!ret && ext4_should_journal_data(inode)) {
1218 ret = ext4_walk_page_buffers(handle, inode,
1219 page_buffers(page), from, to, NULL,
1220 do_journal_get_write_access);
1221 }
1222
1223 if (ret) {
1224 bool extended = (pos + len > inode->i_size) &&
1225 !ext4_verity_in_progress(inode);
1226
1227 unlock_page(page);
1228 /*
1229 * __block_write_begin may have instantiated a few blocks
1230 * outside i_size. Trim these off again. Don't need
1231 * i_size_read because we hold i_mutex.
1232 *
1233 * Add inode to orphan list in case we crash before
1234 * truncate finishes
1235 */
1236 if (extended && ext4_can_truncate(inode))
1237 ext4_orphan_add(handle, inode);
1238
1239 ext4_journal_stop(handle);
1240 if (extended) {
1241 ext4_truncate_failed_write(inode);
1242 /*
1243 * If truncate failed early the inode might
1244 * still be on the orphan list; we need to
1245 * make sure the inode is removed from the
1246 * orphan list in that case.
1247 */
1248 if (inode->i_nlink)
1249 ext4_orphan_del(NULL, inode);
1250 }
1251
1252 if (ret == -ENOSPC &&
1253 ext4_should_retry_alloc(inode->i_sb, &retries))
1254 goto retry_journal;
1255 put_page(page);
1256 return ret;
1257 }
1258 *pagep = page;
1259 return ret;
1260 }
1261
1262 /* For write_end() in data=journal mode */
write_end_fn(handle_t * handle,struct inode * inode,struct buffer_head * bh)1263 static int write_end_fn(handle_t *handle, struct inode *inode,
1264 struct buffer_head *bh)
1265 {
1266 int ret;
1267 if (!buffer_mapped(bh) || buffer_freed(bh))
1268 return 0;
1269 set_buffer_uptodate(bh);
1270 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1271 clear_buffer_meta(bh);
1272 clear_buffer_prio(bh);
1273 return ret;
1274 }
1275
1276 /*
1277 * We need to pick up the new inode size which generic_commit_write gave us
1278 * `file' can be NULL - eg, when called from page_symlink().
1279 *
1280 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1281 * buffers are managed internally.
1282 */
ext4_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)1283 static int ext4_write_end(struct file *file,
1284 struct address_space *mapping,
1285 loff_t pos, unsigned len, unsigned copied,
1286 struct page *page, void *fsdata)
1287 {
1288 handle_t *handle = ext4_journal_current_handle();
1289 struct inode *inode = mapping->host;
1290 loff_t old_size = inode->i_size;
1291 int ret = 0, ret2;
1292 int i_size_changed = 0;
1293 bool verity = ext4_verity_in_progress(inode);
1294
1295 trace_ext4_write_end(inode, pos, len, copied);
1296
1297 if (ext4_has_inline_data(inode) &&
1298 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1299 return ext4_write_inline_data_end(inode, pos, len, copied, page);
1300
1301 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1302 /*
1303 * it's important to update i_size while still holding page lock:
1304 * page writeout could otherwise come in and zero beyond i_size.
1305 *
1306 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1307 * blocks are being written past EOF, so skip the i_size update.
1308 */
1309 if (!verity)
1310 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1311 unlock_page(page);
1312 put_page(page);
1313
1314 if (old_size < pos && !verity)
1315 pagecache_isize_extended(inode, old_size, pos);
1316 /*
1317 * Don't mark the inode dirty under page lock. First, it unnecessarily
1318 * makes the holding time of page lock longer. Second, it forces lock
1319 * ordering of page lock and transaction start for journaling
1320 * filesystems.
1321 */
1322 if (i_size_changed)
1323 ret = ext4_mark_inode_dirty(handle, inode);
1324
1325 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1326 /* if we have allocated more blocks and copied
1327 * less. We will have blocks allocated outside
1328 * inode->i_size. So truncate them
1329 */
1330 ext4_orphan_add(handle, inode);
1331
1332 ret2 = ext4_journal_stop(handle);
1333 if (!ret)
1334 ret = ret2;
1335
1336 if (pos + len > inode->i_size && !verity) {
1337 ext4_truncate_failed_write(inode);
1338 /*
1339 * If truncate failed early the inode might still be
1340 * on the orphan list; we need to make sure the inode
1341 * is removed from the orphan list in that case.
1342 */
1343 if (inode->i_nlink)
1344 ext4_orphan_del(NULL, inode);
1345 }
1346
1347 return ret ? ret : copied;
1348 }
1349
1350 /*
1351 * This is a private version of page_zero_new_buffers() which doesn't
1352 * set the buffer to be dirty, since in data=journalled mode we need
1353 * to call ext4_handle_dirty_metadata() instead.
1354 */
ext4_journalled_zero_new_buffers(handle_t * handle,struct inode * inode,struct page * page,unsigned from,unsigned to)1355 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1356 struct inode *inode,
1357 struct page *page,
1358 unsigned from, unsigned to)
1359 {
1360 unsigned int block_start = 0, block_end;
1361 struct buffer_head *head, *bh;
1362
1363 bh = head = page_buffers(page);
1364 do {
1365 block_end = block_start + bh->b_size;
1366 if (buffer_new(bh)) {
1367 if (block_end > from && block_start < to) {
1368 if (!PageUptodate(page)) {
1369 unsigned start, size;
1370
1371 start = max(from, block_start);
1372 size = min(to, block_end) - start;
1373
1374 zero_user(page, start, size);
1375 write_end_fn(handle, inode, bh);
1376 }
1377 clear_buffer_new(bh);
1378 }
1379 }
1380 block_start = block_end;
1381 bh = bh->b_this_page;
1382 } while (bh != head);
1383 }
1384
ext4_journalled_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)1385 static int ext4_journalled_write_end(struct file *file,
1386 struct address_space *mapping,
1387 loff_t pos, unsigned len, unsigned copied,
1388 struct page *page, void *fsdata)
1389 {
1390 handle_t *handle = ext4_journal_current_handle();
1391 struct inode *inode = mapping->host;
1392 loff_t old_size = inode->i_size;
1393 int ret = 0, ret2;
1394 int partial = 0;
1395 unsigned from, to;
1396 int size_changed = 0;
1397 bool verity = ext4_verity_in_progress(inode);
1398
1399 trace_ext4_journalled_write_end(inode, pos, len, copied);
1400 from = pos & (PAGE_SIZE - 1);
1401 to = from + len;
1402
1403 BUG_ON(!ext4_handle_valid(handle));
1404
1405 if (ext4_has_inline_data(inode))
1406 return ext4_write_inline_data_end(inode, pos, len, copied, page);
1407
1408 if (unlikely(copied < len) && !PageUptodate(page)) {
1409 copied = 0;
1410 ext4_journalled_zero_new_buffers(handle, inode, page, from, to);
1411 } else {
1412 if (unlikely(copied < len))
1413 ext4_journalled_zero_new_buffers(handle, inode, page,
1414 from + copied, to);
1415 ret = ext4_walk_page_buffers(handle, inode, page_buffers(page),
1416 from, from + copied, &partial,
1417 write_end_fn);
1418 if (!partial)
1419 SetPageUptodate(page);
1420 }
1421 if (!verity)
1422 size_changed = ext4_update_inode_size(inode, pos + copied);
1423 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1424 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1425 unlock_page(page);
1426 put_page(page);
1427
1428 if (old_size < pos && !verity)
1429 pagecache_isize_extended(inode, old_size, pos);
1430
1431 if (size_changed) {
1432 ret2 = ext4_mark_inode_dirty(handle, inode);
1433 if (!ret)
1434 ret = ret2;
1435 }
1436
1437 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1438 /* if we have allocated more blocks and copied
1439 * less. We will have blocks allocated outside
1440 * inode->i_size. So truncate them
1441 */
1442 ext4_orphan_add(handle, inode);
1443
1444 ret2 = ext4_journal_stop(handle);
1445 if (!ret)
1446 ret = ret2;
1447 if (pos + len > inode->i_size && !verity) {
1448 ext4_truncate_failed_write(inode);
1449 /*
1450 * If truncate failed early the inode might still be
1451 * on the orphan list; we need to make sure the inode
1452 * is removed from the orphan list in that case.
1453 */
1454 if (inode->i_nlink)
1455 ext4_orphan_del(NULL, inode);
1456 }
1457
1458 return ret ? ret : copied;
1459 }
1460
1461 /*
1462 * Reserve space for a single cluster
1463 */
ext4_da_reserve_space(struct inode * inode)1464 static int ext4_da_reserve_space(struct inode *inode)
1465 {
1466 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1467 struct ext4_inode_info *ei = EXT4_I(inode);
1468 int ret;
1469
1470 /*
1471 * We will charge metadata quota at writeout time; this saves
1472 * us from metadata over-estimation, though we may go over by
1473 * a small amount in the end. Here we just reserve for data.
1474 */
1475 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1476 if (ret)
1477 return ret;
1478
1479 spin_lock(&ei->i_block_reservation_lock);
1480 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1481 spin_unlock(&ei->i_block_reservation_lock);
1482 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1483 return -ENOSPC;
1484 }
1485 ei->i_reserved_data_blocks++;
1486 trace_ext4_da_reserve_space(inode);
1487 spin_unlock(&ei->i_block_reservation_lock);
1488
1489 return 0; /* success */
1490 }
1491
ext4_da_release_space(struct inode * inode,int to_free)1492 void ext4_da_release_space(struct inode *inode, int to_free)
1493 {
1494 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1495 struct ext4_inode_info *ei = EXT4_I(inode);
1496
1497 if (!to_free)
1498 return; /* Nothing to release, exit */
1499
1500 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1501
1502 trace_ext4_da_release_space(inode, to_free);
1503 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1504 /*
1505 * if there aren't enough reserved blocks, then the
1506 * counter is messed up somewhere. Since this
1507 * function is called from invalidate page, it's
1508 * harmless to return without any action.
1509 */
1510 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1511 "ino %lu, to_free %d with only %d reserved "
1512 "data blocks", inode->i_ino, to_free,
1513 ei->i_reserved_data_blocks);
1514 WARN_ON(1);
1515 to_free = ei->i_reserved_data_blocks;
1516 }
1517 ei->i_reserved_data_blocks -= to_free;
1518
1519 /* update fs dirty data blocks counter */
1520 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1521
1522 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1523
1524 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1525 }
1526
1527 /*
1528 * Delayed allocation stuff
1529 */
1530
1531 struct mpage_da_data {
1532 struct inode *inode;
1533 struct writeback_control *wbc;
1534
1535 pgoff_t first_page; /* The first page to write */
1536 pgoff_t next_page; /* Current page to examine */
1537 pgoff_t last_page; /* Last page to examine */
1538 /*
1539 * Extent to map - this can be after first_page because that can be
1540 * fully mapped. We somewhat abuse m_flags to store whether the extent
1541 * is delalloc or unwritten.
1542 */
1543 struct ext4_map_blocks map;
1544 struct ext4_io_submit io_submit; /* IO submission data */
1545 unsigned int do_map:1;
1546 unsigned int scanned_until_end:1;
1547 };
1548
mpage_release_unused_pages(struct mpage_da_data * mpd,bool invalidate)1549 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1550 bool invalidate)
1551 {
1552 int nr_pages, i;
1553 pgoff_t index, end;
1554 struct pagevec pvec;
1555 struct inode *inode = mpd->inode;
1556 struct address_space *mapping = inode->i_mapping;
1557
1558 /* This is necessary when next_page == 0. */
1559 if (mpd->first_page >= mpd->next_page)
1560 return;
1561
1562 mpd->scanned_until_end = 0;
1563 index = mpd->first_page;
1564 end = mpd->next_page - 1;
1565 if (invalidate) {
1566 ext4_lblk_t start, last;
1567 start = index << (PAGE_SHIFT - inode->i_blkbits);
1568 last = end << (PAGE_SHIFT - inode->i_blkbits);
1569
1570 /*
1571 * avoid racing with extent status tree scans made by
1572 * ext4_insert_delayed_block()
1573 */
1574 down_write(&EXT4_I(inode)->i_data_sem);
1575 ext4_es_remove_extent(inode, start, last - start + 1);
1576 up_write(&EXT4_I(inode)->i_data_sem);
1577 }
1578
1579 pagevec_init(&pvec);
1580 while (index <= end) {
1581 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1582 if (nr_pages == 0)
1583 break;
1584 for (i = 0; i < nr_pages; i++) {
1585 struct page *page = pvec.pages[i];
1586
1587 BUG_ON(!PageLocked(page));
1588 BUG_ON(PageWriteback(page));
1589 if (invalidate) {
1590 if (page_mapped(page))
1591 clear_page_dirty_for_io(page);
1592 block_invalidatepage(page, 0, PAGE_SIZE);
1593 ClearPageUptodate(page);
1594 }
1595 unlock_page(page);
1596 }
1597 pagevec_release(&pvec);
1598 }
1599 }
1600
ext4_print_free_blocks(struct inode * inode)1601 static void ext4_print_free_blocks(struct inode *inode)
1602 {
1603 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1604 struct super_block *sb = inode->i_sb;
1605 struct ext4_inode_info *ei = EXT4_I(inode);
1606
1607 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1608 EXT4_C2B(EXT4_SB(inode->i_sb),
1609 ext4_count_free_clusters(sb)));
1610 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1611 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1612 (long long) EXT4_C2B(EXT4_SB(sb),
1613 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1614 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1615 (long long) EXT4_C2B(EXT4_SB(sb),
1616 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1617 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1618 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1619 ei->i_reserved_data_blocks);
1620 return;
1621 }
1622
ext4_bh_delay_or_unwritten(handle_t * handle,struct inode * inode,struct buffer_head * bh)1623 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct inode *inode,
1624 struct buffer_head *bh)
1625 {
1626 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1627 }
1628
1629 /*
1630 * ext4_insert_delayed_block - adds a delayed block to the extents status
1631 * tree, incrementing the reserved cluster/block
1632 * count or making a pending reservation
1633 * where needed
1634 *
1635 * @inode - file containing the newly added block
1636 * @lblk - logical block to be added
1637 *
1638 * Returns 0 on success, negative error code on failure.
1639 */
ext4_insert_delayed_block(struct inode * inode,ext4_lblk_t lblk)1640 static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1641 {
1642 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1643 int ret;
1644 bool allocated = false;
1645 bool reserved = false;
1646
1647 /*
1648 * If the cluster containing lblk is shared with a delayed,
1649 * written, or unwritten extent in a bigalloc file system, it's
1650 * already been accounted for and does not need to be reserved.
1651 * A pending reservation must be made for the cluster if it's
1652 * shared with a written or unwritten extent and doesn't already
1653 * have one. Written and unwritten extents can be purged from the
1654 * extents status tree if the system is under memory pressure, so
1655 * it's necessary to examine the extent tree if a search of the
1656 * extents status tree doesn't get a match.
1657 */
1658 if (sbi->s_cluster_ratio == 1) {
1659 ret = ext4_da_reserve_space(inode);
1660 if (ret != 0) /* ENOSPC */
1661 goto errout;
1662 reserved = true;
1663 } else { /* bigalloc */
1664 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1665 if (!ext4_es_scan_clu(inode,
1666 &ext4_es_is_mapped, lblk)) {
1667 ret = ext4_clu_mapped(inode,
1668 EXT4_B2C(sbi, lblk));
1669 if (ret < 0)
1670 goto errout;
1671 if (ret == 0) {
1672 ret = ext4_da_reserve_space(inode);
1673 if (ret != 0) /* ENOSPC */
1674 goto errout;
1675 reserved = true;
1676 } else {
1677 allocated = true;
1678 }
1679 } else {
1680 allocated = true;
1681 }
1682 }
1683 }
1684
1685 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1686 if (ret && reserved)
1687 ext4_da_release_space(inode, 1);
1688
1689 errout:
1690 return ret;
1691 }
1692
1693 /*
1694 * This function is grabs code from the very beginning of
1695 * ext4_map_blocks, but assumes that the caller is from delayed write
1696 * time. This function looks up the requested blocks and sets the
1697 * buffer delay bit under the protection of i_data_sem.
1698 */
ext4_da_map_blocks(struct inode * inode,sector_t iblock,struct ext4_map_blocks * map,struct buffer_head * bh)1699 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1700 struct ext4_map_blocks *map,
1701 struct buffer_head *bh)
1702 {
1703 struct extent_status es;
1704 int retval;
1705 sector_t invalid_block = ~((sector_t) 0xffff);
1706 #ifdef ES_AGGRESSIVE_TEST
1707 struct ext4_map_blocks orig_map;
1708
1709 memcpy(&orig_map, map, sizeof(*map));
1710 #endif
1711
1712 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1713 invalid_block = ~0;
1714
1715 map->m_flags = 0;
1716 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1717 (unsigned long) map->m_lblk);
1718
1719 /* Lookup extent status tree firstly */
1720 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1721 if (ext4_es_is_hole(&es)) {
1722 retval = 0;
1723 down_read(&EXT4_I(inode)->i_data_sem);
1724 goto add_delayed;
1725 }
1726
1727 /*
1728 * Delayed extent could be allocated by fallocate.
1729 * So we need to check it.
1730 */
1731 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1732 map_bh(bh, inode->i_sb, invalid_block);
1733 set_buffer_new(bh);
1734 set_buffer_delay(bh);
1735 return 0;
1736 }
1737
1738 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1739 retval = es.es_len - (iblock - es.es_lblk);
1740 if (retval > map->m_len)
1741 retval = map->m_len;
1742 map->m_len = retval;
1743 if (ext4_es_is_written(&es))
1744 map->m_flags |= EXT4_MAP_MAPPED;
1745 else if (ext4_es_is_unwritten(&es))
1746 map->m_flags |= EXT4_MAP_UNWRITTEN;
1747 else
1748 BUG();
1749
1750 #ifdef ES_AGGRESSIVE_TEST
1751 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1752 #endif
1753 return retval;
1754 }
1755
1756 /*
1757 * Try to see if we can get the block without requesting a new
1758 * file system block.
1759 */
1760 down_read(&EXT4_I(inode)->i_data_sem);
1761 if (ext4_has_inline_data(inode))
1762 retval = 0;
1763 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1764 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1765 else
1766 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1767
1768 add_delayed:
1769 if (retval == 0) {
1770 int ret;
1771
1772 /*
1773 * XXX: __block_prepare_write() unmaps passed block,
1774 * is it OK?
1775 */
1776
1777 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1778 if (ret != 0) {
1779 retval = ret;
1780 goto out_unlock;
1781 }
1782
1783 map_bh(bh, inode->i_sb, invalid_block);
1784 set_buffer_new(bh);
1785 set_buffer_delay(bh);
1786 } else if (retval > 0) {
1787 int ret;
1788 unsigned int status;
1789
1790 if (unlikely(retval != map->m_len)) {
1791 ext4_warning(inode->i_sb,
1792 "ES len assertion failed for inode "
1793 "%lu: retval %d != map->m_len %d",
1794 inode->i_ino, retval, map->m_len);
1795 WARN_ON(1);
1796 }
1797
1798 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1799 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1800 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1801 map->m_pblk, status);
1802 if (ret != 0)
1803 retval = ret;
1804 }
1805
1806 out_unlock:
1807 up_read((&EXT4_I(inode)->i_data_sem));
1808
1809 return retval;
1810 }
1811
1812 /*
1813 * This is a special get_block_t callback which is used by
1814 * ext4_da_write_begin(). It will either return mapped block or
1815 * reserve space for a single block.
1816 *
1817 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1818 * We also have b_blocknr = -1 and b_bdev initialized properly
1819 *
1820 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1821 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1822 * initialized properly.
1823 */
ext4_da_get_block_prep(struct inode * inode,sector_t iblock,struct buffer_head * bh,int create)1824 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1825 struct buffer_head *bh, int create)
1826 {
1827 struct ext4_map_blocks map;
1828 int ret = 0;
1829
1830 BUG_ON(create == 0);
1831 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1832
1833 map.m_lblk = iblock;
1834 map.m_len = 1;
1835
1836 /*
1837 * first, we need to know whether the block is allocated already
1838 * preallocated blocks are unmapped but should treated
1839 * the same as allocated blocks.
1840 */
1841 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1842 if (ret <= 0)
1843 return ret;
1844
1845 map_bh(bh, inode->i_sb, map.m_pblk);
1846 ext4_update_bh_state(bh, map.m_flags);
1847
1848 if (buffer_unwritten(bh)) {
1849 /* A delayed write to unwritten bh should be marked
1850 * new and mapped. Mapped ensures that we don't do
1851 * get_block multiple times when we write to the same
1852 * offset and new ensures that we do proper zero out
1853 * for partial write.
1854 */
1855 set_buffer_new(bh);
1856 set_buffer_mapped(bh);
1857 }
1858 return 0;
1859 }
1860
__ext4_journalled_writepage(struct page * page,unsigned int len)1861 static int __ext4_journalled_writepage(struct page *page,
1862 unsigned int len)
1863 {
1864 struct address_space *mapping = page->mapping;
1865 struct inode *inode = mapping->host;
1866 handle_t *handle = NULL;
1867 int ret = 0, err = 0;
1868 int inline_data = ext4_has_inline_data(inode);
1869 struct buffer_head *inode_bh = NULL;
1870 loff_t size;
1871
1872 ClearPageChecked(page);
1873
1874 if (inline_data) {
1875 BUG_ON(page->index != 0);
1876 BUG_ON(len > ext4_get_max_inline_size(inode));
1877 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1878 if (inode_bh == NULL)
1879 goto out;
1880 }
1881 /*
1882 * We need to release the page lock before we start the
1883 * journal, so grab a reference so the page won't disappear
1884 * out from under us.
1885 */
1886 get_page(page);
1887 unlock_page(page);
1888
1889 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1890 ext4_writepage_trans_blocks(inode));
1891 if (IS_ERR(handle)) {
1892 ret = PTR_ERR(handle);
1893 put_page(page);
1894 goto out_no_pagelock;
1895 }
1896 BUG_ON(!ext4_handle_valid(handle));
1897
1898 lock_page(page);
1899 put_page(page);
1900 size = i_size_read(inode);
1901 if (page->mapping != mapping || page_offset(page) > size) {
1902 /* The page got truncated from under us */
1903 ext4_journal_stop(handle);
1904 ret = 0;
1905 goto out;
1906 }
1907
1908 if (inline_data) {
1909 ret = ext4_mark_inode_dirty(handle, inode);
1910 } else {
1911 struct buffer_head *page_bufs = page_buffers(page);
1912
1913 if (page->index == size >> PAGE_SHIFT)
1914 len = size & ~PAGE_MASK;
1915 else
1916 len = PAGE_SIZE;
1917
1918 ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1919 NULL, do_journal_get_write_access);
1920
1921 err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1922 NULL, write_end_fn);
1923 }
1924 if (ret == 0)
1925 ret = err;
1926 err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1927 if (ret == 0)
1928 ret = err;
1929 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1930 err = ext4_journal_stop(handle);
1931 if (!ret)
1932 ret = err;
1933
1934 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1935 out:
1936 unlock_page(page);
1937 out_no_pagelock:
1938 brelse(inode_bh);
1939 return ret;
1940 }
1941
1942 /*
1943 * Note that we don't need to start a transaction unless we're journaling data
1944 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1945 * need to file the inode to the transaction's list in ordered mode because if
1946 * we are writing back data added by write(), the inode is already there and if
1947 * we are writing back data modified via mmap(), no one guarantees in which
1948 * transaction the data will hit the disk. In case we are journaling data, we
1949 * cannot start transaction directly because transaction start ranks above page
1950 * lock so we have to do some magic.
1951 *
1952 * This function can get called via...
1953 * - ext4_writepages after taking page lock (have journal handle)
1954 * - journal_submit_inode_data_buffers (no journal handle)
1955 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1956 * - grab_page_cache when doing write_begin (have journal handle)
1957 *
1958 * We don't do any block allocation in this function. If we have page with
1959 * multiple blocks we need to write those buffer_heads that are mapped. This
1960 * is important for mmaped based write. So if we do with blocksize 1K
1961 * truncate(f, 1024);
1962 * a = mmap(f, 0, 4096);
1963 * a[0] = 'a';
1964 * truncate(f, 4096);
1965 * we have in the page first buffer_head mapped via page_mkwrite call back
1966 * but other buffer_heads would be unmapped but dirty (dirty done via the
1967 * do_wp_page). So writepage should write the first block. If we modify
1968 * the mmap area beyond 1024 we will again get a page_fault and the
1969 * page_mkwrite callback will do the block allocation and mark the
1970 * buffer_heads mapped.
1971 *
1972 * We redirty the page if we have any buffer_heads that is either delay or
1973 * unwritten in the page.
1974 *
1975 * We can get recursively called as show below.
1976 *
1977 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1978 * ext4_writepage()
1979 *
1980 * But since we don't do any block allocation we should not deadlock.
1981 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1982 */
ext4_writepage(struct page * page,struct writeback_control * wbc)1983 static int ext4_writepage(struct page *page,
1984 struct writeback_control *wbc)
1985 {
1986 int ret = 0;
1987 loff_t size;
1988 unsigned int len;
1989 struct buffer_head *page_bufs = NULL;
1990 struct inode *inode = page->mapping->host;
1991 struct ext4_io_submit io_submit;
1992 bool keep_towrite = false;
1993
1994 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
1995 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
1996 unlock_page(page);
1997 return -EIO;
1998 }
1999
2000 trace_ext4_writepage(page);
2001 size = i_size_read(inode);
2002 if (page->index == size >> PAGE_SHIFT &&
2003 !ext4_verity_in_progress(inode))
2004 len = size & ~PAGE_MASK;
2005 else
2006 len = PAGE_SIZE;
2007
2008 /* Should never happen but for bugs in other kernel subsystems */
2009 if (!page_has_buffers(page)) {
2010 ext4_warning_inode(inode,
2011 "page %lu does not have buffers attached", page->index);
2012 ClearPageDirty(page);
2013 unlock_page(page);
2014 return 0;
2015 }
2016
2017 page_bufs = page_buffers(page);
2018 /*
2019 * We cannot do block allocation or other extent handling in this
2020 * function. If there are buffers needing that, we have to redirty
2021 * the page. But we may reach here when we do a journal commit via
2022 * journal_submit_inode_data_buffers() and in that case we must write
2023 * allocated buffers to achieve data=ordered mode guarantees.
2024 *
2025 * Also, if there is only one buffer per page (the fs block
2026 * size == the page size), if one buffer needs block
2027 * allocation or needs to modify the extent tree to clear the
2028 * unwritten flag, we know that the page can't be written at
2029 * all, so we might as well refuse the write immediately.
2030 * Unfortunately if the block size != page size, we can't as
2031 * easily detect this case using ext4_walk_page_buffers(), but
2032 * for the extremely common case, this is an optimization that
2033 * skips a useless round trip through ext4_bio_write_page().
2034 */
2035 if (ext4_walk_page_buffers(NULL, inode, page_bufs, 0, len, NULL,
2036 ext4_bh_delay_or_unwritten)) {
2037 redirty_page_for_writepage(wbc, page);
2038 if ((current->flags & PF_MEMALLOC) ||
2039 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2040 /*
2041 * For memory cleaning there's no point in writing only
2042 * some buffers. So just bail out. Warn if we came here
2043 * from direct reclaim.
2044 */
2045 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2046 == PF_MEMALLOC);
2047 unlock_page(page);
2048 return 0;
2049 }
2050 keep_towrite = true;
2051 }
2052
2053 if (PageChecked(page) && ext4_should_journal_data(inode))
2054 /*
2055 * It's mmapped pagecache. Add buffers and journal it. There
2056 * doesn't seem much point in redirtying the page here.
2057 */
2058 return __ext4_journalled_writepage(page, len);
2059
2060 ext4_io_submit_init(&io_submit, wbc);
2061 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2062 if (!io_submit.io_end) {
2063 redirty_page_for_writepage(wbc, page);
2064 unlock_page(page);
2065 return -ENOMEM;
2066 }
2067 ret = ext4_bio_write_page(&io_submit, page, len, keep_towrite);
2068 ext4_io_submit(&io_submit);
2069 /* Drop io_end reference we got from init */
2070 ext4_put_io_end_defer(io_submit.io_end);
2071 return ret;
2072 }
2073
mpage_submit_page(struct mpage_da_data * mpd,struct page * page)2074 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2075 {
2076 int len;
2077 loff_t size;
2078 int err;
2079
2080 BUG_ON(page->index != mpd->first_page);
2081 clear_page_dirty_for_io(page);
2082 /*
2083 * We have to be very careful here! Nothing protects writeback path
2084 * against i_size changes and the page can be writeably mapped into
2085 * page tables. So an application can be growing i_size and writing
2086 * data through mmap while writeback runs. clear_page_dirty_for_io()
2087 * write-protects our page in page tables and the page cannot get
2088 * written to again until we release page lock. So only after
2089 * clear_page_dirty_for_io() we are safe to sample i_size for
2090 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2091 * on the barrier provided by TestClearPageDirty in
2092 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2093 * after page tables are updated.
2094 */
2095 size = i_size_read(mpd->inode);
2096 if (page->index == size >> PAGE_SHIFT &&
2097 !ext4_verity_in_progress(mpd->inode))
2098 len = size & ~PAGE_MASK;
2099 else
2100 len = PAGE_SIZE;
2101 err = ext4_bio_write_page(&mpd->io_submit, page, len, false);
2102 if (!err)
2103 mpd->wbc->nr_to_write--;
2104 mpd->first_page++;
2105
2106 return err;
2107 }
2108
2109 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2110
2111 /*
2112 * mballoc gives us at most this number of blocks...
2113 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2114 * The rest of mballoc seems to handle chunks up to full group size.
2115 */
2116 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2117
2118 /*
2119 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2120 *
2121 * @mpd - extent of blocks
2122 * @lblk - logical number of the block in the file
2123 * @bh - buffer head we want to add to the extent
2124 *
2125 * The function is used to collect contig. blocks in the same state. If the
2126 * buffer doesn't require mapping for writeback and we haven't started the
2127 * extent of buffers to map yet, the function returns 'true' immediately - the
2128 * caller can write the buffer right away. Otherwise the function returns true
2129 * if the block has been added to the extent, false if the block couldn't be
2130 * added.
2131 */
mpage_add_bh_to_extent(struct mpage_da_data * mpd,ext4_lblk_t lblk,struct buffer_head * bh)2132 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2133 struct buffer_head *bh)
2134 {
2135 struct ext4_map_blocks *map = &mpd->map;
2136
2137 /* Buffer that doesn't need mapping for writeback? */
2138 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2139 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2140 /* So far no extent to map => we write the buffer right away */
2141 if (map->m_len == 0)
2142 return true;
2143 return false;
2144 }
2145
2146 /* First block in the extent? */
2147 if (map->m_len == 0) {
2148 /* We cannot map unless handle is started... */
2149 if (!mpd->do_map)
2150 return false;
2151 map->m_lblk = lblk;
2152 map->m_len = 1;
2153 map->m_flags = bh->b_state & BH_FLAGS;
2154 return true;
2155 }
2156
2157 /* Don't go larger than mballoc is willing to allocate */
2158 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2159 return false;
2160
2161 /* Can we merge the block to our big extent? */
2162 if (lblk == map->m_lblk + map->m_len &&
2163 (bh->b_state & BH_FLAGS) == map->m_flags) {
2164 map->m_len++;
2165 return true;
2166 }
2167 return false;
2168 }
2169
2170 /*
2171 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2172 *
2173 * @mpd - extent of blocks for mapping
2174 * @head - the first buffer in the page
2175 * @bh - buffer we should start processing from
2176 * @lblk - logical number of the block in the file corresponding to @bh
2177 *
2178 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2179 * the page for IO if all buffers in this page were mapped and there's no
2180 * accumulated extent of buffers to map or add buffers in the page to the
2181 * extent of buffers to map. The function returns 1 if the caller can continue
2182 * by processing the next page, 0 if it should stop adding buffers to the
2183 * extent to map because we cannot extend it anymore. It can also return value
2184 * < 0 in case of error during IO submission.
2185 */
mpage_process_page_bufs(struct mpage_da_data * mpd,struct buffer_head * head,struct buffer_head * bh,ext4_lblk_t lblk)2186 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2187 struct buffer_head *head,
2188 struct buffer_head *bh,
2189 ext4_lblk_t lblk)
2190 {
2191 struct inode *inode = mpd->inode;
2192 int err;
2193 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2194 >> inode->i_blkbits;
2195
2196 if (ext4_verity_in_progress(inode))
2197 blocks = EXT_MAX_BLOCKS;
2198
2199 do {
2200 BUG_ON(buffer_locked(bh));
2201
2202 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2203 /* Found extent to map? */
2204 if (mpd->map.m_len)
2205 return 0;
2206 /* Buffer needs mapping and handle is not started? */
2207 if (!mpd->do_map)
2208 return 0;
2209 /* Everything mapped so far and we hit EOF */
2210 break;
2211 }
2212 } while (lblk++, (bh = bh->b_this_page) != head);
2213 /* So far everything mapped? Submit the page for IO. */
2214 if (mpd->map.m_len == 0) {
2215 err = mpage_submit_page(mpd, head->b_page);
2216 if (err < 0)
2217 return err;
2218 }
2219 if (lblk >= blocks) {
2220 mpd->scanned_until_end = 1;
2221 return 0;
2222 }
2223 return 1;
2224 }
2225
2226 /*
2227 * mpage_process_page - update page buffers corresponding to changed extent and
2228 * may submit fully mapped page for IO
2229 *
2230 * @mpd - description of extent to map, on return next extent to map
2231 * @m_lblk - logical block mapping.
2232 * @m_pblk - corresponding physical mapping.
2233 * @map_bh - determines on return whether this page requires any further
2234 * mapping or not.
2235 * Scan given page buffers corresponding to changed extent and update buffer
2236 * state according to new extent state.
2237 * We map delalloc buffers to their physical location, clear unwritten bits.
2238 * If the given page is not fully mapped, we update @map to the next extent in
2239 * the given page that needs mapping & return @map_bh as true.
2240 */
mpage_process_page(struct mpage_da_data * mpd,struct page * page,ext4_lblk_t * m_lblk,ext4_fsblk_t * m_pblk,bool * map_bh)2241 static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
2242 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2243 bool *map_bh)
2244 {
2245 struct buffer_head *head, *bh;
2246 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2247 ext4_lblk_t lblk = *m_lblk;
2248 ext4_fsblk_t pblock = *m_pblk;
2249 int err = 0;
2250 int blkbits = mpd->inode->i_blkbits;
2251 ssize_t io_end_size = 0;
2252 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2253
2254 bh = head = page_buffers(page);
2255 do {
2256 if (lblk < mpd->map.m_lblk)
2257 continue;
2258 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2259 /*
2260 * Buffer after end of mapped extent.
2261 * Find next buffer in the page to map.
2262 */
2263 mpd->map.m_len = 0;
2264 mpd->map.m_flags = 0;
2265 io_end_vec->size += io_end_size;
2266 io_end_size = 0;
2267
2268 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2269 if (err > 0)
2270 err = 0;
2271 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2272 io_end_vec = ext4_alloc_io_end_vec(io_end);
2273 if (IS_ERR(io_end_vec)) {
2274 err = PTR_ERR(io_end_vec);
2275 goto out;
2276 }
2277 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2278 }
2279 *map_bh = true;
2280 goto out;
2281 }
2282 if (buffer_delay(bh)) {
2283 clear_buffer_delay(bh);
2284 bh->b_blocknr = pblock++;
2285 }
2286 clear_buffer_unwritten(bh);
2287 io_end_size += (1 << blkbits);
2288 } while (lblk++, (bh = bh->b_this_page) != head);
2289
2290 io_end_vec->size += io_end_size;
2291 io_end_size = 0;
2292 *map_bh = false;
2293 out:
2294 *m_lblk = lblk;
2295 *m_pblk = pblock;
2296 return err;
2297 }
2298
2299 /*
2300 * mpage_map_buffers - update buffers corresponding to changed extent and
2301 * submit fully mapped pages for IO
2302 *
2303 * @mpd - description of extent to map, on return next extent to map
2304 *
2305 * Scan buffers corresponding to changed extent (we expect corresponding pages
2306 * to be already locked) and update buffer state according to new extent state.
2307 * We map delalloc buffers to their physical location, clear unwritten bits,
2308 * and mark buffers as uninit when we perform writes to unwritten extents
2309 * and do extent conversion after IO is finished. If the last page is not fully
2310 * mapped, we update @map to the next extent in the last page that needs
2311 * mapping. Otherwise we submit the page for IO.
2312 */
mpage_map_and_submit_buffers(struct mpage_da_data * mpd)2313 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2314 {
2315 struct pagevec pvec;
2316 int nr_pages, i;
2317 struct inode *inode = mpd->inode;
2318 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2319 pgoff_t start, end;
2320 ext4_lblk_t lblk;
2321 ext4_fsblk_t pblock;
2322 int err;
2323 bool map_bh = false;
2324
2325 start = mpd->map.m_lblk >> bpp_bits;
2326 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2327 lblk = start << bpp_bits;
2328 pblock = mpd->map.m_pblk;
2329
2330 pagevec_init(&pvec);
2331 while (start <= end) {
2332 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2333 &start, end);
2334 if (nr_pages == 0)
2335 break;
2336 for (i = 0; i < nr_pages; i++) {
2337 struct page *page = pvec.pages[i];
2338
2339 err = mpage_process_page(mpd, page, &lblk, &pblock,
2340 &map_bh);
2341 /*
2342 * If map_bh is true, means page may require further bh
2343 * mapping, or maybe the page was submitted for IO.
2344 * So we return to call further extent mapping.
2345 */
2346 if (err < 0 || map_bh)
2347 goto out;
2348 /* Page fully mapped - let IO run! */
2349 err = mpage_submit_page(mpd, page);
2350 if (err < 0)
2351 goto out;
2352 }
2353 pagevec_release(&pvec);
2354 }
2355 /* Extent fully mapped and matches with page boundary. We are done. */
2356 mpd->map.m_len = 0;
2357 mpd->map.m_flags = 0;
2358 return 0;
2359 out:
2360 pagevec_release(&pvec);
2361 return err;
2362 }
2363
mpage_map_one_extent(handle_t * handle,struct mpage_da_data * mpd)2364 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2365 {
2366 struct inode *inode = mpd->inode;
2367 struct ext4_map_blocks *map = &mpd->map;
2368 int get_blocks_flags;
2369 int err, dioread_nolock;
2370
2371 trace_ext4_da_write_pages_extent(inode, map);
2372 /*
2373 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2374 * to convert an unwritten extent to be initialized (in the case
2375 * where we have written into one or more preallocated blocks). It is
2376 * possible that we're going to need more metadata blocks than
2377 * previously reserved. However we must not fail because we're in
2378 * writeback and there is nothing we can do about it so it might result
2379 * in data loss. So use reserved blocks to allocate metadata if
2380 * possible.
2381 *
2382 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2383 * the blocks in question are delalloc blocks. This indicates
2384 * that the blocks and quotas has already been checked when
2385 * the data was copied into the page cache.
2386 */
2387 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2388 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2389 EXT4_GET_BLOCKS_IO_SUBMIT;
2390 dioread_nolock = ext4_should_dioread_nolock(inode);
2391 if (dioread_nolock)
2392 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2393 if (map->m_flags & BIT(BH_Delay))
2394 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2395
2396 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2397 if (err < 0)
2398 return err;
2399 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2400 if (!mpd->io_submit.io_end->handle &&
2401 ext4_handle_valid(handle)) {
2402 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2403 handle->h_rsv_handle = NULL;
2404 }
2405 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2406 }
2407
2408 BUG_ON(map->m_len == 0);
2409 return 0;
2410 }
2411
2412 /*
2413 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2414 * mpd->len and submit pages underlying it for IO
2415 *
2416 * @handle - handle for journal operations
2417 * @mpd - extent to map
2418 * @give_up_on_write - we set this to true iff there is a fatal error and there
2419 * is no hope of writing the data. The caller should discard
2420 * dirty pages to avoid infinite loops.
2421 *
2422 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2423 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2424 * them to initialized or split the described range from larger unwritten
2425 * extent. Note that we need not map all the described range since allocation
2426 * can return less blocks or the range is covered by more unwritten extents. We
2427 * cannot map more because we are limited by reserved transaction credits. On
2428 * the other hand we always make sure that the last touched page is fully
2429 * mapped so that it can be written out (and thus forward progress is
2430 * guaranteed). After mapping we submit all mapped pages for IO.
2431 */
mpage_map_and_submit_extent(handle_t * handle,struct mpage_da_data * mpd,bool * give_up_on_write)2432 static int mpage_map_and_submit_extent(handle_t *handle,
2433 struct mpage_da_data *mpd,
2434 bool *give_up_on_write)
2435 {
2436 struct inode *inode = mpd->inode;
2437 struct ext4_map_blocks *map = &mpd->map;
2438 int err;
2439 loff_t disksize;
2440 int progress = 0;
2441 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2442 struct ext4_io_end_vec *io_end_vec;
2443
2444 io_end_vec = ext4_alloc_io_end_vec(io_end);
2445 if (IS_ERR(io_end_vec))
2446 return PTR_ERR(io_end_vec);
2447 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2448 do {
2449 err = mpage_map_one_extent(handle, mpd);
2450 if (err < 0) {
2451 struct super_block *sb = inode->i_sb;
2452
2453 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2454 ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2455 goto invalidate_dirty_pages;
2456 /*
2457 * Let the uper layers retry transient errors.
2458 * In the case of ENOSPC, if ext4_count_free_blocks()
2459 * is non-zero, a commit should free up blocks.
2460 */
2461 if ((err == -ENOMEM) ||
2462 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2463 if (progress)
2464 goto update_disksize;
2465 return err;
2466 }
2467 ext4_msg(sb, KERN_CRIT,
2468 "Delayed block allocation failed for "
2469 "inode %lu at logical offset %llu with"
2470 " max blocks %u with error %d",
2471 inode->i_ino,
2472 (unsigned long long)map->m_lblk,
2473 (unsigned)map->m_len, -err);
2474 ext4_msg(sb, KERN_CRIT,
2475 "This should not happen!! Data will "
2476 "be lost\n");
2477 if (err == -ENOSPC)
2478 ext4_print_free_blocks(inode);
2479 invalidate_dirty_pages:
2480 *give_up_on_write = true;
2481 return err;
2482 }
2483 progress = 1;
2484 /*
2485 * Update buffer state, submit mapped pages, and get us new
2486 * extent to map
2487 */
2488 err = mpage_map_and_submit_buffers(mpd);
2489 if (err < 0)
2490 goto update_disksize;
2491 } while (map->m_len);
2492
2493 update_disksize:
2494 /*
2495 * Update on-disk size after IO is submitted. Races with
2496 * truncate are avoided by checking i_size under i_data_sem.
2497 */
2498 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2499 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2500 int err2;
2501 loff_t i_size;
2502
2503 down_write(&EXT4_I(inode)->i_data_sem);
2504 i_size = i_size_read(inode);
2505 if (disksize > i_size)
2506 disksize = i_size;
2507 if (disksize > EXT4_I(inode)->i_disksize)
2508 EXT4_I(inode)->i_disksize = disksize;
2509 up_write(&EXT4_I(inode)->i_data_sem);
2510 err2 = ext4_mark_inode_dirty(handle, inode);
2511 if (err2) {
2512 ext4_error_err(inode->i_sb, -err2,
2513 "Failed to mark inode %lu dirty",
2514 inode->i_ino);
2515 }
2516 if (!err)
2517 err = err2;
2518 }
2519 return err;
2520 }
2521
2522 /*
2523 * Calculate the total number of credits to reserve for one writepages
2524 * iteration. This is called from ext4_writepages(). We map an extent of
2525 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2526 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2527 * bpp - 1 blocks in bpp different extents.
2528 */
ext4_da_writepages_trans_blocks(struct inode * inode)2529 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2530 {
2531 int bpp = ext4_journal_blocks_per_page(inode);
2532
2533 return ext4_meta_trans_blocks(inode,
2534 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2535 }
2536
2537 /*
2538 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2539 * and underlying extent to map
2540 *
2541 * @mpd - where to look for pages
2542 *
2543 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2544 * IO immediately. When we find a page which isn't mapped we start accumulating
2545 * extent of buffers underlying these pages that needs mapping (formed by
2546 * either delayed or unwritten buffers). We also lock the pages containing
2547 * these buffers. The extent found is returned in @mpd structure (starting at
2548 * mpd->lblk with length mpd->len blocks).
2549 *
2550 * Note that this function can attach bios to one io_end structure which are
2551 * neither logically nor physically contiguous. Although it may seem as an
2552 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2553 * case as we need to track IO to all buffers underlying a page in one io_end.
2554 */
mpage_prepare_extent_to_map(struct mpage_da_data * mpd)2555 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2556 {
2557 struct address_space *mapping = mpd->inode->i_mapping;
2558 struct pagevec pvec;
2559 unsigned int nr_pages;
2560 long left = mpd->wbc->nr_to_write;
2561 pgoff_t index = mpd->first_page;
2562 pgoff_t end = mpd->last_page;
2563 xa_mark_t tag;
2564 int i, err = 0;
2565 int blkbits = mpd->inode->i_blkbits;
2566 ext4_lblk_t lblk;
2567 struct buffer_head *head;
2568
2569 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2570 tag = PAGECACHE_TAG_TOWRITE;
2571 else
2572 tag = PAGECACHE_TAG_DIRTY;
2573
2574 pagevec_init(&pvec);
2575 mpd->map.m_len = 0;
2576 mpd->next_page = index;
2577 while (index <= end) {
2578 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2579 tag);
2580 if (nr_pages == 0)
2581 break;
2582
2583 for (i = 0; i < nr_pages; i++) {
2584 struct page *page = pvec.pages[i];
2585
2586 /*
2587 * Accumulated enough dirty pages? This doesn't apply
2588 * to WB_SYNC_ALL mode. For integrity sync we have to
2589 * keep going because someone may be concurrently
2590 * dirtying pages, and we might have synced a lot of
2591 * newly appeared dirty pages, but have not synced all
2592 * of the old dirty pages.
2593 */
2594 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2595 goto out;
2596
2597 /* If we can't merge this page, we are done. */
2598 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2599 goto out;
2600
2601 lock_page(page);
2602 /*
2603 * If the page is no longer dirty, or its mapping no
2604 * longer corresponds to inode we are writing (which
2605 * means it has been truncated or invalidated), or the
2606 * page is already under writeback and we are not doing
2607 * a data integrity writeback, skip the page
2608 */
2609 if (!PageDirty(page) ||
2610 (PageWriteback(page) &&
2611 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2612 unlikely(page->mapping != mapping)) {
2613 unlock_page(page);
2614 continue;
2615 }
2616
2617 wait_on_page_writeback(page);
2618 BUG_ON(PageWriteback(page));
2619
2620 /*
2621 * Should never happen but for buggy code in
2622 * other subsystems that call
2623 * set_page_dirty() without properly warning
2624 * the file system first. See [1] for more
2625 * information.
2626 *
2627 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2628 */
2629 if (!page_has_buffers(page)) {
2630 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2631 ClearPageDirty(page);
2632 unlock_page(page);
2633 continue;
2634 }
2635
2636 if (mpd->map.m_len == 0)
2637 mpd->first_page = page->index;
2638 mpd->next_page = page->index + 1;
2639 /* Add all dirty buffers to mpd */
2640 lblk = ((ext4_lblk_t)page->index) <<
2641 (PAGE_SHIFT - blkbits);
2642 head = page_buffers(page);
2643 err = mpage_process_page_bufs(mpd, head, head, lblk);
2644 if (err <= 0)
2645 goto out;
2646 err = 0;
2647 left--;
2648 }
2649 pagevec_release(&pvec);
2650 cond_resched();
2651 }
2652 mpd->scanned_until_end = 1;
2653 return 0;
2654 out:
2655 pagevec_release(&pvec);
2656 return err;
2657 }
2658
ext4_writepages(struct address_space * mapping,struct writeback_control * wbc)2659 static int ext4_writepages(struct address_space *mapping,
2660 struct writeback_control *wbc)
2661 {
2662 pgoff_t writeback_index = 0;
2663 long nr_to_write = wbc->nr_to_write;
2664 int range_whole = 0;
2665 int cycled = 1;
2666 handle_t *handle = NULL;
2667 struct mpage_da_data mpd;
2668 struct inode *inode = mapping->host;
2669 int needed_blocks, rsv_blocks = 0, ret = 0;
2670 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2671 struct blk_plug plug;
2672 bool give_up_on_write = false;
2673
2674 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2675 return -EIO;
2676
2677 percpu_down_read(&sbi->s_writepages_rwsem);
2678 trace_ext4_writepages(inode, wbc);
2679
2680 /*
2681 * No pages to write? This is mainly a kludge to avoid starting
2682 * a transaction for special inodes like journal inode on last iput()
2683 * because that could violate lock ordering on umount
2684 */
2685 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2686 goto out_writepages;
2687
2688 if (ext4_should_journal_data(inode)) {
2689 ret = generic_writepages(mapping, wbc);
2690 goto out_writepages;
2691 }
2692
2693 /*
2694 * If the filesystem has aborted, it is read-only, so return
2695 * right away instead of dumping stack traces later on that
2696 * will obscure the real source of the problem. We test
2697 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2698 * the latter could be true if the filesystem is mounted
2699 * read-only, and in that case, ext4_writepages should
2700 * *never* be called, so if that ever happens, we would want
2701 * the stack trace.
2702 */
2703 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2704 ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2705 ret = -EROFS;
2706 goto out_writepages;
2707 }
2708
2709 /*
2710 * If we have inline data and arrive here, it means that
2711 * we will soon create the block for the 1st page, so
2712 * we'd better clear the inline data here.
2713 */
2714 if (ext4_has_inline_data(inode)) {
2715 /* Just inode will be modified... */
2716 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2717 if (IS_ERR(handle)) {
2718 ret = PTR_ERR(handle);
2719 goto out_writepages;
2720 }
2721 BUG_ON(ext4_test_inode_state(inode,
2722 EXT4_STATE_MAY_INLINE_DATA));
2723 ext4_destroy_inline_data(handle, inode);
2724 ext4_journal_stop(handle);
2725 }
2726
2727 if (ext4_should_dioread_nolock(inode)) {
2728 /*
2729 * We may need to convert up to one extent per block in
2730 * the page and we may dirty the inode.
2731 */
2732 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2733 PAGE_SIZE >> inode->i_blkbits);
2734 }
2735
2736 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2737 range_whole = 1;
2738
2739 if (wbc->range_cyclic) {
2740 writeback_index = mapping->writeback_index;
2741 if (writeback_index)
2742 cycled = 0;
2743 mpd.first_page = writeback_index;
2744 mpd.last_page = -1;
2745 } else {
2746 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2747 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2748 }
2749
2750 mpd.inode = inode;
2751 mpd.wbc = wbc;
2752 ext4_io_submit_init(&mpd.io_submit, wbc);
2753 retry:
2754 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2755 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2756 blk_start_plug(&plug);
2757
2758 /*
2759 * First writeback pages that don't need mapping - we can avoid
2760 * starting a transaction unnecessarily and also avoid being blocked
2761 * in the block layer on device congestion while having transaction
2762 * started.
2763 */
2764 mpd.do_map = 0;
2765 mpd.scanned_until_end = 0;
2766 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2767 if (!mpd.io_submit.io_end) {
2768 ret = -ENOMEM;
2769 goto unplug;
2770 }
2771 ret = mpage_prepare_extent_to_map(&mpd);
2772 /* Unlock pages we didn't use */
2773 mpage_release_unused_pages(&mpd, false);
2774 /* Submit prepared bio */
2775 ext4_io_submit(&mpd.io_submit);
2776 ext4_put_io_end_defer(mpd.io_submit.io_end);
2777 mpd.io_submit.io_end = NULL;
2778 if (ret < 0)
2779 goto unplug;
2780
2781 while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
2782 /* For each extent of pages we use new io_end */
2783 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2784 if (!mpd.io_submit.io_end) {
2785 ret = -ENOMEM;
2786 break;
2787 }
2788
2789 /*
2790 * We have two constraints: We find one extent to map and we
2791 * must always write out whole page (makes a difference when
2792 * blocksize < pagesize) so that we don't block on IO when we
2793 * try to write out the rest of the page. Journalled mode is
2794 * not supported by delalloc.
2795 */
2796 BUG_ON(ext4_should_journal_data(inode));
2797 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2798
2799 /* start a new transaction */
2800 handle = ext4_journal_start_with_reserve(inode,
2801 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2802 if (IS_ERR(handle)) {
2803 ret = PTR_ERR(handle);
2804 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2805 "%ld pages, ino %lu; err %d", __func__,
2806 wbc->nr_to_write, inode->i_ino, ret);
2807 /* Release allocated io_end */
2808 ext4_put_io_end(mpd.io_submit.io_end);
2809 mpd.io_submit.io_end = NULL;
2810 break;
2811 }
2812 mpd.do_map = 1;
2813
2814 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2815 ret = mpage_prepare_extent_to_map(&mpd);
2816 if (!ret && mpd.map.m_len)
2817 ret = mpage_map_and_submit_extent(handle, &mpd,
2818 &give_up_on_write);
2819 /*
2820 * Caution: If the handle is synchronous,
2821 * ext4_journal_stop() can wait for transaction commit
2822 * to finish which may depend on writeback of pages to
2823 * complete or on page lock to be released. In that
2824 * case, we have to wait until after we have
2825 * submitted all the IO, released page locks we hold,
2826 * and dropped io_end reference (for extent conversion
2827 * to be able to complete) before stopping the handle.
2828 */
2829 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2830 ext4_journal_stop(handle);
2831 handle = NULL;
2832 mpd.do_map = 0;
2833 }
2834 /* Unlock pages we didn't use */
2835 mpage_release_unused_pages(&mpd, give_up_on_write);
2836 /* Submit prepared bio */
2837 ext4_io_submit(&mpd.io_submit);
2838
2839 /*
2840 * Drop our io_end reference we got from init. We have
2841 * to be careful and use deferred io_end finishing if
2842 * we are still holding the transaction as we can
2843 * release the last reference to io_end which may end
2844 * up doing unwritten extent conversion.
2845 */
2846 if (handle) {
2847 ext4_put_io_end_defer(mpd.io_submit.io_end);
2848 ext4_journal_stop(handle);
2849 } else
2850 ext4_put_io_end(mpd.io_submit.io_end);
2851 mpd.io_submit.io_end = NULL;
2852
2853 if (ret == -ENOSPC && sbi->s_journal) {
2854 /*
2855 * Commit the transaction which would
2856 * free blocks released in the transaction
2857 * and try again
2858 */
2859 jbd2_journal_force_commit_nested(sbi->s_journal);
2860 ret = 0;
2861 continue;
2862 }
2863 /* Fatal error - ENOMEM, EIO... */
2864 if (ret)
2865 break;
2866 }
2867 unplug:
2868 blk_finish_plug(&plug);
2869 if (!ret && !cycled && wbc->nr_to_write > 0) {
2870 cycled = 1;
2871 mpd.last_page = writeback_index - 1;
2872 mpd.first_page = 0;
2873 goto retry;
2874 }
2875
2876 /* Update index */
2877 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2878 /*
2879 * Set the writeback_index so that range_cyclic
2880 * mode will write it back later
2881 */
2882 mapping->writeback_index = mpd.first_page;
2883
2884 out_writepages:
2885 trace_ext4_writepages_result(inode, wbc, ret,
2886 nr_to_write - wbc->nr_to_write);
2887 percpu_up_read(&sbi->s_writepages_rwsem);
2888 return ret;
2889 }
2890
ext4_dax_writepages(struct address_space * mapping,struct writeback_control * wbc)2891 static int ext4_dax_writepages(struct address_space *mapping,
2892 struct writeback_control *wbc)
2893 {
2894 int ret;
2895 long nr_to_write = wbc->nr_to_write;
2896 struct inode *inode = mapping->host;
2897 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2898
2899 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2900 return -EIO;
2901
2902 percpu_down_read(&sbi->s_writepages_rwsem);
2903 trace_ext4_writepages(inode, wbc);
2904
2905 ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
2906 trace_ext4_writepages_result(inode, wbc, ret,
2907 nr_to_write - wbc->nr_to_write);
2908 percpu_up_read(&sbi->s_writepages_rwsem);
2909 return ret;
2910 }
2911
ext4_nonda_switch(struct super_block * sb)2912 static int ext4_nonda_switch(struct super_block *sb)
2913 {
2914 s64 free_clusters, dirty_clusters;
2915 struct ext4_sb_info *sbi = EXT4_SB(sb);
2916
2917 /*
2918 * switch to non delalloc mode if we are running low
2919 * on free block. The free block accounting via percpu
2920 * counters can get slightly wrong with percpu_counter_batch getting
2921 * accumulated on each CPU without updating global counters
2922 * Delalloc need an accurate free block accounting. So switch
2923 * to non delalloc when we are near to error range.
2924 */
2925 free_clusters =
2926 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2927 dirty_clusters =
2928 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2929 /*
2930 * Start pushing delalloc when 1/2 of free blocks are dirty.
2931 */
2932 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2933 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2934
2935 if (2 * free_clusters < 3 * dirty_clusters ||
2936 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2937 /*
2938 * free block count is less than 150% of dirty blocks
2939 * or free blocks is less than watermark
2940 */
2941 return 1;
2942 }
2943 return 0;
2944 }
2945
ext4_da_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned flags,struct page ** pagep,void ** fsdata)2946 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2947 loff_t pos, unsigned len, unsigned flags,
2948 struct page **pagep, void **fsdata)
2949 {
2950 int ret, retries = 0;
2951 struct page *page;
2952 pgoff_t index;
2953 struct inode *inode = mapping->host;
2954
2955 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2956 return -EIO;
2957
2958 index = pos >> PAGE_SHIFT;
2959
2960 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
2961 ext4_verity_in_progress(inode)) {
2962 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2963 return ext4_write_begin(file, mapping, pos,
2964 len, flags, pagep, fsdata);
2965 }
2966 *fsdata = (void *)0;
2967 trace_ext4_da_write_begin(inode, pos, len, flags);
2968
2969 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2970 ret = ext4_da_write_inline_data_begin(mapping, inode,
2971 pos, len, flags,
2972 pagep, fsdata);
2973 if (ret < 0)
2974 return ret;
2975 if (ret == 1)
2976 return 0;
2977 }
2978
2979 retry:
2980 page = grab_cache_page_write_begin(mapping, index, flags);
2981 if (!page)
2982 return -ENOMEM;
2983
2984 /* In case writeback began while the page was unlocked */
2985 wait_for_stable_page(page);
2986
2987 #ifdef CONFIG_FS_ENCRYPTION
2988 ret = ext4_block_write_begin(page, pos, len,
2989 ext4_da_get_block_prep);
2990 #else
2991 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2992 #endif
2993 if (ret < 0) {
2994 unlock_page(page);
2995 put_page(page);
2996 /*
2997 * block_write_begin may have instantiated a few blocks
2998 * outside i_size. Trim these off again. Don't need
2999 * i_size_read because we hold inode lock.
3000 */
3001 if (pos + len > inode->i_size)
3002 ext4_truncate_failed_write(inode);
3003
3004 if (ret == -ENOSPC &&
3005 ext4_should_retry_alloc(inode->i_sb, &retries))
3006 goto retry;
3007 return ret;
3008 }
3009
3010 *pagep = page;
3011 return ret;
3012 }
3013
3014 /*
3015 * Check if we should update i_disksize
3016 * when write to the end of file but not require block allocation
3017 */
ext4_da_should_update_i_disksize(struct page * page,unsigned long offset)3018 static int ext4_da_should_update_i_disksize(struct page *page,
3019 unsigned long offset)
3020 {
3021 struct buffer_head *bh;
3022 struct inode *inode = page->mapping->host;
3023 unsigned int idx;
3024 int i;
3025
3026 bh = page_buffers(page);
3027 idx = offset >> inode->i_blkbits;
3028
3029 for (i = 0; i < idx; i++)
3030 bh = bh->b_this_page;
3031
3032 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3033 return 0;
3034 return 1;
3035 }
3036
ext4_da_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)3037 static int ext4_da_write_end(struct file *file,
3038 struct address_space *mapping,
3039 loff_t pos, unsigned len, unsigned copied,
3040 struct page *page, void *fsdata)
3041 {
3042 struct inode *inode = mapping->host;
3043 loff_t new_i_size;
3044 unsigned long start, end;
3045 int write_mode = (int)(unsigned long)fsdata;
3046
3047 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3048 return ext4_write_end(file, mapping, pos,
3049 len, copied, page, fsdata);
3050
3051 trace_ext4_da_write_end(inode, pos, len, copied);
3052
3053 if (write_mode != CONVERT_INLINE_DATA &&
3054 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3055 ext4_has_inline_data(inode))
3056 return ext4_write_inline_data_end(inode, pos, len, copied, page);
3057
3058 if (unlikely(copied < len) && !PageUptodate(page))
3059 copied = 0;
3060
3061 start = pos & (PAGE_SIZE - 1);
3062 end = start + copied - 1;
3063
3064 /*
3065 * Since we are holding inode lock, we are sure i_disksize <=
3066 * i_size. We also know that if i_disksize < i_size, there are
3067 * delalloc writes pending in the range upto i_size. If the end of
3068 * the current write is <= i_size, there's no need to touch
3069 * i_disksize since writeback will push i_disksize upto i_size
3070 * eventually. If the end of the current write is > i_size and
3071 * inside an allocated block (ext4_da_should_update_i_disksize()
3072 * check), we need to update i_disksize here as neither
3073 * ext4_writepage() nor certain ext4_writepages() paths not
3074 * allocating blocks update i_disksize.
3075 *
3076 * Note that we defer inode dirtying to generic_write_end() /
3077 * ext4_da_write_inline_data_end().
3078 */
3079 new_i_size = pos + copied;
3080 if (copied && new_i_size > inode->i_size &&
3081 ext4_da_should_update_i_disksize(page, end))
3082 ext4_update_i_disksize(inode, new_i_size);
3083
3084 return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3085 }
3086
3087 /*
3088 * Force all delayed allocation blocks to be allocated for a given inode.
3089 */
ext4_alloc_da_blocks(struct inode * inode)3090 int ext4_alloc_da_blocks(struct inode *inode)
3091 {
3092 trace_ext4_alloc_da_blocks(inode);
3093
3094 if (!EXT4_I(inode)->i_reserved_data_blocks)
3095 return 0;
3096
3097 /*
3098 * We do something simple for now. The filemap_flush() will
3099 * also start triggering a write of the data blocks, which is
3100 * not strictly speaking necessary (and for users of
3101 * laptop_mode, not even desirable). However, to do otherwise
3102 * would require replicating code paths in:
3103 *
3104 * ext4_writepages() ->
3105 * write_cache_pages() ---> (via passed in callback function)
3106 * __mpage_da_writepage() -->
3107 * mpage_add_bh_to_extent()
3108 * mpage_da_map_blocks()
3109 *
3110 * The problem is that write_cache_pages(), located in
3111 * mm/page-writeback.c, marks pages clean in preparation for
3112 * doing I/O, which is not desirable if we're not planning on
3113 * doing I/O at all.
3114 *
3115 * We could call write_cache_pages(), and then redirty all of
3116 * the pages by calling redirty_page_for_writepage() but that
3117 * would be ugly in the extreme. So instead we would need to
3118 * replicate parts of the code in the above functions,
3119 * simplifying them because we wouldn't actually intend to
3120 * write out the pages, but rather only collect contiguous
3121 * logical block extents, call the multi-block allocator, and
3122 * then update the buffer heads with the block allocations.
3123 *
3124 * For now, though, we'll cheat by calling filemap_flush(),
3125 * which will map the blocks, and start the I/O, but not
3126 * actually wait for the I/O to complete.
3127 */
3128 return filemap_flush(inode->i_mapping);
3129 }
3130
3131 /*
3132 * bmap() is special. It gets used by applications such as lilo and by
3133 * the swapper to find the on-disk block of a specific piece of data.
3134 *
3135 * Naturally, this is dangerous if the block concerned is still in the
3136 * journal. If somebody makes a swapfile on an ext4 data-journaling
3137 * filesystem and enables swap, then they may get a nasty shock when the
3138 * data getting swapped to that swapfile suddenly gets overwritten by
3139 * the original zero's written out previously to the journal and
3140 * awaiting writeback in the kernel's buffer cache.
3141 *
3142 * So, if we see any bmap calls here on a modified, data-journaled file,
3143 * take extra steps to flush any blocks which might be in the cache.
3144 */
ext4_bmap(struct address_space * mapping,sector_t block)3145 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3146 {
3147 struct inode *inode = mapping->host;
3148 journal_t *journal;
3149 sector_t ret = 0;
3150 int err;
3151
3152 inode_lock_shared(inode);
3153 /*
3154 * We can get here for an inline file via the FIBMAP ioctl
3155 */
3156 if (ext4_has_inline_data(inode))
3157 goto out;
3158
3159 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3160 test_opt(inode->i_sb, DELALLOC)) {
3161 /*
3162 * With delalloc we want to sync the file
3163 * so that we can make sure we allocate
3164 * blocks for file
3165 */
3166 filemap_write_and_wait(mapping);
3167 }
3168
3169 if (EXT4_JOURNAL(inode) &&
3170 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3171 /*
3172 * This is a REALLY heavyweight approach, but the use of
3173 * bmap on dirty files is expected to be extremely rare:
3174 * only if we run lilo or swapon on a freshly made file
3175 * do we expect this to happen.
3176 *
3177 * (bmap requires CAP_SYS_RAWIO so this does not
3178 * represent an unprivileged user DOS attack --- we'd be
3179 * in trouble if mortal users could trigger this path at
3180 * will.)
3181 *
3182 * NB. EXT4_STATE_JDATA is not set on files other than
3183 * regular files. If somebody wants to bmap a directory
3184 * or symlink and gets confused because the buffer
3185 * hasn't yet been flushed to disk, they deserve
3186 * everything they get.
3187 */
3188
3189 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3190 journal = EXT4_JOURNAL(inode);
3191 jbd2_journal_lock_updates(journal);
3192 err = jbd2_journal_flush(journal, 0);
3193 jbd2_journal_unlock_updates(journal);
3194
3195 if (err)
3196 goto out;
3197 }
3198
3199 ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3200
3201 out:
3202 inode_unlock_shared(inode);
3203 return ret;
3204 }
3205
ext4_readpage(struct file * file,struct page * page)3206 static int ext4_readpage(struct file *file, struct page *page)
3207 {
3208 int ret = -EAGAIN;
3209 struct inode *inode = page->mapping->host;
3210
3211 trace_ext4_readpage(page);
3212
3213 if (ext4_has_inline_data(inode))
3214 ret = ext4_readpage_inline(inode, page);
3215
3216 if (ret == -EAGAIN)
3217 return ext4_mpage_readpages(inode, NULL, page);
3218
3219 return ret;
3220 }
3221
ext4_readahead(struct readahead_control * rac)3222 static void ext4_readahead(struct readahead_control *rac)
3223 {
3224 struct inode *inode = rac->mapping->host;
3225
3226 /* If the file has inline data, no need to do readahead. */
3227 if (ext4_has_inline_data(inode))
3228 return;
3229
3230 ext4_mpage_readpages(inode, rac, NULL);
3231 }
3232
ext4_invalidatepage(struct page * page,unsigned int offset,unsigned int length)3233 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3234 unsigned int length)
3235 {
3236 trace_ext4_invalidatepage(page, offset, length);
3237
3238 /* No journalling happens on data buffers when this function is used */
3239 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3240
3241 block_invalidatepage(page, offset, length);
3242 }
3243
__ext4_journalled_invalidatepage(struct page * page,unsigned int offset,unsigned int length)3244 static int __ext4_journalled_invalidatepage(struct page *page,
3245 unsigned int offset,
3246 unsigned int length)
3247 {
3248 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3249
3250 trace_ext4_journalled_invalidatepage(page, offset, length);
3251
3252 /*
3253 * If it's a full truncate we just forget about the pending dirtying
3254 */
3255 if (offset == 0 && length == PAGE_SIZE)
3256 ClearPageChecked(page);
3257
3258 return jbd2_journal_invalidatepage(journal, page, offset, length);
3259 }
3260
3261 /* Wrapper for aops... */
ext4_journalled_invalidatepage(struct page * page,unsigned int offset,unsigned int length)3262 static void ext4_journalled_invalidatepage(struct page *page,
3263 unsigned int offset,
3264 unsigned int length)
3265 {
3266 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3267 }
3268
ext4_releasepage(struct page * page,gfp_t wait)3269 static int ext4_releasepage(struct page *page, gfp_t wait)
3270 {
3271 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3272
3273 trace_ext4_releasepage(page);
3274
3275 /* Page has dirty journalled data -> cannot release */
3276 if (PageChecked(page))
3277 return 0;
3278 if (journal)
3279 return jbd2_journal_try_to_free_buffers(journal, page);
3280 else
3281 return try_to_free_buffers(page);
3282 }
3283
ext4_inode_datasync_dirty(struct inode * inode)3284 static bool ext4_inode_datasync_dirty(struct inode *inode)
3285 {
3286 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3287
3288 if (journal) {
3289 if (jbd2_transaction_committed(journal,
3290 EXT4_I(inode)->i_datasync_tid))
3291 return false;
3292 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3293 return !list_empty(&EXT4_I(inode)->i_fc_list);
3294 return true;
3295 }
3296
3297 /* Any metadata buffers to write? */
3298 if (!list_empty(&inode->i_mapping->private_list))
3299 return true;
3300 return inode->i_state & I_DIRTY_DATASYNC;
3301 }
3302
ext4_set_iomap(struct inode * inode,struct iomap * iomap,struct ext4_map_blocks * map,loff_t offset,loff_t length)3303 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3304 struct ext4_map_blocks *map, loff_t offset,
3305 loff_t length)
3306 {
3307 u8 blkbits = inode->i_blkbits;
3308
3309 /*
3310 * Writes that span EOF might trigger an I/O size update on completion,
3311 * so consider them to be dirty for the purpose of O_DSYNC, even if
3312 * there is no other metadata changes being made or are pending.
3313 */
3314 iomap->flags = 0;
3315 if (ext4_inode_datasync_dirty(inode) ||
3316 offset + length > i_size_read(inode))
3317 iomap->flags |= IOMAP_F_DIRTY;
3318
3319 if (map->m_flags & EXT4_MAP_NEW)
3320 iomap->flags |= IOMAP_F_NEW;
3321
3322 iomap->bdev = inode->i_sb->s_bdev;
3323 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3324 iomap->offset = (u64) map->m_lblk << blkbits;
3325 iomap->length = (u64) map->m_len << blkbits;
3326
3327 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3328 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3329 iomap->flags |= IOMAP_F_MERGED;
3330
3331 /*
3332 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3333 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3334 * set. In order for any allocated unwritten extents to be converted
3335 * into written extents correctly within the ->end_io() handler, we
3336 * need to ensure that the iomap->type is set appropriately. Hence, the
3337 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3338 * been set first.
3339 */
3340 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3341 iomap->type = IOMAP_UNWRITTEN;
3342 iomap->addr = (u64) map->m_pblk << blkbits;
3343 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3344 iomap->type = IOMAP_MAPPED;
3345 iomap->addr = (u64) map->m_pblk << blkbits;
3346 } else {
3347 iomap->type = IOMAP_HOLE;
3348 iomap->addr = IOMAP_NULL_ADDR;
3349 }
3350 }
3351
ext4_iomap_alloc(struct inode * inode,struct ext4_map_blocks * map,unsigned int flags)3352 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3353 unsigned int flags)
3354 {
3355 handle_t *handle;
3356 u8 blkbits = inode->i_blkbits;
3357 int ret, dio_credits, m_flags = 0, retries = 0;
3358
3359 /*
3360 * Trim the mapping request to the maximum value that we can map at
3361 * once for direct I/O.
3362 */
3363 if (map->m_len > DIO_MAX_BLOCKS)
3364 map->m_len = DIO_MAX_BLOCKS;
3365 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3366
3367 retry:
3368 /*
3369 * Either we allocate blocks and then don't get an unwritten extent, so
3370 * in that case we have reserved enough credits. Or, the blocks are
3371 * already allocated and unwritten. In that case, the extent conversion
3372 * fits into the credits as well.
3373 */
3374 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3375 if (IS_ERR(handle))
3376 return PTR_ERR(handle);
3377
3378 /*
3379 * DAX and direct I/O are the only two operations that are currently
3380 * supported with IOMAP_WRITE.
3381 */
3382 WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3383 if (IS_DAX(inode))
3384 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3385 /*
3386 * We use i_size instead of i_disksize here because delalloc writeback
3387 * can complete at any point during the I/O and subsequently push the
3388 * i_disksize out to i_size. This could be beyond where direct I/O is
3389 * happening and thus expose allocated blocks to direct I/O reads.
3390 */
3391 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3392 m_flags = EXT4_GET_BLOCKS_CREATE;
3393 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3394 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3395
3396 ret = ext4_map_blocks(handle, inode, map, m_flags);
3397
3398 /*
3399 * We cannot fill holes in indirect tree based inodes as that could
3400 * expose stale data in the case of a crash. Use the magic error code
3401 * to fallback to buffered I/O.
3402 */
3403 if (!m_flags && !ret)
3404 ret = -ENOTBLK;
3405
3406 ext4_journal_stop(handle);
3407 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3408 goto retry;
3409
3410 return ret;
3411 }
3412
3413
ext4_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)3414 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3415 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3416 {
3417 int ret;
3418 struct ext4_map_blocks map;
3419 u8 blkbits = inode->i_blkbits;
3420
3421 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3422 return -EINVAL;
3423
3424 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3425 return -ERANGE;
3426
3427 /*
3428 * Calculate the first and last logical blocks respectively.
3429 */
3430 map.m_lblk = offset >> blkbits;
3431 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3432 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3433
3434 if (flags & IOMAP_WRITE) {
3435 /*
3436 * We check here if the blocks are already allocated, then we
3437 * don't need to start a journal txn and we can directly return
3438 * the mapping information. This could boost performance
3439 * especially in multi-threaded overwrite requests.
3440 */
3441 if (offset + length <= i_size_read(inode)) {
3442 ret = ext4_map_blocks(NULL, inode, &map, 0);
3443 if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3444 goto out;
3445 }
3446 ret = ext4_iomap_alloc(inode, &map, flags);
3447 } else {
3448 ret = ext4_map_blocks(NULL, inode, &map, 0);
3449 }
3450
3451 if (ret < 0)
3452 return ret;
3453 out:
3454 /*
3455 * When inline encryption is enabled, sometimes I/O to an encrypted file
3456 * has to be broken up to guarantee DUN contiguity. Handle this by
3457 * limiting the length of the mapping returned.
3458 */
3459 map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
3460
3461 ext4_set_iomap(inode, iomap, &map, offset, length);
3462
3463 return 0;
3464 }
3465
ext4_iomap_overwrite_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)3466 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3467 loff_t length, unsigned flags, struct iomap *iomap,
3468 struct iomap *srcmap)
3469 {
3470 int ret;
3471
3472 /*
3473 * Even for writes we don't need to allocate blocks, so just pretend
3474 * we are reading to save overhead of starting a transaction.
3475 */
3476 flags &= ~IOMAP_WRITE;
3477 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3478 WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
3479 return ret;
3480 }
3481
ext4_iomap_end(struct inode * inode,loff_t offset,loff_t length,ssize_t written,unsigned flags,struct iomap * iomap)3482 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3483 ssize_t written, unsigned flags, struct iomap *iomap)
3484 {
3485 /*
3486 * Check to see whether an error occurred while writing out the data to
3487 * the allocated blocks. If so, return the magic error code so that we
3488 * fallback to buffered I/O and attempt to complete the remainder of
3489 * the I/O. Any blocks that may have been allocated in preparation for
3490 * the direct I/O will be reused during buffered I/O.
3491 */
3492 if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3493 return -ENOTBLK;
3494
3495 return 0;
3496 }
3497
3498 const struct iomap_ops ext4_iomap_ops = {
3499 .iomap_begin = ext4_iomap_begin,
3500 .iomap_end = ext4_iomap_end,
3501 };
3502
3503 const struct iomap_ops ext4_iomap_overwrite_ops = {
3504 .iomap_begin = ext4_iomap_overwrite_begin,
3505 .iomap_end = ext4_iomap_end,
3506 };
3507
ext4_iomap_is_delalloc(struct inode * inode,struct ext4_map_blocks * map)3508 static bool ext4_iomap_is_delalloc(struct inode *inode,
3509 struct ext4_map_blocks *map)
3510 {
3511 struct extent_status es;
3512 ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3513
3514 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3515 map->m_lblk, end, &es);
3516
3517 if (!es.es_len || es.es_lblk > end)
3518 return false;
3519
3520 if (es.es_lblk > map->m_lblk) {
3521 map->m_len = es.es_lblk - map->m_lblk;
3522 return false;
3523 }
3524
3525 offset = map->m_lblk - es.es_lblk;
3526 map->m_len = es.es_len - offset;
3527
3528 return true;
3529 }
3530
ext4_iomap_begin_report(struct inode * inode,loff_t offset,loff_t length,unsigned int flags,struct iomap * iomap,struct iomap * srcmap)3531 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3532 loff_t length, unsigned int flags,
3533 struct iomap *iomap, struct iomap *srcmap)
3534 {
3535 int ret;
3536 bool delalloc = false;
3537 struct ext4_map_blocks map;
3538 u8 blkbits = inode->i_blkbits;
3539
3540 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3541 return -EINVAL;
3542
3543 if (ext4_has_inline_data(inode)) {
3544 ret = ext4_inline_data_iomap(inode, iomap);
3545 if (ret != -EAGAIN) {
3546 if (ret == 0 && offset >= iomap->length)
3547 ret = -ENOENT;
3548 return ret;
3549 }
3550 }
3551
3552 /*
3553 * Calculate the first and last logical block respectively.
3554 */
3555 map.m_lblk = offset >> blkbits;
3556 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3557 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3558
3559 /*
3560 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3561 * So handle it here itself instead of querying ext4_map_blocks().
3562 * Since ext4_map_blocks() will warn about it and will return
3563 * -EIO error.
3564 */
3565 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3566 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3567
3568 if (offset >= sbi->s_bitmap_maxbytes) {
3569 map.m_flags = 0;
3570 goto set_iomap;
3571 }
3572 }
3573
3574 ret = ext4_map_blocks(NULL, inode, &map, 0);
3575 if (ret < 0)
3576 return ret;
3577 if (ret == 0)
3578 delalloc = ext4_iomap_is_delalloc(inode, &map);
3579
3580 set_iomap:
3581 ext4_set_iomap(inode, iomap, &map, offset, length);
3582 if (delalloc && iomap->type == IOMAP_HOLE)
3583 iomap->type = IOMAP_DELALLOC;
3584
3585 return 0;
3586 }
3587
3588 const struct iomap_ops ext4_iomap_report_ops = {
3589 .iomap_begin = ext4_iomap_begin_report,
3590 };
3591
3592 /*
3593 * Pages can be marked dirty completely asynchronously from ext4's journalling
3594 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3595 * much here because ->set_page_dirty is called under VFS locks. The page is
3596 * not necessarily locked.
3597 *
3598 * We cannot just dirty the page and leave attached buffers clean, because the
3599 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3600 * or jbddirty because all the journalling code will explode.
3601 *
3602 * So what we do is to mark the page "pending dirty" and next time writepage
3603 * is called, propagate that into the buffers appropriately.
3604 */
ext4_journalled_set_page_dirty(struct page * page)3605 static int ext4_journalled_set_page_dirty(struct page *page)
3606 {
3607 SetPageChecked(page);
3608 return __set_page_dirty_nobuffers(page);
3609 }
3610
ext4_set_page_dirty(struct page * page)3611 static int ext4_set_page_dirty(struct page *page)
3612 {
3613 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3614 WARN_ON_ONCE(!page_has_buffers(page));
3615 return __set_page_dirty_buffers(page);
3616 }
3617
ext4_iomap_swap_activate(struct swap_info_struct * sis,struct file * file,sector_t * span)3618 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3619 struct file *file, sector_t *span)
3620 {
3621 return iomap_swapfile_activate(sis, file, span,
3622 &ext4_iomap_report_ops);
3623 }
3624
3625 static const struct address_space_operations ext4_aops = {
3626 .readpage = ext4_readpage,
3627 .readahead = ext4_readahead,
3628 .writepage = ext4_writepage,
3629 .writepages = ext4_writepages,
3630 .write_begin = ext4_write_begin,
3631 .write_end = ext4_write_end,
3632 .set_page_dirty = ext4_set_page_dirty,
3633 .bmap = ext4_bmap,
3634 .invalidatepage = ext4_invalidatepage,
3635 .releasepage = ext4_releasepage,
3636 .direct_IO = noop_direct_IO,
3637 .migratepage = buffer_migrate_page,
3638 .is_partially_uptodate = block_is_partially_uptodate,
3639 .error_remove_page = generic_error_remove_page,
3640 .swap_activate = ext4_iomap_swap_activate,
3641 };
3642
3643 static const struct address_space_operations ext4_journalled_aops = {
3644 .readpage = ext4_readpage,
3645 .readahead = ext4_readahead,
3646 .writepage = ext4_writepage,
3647 .writepages = ext4_writepages,
3648 .write_begin = ext4_write_begin,
3649 .write_end = ext4_journalled_write_end,
3650 .set_page_dirty = ext4_journalled_set_page_dirty,
3651 .bmap = ext4_bmap,
3652 .invalidatepage = ext4_journalled_invalidatepage,
3653 .releasepage = ext4_releasepage,
3654 .direct_IO = noop_direct_IO,
3655 .is_partially_uptodate = block_is_partially_uptodate,
3656 .error_remove_page = generic_error_remove_page,
3657 .swap_activate = ext4_iomap_swap_activate,
3658 };
3659
3660 static const struct address_space_operations ext4_da_aops = {
3661 .readpage = ext4_readpage,
3662 .readahead = ext4_readahead,
3663 .writepage = ext4_writepage,
3664 .writepages = ext4_writepages,
3665 .write_begin = ext4_da_write_begin,
3666 .write_end = ext4_da_write_end,
3667 .set_page_dirty = ext4_set_page_dirty,
3668 .bmap = ext4_bmap,
3669 .invalidatepage = ext4_invalidatepage,
3670 .releasepage = ext4_releasepage,
3671 .direct_IO = noop_direct_IO,
3672 .migratepage = buffer_migrate_page,
3673 .is_partially_uptodate = block_is_partially_uptodate,
3674 .error_remove_page = generic_error_remove_page,
3675 .swap_activate = ext4_iomap_swap_activate,
3676 };
3677
3678 static const struct address_space_operations ext4_dax_aops = {
3679 .writepages = ext4_dax_writepages,
3680 .direct_IO = noop_direct_IO,
3681 .set_page_dirty = __set_page_dirty_no_writeback,
3682 .bmap = ext4_bmap,
3683 .invalidatepage = noop_invalidatepage,
3684 .swap_activate = ext4_iomap_swap_activate,
3685 };
3686
ext4_set_aops(struct inode * inode)3687 void ext4_set_aops(struct inode *inode)
3688 {
3689 switch (ext4_inode_journal_mode(inode)) {
3690 case EXT4_INODE_ORDERED_DATA_MODE:
3691 case EXT4_INODE_WRITEBACK_DATA_MODE:
3692 break;
3693 case EXT4_INODE_JOURNAL_DATA_MODE:
3694 inode->i_mapping->a_ops = &ext4_journalled_aops;
3695 return;
3696 default:
3697 BUG();
3698 }
3699 if (IS_DAX(inode))
3700 inode->i_mapping->a_ops = &ext4_dax_aops;
3701 else if (test_opt(inode->i_sb, DELALLOC))
3702 inode->i_mapping->a_ops = &ext4_da_aops;
3703 else
3704 inode->i_mapping->a_ops = &ext4_aops;
3705 }
3706
__ext4_block_zero_page_range(handle_t * handle,struct address_space * mapping,loff_t from,loff_t length)3707 static int __ext4_block_zero_page_range(handle_t *handle,
3708 struct address_space *mapping, loff_t from, loff_t length)
3709 {
3710 ext4_fsblk_t index = from >> PAGE_SHIFT;
3711 unsigned offset = from & (PAGE_SIZE-1);
3712 unsigned blocksize, pos;
3713 ext4_lblk_t iblock;
3714 struct inode *inode = mapping->host;
3715 struct buffer_head *bh;
3716 struct page *page;
3717 int err = 0;
3718
3719 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3720 mapping_gfp_constraint(mapping, ~__GFP_FS));
3721 if (!page)
3722 return -ENOMEM;
3723
3724 blocksize = inode->i_sb->s_blocksize;
3725
3726 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3727
3728 if (!page_has_buffers(page))
3729 create_empty_buffers(page, blocksize, 0);
3730
3731 /* Find the buffer that contains "offset" */
3732 bh = page_buffers(page);
3733 pos = blocksize;
3734 while (offset >= pos) {
3735 bh = bh->b_this_page;
3736 iblock++;
3737 pos += blocksize;
3738 }
3739 if (buffer_freed(bh)) {
3740 BUFFER_TRACE(bh, "freed: skip");
3741 goto unlock;
3742 }
3743 if (!buffer_mapped(bh)) {
3744 BUFFER_TRACE(bh, "unmapped");
3745 ext4_get_block(inode, iblock, bh, 0);
3746 /* unmapped? It's a hole - nothing to do */
3747 if (!buffer_mapped(bh)) {
3748 BUFFER_TRACE(bh, "still unmapped");
3749 goto unlock;
3750 }
3751 }
3752
3753 /* Ok, it's mapped. Make sure it's up-to-date */
3754 if (PageUptodate(page))
3755 set_buffer_uptodate(bh);
3756
3757 if (!buffer_uptodate(bh)) {
3758 err = ext4_read_bh_lock(bh, 0, true);
3759 if (err)
3760 goto unlock;
3761 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3762 /* We expect the key to be set. */
3763 BUG_ON(!fscrypt_has_encryption_key(inode));
3764 err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3765 bh_offset(bh));
3766 if (err) {
3767 clear_buffer_uptodate(bh);
3768 goto unlock;
3769 }
3770 }
3771 }
3772 if (ext4_should_journal_data(inode)) {
3773 BUFFER_TRACE(bh, "get write access");
3774 err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3775 EXT4_JTR_NONE);
3776 if (err)
3777 goto unlock;
3778 }
3779 zero_user(page, offset, length);
3780 BUFFER_TRACE(bh, "zeroed end of block");
3781
3782 if (ext4_should_journal_data(inode)) {
3783 err = ext4_handle_dirty_metadata(handle, inode, bh);
3784 } else {
3785 err = 0;
3786 mark_buffer_dirty(bh);
3787 if (ext4_should_order_data(inode))
3788 err = ext4_jbd2_inode_add_write(handle, inode, from,
3789 length);
3790 }
3791
3792 unlock:
3793 unlock_page(page);
3794 put_page(page);
3795 return err;
3796 }
3797
3798 /*
3799 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3800 * starting from file offset 'from'. The range to be zero'd must
3801 * be contained with in one block. If the specified range exceeds
3802 * the end of the block it will be shortened to end of the block
3803 * that corresponds to 'from'
3804 */
ext4_block_zero_page_range(handle_t * handle,struct address_space * mapping,loff_t from,loff_t length)3805 static int ext4_block_zero_page_range(handle_t *handle,
3806 struct address_space *mapping, loff_t from, loff_t length)
3807 {
3808 struct inode *inode = mapping->host;
3809 unsigned offset = from & (PAGE_SIZE-1);
3810 unsigned blocksize = inode->i_sb->s_blocksize;
3811 unsigned max = blocksize - (offset & (blocksize - 1));
3812
3813 /*
3814 * correct length if it does not fall between
3815 * 'from' and the end of the block
3816 */
3817 if (length > max || length < 0)
3818 length = max;
3819
3820 if (IS_DAX(inode)) {
3821 return iomap_zero_range(inode, from, length, NULL,
3822 &ext4_iomap_ops);
3823 }
3824 return __ext4_block_zero_page_range(handle, mapping, from, length);
3825 }
3826
3827 /*
3828 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3829 * up to the end of the block which corresponds to `from'.
3830 * This required during truncate. We need to physically zero the tail end
3831 * of that block so it doesn't yield old data if the file is later grown.
3832 */
ext4_block_truncate_page(handle_t * handle,struct address_space * mapping,loff_t from)3833 static int ext4_block_truncate_page(handle_t *handle,
3834 struct address_space *mapping, loff_t from)
3835 {
3836 unsigned offset = from & (PAGE_SIZE-1);
3837 unsigned length;
3838 unsigned blocksize;
3839 struct inode *inode = mapping->host;
3840
3841 /* If we are processing an encrypted inode during orphan list handling */
3842 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3843 return 0;
3844
3845 blocksize = inode->i_sb->s_blocksize;
3846 length = blocksize - (offset & (blocksize - 1));
3847
3848 return ext4_block_zero_page_range(handle, mapping, from, length);
3849 }
3850
ext4_zero_partial_blocks(handle_t * handle,struct inode * inode,loff_t lstart,loff_t length)3851 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3852 loff_t lstart, loff_t length)
3853 {
3854 struct super_block *sb = inode->i_sb;
3855 struct address_space *mapping = inode->i_mapping;
3856 unsigned partial_start, partial_end;
3857 ext4_fsblk_t start, end;
3858 loff_t byte_end = (lstart + length - 1);
3859 int err = 0;
3860
3861 partial_start = lstart & (sb->s_blocksize - 1);
3862 partial_end = byte_end & (sb->s_blocksize - 1);
3863
3864 start = lstart >> sb->s_blocksize_bits;
3865 end = byte_end >> sb->s_blocksize_bits;
3866
3867 /* Handle partial zero within the single block */
3868 if (start == end &&
3869 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3870 err = ext4_block_zero_page_range(handle, mapping,
3871 lstart, length);
3872 return err;
3873 }
3874 /* Handle partial zero out on the start of the range */
3875 if (partial_start) {
3876 err = ext4_block_zero_page_range(handle, mapping,
3877 lstart, sb->s_blocksize);
3878 if (err)
3879 return err;
3880 }
3881 /* Handle partial zero out on the end of the range */
3882 if (partial_end != sb->s_blocksize - 1)
3883 err = ext4_block_zero_page_range(handle, mapping,
3884 byte_end - partial_end,
3885 partial_end + 1);
3886 return err;
3887 }
3888
ext4_can_truncate(struct inode * inode)3889 int ext4_can_truncate(struct inode *inode)
3890 {
3891 if (S_ISREG(inode->i_mode))
3892 return 1;
3893 if (S_ISDIR(inode->i_mode))
3894 return 1;
3895 if (S_ISLNK(inode->i_mode))
3896 return !ext4_inode_is_fast_symlink(inode);
3897 return 0;
3898 }
3899
3900 /*
3901 * We have to make sure i_disksize gets properly updated before we truncate
3902 * page cache due to hole punching or zero range. Otherwise i_disksize update
3903 * can get lost as it may have been postponed to submission of writeback but
3904 * that will never happen after we truncate page cache.
3905 */
ext4_update_disksize_before_punch(struct inode * inode,loff_t offset,loff_t len)3906 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3907 loff_t len)
3908 {
3909 handle_t *handle;
3910 int ret;
3911
3912 loff_t size = i_size_read(inode);
3913
3914 WARN_ON(!inode_is_locked(inode));
3915 if (offset > size || offset + len < size)
3916 return 0;
3917
3918 if (EXT4_I(inode)->i_disksize >= size)
3919 return 0;
3920
3921 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3922 if (IS_ERR(handle))
3923 return PTR_ERR(handle);
3924 ext4_update_i_disksize(inode, size);
3925 ret = ext4_mark_inode_dirty(handle, inode);
3926 ext4_journal_stop(handle);
3927
3928 return ret;
3929 }
3930
ext4_wait_dax_page(struct inode * inode)3931 static void ext4_wait_dax_page(struct inode *inode)
3932 {
3933 filemap_invalidate_unlock(inode->i_mapping);
3934 schedule();
3935 filemap_invalidate_lock(inode->i_mapping);
3936 }
3937
ext4_break_layouts(struct inode * inode)3938 int ext4_break_layouts(struct inode *inode)
3939 {
3940 struct page *page;
3941 int error;
3942
3943 if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3944 return -EINVAL;
3945
3946 do {
3947 page = dax_layout_busy_page(inode->i_mapping);
3948 if (!page)
3949 return 0;
3950
3951 error = ___wait_var_event(&page->_refcount,
3952 atomic_read(&page->_refcount) == 1,
3953 TASK_INTERRUPTIBLE, 0, 0,
3954 ext4_wait_dax_page(inode));
3955 } while (error == 0);
3956
3957 return error;
3958 }
3959
3960 /*
3961 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3962 * associated with the given offset and length
3963 *
3964 * @inode: File inode
3965 * @offset: The offset where the hole will begin
3966 * @len: The length of the hole
3967 *
3968 * Returns: 0 on success or negative on failure
3969 */
3970
ext4_punch_hole(struct file * file,loff_t offset,loff_t length)3971 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3972 {
3973 struct inode *inode = file_inode(file);
3974 struct super_block *sb = inode->i_sb;
3975 ext4_lblk_t first_block, stop_block;
3976 struct address_space *mapping = inode->i_mapping;
3977 loff_t first_block_offset, last_block_offset, max_length;
3978 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3979 handle_t *handle;
3980 unsigned int credits;
3981 int ret = 0, ret2 = 0;
3982
3983 trace_ext4_punch_hole(inode, offset, length, 0);
3984
3985 /*
3986 * Write out all dirty pages to avoid race conditions
3987 * Then release them.
3988 */
3989 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3990 ret = filemap_write_and_wait_range(mapping, offset,
3991 offset + length - 1);
3992 if (ret)
3993 return ret;
3994 }
3995
3996 inode_lock(inode);
3997
3998 /* No need to punch hole beyond i_size */
3999 if (offset >= inode->i_size)
4000 goto out_mutex;
4001
4002 /*
4003 * If the hole extends beyond i_size, set the hole
4004 * to end after the page that contains i_size
4005 */
4006 if (offset + length > inode->i_size) {
4007 length = inode->i_size +
4008 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4009 offset;
4010 }
4011
4012 /*
4013 * For punch hole the length + offset needs to be within one block
4014 * before last range. Adjust the length if it goes beyond that limit.
4015 */
4016 max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
4017 if (offset + length > max_length)
4018 length = max_length - offset;
4019
4020 if (offset & (sb->s_blocksize - 1) ||
4021 (offset + length) & (sb->s_blocksize - 1)) {
4022 /*
4023 * Attach jinode to inode for jbd2 if we do any zeroing of
4024 * partial block
4025 */
4026 ret = ext4_inode_attach_jinode(inode);
4027 if (ret < 0)
4028 goto out_mutex;
4029
4030 }
4031
4032 /* Wait all existing dio workers, newcomers will block on i_mutex */
4033 inode_dio_wait(inode);
4034
4035 ret = file_modified(file);
4036 if (ret)
4037 goto out_mutex;
4038
4039 /*
4040 * Prevent page faults from reinstantiating pages we have released from
4041 * page cache.
4042 */
4043 filemap_invalidate_lock(mapping);
4044
4045 ret = ext4_break_layouts(inode);
4046 if (ret)
4047 goto out_dio;
4048
4049 first_block_offset = round_up(offset, sb->s_blocksize);
4050 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4051
4052 /* Now release the pages and zero block aligned part of pages*/
4053 if (last_block_offset > first_block_offset) {
4054 ret = ext4_update_disksize_before_punch(inode, offset, length);
4055 if (ret)
4056 goto out_dio;
4057 truncate_pagecache_range(inode, first_block_offset,
4058 last_block_offset);
4059 }
4060
4061 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4062 credits = ext4_writepage_trans_blocks(inode);
4063 else
4064 credits = ext4_blocks_for_truncate(inode);
4065 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4066 if (IS_ERR(handle)) {
4067 ret = PTR_ERR(handle);
4068 ext4_std_error(sb, ret);
4069 goto out_dio;
4070 }
4071
4072 ret = ext4_zero_partial_blocks(handle, inode, offset,
4073 length);
4074 if (ret)
4075 goto out_stop;
4076
4077 first_block = (offset + sb->s_blocksize - 1) >>
4078 EXT4_BLOCK_SIZE_BITS(sb);
4079 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4080
4081 /* If there are blocks to remove, do it */
4082 if (stop_block > first_block) {
4083
4084 down_write(&EXT4_I(inode)->i_data_sem);
4085 ext4_discard_preallocations(inode, 0);
4086
4087 ret = ext4_es_remove_extent(inode, first_block,
4088 stop_block - first_block);
4089 if (ret) {
4090 up_write(&EXT4_I(inode)->i_data_sem);
4091 goto out_stop;
4092 }
4093
4094 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4095 ret = ext4_ext_remove_space(inode, first_block,
4096 stop_block - 1);
4097 else
4098 ret = ext4_ind_remove_space(handle, inode, first_block,
4099 stop_block);
4100
4101 up_write(&EXT4_I(inode)->i_data_sem);
4102 }
4103 ext4_fc_track_range(handle, inode, first_block, stop_block);
4104 if (IS_SYNC(inode))
4105 ext4_handle_sync(handle);
4106
4107 inode->i_mtime = inode->i_ctime = current_time(inode);
4108 ret2 = ext4_mark_inode_dirty(handle, inode);
4109 if (unlikely(ret2))
4110 ret = ret2;
4111 if (ret >= 0)
4112 ext4_update_inode_fsync_trans(handle, inode, 1);
4113 out_stop:
4114 ext4_journal_stop(handle);
4115 out_dio:
4116 filemap_invalidate_unlock(mapping);
4117 out_mutex:
4118 inode_unlock(inode);
4119 return ret;
4120 }
4121
ext4_inode_attach_jinode(struct inode * inode)4122 int ext4_inode_attach_jinode(struct inode *inode)
4123 {
4124 struct ext4_inode_info *ei = EXT4_I(inode);
4125 struct jbd2_inode *jinode;
4126
4127 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4128 return 0;
4129
4130 jinode = jbd2_alloc_inode(GFP_KERNEL);
4131 spin_lock(&inode->i_lock);
4132 if (!ei->jinode) {
4133 if (!jinode) {
4134 spin_unlock(&inode->i_lock);
4135 return -ENOMEM;
4136 }
4137 ei->jinode = jinode;
4138 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4139 jinode = NULL;
4140 }
4141 spin_unlock(&inode->i_lock);
4142 if (unlikely(jinode != NULL))
4143 jbd2_free_inode(jinode);
4144 return 0;
4145 }
4146
4147 /*
4148 * ext4_truncate()
4149 *
4150 * We block out ext4_get_block() block instantiations across the entire
4151 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4152 * simultaneously on behalf of the same inode.
4153 *
4154 * As we work through the truncate and commit bits of it to the journal there
4155 * is one core, guiding principle: the file's tree must always be consistent on
4156 * disk. We must be able to restart the truncate after a crash.
4157 *
4158 * The file's tree may be transiently inconsistent in memory (although it
4159 * probably isn't), but whenever we close off and commit a journal transaction,
4160 * the contents of (the filesystem + the journal) must be consistent and
4161 * restartable. It's pretty simple, really: bottom up, right to left (although
4162 * left-to-right works OK too).
4163 *
4164 * Note that at recovery time, journal replay occurs *before* the restart of
4165 * truncate against the orphan inode list.
4166 *
4167 * The committed inode has the new, desired i_size (which is the same as
4168 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4169 * that this inode's truncate did not complete and it will again call
4170 * ext4_truncate() to have another go. So there will be instantiated blocks
4171 * to the right of the truncation point in a crashed ext4 filesystem. But
4172 * that's fine - as long as they are linked from the inode, the post-crash
4173 * ext4_truncate() run will find them and release them.
4174 */
ext4_truncate(struct inode * inode)4175 int ext4_truncate(struct inode *inode)
4176 {
4177 struct ext4_inode_info *ei = EXT4_I(inode);
4178 unsigned int credits;
4179 int err = 0, err2;
4180 handle_t *handle;
4181 struct address_space *mapping = inode->i_mapping;
4182
4183 /*
4184 * There is a possibility that we're either freeing the inode
4185 * or it's a completely new inode. In those cases we might not
4186 * have i_mutex locked because it's not necessary.
4187 */
4188 if (!(inode->i_state & (I_NEW|I_FREEING)))
4189 WARN_ON(!inode_is_locked(inode));
4190 trace_ext4_truncate_enter(inode);
4191
4192 if (!ext4_can_truncate(inode))
4193 goto out_trace;
4194
4195 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4196 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4197
4198 if (ext4_has_inline_data(inode)) {
4199 int has_inline = 1;
4200
4201 err = ext4_inline_data_truncate(inode, &has_inline);
4202 if (err || has_inline)
4203 goto out_trace;
4204 }
4205
4206 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4207 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4208 err = ext4_inode_attach_jinode(inode);
4209 if (err)
4210 goto out_trace;
4211 }
4212
4213 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4214 credits = ext4_writepage_trans_blocks(inode);
4215 else
4216 credits = ext4_blocks_for_truncate(inode);
4217
4218 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4219 if (IS_ERR(handle)) {
4220 err = PTR_ERR(handle);
4221 goto out_trace;
4222 }
4223
4224 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4225 ext4_block_truncate_page(handle, mapping, inode->i_size);
4226
4227 /*
4228 * We add the inode to the orphan list, so that if this
4229 * truncate spans multiple transactions, and we crash, we will
4230 * resume the truncate when the filesystem recovers. It also
4231 * marks the inode dirty, to catch the new size.
4232 *
4233 * Implication: the file must always be in a sane, consistent
4234 * truncatable state while each transaction commits.
4235 */
4236 err = ext4_orphan_add(handle, inode);
4237 if (err)
4238 goto out_stop;
4239
4240 down_write(&EXT4_I(inode)->i_data_sem);
4241
4242 ext4_discard_preallocations(inode, 0);
4243
4244 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4245 err = ext4_ext_truncate(handle, inode);
4246 else
4247 ext4_ind_truncate(handle, inode);
4248
4249 up_write(&ei->i_data_sem);
4250 if (err)
4251 goto out_stop;
4252
4253 if (IS_SYNC(inode))
4254 ext4_handle_sync(handle);
4255
4256 out_stop:
4257 /*
4258 * If this was a simple ftruncate() and the file will remain alive,
4259 * then we need to clear up the orphan record which we created above.
4260 * However, if this was a real unlink then we were called by
4261 * ext4_evict_inode(), and we allow that function to clean up the
4262 * orphan info for us.
4263 */
4264 if (inode->i_nlink)
4265 ext4_orphan_del(handle, inode);
4266
4267 inode->i_mtime = inode->i_ctime = current_time(inode);
4268 err2 = ext4_mark_inode_dirty(handle, inode);
4269 if (unlikely(err2 && !err))
4270 err = err2;
4271 ext4_journal_stop(handle);
4272
4273 out_trace:
4274 trace_ext4_truncate_exit(inode);
4275 return err;
4276 }
4277
4278 /*
4279 * ext4_get_inode_loc returns with an extra refcount against the inode's
4280 * underlying buffer_head on success. If 'in_mem' is true, we have all
4281 * data in memory that is needed to recreate the on-disk version of this
4282 * inode.
4283 */
__ext4_get_inode_loc(struct super_block * sb,unsigned long ino,struct ext4_iloc * iloc,int in_mem,ext4_fsblk_t * ret_block)4284 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4285 struct ext4_iloc *iloc, int in_mem,
4286 ext4_fsblk_t *ret_block)
4287 {
4288 struct ext4_group_desc *gdp;
4289 struct buffer_head *bh;
4290 ext4_fsblk_t block;
4291 struct blk_plug plug;
4292 int inodes_per_block, inode_offset;
4293
4294 iloc->bh = NULL;
4295 if (ino < EXT4_ROOT_INO ||
4296 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4297 return -EFSCORRUPTED;
4298
4299 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4300 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4301 if (!gdp)
4302 return -EIO;
4303
4304 /*
4305 * Figure out the offset within the block group inode table
4306 */
4307 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4308 inode_offset = ((ino - 1) %
4309 EXT4_INODES_PER_GROUP(sb));
4310 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4311
4312 block = ext4_inode_table(sb, gdp);
4313 if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4314 (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4315 ext4_error(sb, "Invalid inode table block %llu in "
4316 "block_group %u", block, iloc->block_group);
4317 return -EFSCORRUPTED;
4318 }
4319 block += (inode_offset / inodes_per_block);
4320
4321 bh = sb_getblk(sb, block);
4322 if (unlikely(!bh))
4323 return -ENOMEM;
4324 if (ext4_buffer_uptodate(bh))
4325 goto has_buffer;
4326
4327 lock_buffer(bh);
4328 if (ext4_buffer_uptodate(bh)) {
4329 /* Someone brought it uptodate while we waited */
4330 unlock_buffer(bh);
4331 goto has_buffer;
4332 }
4333
4334 /*
4335 * If we have all information of the inode in memory and this
4336 * is the only valid inode in the block, we need not read the
4337 * block.
4338 */
4339 if (in_mem) {
4340 struct buffer_head *bitmap_bh;
4341 int i, start;
4342
4343 start = inode_offset & ~(inodes_per_block - 1);
4344
4345 /* Is the inode bitmap in cache? */
4346 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4347 if (unlikely(!bitmap_bh))
4348 goto make_io;
4349
4350 /*
4351 * If the inode bitmap isn't in cache then the
4352 * optimisation may end up performing two reads instead
4353 * of one, so skip it.
4354 */
4355 if (!buffer_uptodate(bitmap_bh)) {
4356 brelse(bitmap_bh);
4357 goto make_io;
4358 }
4359 for (i = start; i < start + inodes_per_block; i++) {
4360 if (i == inode_offset)
4361 continue;
4362 if (ext4_test_bit(i, bitmap_bh->b_data))
4363 break;
4364 }
4365 brelse(bitmap_bh);
4366 if (i == start + inodes_per_block) {
4367 /* all other inodes are free, so skip I/O */
4368 memset(bh->b_data, 0, bh->b_size);
4369 set_buffer_uptodate(bh);
4370 unlock_buffer(bh);
4371 goto has_buffer;
4372 }
4373 }
4374
4375 make_io:
4376 /*
4377 * If we need to do any I/O, try to pre-readahead extra
4378 * blocks from the inode table.
4379 */
4380 blk_start_plug(&plug);
4381 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4382 ext4_fsblk_t b, end, table;
4383 unsigned num;
4384 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4385
4386 table = ext4_inode_table(sb, gdp);
4387 /* s_inode_readahead_blks is always a power of 2 */
4388 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4389 if (table > b)
4390 b = table;
4391 end = b + ra_blks;
4392 num = EXT4_INODES_PER_GROUP(sb);
4393 if (ext4_has_group_desc_csum(sb))
4394 num -= ext4_itable_unused_count(sb, gdp);
4395 table += num / inodes_per_block;
4396 if (end > table)
4397 end = table;
4398 while (b <= end)
4399 ext4_sb_breadahead_unmovable(sb, b++);
4400 }
4401
4402 /*
4403 * There are other valid inodes in the buffer, this inode
4404 * has in-inode xattrs, or we don't have this inode in memory.
4405 * Read the block from disk.
4406 */
4407 trace_ext4_load_inode(sb, ino);
4408 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4409 blk_finish_plug(&plug);
4410 wait_on_buffer(bh);
4411 ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4412 if (!buffer_uptodate(bh)) {
4413 if (ret_block)
4414 *ret_block = block;
4415 brelse(bh);
4416 return -EIO;
4417 }
4418 has_buffer:
4419 iloc->bh = bh;
4420 return 0;
4421 }
4422
__ext4_get_inode_loc_noinmem(struct inode * inode,struct ext4_iloc * iloc)4423 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4424 struct ext4_iloc *iloc)
4425 {
4426 ext4_fsblk_t err_blk = 0;
4427 int ret;
4428
4429 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc, 0,
4430 &err_blk);
4431
4432 if (ret == -EIO)
4433 ext4_error_inode_block(inode, err_blk, EIO,
4434 "unable to read itable block");
4435
4436 return ret;
4437 }
4438
ext4_get_inode_loc(struct inode * inode,struct ext4_iloc * iloc)4439 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4440 {
4441 ext4_fsblk_t err_blk = 0;
4442 int ret;
4443
4444 /* We have all inode data except xattrs in memory here. */
4445 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc,
4446 !ext4_test_inode_state(inode, EXT4_STATE_XATTR), &err_blk);
4447
4448 if (ret == -EIO)
4449 ext4_error_inode_block(inode, err_blk, EIO,
4450 "unable to read itable block");
4451
4452 return ret;
4453 }
4454
4455
ext4_get_fc_inode_loc(struct super_block * sb,unsigned long ino,struct ext4_iloc * iloc)4456 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4457 struct ext4_iloc *iloc)
4458 {
4459 return __ext4_get_inode_loc(sb, ino, iloc, 0, NULL);
4460 }
4461
ext4_should_enable_dax(struct inode * inode)4462 static bool ext4_should_enable_dax(struct inode *inode)
4463 {
4464 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4465
4466 if (test_opt2(inode->i_sb, DAX_NEVER))
4467 return false;
4468 if (!S_ISREG(inode->i_mode))
4469 return false;
4470 if (ext4_should_journal_data(inode))
4471 return false;
4472 if (ext4_has_inline_data(inode))
4473 return false;
4474 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4475 return false;
4476 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4477 return false;
4478 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4479 return false;
4480 if (test_opt(inode->i_sb, DAX_ALWAYS))
4481 return true;
4482
4483 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4484 }
4485
ext4_set_inode_flags(struct inode * inode,bool init)4486 void ext4_set_inode_flags(struct inode *inode, bool init)
4487 {
4488 unsigned int flags = EXT4_I(inode)->i_flags;
4489 unsigned int new_fl = 0;
4490
4491 WARN_ON_ONCE(IS_DAX(inode) && init);
4492
4493 if (flags & EXT4_SYNC_FL)
4494 new_fl |= S_SYNC;
4495 if (flags & EXT4_APPEND_FL)
4496 new_fl |= S_APPEND;
4497 if (flags & EXT4_IMMUTABLE_FL)
4498 new_fl |= S_IMMUTABLE;
4499 if (flags & EXT4_NOATIME_FL)
4500 new_fl |= S_NOATIME;
4501 if (flags & EXT4_DIRSYNC_FL)
4502 new_fl |= S_DIRSYNC;
4503
4504 /* Because of the way inode_set_flags() works we must preserve S_DAX
4505 * here if already set. */
4506 new_fl |= (inode->i_flags & S_DAX);
4507 if (init && ext4_should_enable_dax(inode))
4508 new_fl |= S_DAX;
4509
4510 if (flags & EXT4_ENCRYPT_FL)
4511 new_fl |= S_ENCRYPTED;
4512 if (flags & EXT4_CASEFOLD_FL)
4513 new_fl |= S_CASEFOLD;
4514 if (flags & EXT4_VERITY_FL)
4515 new_fl |= S_VERITY;
4516 inode_set_flags(inode, new_fl,
4517 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4518 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4519 }
4520
ext4_inode_blocks(struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4521 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4522 struct ext4_inode_info *ei)
4523 {
4524 blkcnt_t i_blocks ;
4525 struct inode *inode = &(ei->vfs_inode);
4526 struct super_block *sb = inode->i_sb;
4527
4528 if (ext4_has_feature_huge_file(sb)) {
4529 /* we are using combined 48 bit field */
4530 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4531 le32_to_cpu(raw_inode->i_blocks_lo);
4532 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4533 /* i_blocks represent file system block size */
4534 return i_blocks << (inode->i_blkbits - 9);
4535 } else {
4536 return i_blocks;
4537 }
4538 } else {
4539 return le32_to_cpu(raw_inode->i_blocks_lo);
4540 }
4541 }
4542
ext4_iget_extra_inode(struct inode * inode,struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4543 static inline int ext4_iget_extra_inode(struct inode *inode,
4544 struct ext4_inode *raw_inode,
4545 struct ext4_inode_info *ei)
4546 {
4547 __le32 *magic = (void *)raw_inode +
4548 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4549
4550 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
4551 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4552 int err;
4553
4554 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4555 err = ext4_find_inline_data_nolock(inode);
4556 if (!err && ext4_has_inline_data(inode))
4557 ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4558 return err;
4559 } else
4560 EXT4_I(inode)->i_inline_off = 0;
4561 return 0;
4562 }
4563
ext4_get_projid(struct inode * inode,kprojid_t * projid)4564 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4565 {
4566 if (!ext4_has_feature_project(inode->i_sb))
4567 return -EOPNOTSUPP;
4568 *projid = EXT4_I(inode)->i_projid;
4569 return 0;
4570 }
4571
4572 /*
4573 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4574 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4575 * set.
4576 */
ext4_inode_set_iversion_queried(struct inode * inode,u64 val)4577 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4578 {
4579 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4580 inode_set_iversion_raw(inode, val);
4581 else
4582 inode_set_iversion_queried(inode, val);
4583 }
ext4_inode_peek_iversion(const struct inode * inode)4584 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4585 {
4586 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4587 return inode_peek_iversion_raw(inode);
4588 else
4589 return inode_peek_iversion(inode);
4590 }
4591
check_igot_inode(struct inode * inode,ext4_iget_flags flags)4592 static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)
4593
4594 {
4595 if (flags & EXT4_IGET_EA_INODE) {
4596 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4597 return "missing EA_INODE flag";
4598 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4599 EXT4_I(inode)->i_file_acl)
4600 return "ea_inode with extended attributes";
4601 } else {
4602 if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4603 return "unexpected EA_INODE flag";
4604 }
4605 if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
4606 return "unexpected bad inode w/o EXT4_IGET_BAD";
4607 return NULL;
4608 }
4609
__ext4_iget(struct super_block * sb,unsigned long ino,ext4_iget_flags flags,const char * function,unsigned int line)4610 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4611 ext4_iget_flags flags, const char *function,
4612 unsigned int line)
4613 {
4614 struct ext4_iloc iloc;
4615 struct ext4_inode *raw_inode;
4616 struct ext4_inode_info *ei;
4617 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
4618 struct inode *inode;
4619 const char *err_str;
4620 journal_t *journal = EXT4_SB(sb)->s_journal;
4621 long ret;
4622 loff_t size;
4623 int block;
4624 uid_t i_uid;
4625 gid_t i_gid;
4626 projid_t i_projid;
4627
4628 if ((!(flags & EXT4_IGET_SPECIAL) &&
4629 ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4630 ino == le32_to_cpu(es->s_usr_quota_inum) ||
4631 ino == le32_to_cpu(es->s_grp_quota_inum) ||
4632 ino == le32_to_cpu(es->s_prj_quota_inum) ||
4633 ino == le32_to_cpu(es->s_orphan_file_inum))) ||
4634 (ino < EXT4_ROOT_INO) ||
4635 (ino > le32_to_cpu(es->s_inodes_count))) {
4636 if (flags & EXT4_IGET_HANDLE)
4637 return ERR_PTR(-ESTALE);
4638 __ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
4639 "inode #%lu: comm %s: iget: illegal inode #",
4640 ino, current->comm);
4641 return ERR_PTR(-EFSCORRUPTED);
4642 }
4643
4644 inode = iget_locked(sb, ino);
4645 if (!inode)
4646 return ERR_PTR(-ENOMEM);
4647 if (!(inode->i_state & I_NEW)) {
4648 if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4649 ext4_error_inode(inode, function, line, 0, err_str);
4650 iput(inode);
4651 return ERR_PTR(-EFSCORRUPTED);
4652 }
4653 return inode;
4654 }
4655
4656 ei = EXT4_I(inode);
4657 iloc.bh = NULL;
4658
4659 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4660 if (ret < 0)
4661 goto bad_inode;
4662 raw_inode = ext4_raw_inode(&iloc);
4663
4664 if ((flags & EXT4_IGET_HANDLE) &&
4665 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4666 ret = -ESTALE;
4667 goto bad_inode;
4668 }
4669
4670 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4671 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4672 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4673 EXT4_INODE_SIZE(inode->i_sb) ||
4674 (ei->i_extra_isize & 3)) {
4675 ext4_error_inode(inode, function, line, 0,
4676 "iget: bad extra_isize %u "
4677 "(inode size %u)",
4678 ei->i_extra_isize,
4679 EXT4_INODE_SIZE(inode->i_sb));
4680 ret = -EFSCORRUPTED;
4681 goto bad_inode;
4682 }
4683 } else
4684 ei->i_extra_isize = 0;
4685
4686 /* Precompute checksum seed for inode metadata */
4687 if (ext4_has_metadata_csum(sb)) {
4688 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4689 __u32 csum;
4690 __le32 inum = cpu_to_le32(inode->i_ino);
4691 __le32 gen = raw_inode->i_generation;
4692 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4693 sizeof(inum));
4694 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4695 sizeof(gen));
4696 }
4697
4698 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4699 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4700 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4701 ext4_error_inode_err(inode, function, line, 0,
4702 EFSBADCRC, "iget: checksum invalid");
4703 ret = -EFSBADCRC;
4704 goto bad_inode;
4705 }
4706
4707 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4708 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4709 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4710 if (ext4_has_feature_project(sb) &&
4711 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4712 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4713 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4714 else
4715 i_projid = EXT4_DEF_PROJID;
4716
4717 if (!(test_opt(inode->i_sb, NO_UID32))) {
4718 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4719 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4720 }
4721 i_uid_write(inode, i_uid);
4722 i_gid_write(inode, i_gid);
4723 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4724 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4725
4726 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4727 ei->i_inline_off = 0;
4728 ei->i_dir_start_lookup = 0;
4729 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4730 /* We now have enough fields to check if the inode was active or not.
4731 * This is needed because nfsd might try to access dead inodes
4732 * the test is that same one that e2fsck uses
4733 * NeilBrown 1999oct15
4734 */
4735 if (inode->i_nlink == 0) {
4736 if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4737 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4738 ino != EXT4_BOOT_LOADER_INO) {
4739 /* this inode is deleted or unallocated */
4740 if (flags & EXT4_IGET_SPECIAL) {
4741 ext4_error_inode(inode, function, line, 0,
4742 "iget: special inode unallocated");
4743 ret = -EFSCORRUPTED;
4744 } else
4745 ret = -ESTALE;
4746 goto bad_inode;
4747 }
4748 /* The only unlinked inodes we let through here have
4749 * valid i_mode and are being read by the orphan
4750 * recovery code: that's fine, we're about to complete
4751 * the process of deleting those.
4752 * OR it is the EXT4_BOOT_LOADER_INO which is
4753 * not initialized on a new filesystem. */
4754 }
4755 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4756 ext4_set_inode_flags(inode, true);
4757 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4758 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4759 if (ext4_has_feature_64bit(sb))
4760 ei->i_file_acl |=
4761 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4762 inode->i_size = ext4_isize(sb, raw_inode);
4763 if ((size = i_size_read(inode)) < 0) {
4764 ext4_error_inode(inode, function, line, 0,
4765 "iget: bad i_size value: %lld", size);
4766 ret = -EFSCORRUPTED;
4767 goto bad_inode;
4768 }
4769 /*
4770 * If dir_index is not enabled but there's dir with INDEX flag set,
4771 * we'd normally treat htree data as empty space. But with metadata
4772 * checksumming that corrupts checksums so forbid that.
4773 */
4774 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4775 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4776 ext4_error_inode(inode, function, line, 0,
4777 "iget: Dir with htree data on filesystem without dir_index feature.");
4778 ret = -EFSCORRUPTED;
4779 goto bad_inode;
4780 }
4781 ei->i_disksize = inode->i_size;
4782 #ifdef CONFIG_QUOTA
4783 ei->i_reserved_quota = 0;
4784 #endif
4785 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4786 ei->i_block_group = iloc.block_group;
4787 ei->i_last_alloc_group = ~0;
4788 /*
4789 * NOTE! The in-memory inode i_data array is in little-endian order
4790 * even on big-endian machines: we do NOT byteswap the block numbers!
4791 */
4792 for (block = 0; block < EXT4_N_BLOCKS; block++)
4793 ei->i_data[block] = raw_inode->i_block[block];
4794 INIT_LIST_HEAD(&ei->i_orphan);
4795 ext4_fc_init_inode(&ei->vfs_inode);
4796
4797 /*
4798 * Set transaction id's of transactions that have to be committed
4799 * to finish f[data]sync. We set them to currently running transaction
4800 * as we cannot be sure that the inode or some of its metadata isn't
4801 * part of the transaction - the inode could have been reclaimed and
4802 * now it is reread from disk.
4803 */
4804 if (journal) {
4805 transaction_t *transaction;
4806 tid_t tid;
4807
4808 read_lock(&journal->j_state_lock);
4809 if (journal->j_running_transaction)
4810 transaction = journal->j_running_transaction;
4811 else
4812 transaction = journal->j_committing_transaction;
4813 if (transaction)
4814 tid = transaction->t_tid;
4815 else
4816 tid = journal->j_commit_sequence;
4817 read_unlock(&journal->j_state_lock);
4818 ei->i_sync_tid = tid;
4819 ei->i_datasync_tid = tid;
4820 }
4821
4822 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4823 if (ei->i_extra_isize == 0) {
4824 /* The extra space is currently unused. Use it. */
4825 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4826 ei->i_extra_isize = sizeof(struct ext4_inode) -
4827 EXT4_GOOD_OLD_INODE_SIZE;
4828 } else {
4829 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4830 if (ret)
4831 goto bad_inode;
4832 }
4833 }
4834
4835 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4836 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4837 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4838 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4839
4840 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4841 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4842
4843 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4844 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4845 ivers |=
4846 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4847 }
4848 ext4_inode_set_iversion_queried(inode, ivers);
4849 }
4850
4851 ret = 0;
4852 if (ei->i_file_acl &&
4853 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4854 ext4_error_inode(inode, function, line, 0,
4855 "iget: bad extended attribute block %llu",
4856 ei->i_file_acl);
4857 ret = -EFSCORRUPTED;
4858 goto bad_inode;
4859 } else if (!ext4_has_inline_data(inode)) {
4860 /* validate the block references in the inode */
4861 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4862 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4863 (S_ISLNK(inode->i_mode) &&
4864 !ext4_inode_is_fast_symlink(inode)))) {
4865 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4866 ret = ext4_ext_check_inode(inode);
4867 else
4868 ret = ext4_ind_check_inode(inode);
4869 }
4870 }
4871 if (ret)
4872 goto bad_inode;
4873
4874 if (S_ISREG(inode->i_mode)) {
4875 inode->i_op = &ext4_file_inode_operations;
4876 inode->i_fop = &ext4_file_operations;
4877 ext4_set_aops(inode);
4878 } else if (S_ISDIR(inode->i_mode)) {
4879 inode->i_op = &ext4_dir_inode_operations;
4880 inode->i_fop = &ext4_dir_operations;
4881 } else if (S_ISLNK(inode->i_mode)) {
4882 /* VFS does not allow setting these so must be corruption */
4883 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
4884 ext4_error_inode(inode, function, line, 0,
4885 "iget: immutable or append flags "
4886 "not allowed on symlinks");
4887 ret = -EFSCORRUPTED;
4888 goto bad_inode;
4889 }
4890 if (IS_ENCRYPTED(inode)) {
4891 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4892 ext4_set_aops(inode);
4893 } else if (ext4_inode_is_fast_symlink(inode)) {
4894 inode->i_link = (char *)ei->i_data;
4895 inode->i_op = &ext4_fast_symlink_inode_operations;
4896 nd_terminate_link(ei->i_data, inode->i_size,
4897 sizeof(ei->i_data) - 1);
4898 } else {
4899 inode->i_op = &ext4_symlink_inode_operations;
4900 ext4_set_aops(inode);
4901 }
4902 inode_nohighmem(inode);
4903 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4904 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4905 inode->i_op = &ext4_special_inode_operations;
4906 if (raw_inode->i_block[0])
4907 init_special_inode(inode, inode->i_mode,
4908 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4909 else
4910 init_special_inode(inode, inode->i_mode,
4911 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4912 } else if (ino == EXT4_BOOT_LOADER_INO) {
4913 make_bad_inode(inode);
4914 } else {
4915 ret = -EFSCORRUPTED;
4916 ext4_error_inode(inode, function, line, 0,
4917 "iget: bogus i_mode (%o)", inode->i_mode);
4918 goto bad_inode;
4919 }
4920 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
4921 ext4_error_inode(inode, function, line, 0,
4922 "casefold flag without casefold feature");
4923 if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4924 ext4_error_inode(inode, function, line, 0, err_str);
4925 ret = -EFSCORRUPTED;
4926 goto bad_inode;
4927 }
4928
4929 brelse(iloc.bh);
4930 unlock_new_inode(inode);
4931 return inode;
4932
4933 bad_inode:
4934 brelse(iloc.bh);
4935 iget_failed(inode);
4936 return ERR_PTR(ret);
4937 }
4938
ext4_inode_blocks_set(handle_t * handle,struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4939 static int ext4_inode_blocks_set(handle_t *handle,
4940 struct ext4_inode *raw_inode,
4941 struct ext4_inode_info *ei)
4942 {
4943 struct inode *inode = &(ei->vfs_inode);
4944 u64 i_blocks = READ_ONCE(inode->i_blocks);
4945 struct super_block *sb = inode->i_sb;
4946
4947 if (i_blocks <= ~0U) {
4948 /*
4949 * i_blocks can be represented in a 32 bit variable
4950 * as multiple of 512 bytes
4951 */
4952 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4953 raw_inode->i_blocks_high = 0;
4954 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4955 return 0;
4956 }
4957
4958 /*
4959 * This should never happen since sb->s_maxbytes should not have
4960 * allowed this, sb->s_maxbytes was set according to the huge_file
4961 * feature in ext4_fill_super().
4962 */
4963 if (!ext4_has_feature_huge_file(sb))
4964 return -EFSCORRUPTED;
4965
4966 if (i_blocks <= 0xffffffffffffULL) {
4967 /*
4968 * i_blocks can be represented in a 48 bit variable
4969 * as multiple of 512 bytes
4970 */
4971 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4972 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4973 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4974 } else {
4975 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4976 /* i_block is stored in file system block size */
4977 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4978 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4979 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4980 }
4981 return 0;
4982 }
4983
__ext4_update_other_inode_time(struct super_block * sb,unsigned long orig_ino,unsigned long ino,struct ext4_inode * raw_inode)4984 static void __ext4_update_other_inode_time(struct super_block *sb,
4985 unsigned long orig_ino,
4986 unsigned long ino,
4987 struct ext4_inode *raw_inode)
4988 {
4989 struct inode *inode;
4990
4991 inode = find_inode_by_ino_rcu(sb, ino);
4992 if (!inode)
4993 return;
4994
4995 if (!inode_is_dirtytime_only(inode))
4996 return;
4997
4998 spin_lock(&inode->i_lock);
4999 if (inode_is_dirtytime_only(inode)) {
5000 struct ext4_inode_info *ei = EXT4_I(inode);
5001
5002 inode->i_state &= ~I_DIRTY_TIME;
5003 spin_unlock(&inode->i_lock);
5004
5005 spin_lock(&ei->i_raw_lock);
5006 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5007 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5008 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5009 ext4_inode_csum_set(inode, raw_inode, ei);
5010 spin_unlock(&ei->i_raw_lock);
5011 trace_ext4_other_inode_update_time(inode, orig_ino);
5012 return;
5013 }
5014 spin_unlock(&inode->i_lock);
5015 }
5016
5017 /*
5018 * Opportunistically update the other time fields for other inodes in
5019 * the same inode table block.
5020 */
ext4_update_other_inodes_time(struct super_block * sb,unsigned long orig_ino,char * buf)5021 static void ext4_update_other_inodes_time(struct super_block *sb,
5022 unsigned long orig_ino, char *buf)
5023 {
5024 unsigned long ino;
5025 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5026 int inode_size = EXT4_INODE_SIZE(sb);
5027
5028 /*
5029 * Calculate the first inode in the inode table block. Inode
5030 * numbers are one-based. That is, the first inode in a block
5031 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5032 */
5033 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5034 rcu_read_lock();
5035 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5036 if (ino == orig_ino)
5037 continue;
5038 __ext4_update_other_inode_time(sb, orig_ino, ino,
5039 (struct ext4_inode *)buf);
5040 }
5041 rcu_read_unlock();
5042 }
5043
5044 /*
5045 * Post the struct inode info into an on-disk inode location in the
5046 * buffer-cache. This gobbles the caller's reference to the
5047 * buffer_head in the inode location struct.
5048 *
5049 * The caller must have write access to iloc->bh.
5050 */
ext4_do_update_inode(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5051 static int ext4_do_update_inode(handle_t *handle,
5052 struct inode *inode,
5053 struct ext4_iloc *iloc)
5054 {
5055 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5056 struct ext4_inode_info *ei = EXT4_I(inode);
5057 struct buffer_head *bh = iloc->bh;
5058 struct super_block *sb = inode->i_sb;
5059 int err = 0, block;
5060 int need_datasync = 0, set_large_file = 0;
5061 uid_t i_uid;
5062 gid_t i_gid;
5063 projid_t i_projid;
5064
5065 spin_lock(&ei->i_raw_lock);
5066
5067 /*
5068 * For fields not tracked in the in-memory inode, initialise them
5069 * to zero for new inodes.
5070 */
5071 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5072 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5073
5074 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5075
5076 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5077 i_uid = i_uid_read(inode);
5078 i_gid = i_gid_read(inode);
5079 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5080 if (!(test_opt(inode->i_sb, NO_UID32))) {
5081 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5082 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5083 /*
5084 * Fix up interoperability with old kernels. Otherwise,
5085 * old inodes get re-used with the upper 16 bits of the
5086 * uid/gid intact.
5087 */
5088 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5089 raw_inode->i_uid_high = 0;
5090 raw_inode->i_gid_high = 0;
5091 } else {
5092 raw_inode->i_uid_high =
5093 cpu_to_le16(high_16_bits(i_uid));
5094 raw_inode->i_gid_high =
5095 cpu_to_le16(high_16_bits(i_gid));
5096 }
5097 } else {
5098 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5099 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5100 raw_inode->i_uid_high = 0;
5101 raw_inode->i_gid_high = 0;
5102 }
5103 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5104
5105 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5106 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5107 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5108 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5109
5110 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5111 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5112 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5113 raw_inode->i_file_acl_high =
5114 cpu_to_le16(ei->i_file_acl >> 32);
5115 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5116 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5117 ext4_isize_set(raw_inode, ei->i_disksize);
5118 need_datasync = 1;
5119 }
5120 if (ei->i_disksize > 0x7fffffffULL) {
5121 if (!ext4_has_feature_large_file(sb) ||
5122 EXT4_SB(sb)->s_es->s_rev_level ==
5123 cpu_to_le32(EXT4_GOOD_OLD_REV))
5124 set_large_file = 1;
5125 }
5126 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5127 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5128 if (old_valid_dev(inode->i_rdev)) {
5129 raw_inode->i_block[0] =
5130 cpu_to_le32(old_encode_dev(inode->i_rdev));
5131 raw_inode->i_block[1] = 0;
5132 } else {
5133 raw_inode->i_block[0] = 0;
5134 raw_inode->i_block[1] =
5135 cpu_to_le32(new_encode_dev(inode->i_rdev));
5136 raw_inode->i_block[2] = 0;
5137 }
5138 } else if (!ext4_has_inline_data(inode)) {
5139 for (block = 0; block < EXT4_N_BLOCKS; block++)
5140 raw_inode->i_block[block] = ei->i_data[block];
5141 }
5142
5143 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5144 u64 ivers = ext4_inode_peek_iversion(inode);
5145
5146 raw_inode->i_disk_version = cpu_to_le32(ivers);
5147 if (ei->i_extra_isize) {
5148 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5149 raw_inode->i_version_hi =
5150 cpu_to_le32(ivers >> 32);
5151 raw_inode->i_extra_isize =
5152 cpu_to_le16(ei->i_extra_isize);
5153 }
5154 }
5155
5156 if (i_projid != EXT4_DEF_PROJID &&
5157 !ext4_has_feature_project(inode->i_sb))
5158 err = err ?: -EFSCORRUPTED;
5159
5160 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5161 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5162 raw_inode->i_projid = cpu_to_le32(i_projid);
5163
5164 ext4_inode_csum_set(inode, raw_inode, ei);
5165 spin_unlock(&ei->i_raw_lock);
5166 if (err) {
5167 EXT4_ERROR_INODE(inode, "corrupted inode contents");
5168 goto out_brelse;
5169 }
5170
5171 if (inode->i_sb->s_flags & SB_LAZYTIME)
5172 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5173 bh->b_data);
5174
5175 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5176 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5177 if (err)
5178 goto out_error;
5179 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5180 if (set_large_file) {
5181 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5182 err = ext4_journal_get_write_access(handle, sb,
5183 EXT4_SB(sb)->s_sbh,
5184 EXT4_JTR_NONE);
5185 if (err)
5186 goto out_error;
5187 lock_buffer(EXT4_SB(sb)->s_sbh);
5188 ext4_set_feature_large_file(sb);
5189 ext4_superblock_csum_set(sb);
5190 unlock_buffer(EXT4_SB(sb)->s_sbh);
5191 ext4_handle_sync(handle);
5192 err = ext4_handle_dirty_metadata(handle, NULL,
5193 EXT4_SB(sb)->s_sbh);
5194 }
5195 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5196 out_error:
5197 ext4_std_error(inode->i_sb, err);
5198 out_brelse:
5199 brelse(bh);
5200 return err;
5201 }
5202
5203 /*
5204 * ext4_write_inode()
5205 *
5206 * We are called from a few places:
5207 *
5208 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5209 * Here, there will be no transaction running. We wait for any running
5210 * transaction to commit.
5211 *
5212 * - Within flush work (sys_sync(), kupdate and such).
5213 * We wait on commit, if told to.
5214 *
5215 * - Within iput_final() -> write_inode_now()
5216 * We wait on commit, if told to.
5217 *
5218 * In all cases it is actually safe for us to return without doing anything,
5219 * because the inode has been copied into a raw inode buffer in
5220 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5221 * writeback.
5222 *
5223 * Note that we are absolutely dependent upon all inode dirtiers doing the
5224 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5225 * which we are interested.
5226 *
5227 * It would be a bug for them to not do this. The code:
5228 *
5229 * mark_inode_dirty(inode)
5230 * stuff();
5231 * inode->i_size = expr;
5232 *
5233 * is in error because write_inode() could occur while `stuff()' is running,
5234 * and the new i_size will be lost. Plus the inode will no longer be on the
5235 * superblock's dirty inode list.
5236 */
ext4_write_inode(struct inode * inode,struct writeback_control * wbc)5237 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5238 {
5239 int err;
5240
5241 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5242 sb_rdonly(inode->i_sb))
5243 return 0;
5244
5245 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5246 return -EIO;
5247
5248 if (EXT4_SB(inode->i_sb)->s_journal) {
5249 if (ext4_journal_current_handle()) {
5250 ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5251 dump_stack();
5252 return -EIO;
5253 }
5254
5255 /*
5256 * No need to force transaction in WB_SYNC_NONE mode. Also
5257 * ext4_sync_fs() will force the commit after everything is
5258 * written.
5259 */
5260 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5261 return 0;
5262
5263 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5264 EXT4_I(inode)->i_sync_tid);
5265 } else {
5266 struct ext4_iloc iloc;
5267
5268 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5269 if (err)
5270 return err;
5271 /*
5272 * sync(2) will flush the whole buffer cache. No need to do
5273 * it here separately for each inode.
5274 */
5275 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5276 sync_dirty_buffer(iloc.bh);
5277 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5278 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5279 "IO error syncing inode");
5280 err = -EIO;
5281 }
5282 brelse(iloc.bh);
5283 }
5284 return err;
5285 }
5286
5287 /*
5288 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5289 * buffers that are attached to a page stradding i_size and are undergoing
5290 * commit. In that case we have to wait for commit to finish and try again.
5291 */
ext4_wait_for_tail_page_commit(struct inode * inode)5292 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5293 {
5294 struct page *page;
5295 unsigned offset;
5296 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5297 tid_t commit_tid = 0;
5298 int ret;
5299
5300 offset = inode->i_size & (PAGE_SIZE - 1);
5301 /*
5302 * If the page is fully truncated, we don't need to wait for any commit
5303 * (and we even should not as __ext4_journalled_invalidatepage() may
5304 * strip all buffers from the page but keep the page dirty which can then
5305 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5306 * buffers). Also we don't need to wait for any commit if all buffers in
5307 * the page remain valid. This is most beneficial for the common case of
5308 * blocksize == PAGESIZE.
5309 */
5310 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5311 return;
5312 while (1) {
5313 page = find_lock_page(inode->i_mapping,
5314 inode->i_size >> PAGE_SHIFT);
5315 if (!page)
5316 return;
5317 ret = __ext4_journalled_invalidatepage(page, offset,
5318 PAGE_SIZE - offset);
5319 unlock_page(page);
5320 put_page(page);
5321 if (ret != -EBUSY)
5322 return;
5323 commit_tid = 0;
5324 read_lock(&journal->j_state_lock);
5325 if (journal->j_committing_transaction)
5326 commit_tid = journal->j_committing_transaction->t_tid;
5327 read_unlock(&journal->j_state_lock);
5328 if (commit_tid)
5329 jbd2_log_wait_commit(journal, commit_tid);
5330 }
5331 }
5332
5333 /*
5334 * ext4_setattr()
5335 *
5336 * Called from notify_change.
5337 *
5338 * We want to trap VFS attempts to truncate the file as soon as
5339 * possible. In particular, we want to make sure that when the VFS
5340 * shrinks i_size, we put the inode on the orphan list and modify
5341 * i_disksize immediately, so that during the subsequent flushing of
5342 * dirty pages and freeing of disk blocks, we can guarantee that any
5343 * commit will leave the blocks being flushed in an unused state on
5344 * disk. (On recovery, the inode will get truncated and the blocks will
5345 * be freed, so we have a strong guarantee that no future commit will
5346 * leave these blocks visible to the user.)
5347 *
5348 * Another thing we have to assure is that if we are in ordered mode
5349 * and inode is still attached to the committing transaction, we must
5350 * we start writeout of all the dirty pages which are being truncated.
5351 * This way we are sure that all the data written in the previous
5352 * transaction are already on disk (truncate waits for pages under
5353 * writeback).
5354 *
5355 * Called with inode->i_mutex down.
5356 */
ext4_setattr(struct user_namespace * mnt_userns,struct dentry * dentry,struct iattr * attr)5357 int ext4_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5358 struct iattr *attr)
5359 {
5360 struct inode *inode = d_inode(dentry);
5361 int error, rc = 0;
5362 int orphan = 0;
5363 const unsigned int ia_valid = attr->ia_valid;
5364
5365 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5366 return -EIO;
5367
5368 if (unlikely(IS_IMMUTABLE(inode)))
5369 return -EPERM;
5370
5371 if (unlikely(IS_APPEND(inode) &&
5372 (ia_valid & (ATTR_MODE | ATTR_UID |
5373 ATTR_GID | ATTR_TIMES_SET))))
5374 return -EPERM;
5375
5376 error = setattr_prepare(mnt_userns, dentry, attr);
5377 if (error)
5378 return error;
5379
5380 error = fscrypt_prepare_setattr(dentry, attr);
5381 if (error)
5382 return error;
5383
5384 error = fsverity_prepare_setattr(dentry, attr);
5385 if (error)
5386 return error;
5387
5388 if (is_quota_modification(inode, attr)) {
5389 error = dquot_initialize(inode);
5390 if (error)
5391 return error;
5392 }
5393
5394 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5395 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5396 handle_t *handle;
5397
5398 /* (user+group)*(old+new) structure, inode write (sb,
5399 * inode block, ? - but truncate inode update has it) */
5400 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5401 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5402 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5403 if (IS_ERR(handle)) {
5404 error = PTR_ERR(handle);
5405 goto err_out;
5406 }
5407
5408 /* dquot_transfer() calls back ext4_get_inode_usage() which
5409 * counts xattr inode references.
5410 */
5411 down_read(&EXT4_I(inode)->xattr_sem);
5412 error = dquot_transfer(inode, attr);
5413 up_read(&EXT4_I(inode)->xattr_sem);
5414
5415 if (error) {
5416 ext4_journal_stop(handle);
5417 return error;
5418 }
5419 /* Update corresponding info in inode so that everything is in
5420 * one transaction */
5421 if (attr->ia_valid & ATTR_UID)
5422 inode->i_uid = attr->ia_uid;
5423 if (attr->ia_valid & ATTR_GID)
5424 inode->i_gid = attr->ia_gid;
5425 error = ext4_mark_inode_dirty(handle, inode);
5426 ext4_journal_stop(handle);
5427 if (unlikely(error)) {
5428 return error;
5429 }
5430 }
5431
5432 if (attr->ia_valid & ATTR_SIZE) {
5433 handle_t *handle;
5434 loff_t oldsize = inode->i_size;
5435 loff_t old_disksize;
5436 int shrink = (attr->ia_size < inode->i_size);
5437
5438 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5439 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5440
5441 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5442 return -EFBIG;
5443 }
5444 }
5445 if (!S_ISREG(inode->i_mode)) {
5446 return -EINVAL;
5447 }
5448
5449 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5450 inode_inc_iversion(inode);
5451
5452 if (shrink) {
5453 if (ext4_should_order_data(inode)) {
5454 error = ext4_begin_ordered_truncate(inode,
5455 attr->ia_size);
5456 if (error)
5457 goto err_out;
5458 }
5459 /*
5460 * Blocks are going to be removed from the inode. Wait
5461 * for dio in flight.
5462 */
5463 inode_dio_wait(inode);
5464 }
5465
5466 filemap_invalidate_lock(inode->i_mapping);
5467
5468 rc = ext4_break_layouts(inode);
5469 if (rc) {
5470 filemap_invalidate_unlock(inode->i_mapping);
5471 goto err_out;
5472 }
5473
5474 if (attr->ia_size != inode->i_size) {
5475 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5476 if (IS_ERR(handle)) {
5477 error = PTR_ERR(handle);
5478 goto out_mmap_sem;
5479 }
5480 if (ext4_handle_valid(handle) && shrink) {
5481 error = ext4_orphan_add(handle, inode);
5482 orphan = 1;
5483 }
5484 /*
5485 * Update c/mtime on truncate up, ext4_truncate() will
5486 * update c/mtime in shrink case below
5487 */
5488 if (!shrink) {
5489 inode->i_mtime = current_time(inode);
5490 inode->i_ctime = inode->i_mtime;
5491 }
5492
5493 if (shrink)
5494 ext4_fc_track_range(handle, inode,
5495 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5496 inode->i_sb->s_blocksize_bits,
5497 EXT_MAX_BLOCKS - 1);
5498 else
5499 ext4_fc_track_range(
5500 handle, inode,
5501 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5502 inode->i_sb->s_blocksize_bits,
5503 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5504 inode->i_sb->s_blocksize_bits);
5505
5506 down_write(&EXT4_I(inode)->i_data_sem);
5507 old_disksize = EXT4_I(inode)->i_disksize;
5508 EXT4_I(inode)->i_disksize = attr->ia_size;
5509 rc = ext4_mark_inode_dirty(handle, inode);
5510 if (!error)
5511 error = rc;
5512 /*
5513 * We have to update i_size under i_data_sem together
5514 * with i_disksize to avoid races with writeback code
5515 * running ext4_wb_update_i_disksize().
5516 */
5517 if (!error)
5518 i_size_write(inode, attr->ia_size);
5519 else
5520 EXT4_I(inode)->i_disksize = old_disksize;
5521 up_write(&EXT4_I(inode)->i_data_sem);
5522 ext4_journal_stop(handle);
5523 if (error)
5524 goto out_mmap_sem;
5525 if (!shrink) {
5526 pagecache_isize_extended(inode, oldsize,
5527 inode->i_size);
5528 } else if (ext4_should_journal_data(inode)) {
5529 ext4_wait_for_tail_page_commit(inode);
5530 }
5531 }
5532
5533 /*
5534 * Truncate pagecache after we've waited for commit
5535 * in data=journal mode to make pages freeable.
5536 */
5537 truncate_pagecache(inode, inode->i_size);
5538 /*
5539 * Call ext4_truncate() even if i_size didn't change to
5540 * truncate possible preallocated blocks.
5541 */
5542 if (attr->ia_size <= oldsize) {
5543 rc = ext4_truncate(inode);
5544 if (rc)
5545 error = rc;
5546 }
5547 out_mmap_sem:
5548 filemap_invalidate_unlock(inode->i_mapping);
5549 }
5550
5551 if (!error) {
5552 setattr_copy(mnt_userns, inode, attr);
5553 mark_inode_dirty(inode);
5554 }
5555
5556 /*
5557 * If the call to ext4_truncate failed to get a transaction handle at
5558 * all, we need to clean up the in-core orphan list manually.
5559 */
5560 if (orphan && inode->i_nlink)
5561 ext4_orphan_del(NULL, inode);
5562
5563 if (!error && (ia_valid & ATTR_MODE))
5564 rc = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5565
5566 err_out:
5567 if (error)
5568 ext4_std_error(inode->i_sb, error);
5569 if (!error)
5570 error = rc;
5571 return error;
5572 }
5573
ext4_getattr(struct user_namespace * mnt_userns,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)5574 int ext4_getattr(struct user_namespace *mnt_userns, const struct path *path,
5575 struct kstat *stat, u32 request_mask, unsigned int query_flags)
5576 {
5577 struct inode *inode = d_inode(path->dentry);
5578 struct ext4_inode *raw_inode;
5579 struct ext4_inode_info *ei = EXT4_I(inode);
5580 unsigned int flags;
5581
5582 if ((request_mask & STATX_BTIME) &&
5583 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5584 stat->result_mask |= STATX_BTIME;
5585 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5586 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5587 }
5588
5589 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5590 if (flags & EXT4_APPEND_FL)
5591 stat->attributes |= STATX_ATTR_APPEND;
5592 if (flags & EXT4_COMPR_FL)
5593 stat->attributes |= STATX_ATTR_COMPRESSED;
5594 if (flags & EXT4_ENCRYPT_FL)
5595 stat->attributes |= STATX_ATTR_ENCRYPTED;
5596 if (flags & EXT4_IMMUTABLE_FL)
5597 stat->attributes |= STATX_ATTR_IMMUTABLE;
5598 if (flags & EXT4_NODUMP_FL)
5599 stat->attributes |= STATX_ATTR_NODUMP;
5600 if (flags & EXT4_VERITY_FL)
5601 stat->attributes |= STATX_ATTR_VERITY;
5602
5603 stat->attributes_mask |= (STATX_ATTR_APPEND |
5604 STATX_ATTR_COMPRESSED |
5605 STATX_ATTR_ENCRYPTED |
5606 STATX_ATTR_IMMUTABLE |
5607 STATX_ATTR_NODUMP |
5608 STATX_ATTR_VERITY);
5609
5610 generic_fillattr(mnt_userns, inode, stat);
5611 return 0;
5612 }
5613
ext4_file_getattr(struct user_namespace * mnt_userns,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)5614 int ext4_file_getattr(struct user_namespace *mnt_userns,
5615 const struct path *path, struct kstat *stat,
5616 u32 request_mask, unsigned int query_flags)
5617 {
5618 struct inode *inode = d_inode(path->dentry);
5619 u64 delalloc_blocks;
5620
5621 ext4_getattr(mnt_userns, path, stat, request_mask, query_flags);
5622
5623 /*
5624 * If there is inline data in the inode, the inode will normally not
5625 * have data blocks allocated (it may have an external xattr block).
5626 * Report at least one sector for such files, so tools like tar, rsync,
5627 * others don't incorrectly think the file is completely sparse.
5628 */
5629 if (unlikely(ext4_has_inline_data(inode)))
5630 stat->blocks += (stat->size + 511) >> 9;
5631
5632 /*
5633 * We can't update i_blocks if the block allocation is delayed
5634 * otherwise in the case of system crash before the real block
5635 * allocation is done, we will have i_blocks inconsistent with
5636 * on-disk file blocks.
5637 * We always keep i_blocks updated together with real
5638 * allocation. But to not confuse with user, stat
5639 * will return the blocks that include the delayed allocation
5640 * blocks for this file.
5641 */
5642 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5643 EXT4_I(inode)->i_reserved_data_blocks);
5644 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5645 return 0;
5646 }
5647
ext4_index_trans_blocks(struct inode * inode,int lblocks,int pextents)5648 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5649 int pextents)
5650 {
5651 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5652 return ext4_ind_trans_blocks(inode, lblocks);
5653 return ext4_ext_index_trans_blocks(inode, pextents);
5654 }
5655
5656 /*
5657 * Account for index blocks, block groups bitmaps and block group
5658 * descriptor blocks if modify datablocks and index blocks
5659 * worse case, the indexs blocks spread over different block groups
5660 *
5661 * If datablocks are discontiguous, they are possible to spread over
5662 * different block groups too. If they are contiguous, with flexbg,
5663 * they could still across block group boundary.
5664 *
5665 * Also account for superblock, inode, quota and xattr blocks
5666 */
ext4_meta_trans_blocks(struct inode * inode,int lblocks,int pextents)5667 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5668 int pextents)
5669 {
5670 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5671 int gdpblocks;
5672 int idxblocks;
5673 int ret = 0;
5674
5675 /*
5676 * How many index blocks need to touch to map @lblocks logical blocks
5677 * to @pextents physical extents?
5678 */
5679 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5680
5681 ret = idxblocks;
5682
5683 /*
5684 * Now let's see how many group bitmaps and group descriptors need
5685 * to account
5686 */
5687 groups = idxblocks + pextents;
5688 gdpblocks = groups;
5689 if (groups > ngroups)
5690 groups = ngroups;
5691 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5692 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5693
5694 /* bitmaps and block group descriptor blocks */
5695 ret += groups + gdpblocks;
5696
5697 /* Blocks for super block, inode, quota and xattr blocks */
5698 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5699
5700 return ret;
5701 }
5702
5703 /*
5704 * Calculate the total number of credits to reserve to fit
5705 * the modification of a single pages into a single transaction,
5706 * which may include multiple chunks of block allocations.
5707 *
5708 * This could be called via ext4_write_begin()
5709 *
5710 * We need to consider the worse case, when
5711 * one new block per extent.
5712 */
ext4_writepage_trans_blocks(struct inode * inode)5713 int ext4_writepage_trans_blocks(struct inode *inode)
5714 {
5715 int bpp = ext4_journal_blocks_per_page(inode);
5716 int ret;
5717
5718 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5719
5720 /* Account for data blocks for journalled mode */
5721 if (ext4_should_journal_data(inode))
5722 ret += bpp;
5723 return ret;
5724 }
5725
5726 /*
5727 * Calculate the journal credits for a chunk of data modification.
5728 *
5729 * This is called from DIO, fallocate or whoever calling
5730 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5731 *
5732 * journal buffers for data blocks are not included here, as DIO
5733 * and fallocate do no need to journal data buffers.
5734 */
ext4_chunk_trans_blocks(struct inode * inode,int nrblocks)5735 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5736 {
5737 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5738 }
5739
5740 /*
5741 * The caller must have previously called ext4_reserve_inode_write().
5742 * Give this, we know that the caller already has write access to iloc->bh.
5743 */
ext4_mark_iloc_dirty(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5744 int ext4_mark_iloc_dirty(handle_t *handle,
5745 struct inode *inode, struct ext4_iloc *iloc)
5746 {
5747 int err = 0;
5748
5749 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5750 put_bh(iloc->bh);
5751 return -EIO;
5752 }
5753 ext4_fc_track_inode(handle, inode);
5754
5755 /*
5756 * ea_inodes are using i_version for storing reference count, don't
5757 * mess with it
5758 */
5759 if (IS_I_VERSION(inode) &&
5760 !(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
5761 inode_inc_iversion(inode);
5762
5763 /* the do_update_inode consumes one bh->b_count */
5764 get_bh(iloc->bh);
5765
5766 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5767 err = ext4_do_update_inode(handle, inode, iloc);
5768 put_bh(iloc->bh);
5769 return err;
5770 }
5771
5772 /*
5773 * On success, We end up with an outstanding reference count against
5774 * iloc->bh. This _must_ be cleaned up later.
5775 */
5776
5777 int
ext4_reserve_inode_write(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5778 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5779 struct ext4_iloc *iloc)
5780 {
5781 int err;
5782
5783 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5784 return -EIO;
5785
5786 err = ext4_get_inode_loc(inode, iloc);
5787 if (!err) {
5788 BUFFER_TRACE(iloc->bh, "get_write_access");
5789 err = ext4_journal_get_write_access(handle, inode->i_sb,
5790 iloc->bh, EXT4_JTR_NONE);
5791 if (err) {
5792 brelse(iloc->bh);
5793 iloc->bh = NULL;
5794 }
5795 }
5796 ext4_std_error(inode->i_sb, err);
5797 return err;
5798 }
5799
__ext4_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc * iloc,handle_t * handle,int * no_expand)5800 static int __ext4_expand_extra_isize(struct inode *inode,
5801 unsigned int new_extra_isize,
5802 struct ext4_iloc *iloc,
5803 handle_t *handle, int *no_expand)
5804 {
5805 struct ext4_inode *raw_inode;
5806 struct ext4_xattr_ibody_header *header;
5807 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5808 struct ext4_inode_info *ei = EXT4_I(inode);
5809 int error;
5810
5811 /* this was checked at iget time, but double check for good measure */
5812 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5813 (ei->i_extra_isize & 3)) {
5814 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5815 ei->i_extra_isize,
5816 EXT4_INODE_SIZE(inode->i_sb));
5817 return -EFSCORRUPTED;
5818 }
5819 if ((new_extra_isize < ei->i_extra_isize) ||
5820 (new_extra_isize < 4) ||
5821 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5822 return -EINVAL; /* Should never happen */
5823
5824 raw_inode = ext4_raw_inode(iloc);
5825
5826 header = IHDR(inode, raw_inode);
5827
5828 /* No extended attributes present */
5829 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5830 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5831 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5832 EXT4_I(inode)->i_extra_isize, 0,
5833 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5834 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5835 return 0;
5836 }
5837
5838 /*
5839 * We may need to allocate external xattr block so we need quotas
5840 * initialized. Here we can be called with various locks held so we
5841 * cannot affort to initialize quotas ourselves. So just bail.
5842 */
5843 if (dquot_initialize_needed(inode))
5844 return -EAGAIN;
5845
5846 /* try to expand with EAs present */
5847 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5848 raw_inode, handle);
5849 if (error) {
5850 /*
5851 * Inode size expansion failed; don't try again
5852 */
5853 *no_expand = 1;
5854 }
5855
5856 return error;
5857 }
5858
5859 /*
5860 * Expand an inode by new_extra_isize bytes.
5861 * Returns 0 on success or negative error number on failure.
5862 */
ext4_try_to_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc iloc,handle_t * handle)5863 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5864 unsigned int new_extra_isize,
5865 struct ext4_iloc iloc,
5866 handle_t *handle)
5867 {
5868 int no_expand;
5869 int error;
5870
5871 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5872 return -EOVERFLOW;
5873
5874 /*
5875 * In nojournal mode, we can immediately attempt to expand
5876 * the inode. When journaled, we first need to obtain extra
5877 * buffer credits since we may write into the EA block
5878 * with this same handle. If journal_extend fails, then it will
5879 * only result in a minor loss of functionality for that inode.
5880 * If this is felt to be critical, then e2fsck should be run to
5881 * force a large enough s_min_extra_isize.
5882 */
5883 if (ext4_journal_extend(handle,
5884 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5885 return -ENOSPC;
5886
5887 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5888 return -EBUSY;
5889
5890 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5891 handle, &no_expand);
5892 ext4_write_unlock_xattr(inode, &no_expand);
5893
5894 return error;
5895 }
5896
ext4_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc * iloc)5897 int ext4_expand_extra_isize(struct inode *inode,
5898 unsigned int new_extra_isize,
5899 struct ext4_iloc *iloc)
5900 {
5901 handle_t *handle;
5902 int no_expand;
5903 int error, rc;
5904
5905 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5906 brelse(iloc->bh);
5907 return -EOVERFLOW;
5908 }
5909
5910 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5911 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5912 if (IS_ERR(handle)) {
5913 error = PTR_ERR(handle);
5914 brelse(iloc->bh);
5915 return error;
5916 }
5917
5918 ext4_write_lock_xattr(inode, &no_expand);
5919
5920 BUFFER_TRACE(iloc->bh, "get_write_access");
5921 error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5922 EXT4_JTR_NONE);
5923 if (error) {
5924 brelse(iloc->bh);
5925 goto out_unlock;
5926 }
5927
5928 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5929 handle, &no_expand);
5930
5931 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5932 if (!error)
5933 error = rc;
5934
5935 out_unlock:
5936 ext4_write_unlock_xattr(inode, &no_expand);
5937 ext4_journal_stop(handle);
5938 return error;
5939 }
5940
5941 /*
5942 * What we do here is to mark the in-core inode as clean with respect to inode
5943 * dirtiness (it may still be data-dirty).
5944 * This means that the in-core inode may be reaped by prune_icache
5945 * without having to perform any I/O. This is a very good thing,
5946 * because *any* task may call prune_icache - even ones which
5947 * have a transaction open against a different journal.
5948 *
5949 * Is this cheating? Not really. Sure, we haven't written the
5950 * inode out, but prune_icache isn't a user-visible syncing function.
5951 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5952 * we start and wait on commits.
5953 */
__ext4_mark_inode_dirty(handle_t * handle,struct inode * inode,const char * func,unsigned int line)5954 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5955 const char *func, unsigned int line)
5956 {
5957 struct ext4_iloc iloc;
5958 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5959 int err;
5960
5961 might_sleep();
5962 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5963 err = ext4_reserve_inode_write(handle, inode, &iloc);
5964 if (err)
5965 goto out;
5966
5967 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5968 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5969 iloc, handle);
5970
5971 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5972 out:
5973 if (unlikely(err))
5974 ext4_error_inode_err(inode, func, line, 0, err,
5975 "mark_inode_dirty error");
5976 return err;
5977 }
5978
5979 /*
5980 * ext4_dirty_inode() is called from __mark_inode_dirty()
5981 *
5982 * We're really interested in the case where a file is being extended.
5983 * i_size has been changed by generic_commit_write() and we thus need
5984 * to include the updated inode in the current transaction.
5985 *
5986 * Also, dquot_alloc_block() will always dirty the inode when blocks
5987 * are allocated to the file.
5988 *
5989 * If the inode is marked synchronous, we don't honour that here - doing
5990 * so would cause a commit on atime updates, which we don't bother doing.
5991 * We handle synchronous inodes at the highest possible level.
5992 */
ext4_dirty_inode(struct inode * inode,int flags)5993 void ext4_dirty_inode(struct inode *inode, int flags)
5994 {
5995 handle_t *handle;
5996
5997 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5998 if (IS_ERR(handle))
5999 return;
6000 ext4_mark_inode_dirty(handle, inode);
6001 ext4_journal_stop(handle);
6002 }
6003
ext4_change_inode_journal_flag(struct inode * inode,int val)6004 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6005 {
6006 journal_t *journal;
6007 handle_t *handle;
6008 int err;
6009 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6010
6011 /*
6012 * We have to be very careful here: changing a data block's
6013 * journaling status dynamically is dangerous. If we write a
6014 * data block to the journal, change the status and then delete
6015 * that block, we risk forgetting to revoke the old log record
6016 * from the journal and so a subsequent replay can corrupt data.
6017 * So, first we make sure that the journal is empty and that
6018 * nobody is changing anything.
6019 */
6020
6021 journal = EXT4_JOURNAL(inode);
6022 if (!journal)
6023 return 0;
6024 if (is_journal_aborted(journal))
6025 return -EROFS;
6026
6027 /* Wait for all existing dio workers */
6028 inode_dio_wait(inode);
6029
6030 /*
6031 * Before flushing the journal and switching inode's aops, we have
6032 * to flush all dirty data the inode has. There can be outstanding
6033 * delayed allocations, there can be unwritten extents created by
6034 * fallocate or buffered writes in dioread_nolock mode covered by
6035 * dirty data which can be converted only after flushing the dirty
6036 * data (and journalled aops don't know how to handle these cases).
6037 */
6038 if (val) {
6039 filemap_invalidate_lock(inode->i_mapping);
6040 err = filemap_write_and_wait(inode->i_mapping);
6041 if (err < 0) {
6042 filemap_invalidate_unlock(inode->i_mapping);
6043 return err;
6044 }
6045 }
6046
6047 percpu_down_write(&sbi->s_writepages_rwsem);
6048 jbd2_journal_lock_updates(journal);
6049
6050 /*
6051 * OK, there are no updates running now, and all cached data is
6052 * synced to disk. We are now in a completely consistent state
6053 * which doesn't have anything in the journal, and we know that
6054 * no filesystem updates are running, so it is safe to modify
6055 * the inode's in-core data-journaling state flag now.
6056 */
6057
6058 if (val)
6059 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6060 else {
6061 err = jbd2_journal_flush(journal, 0);
6062 if (err < 0) {
6063 jbd2_journal_unlock_updates(journal);
6064 percpu_up_write(&sbi->s_writepages_rwsem);
6065 return err;
6066 }
6067 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6068 }
6069 ext4_set_aops(inode);
6070
6071 jbd2_journal_unlock_updates(journal);
6072 percpu_up_write(&sbi->s_writepages_rwsem);
6073
6074 if (val)
6075 filemap_invalidate_unlock(inode->i_mapping);
6076
6077 /* Finally we can mark the inode as dirty. */
6078
6079 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6080 if (IS_ERR(handle))
6081 return PTR_ERR(handle);
6082
6083 ext4_fc_mark_ineligible(inode->i_sb,
6084 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6085 err = ext4_mark_inode_dirty(handle, inode);
6086 ext4_handle_sync(handle);
6087 ext4_journal_stop(handle);
6088 ext4_std_error(inode->i_sb, err);
6089
6090 return err;
6091 }
6092
ext4_bh_unmapped(handle_t * handle,struct inode * inode,struct buffer_head * bh)6093 static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6094 struct buffer_head *bh)
6095 {
6096 return !buffer_mapped(bh);
6097 }
6098
ext4_page_mkwrite(struct vm_fault * vmf)6099 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6100 {
6101 struct vm_area_struct *vma = vmf->vma;
6102 struct page *page = vmf->page;
6103 loff_t size;
6104 unsigned long len;
6105 int err;
6106 vm_fault_t ret;
6107 struct file *file = vma->vm_file;
6108 struct inode *inode = file_inode(file);
6109 struct address_space *mapping = inode->i_mapping;
6110 handle_t *handle;
6111 get_block_t *get_block;
6112 int retries = 0;
6113
6114 if (unlikely(IS_IMMUTABLE(inode)))
6115 return VM_FAULT_SIGBUS;
6116
6117 sb_start_pagefault(inode->i_sb);
6118 file_update_time(vma->vm_file);
6119
6120 filemap_invalidate_lock_shared(mapping);
6121
6122 err = ext4_convert_inline_data(inode);
6123 if (err)
6124 goto out_ret;
6125
6126 /*
6127 * On data journalling we skip straight to the transaction handle:
6128 * there's no delalloc; page truncated will be checked later; the
6129 * early return w/ all buffers mapped (calculates size/len) can't
6130 * be used; and there's no dioread_nolock, so only ext4_get_block.
6131 */
6132 if (ext4_should_journal_data(inode))
6133 goto retry_alloc;
6134
6135 /* Delalloc case is easy... */
6136 if (test_opt(inode->i_sb, DELALLOC) &&
6137 !ext4_nonda_switch(inode->i_sb)) {
6138 do {
6139 err = block_page_mkwrite(vma, vmf,
6140 ext4_da_get_block_prep);
6141 } while (err == -ENOSPC &&
6142 ext4_should_retry_alloc(inode->i_sb, &retries));
6143 goto out_ret;
6144 }
6145
6146 lock_page(page);
6147 size = i_size_read(inode);
6148 /* Page got truncated from under us? */
6149 if (page->mapping != mapping || page_offset(page) > size) {
6150 unlock_page(page);
6151 ret = VM_FAULT_NOPAGE;
6152 goto out;
6153 }
6154
6155 if (page->index == size >> PAGE_SHIFT)
6156 len = size & ~PAGE_MASK;
6157 else
6158 len = PAGE_SIZE;
6159 /*
6160 * Return if we have all the buffers mapped. This avoids the need to do
6161 * journal_start/journal_stop which can block and take a long time
6162 *
6163 * This cannot be done for data journalling, as we have to add the
6164 * inode to the transaction's list to writeprotect pages on commit.
6165 */
6166 if (page_has_buffers(page)) {
6167 if (!ext4_walk_page_buffers(NULL, inode, page_buffers(page),
6168 0, len, NULL,
6169 ext4_bh_unmapped)) {
6170 /* Wait so that we don't change page under IO */
6171 wait_for_stable_page(page);
6172 ret = VM_FAULT_LOCKED;
6173 goto out;
6174 }
6175 }
6176 unlock_page(page);
6177 /* OK, we need to fill the hole... */
6178 if (ext4_should_dioread_nolock(inode))
6179 get_block = ext4_get_block_unwritten;
6180 else
6181 get_block = ext4_get_block;
6182 retry_alloc:
6183 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6184 ext4_writepage_trans_blocks(inode));
6185 if (IS_ERR(handle)) {
6186 ret = VM_FAULT_SIGBUS;
6187 goto out;
6188 }
6189 /*
6190 * Data journalling can't use block_page_mkwrite() because it
6191 * will set_buffer_dirty() before do_journal_get_write_access()
6192 * thus might hit warning messages for dirty metadata buffers.
6193 */
6194 if (!ext4_should_journal_data(inode)) {
6195 err = block_page_mkwrite(vma, vmf, get_block);
6196 } else {
6197 lock_page(page);
6198 size = i_size_read(inode);
6199 /* Page got truncated from under us? */
6200 if (page->mapping != mapping || page_offset(page) > size) {
6201 ret = VM_FAULT_NOPAGE;
6202 goto out_error;
6203 }
6204
6205 if (page->index == size >> PAGE_SHIFT)
6206 len = size & ~PAGE_MASK;
6207 else
6208 len = PAGE_SIZE;
6209
6210 err = __block_write_begin(page, 0, len, ext4_get_block);
6211 if (!err) {
6212 ret = VM_FAULT_SIGBUS;
6213 if (ext4_walk_page_buffers(handle, inode,
6214 page_buffers(page), 0, len, NULL,
6215 do_journal_get_write_access))
6216 goto out_error;
6217 if (ext4_walk_page_buffers(handle, inode,
6218 page_buffers(page), 0, len, NULL,
6219 write_end_fn))
6220 goto out_error;
6221 if (ext4_jbd2_inode_add_write(handle, inode,
6222 page_offset(page), len))
6223 goto out_error;
6224 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6225 } else {
6226 unlock_page(page);
6227 }
6228 }
6229 ext4_journal_stop(handle);
6230 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6231 goto retry_alloc;
6232 out_ret:
6233 ret = block_page_mkwrite_return(err);
6234 out:
6235 filemap_invalidate_unlock_shared(mapping);
6236 sb_end_pagefault(inode->i_sb);
6237 return ret;
6238 out_error:
6239 unlock_page(page);
6240 ext4_journal_stop(handle);
6241 goto out;
6242 }
6243