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