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