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