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