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