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