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