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