xref: /linux/fs/f2fs/data.c (revision f3a8b6645dc2e60d11f20c1c23afd964ff4e55ae)
1 /*
2  * fs/f2fs/data.c
3  *
4  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
5  *             http://www.samsung.com/
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11 #include <linux/fs.h>
12 #include <linux/f2fs_fs.h>
13 #include <linux/buffer_head.h>
14 #include <linux/mpage.h>
15 #include <linux/writeback.h>
16 #include <linux/backing-dev.h>
17 #include <linux/pagevec.h>
18 #include <linux/blkdev.h>
19 #include <linux/bio.h>
20 #include <linux/prefetch.h>
21 #include <linux/uio.h>
22 #include <linux/mm.h>
23 #include <linux/memcontrol.h>
24 #include <linux/cleancache.h>
25 
26 #include "f2fs.h"
27 #include "node.h"
28 #include "segment.h"
29 #include "trace.h"
30 #include <trace/events/f2fs.h>
31 
32 static void f2fs_read_end_io(struct bio *bio)
33 {
34 	struct bio_vec *bvec;
35 	int i;
36 
37 #ifdef CONFIG_F2FS_FAULT_INJECTION
38 	if (time_to_inject(F2FS_P_SB(bio->bi_io_vec->bv_page), FAULT_IO))
39 		bio->bi_error = -EIO;
40 #endif
41 
42 	if (f2fs_bio_encrypted(bio)) {
43 		if (bio->bi_error) {
44 			fscrypt_release_ctx(bio->bi_private);
45 		} else {
46 			fscrypt_decrypt_bio_pages(bio->bi_private, bio);
47 			return;
48 		}
49 	}
50 
51 	bio_for_each_segment_all(bvec, bio, i) {
52 		struct page *page = bvec->bv_page;
53 
54 		if (!bio->bi_error) {
55 			if (!PageUptodate(page))
56 				SetPageUptodate(page);
57 		} else {
58 			ClearPageUptodate(page);
59 			SetPageError(page);
60 		}
61 		unlock_page(page);
62 	}
63 	bio_put(bio);
64 }
65 
66 static void f2fs_write_end_io(struct bio *bio)
67 {
68 	struct f2fs_sb_info *sbi = bio->bi_private;
69 	struct bio_vec *bvec;
70 	int i;
71 
72 	bio_for_each_segment_all(bvec, bio, i) {
73 		struct page *page = bvec->bv_page;
74 
75 		fscrypt_pullback_bio_page(&page, true);
76 
77 		if (unlikely(bio->bi_error)) {
78 			mapping_set_error(page->mapping, -EIO);
79 			f2fs_stop_checkpoint(sbi, true);
80 		}
81 		end_page_writeback(page);
82 	}
83 	if (atomic_dec_and_test(&sbi->nr_wb_bios) &&
84 				wq_has_sleeper(&sbi->cp_wait))
85 		wake_up(&sbi->cp_wait);
86 
87 	bio_put(bio);
88 }
89 
90 /*
91  * Low-level block read/write IO operations.
92  */
93 static struct bio *__bio_alloc(struct f2fs_sb_info *sbi, block_t blk_addr,
94 				int npages, bool is_read)
95 {
96 	struct bio *bio;
97 
98 	bio = f2fs_bio_alloc(npages);
99 
100 	bio->bi_bdev = sbi->sb->s_bdev;
101 	bio->bi_iter.bi_sector = SECTOR_FROM_BLOCK(blk_addr);
102 	bio->bi_end_io = is_read ? f2fs_read_end_io : f2fs_write_end_io;
103 	bio->bi_private = is_read ? NULL : sbi;
104 
105 	return bio;
106 }
107 
108 static inline void __submit_bio(struct f2fs_sb_info *sbi,
109 				struct bio *bio, enum page_type type)
110 {
111 	if (!is_read_io(bio_op(bio))) {
112 		atomic_inc(&sbi->nr_wb_bios);
113 		if (f2fs_sb_mounted_hmsmr(sbi->sb) &&
114 			current->plug && (type == DATA || type == NODE))
115 			blk_finish_plug(current->plug);
116 	}
117 	submit_bio(bio);
118 }
119 
120 static void __submit_merged_bio(struct f2fs_bio_info *io)
121 {
122 	struct f2fs_io_info *fio = &io->fio;
123 
124 	if (!io->bio)
125 		return;
126 
127 	if (is_read_io(fio->op))
128 		trace_f2fs_submit_read_bio(io->sbi->sb, fio, io->bio);
129 	else
130 		trace_f2fs_submit_write_bio(io->sbi->sb, fio, io->bio);
131 
132 	bio_set_op_attrs(io->bio, fio->op, fio->op_flags);
133 
134 	__submit_bio(io->sbi, io->bio, fio->type);
135 	io->bio = NULL;
136 }
137 
138 static bool __has_merged_page(struct f2fs_bio_info *io, struct inode *inode,
139 						struct page *page, nid_t ino)
140 {
141 	struct bio_vec *bvec;
142 	struct page *target;
143 	int i;
144 
145 	if (!io->bio)
146 		return false;
147 
148 	if (!inode && !page && !ino)
149 		return true;
150 
151 	bio_for_each_segment_all(bvec, io->bio, i) {
152 
153 		if (bvec->bv_page->mapping)
154 			target = bvec->bv_page;
155 		else
156 			target = fscrypt_control_page(bvec->bv_page);
157 
158 		if (inode && inode == target->mapping->host)
159 			return true;
160 		if (page && page == target)
161 			return true;
162 		if (ino && ino == ino_of_node(target))
163 			return true;
164 	}
165 
166 	return false;
167 }
168 
169 static bool has_merged_page(struct f2fs_sb_info *sbi, struct inode *inode,
170 						struct page *page, nid_t ino,
171 						enum page_type type)
172 {
173 	enum page_type btype = PAGE_TYPE_OF_BIO(type);
174 	struct f2fs_bio_info *io = &sbi->write_io[btype];
175 	bool ret;
176 
177 	down_read(&io->io_rwsem);
178 	ret = __has_merged_page(io, inode, page, ino);
179 	up_read(&io->io_rwsem);
180 	return ret;
181 }
182 
183 static void __f2fs_submit_merged_bio(struct f2fs_sb_info *sbi,
184 				struct inode *inode, struct page *page,
185 				nid_t ino, enum page_type type, int rw)
186 {
187 	enum page_type btype = PAGE_TYPE_OF_BIO(type);
188 	struct f2fs_bio_info *io;
189 
190 	io = is_read_io(rw) ? &sbi->read_io : &sbi->write_io[btype];
191 
192 	down_write(&io->io_rwsem);
193 
194 	if (!__has_merged_page(io, inode, page, ino))
195 		goto out;
196 
197 	/* change META to META_FLUSH in the checkpoint procedure */
198 	if (type >= META_FLUSH) {
199 		io->fio.type = META_FLUSH;
200 		io->fio.op = REQ_OP_WRITE;
201 		if (test_opt(sbi, NOBARRIER))
202 			io->fio.op_flags = WRITE_FLUSH | REQ_META | REQ_PRIO;
203 		else
204 			io->fio.op_flags = WRITE_FLUSH_FUA | REQ_META |
205 								REQ_PRIO;
206 	}
207 	__submit_merged_bio(io);
208 out:
209 	up_write(&io->io_rwsem);
210 }
211 
212 void f2fs_submit_merged_bio(struct f2fs_sb_info *sbi, enum page_type type,
213 									int rw)
214 {
215 	__f2fs_submit_merged_bio(sbi, NULL, NULL, 0, type, rw);
216 }
217 
218 void f2fs_submit_merged_bio_cond(struct f2fs_sb_info *sbi,
219 				struct inode *inode, struct page *page,
220 				nid_t ino, enum page_type type, int rw)
221 {
222 	if (has_merged_page(sbi, inode, page, ino, type))
223 		__f2fs_submit_merged_bio(sbi, inode, page, ino, type, rw);
224 }
225 
226 void f2fs_flush_merged_bios(struct f2fs_sb_info *sbi)
227 {
228 	f2fs_submit_merged_bio(sbi, DATA, WRITE);
229 	f2fs_submit_merged_bio(sbi, NODE, WRITE);
230 	f2fs_submit_merged_bio(sbi, META, WRITE);
231 }
232 
233 /*
234  * Fill the locked page with data located in the block address.
235  * Return unlocked page.
236  */
237 int f2fs_submit_page_bio(struct f2fs_io_info *fio)
238 {
239 	struct bio *bio;
240 	struct page *page = fio->encrypted_page ?
241 			fio->encrypted_page : fio->page;
242 
243 	trace_f2fs_submit_page_bio(page, fio);
244 	f2fs_trace_ios(fio, 0);
245 
246 	/* Allocate a new bio */
247 	bio = __bio_alloc(fio->sbi, fio->new_blkaddr, 1, is_read_io(fio->op));
248 
249 	if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE) {
250 		bio_put(bio);
251 		return -EFAULT;
252 	}
253 	bio_set_op_attrs(bio, fio->op, fio->op_flags);
254 
255 	__submit_bio(fio->sbi, bio, fio->type);
256 	return 0;
257 }
258 
259 void f2fs_submit_page_mbio(struct f2fs_io_info *fio)
260 {
261 	struct f2fs_sb_info *sbi = fio->sbi;
262 	enum page_type btype = PAGE_TYPE_OF_BIO(fio->type);
263 	struct f2fs_bio_info *io;
264 	bool is_read = is_read_io(fio->op);
265 	struct page *bio_page;
266 
267 	io = is_read ? &sbi->read_io : &sbi->write_io[btype];
268 
269 	if (fio->old_blkaddr != NEW_ADDR)
270 		verify_block_addr(sbi, fio->old_blkaddr);
271 	verify_block_addr(sbi, fio->new_blkaddr);
272 
273 	down_write(&io->io_rwsem);
274 
275 	if (io->bio && (io->last_block_in_bio != fio->new_blkaddr - 1 ||
276 	    (io->fio.op != fio->op || io->fio.op_flags != fio->op_flags)))
277 		__submit_merged_bio(io);
278 alloc_new:
279 	if (io->bio == NULL) {
280 		int bio_blocks = MAX_BIO_BLOCKS(sbi);
281 
282 		io->bio = __bio_alloc(sbi, fio->new_blkaddr,
283 						bio_blocks, is_read);
284 		io->fio = *fio;
285 	}
286 
287 	bio_page = fio->encrypted_page ? fio->encrypted_page : fio->page;
288 
289 	if (bio_add_page(io->bio, bio_page, PAGE_SIZE, 0) <
290 							PAGE_SIZE) {
291 		__submit_merged_bio(io);
292 		goto alloc_new;
293 	}
294 
295 	io->last_block_in_bio = fio->new_blkaddr;
296 	f2fs_trace_ios(fio, 0);
297 
298 	up_write(&io->io_rwsem);
299 	trace_f2fs_submit_page_mbio(fio->page, fio);
300 }
301 
302 static void __set_data_blkaddr(struct dnode_of_data *dn)
303 {
304 	struct f2fs_node *rn = F2FS_NODE(dn->node_page);
305 	__le32 *addr_array;
306 
307 	/* Get physical address of data block */
308 	addr_array = blkaddr_in_node(rn);
309 	addr_array[dn->ofs_in_node] = cpu_to_le32(dn->data_blkaddr);
310 }
311 
312 /*
313  * Lock ordering for the change of data block address:
314  * ->data_page
315  *  ->node_page
316  *    update block addresses in the node page
317  */
318 void set_data_blkaddr(struct dnode_of_data *dn)
319 {
320 	f2fs_wait_on_page_writeback(dn->node_page, NODE, true);
321 	__set_data_blkaddr(dn);
322 	if (set_page_dirty(dn->node_page))
323 		dn->node_changed = true;
324 }
325 
326 void f2fs_update_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr)
327 {
328 	dn->data_blkaddr = blkaddr;
329 	set_data_blkaddr(dn);
330 	f2fs_update_extent_cache(dn);
331 }
332 
333 /* dn->ofs_in_node will be returned with up-to-date last block pointer */
334 int reserve_new_blocks(struct dnode_of_data *dn, blkcnt_t count)
335 {
336 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
337 
338 	if (!count)
339 		return 0;
340 
341 	if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
342 		return -EPERM;
343 	if (unlikely(!inc_valid_block_count(sbi, dn->inode, &count)))
344 		return -ENOSPC;
345 
346 	trace_f2fs_reserve_new_blocks(dn->inode, dn->nid,
347 						dn->ofs_in_node, count);
348 
349 	f2fs_wait_on_page_writeback(dn->node_page, NODE, true);
350 
351 	for (; count > 0; dn->ofs_in_node++) {
352 		block_t blkaddr =
353 			datablock_addr(dn->node_page, dn->ofs_in_node);
354 		if (blkaddr == NULL_ADDR) {
355 			dn->data_blkaddr = NEW_ADDR;
356 			__set_data_blkaddr(dn);
357 			count--;
358 		}
359 	}
360 
361 	if (set_page_dirty(dn->node_page))
362 		dn->node_changed = true;
363 	return 0;
364 }
365 
366 /* Should keep dn->ofs_in_node unchanged */
367 int reserve_new_block(struct dnode_of_data *dn)
368 {
369 	unsigned int ofs_in_node = dn->ofs_in_node;
370 	int ret;
371 
372 	ret = reserve_new_blocks(dn, 1);
373 	dn->ofs_in_node = ofs_in_node;
374 	return ret;
375 }
376 
377 int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index)
378 {
379 	bool need_put = dn->inode_page ? false : true;
380 	int err;
381 
382 	err = get_dnode_of_data(dn, index, ALLOC_NODE);
383 	if (err)
384 		return err;
385 
386 	if (dn->data_blkaddr == NULL_ADDR)
387 		err = reserve_new_block(dn);
388 	if (err || need_put)
389 		f2fs_put_dnode(dn);
390 	return err;
391 }
392 
393 int f2fs_get_block(struct dnode_of_data *dn, pgoff_t index)
394 {
395 	struct extent_info ei;
396 	struct inode *inode = dn->inode;
397 
398 	if (f2fs_lookup_extent_cache(inode, index, &ei)) {
399 		dn->data_blkaddr = ei.blk + index - ei.fofs;
400 		return 0;
401 	}
402 
403 	return f2fs_reserve_block(dn, index);
404 }
405 
406 struct page *get_read_data_page(struct inode *inode, pgoff_t index,
407 						int op_flags, bool for_write)
408 {
409 	struct address_space *mapping = inode->i_mapping;
410 	struct dnode_of_data dn;
411 	struct page *page;
412 	struct extent_info ei;
413 	int err;
414 	struct f2fs_io_info fio = {
415 		.sbi = F2FS_I_SB(inode),
416 		.type = DATA,
417 		.op = REQ_OP_READ,
418 		.op_flags = op_flags,
419 		.encrypted_page = NULL,
420 	};
421 
422 	if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode))
423 		return read_mapping_page(mapping, index, NULL);
424 
425 	page = f2fs_grab_cache_page(mapping, index, for_write);
426 	if (!page)
427 		return ERR_PTR(-ENOMEM);
428 
429 	if (f2fs_lookup_extent_cache(inode, index, &ei)) {
430 		dn.data_blkaddr = ei.blk + index - ei.fofs;
431 		goto got_it;
432 	}
433 
434 	set_new_dnode(&dn, inode, NULL, NULL, 0);
435 	err = get_dnode_of_data(&dn, index, LOOKUP_NODE);
436 	if (err)
437 		goto put_err;
438 	f2fs_put_dnode(&dn);
439 
440 	if (unlikely(dn.data_blkaddr == NULL_ADDR)) {
441 		err = -ENOENT;
442 		goto put_err;
443 	}
444 got_it:
445 	if (PageUptodate(page)) {
446 		unlock_page(page);
447 		return page;
448 	}
449 
450 	/*
451 	 * A new dentry page is allocated but not able to be written, since its
452 	 * new inode page couldn't be allocated due to -ENOSPC.
453 	 * In such the case, its blkaddr can be remained as NEW_ADDR.
454 	 * see, f2fs_add_link -> get_new_data_page -> init_inode_metadata.
455 	 */
456 	if (dn.data_blkaddr == NEW_ADDR) {
457 		zero_user_segment(page, 0, PAGE_SIZE);
458 		if (!PageUptodate(page))
459 			SetPageUptodate(page);
460 		unlock_page(page);
461 		return page;
462 	}
463 
464 	fio.new_blkaddr = fio.old_blkaddr = dn.data_blkaddr;
465 	fio.page = page;
466 	err = f2fs_submit_page_bio(&fio);
467 	if (err)
468 		goto put_err;
469 	return page;
470 
471 put_err:
472 	f2fs_put_page(page, 1);
473 	return ERR_PTR(err);
474 }
475 
476 struct page *find_data_page(struct inode *inode, pgoff_t index)
477 {
478 	struct address_space *mapping = inode->i_mapping;
479 	struct page *page;
480 
481 	page = find_get_page(mapping, index);
482 	if (page && PageUptodate(page))
483 		return page;
484 	f2fs_put_page(page, 0);
485 
486 	page = get_read_data_page(inode, index, READ_SYNC, false);
487 	if (IS_ERR(page))
488 		return page;
489 
490 	if (PageUptodate(page))
491 		return page;
492 
493 	wait_on_page_locked(page);
494 	if (unlikely(!PageUptodate(page))) {
495 		f2fs_put_page(page, 0);
496 		return ERR_PTR(-EIO);
497 	}
498 	return page;
499 }
500 
501 /*
502  * If it tries to access a hole, return an error.
503  * Because, the callers, functions in dir.c and GC, should be able to know
504  * whether this page exists or not.
505  */
506 struct page *get_lock_data_page(struct inode *inode, pgoff_t index,
507 							bool for_write)
508 {
509 	struct address_space *mapping = inode->i_mapping;
510 	struct page *page;
511 repeat:
512 	page = get_read_data_page(inode, index, READ_SYNC, for_write);
513 	if (IS_ERR(page))
514 		return page;
515 
516 	/* wait for read completion */
517 	lock_page(page);
518 	if (unlikely(page->mapping != mapping)) {
519 		f2fs_put_page(page, 1);
520 		goto repeat;
521 	}
522 	if (unlikely(!PageUptodate(page))) {
523 		f2fs_put_page(page, 1);
524 		return ERR_PTR(-EIO);
525 	}
526 	return page;
527 }
528 
529 /*
530  * Caller ensures that this data page is never allocated.
531  * A new zero-filled data page is allocated in the page cache.
532  *
533  * Also, caller should grab and release a rwsem by calling f2fs_lock_op() and
534  * f2fs_unlock_op().
535  * Note that, ipage is set only by make_empty_dir, and if any error occur,
536  * ipage should be released by this function.
537  */
538 struct page *get_new_data_page(struct inode *inode,
539 		struct page *ipage, pgoff_t index, bool new_i_size)
540 {
541 	struct address_space *mapping = inode->i_mapping;
542 	struct page *page;
543 	struct dnode_of_data dn;
544 	int err;
545 
546 	page = f2fs_grab_cache_page(mapping, index, true);
547 	if (!page) {
548 		/*
549 		 * before exiting, we should make sure ipage will be released
550 		 * if any error occur.
551 		 */
552 		f2fs_put_page(ipage, 1);
553 		return ERR_PTR(-ENOMEM);
554 	}
555 
556 	set_new_dnode(&dn, inode, ipage, NULL, 0);
557 	err = f2fs_reserve_block(&dn, index);
558 	if (err) {
559 		f2fs_put_page(page, 1);
560 		return ERR_PTR(err);
561 	}
562 	if (!ipage)
563 		f2fs_put_dnode(&dn);
564 
565 	if (PageUptodate(page))
566 		goto got_it;
567 
568 	if (dn.data_blkaddr == NEW_ADDR) {
569 		zero_user_segment(page, 0, PAGE_SIZE);
570 		if (!PageUptodate(page))
571 			SetPageUptodate(page);
572 	} else {
573 		f2fs_put_page(page, 1);
574 
575 		/* if ipage exists, blkaddr should be NEW_ADDR */
576 		f2fs_bug_on(F2FS_I_SB(inode), ipage);
577 		page = get_lock_data_page(inode, index, true);
578 		if (IS_ERR(page))
579 			return page;
580 	}
581 got_it:
582 	if (new_i_size && i_size_read(inode) <
583 				((loff_t)(index + 1) << PAGE_SHIFT))
584 		f2fs_i_size_write(inode, ((loff_t)(index + 1) << PAGE_SHIFT));
585 	return page;
586 }
587 
588 static int __allocate_data_block(struct dnode_of_data *dn)
589 {
590 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
591 	struct f2fs_summary sum;
592 	struct node_info ni;
593 	int seg = CURSEG_WARM_DATA;
594 	pgoff_t fofs;
595 	blkcnt_t count = 1;
596 
597 	if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
598 		return -EPERM;
599 
600 	dn->data_blkaddr = datablock_addr(dn->node_page, dn->ofs_in_node);
601 	if (dn->data_blkaddr == NEW_ADDR)
602 		goto alloc;
603 
604 	if (unlikely(!inc_valid_block_count(sbi, dn->inode, &count)))
605 		return -ENOSPC;
606 
607 alloc:
608 	get_node_info(sbi, dn->nid, &ni);
609 	set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
610 
611 	if (dn->ofs_in_node == 0 && dn->inode_page == dn->node_page)
612 		seg = CURSEG_DIRECT_IO;
613 
614 	allocate_data_block(sbi, NULL, dn->data_blkaddr, &dn->data_blkaddr,
615 								&sum, seg);
616 	set_data_blkaddr(dn);
617 
618 	/* update i_size */
619 	fofs = start_bidx_of_node(ofs_of_node(dn->node_page), dn->inode) +
620 							dn->ofs_in_node;
621 	if (i_size_read(dn->inode) < ((loff_t)(fofs + 1) << PAGE_SHIFT))
622 		f2fs_i_size_write(dn->inode,
623 				((loff_t)(fofs + 1) << PAGE_SHIFT));
624 	return 0;
625 }
626 
627 ssize_t f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *from)
628 {
629 	struct inode *inode = file_inode(iocb->ki_filp);
630 	struct f2fs_map_blocks map;
631 	ssize_t ret = 0;
632 
633 	map.m_lblk = F2FS_BLK_ALIGN(iocb->ki_pos);
634 	map.m_len = F2FS_BYTES_TO_BLK(iocb->ki_pos + iov_iter_count(from));
635 	if (map.m_len > map.m_lblk)
636 		map.m_len -= map.m_lblk;
637 	else
638 		map.m_len = 0;
639 
640 	map.m_next_pgofs = NULL;
641 
642 	if (iocb->ki_flags & IOCB_DIRECT) {
643 		ret = f2fs_convert_inline_inode(inode);
644 		if (ret)
645 			return ret;
646 		return f2fs_map_blocks(inode, &map, 1, F2FS_GET_BLOCK_PRE_DIO);
647 	}
648 	if (iocb->ki_pos + iov_iter_count(from) > MAX_INLINE_DATA) {
649 		ret = f2fs_convert_inline_inode(inode);
650 		if (ret)
651 			return ret;
652 	}
653 	if (!f2fs_has_inline_data(inode))
654 		return f2fs_map_blocks(inode, &map, 1, F2FS_GET_BLOCK_PRE_AIO);
655 	return ret;
656 }
657 
658 /*
659  * f2fs_map_blocks() now supported readahead/bmap/rw direct_IO with
660  * f2fs_map_blocks structure.
661  * If original data blocks are allocated, then give them to blockdev.
662  * Otherwise,
663  *     a. preallocate requested block addresses
664  *     b. do not use extent cache for better performance
665  *     c. give the block addresses to blockdev
666  */
667 int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map,
668 						int create, int flag)
669 {
670 	unsigned int maxblocks = map->m_len;
671 	struct dnode_of_data dn;
672 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
673 	int mode = create ? ALLOC_NODE : LOOKUP_NODE;
674 	pgoff_t pgofs, end_offset, end;
675 	int err = 0, ofs = 1;
676 	unsigned int ofs_in_node, last_ofs_in_node;
677 	blkcnt_t prealloc;
678 	struct extent_info ei;
679 	bool allocated = false;
680 	block_t blkaddr;
681 
682 	if (!maxblocks)
683 		return 0;
684 
685 	map->m_len = 0;
686 	map->m_flags = 0;
687 
688 	/* it only supports block size == page size */
689 	pgofs =	(pgoff_t)map->m_lblk;
690 	end = pgofs + maxblocks;
691 
692 	if (!create && f2fs_lookup_extent_cache(inode, pgofs, &ei)) {
693 		map->m_pblk = ei.blk + pgofs - ei.fofs;
694 		map->m_len = min((pgoff_t)maxblocks, ei.fofs + ei.len - pgofs);
695 		map->m_flags = F2FS_MAP_MAPPED;
696 		goto out;
697 	}
698 
699 next_dnode:
700 	if (create)
701 		f2fs_lock_op(sbi);
702 
703 	/* When reading holes, we need its node page */
704 	set_new_dnode(&dn, inode, NULL, NULL, 0);
705 	err = get_dnode_of_data(&dn, pgofs, mode);
706 	if (err) {
707 		if (flag == F2FS_GET_BLOCK_BMAP)
708 			map->m_pblk = 0;
709 		if (err == -ENOENT) {
710 			err = 0;
711 			if (map->m_next_pgofs)
712 				*map->m_next_pgofs =
713 					get_next_page_offset(&dn, pgofs);
714 		}
715 		goto unlock_out;
716 	}
717 
718 	prealloc = 0;
719 	ofs_in_node = dn.ofs_in_node;
720 	end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
721 
722 next_block:
723 	blkaddr = datablock_addr(dn.node_page, dn.ofs_in_node);
724 
725 	if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR) {
726 		if (create) {
727 			if (unlikely(f2fs_cp_error(sbi))) {
728 				err = -EIO;
729 				goto sync_out;
730 			}
731 			if (flag == F2FS_GET_BLOCK_PRE_AIO) {
732 				if (blkaddr == NULL_ADDR) {
733 					prealloc++;
734 					last_ofs_in_node = dn.ofs_in_node;
735 				}
736 			} else {
737 				err = __allocate_data_block(&dn);
738 				if (!err) {
739 					set_inode_flag(inode, FI_APPEND_WRITE);
740 					allocated = true;
741 				}
742 			}
743 			if (err)
744 				goto sync_out;
745 			map->m_flags = F2FS_MAP_NEW;
746 			blkaddr = dn.data_blkaddr;
747 		} else {
748 			if (flag == F2FS_GET_BLOCK_BMAP) {
749 				map->m_pblk = 0;
750 				goto sync_out;
751 			}
752 			if (flag == F2FS_GET_BLOCK_FIEMAP &&
753 						blkaddr == NULL_ADDR) {
754 				if (map->m_next_pgofs)
755 					*map->m_next_pgofs = pgofs + 1;
756 			}
757 			if (flag != F2FS_GET_BLOCK_FIEMAP ||
758 						blkaddr != NEW_ADDR)
759 				goto sync_out;
760 		}
761 	}
762 
763 	if (flag == F2FS_GET_BLOCK_PRE_AIO)
764 		goto skip;
765 
766 	if (map->m_len == 0) {
767 		/* preallocated unwritten block should be mapped for fiemap. */
768 		if (blkaddr == NEW_ADDR)
769 			map->m_flags |= F2FS_MAP_UNWRITTEN;
770 		map->m_flags |= F2FS_MAP_MAPPED;
771 
772 		map->m_pblk = blkaddr;
773 		map->m_len = 1;
774 	} else if ((map->m_pblk != NEW_ADDR &&
775 			blkaddr == (map->m_pblk + ofs)) ||
776 			(map->m_pblk == NEW_ADDR && blkaddr == NEW_ADDR) ||
777 			flag == F2FS_GET_BLOCK_PRE_DIO) {
778 		ofs++;
779 		map->m_len++;
780 	} else {
781 		goto sync_out;
782 	}
783 
784 skip:
785 	dn.ofs_in_node++;
786 	pgofs++;
787 
788 	/* preallocate blocks in batch for one dnode page */
789 	if (flag == F2FS_GET_BLOCK_PRE_AIO &&
790 			(pgofs == end || dn.ofs_in_node == end_offset)) {
791 
792 		dn.ofs_in_node = ofs_in_node;
793 		err = reserve_new_blocks(&dn, prealloc);
794 		if (err)
795 			goto sync_out;
796 		allocated = dn.node_changed;
797 
798 		map->m_len += dn.ofs_in_node - ofs_in_node;
799 		if (prealloc && dn.ofs_in_node != last_ofs_in_node + 1) {
800 			err = -ENOSPC;
801 			goto sync_out;
802 		}
803 		dn.ofs_in_node = end_offset;
804 	}
805 
806 	if (pgofs >= end)
807 		goto sync_out;
808 	else if (dn.ofs_in_node < end_offset)
809 		goto next_block;
810 
811 	f2fs_put_dnode(&dn);
812 
813 	if (create) {
814 		f2fs_unlock_op(sbi);
815 		f2fs_balance_fs(sbi, allocated);
816 	}
817 	allocated = false;
818 	goto next_dnode;
819 
820 sync_out:
821 	f2fs_put_dnode(&dn);
822 unlock_out:
823 	if (create) {
824 		f2fs_unlock_op(sbi);
825 		f2fs_balance_fs(sbi, allocated);
826 	}
827 out:
828 	trace_f2fs_map_blocks(inode, map, err);
829 	return err;
830 }
831 
832 static int __get_data_block(struct inode *inode, sector_t iblock,
833 			struct buffer_head *bh, int create, int flag,
834 			pgoff_t *next_pgofs)
835 {
836 	struct f2fs_map_blocks map;
837 	int ret;
838 
839 	map.m_lblk = iblock;
840 	map.m_len = bh->b_size >> inode->i_blkbits;
841 	map.m_next_pgofs = next_pgofs;
842 
843 	ret = f2fs_map_blocks(inode, &map, create, flag);
844 	if (!ret) {
845 		map_bh(bh, inode->i_sb, map.m_pblk);
846 		bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;
847 		bh->b_size = map.m_len << inode->i_blkbits;
848 	}
849 	return ret;
850 }
851 
852 static int get_data_block(struct inode *inode, sector_t iblock,
853 			struct buffer_head *bh_result, int create, int flag,
854 			pgoff_t *next_pgofs)
855 {
856 	return __get_data_block(inode, iblock, bh_result, create,
857 							flag, next_pgofs);
858 }
859 
860 static int get_data_block_dio(struct inode *inode, sector_t iblock,
861 			struct buffer_head *bh_result, int create)
862 {
863 	return __get_data_block(inode, iblock, bh_result, create,
864 						F2FS_GET_BLOCK_DIO, NULL);
865 }
866 
867 static int get_data_block_bmap(struct inode *inode, sector_t iblock,
868 			struct buffer_head *bh_result, int create)
869 {
870 	/* Block number less than F2FS MAX BLOCKS */
871 	if (unlikely(iblock >= F2FS_I_SB(inode)->max_file_blocks))
872 		return -EFBIG;
873 
874 	return __get_data_block(inode, iblock, bh_result, create,
875 						F2FS_GET_BLOCK_BMAP, NULL);
876 }
877 
878 static inline sector_t logical_to_blk(struct inode *inode, loff_t offset)
879 {
880 	return (offset >> inode->i_blkbits);
881 }
882 
883 static inline loff_t blk_to_logical(struct inode *inode, sector_t blk)
884 {
885 	return (blk << inode->i_blkbits);
886 }
887 
888 int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
889 		u64 start, u64 len)
890 {
891 	struct buffer_head map_bh;
892 	sector_t start_blk, last_blk;
893 	pgoff_t next_pgofs;
894 	loff_t isize;
895 	u64 logical = 0, phys = 0, size = 0;
896 	u32 flags = 0;
897 	int ret = 0;
898 
899 	ret = fiemap_check_flags(fieinfo, FIEMAP_FLAG_SYNC);
900 	if (ret)
901 		return ret;
902 
903 	if (f2fs_has_inline_data(inode)) {
904 		ret = f2fs_inline_data_fiemap(inode, fieinfo, start, len);
905 		if (ret != -EAGAIN)
906 			return ret;
907 	}
908 
909 	inode_lock(inode);
910 
911 	isize = i_size_read(inode);
912 	if (start >= isize)
913 		goto out;
914 
915 	if (start + len > isize)
916 		len = isize - start;
917 
918 	if (logical_to_blk(inode, len) == 0)
919 		len = blk_to_logical(inode, 1);
920 
921 	start_blk = logical_to_blk(inode, start);
922 	last_blk = logical_to_blk(inode, start + len - 1);
923 
924 next:
925 	memset(&map_bh, 0, sizeof(struct buffer_head));
926 	map_bh.b_size = len;
927 
928 	ret = get_data_block(inode, start_blk, &map_bh, 0,
929 					F2FS_GET_BLOCK_FIEMAP, &next_pgofs);
930 	if (ret)
931 		goto out;
932 
933 	/* HOLE */
934 	if (!buffer_mapped(&map_bh)) {
935 		start_blk = next_pgofs;
936 		/* Go through holes util pass the EOF */
937 		if (blk_to_logical(inode, start_blk) < isize)
938 			goto prep_next;
939 		/* Found a hole beyond isize means no more extents.
940 		 * Note that the premise is that filesystems don't
941 		 * punch holes beyond isize and keep size unchanged.
942 		 */
943 		flags |= FIEMAP_EXTENT_LAST;
944 	}
945 
946 	if (size) {
947 		if (f2fs_encrypted_inode(inode))
948 			flags |= FIEMAP_EXTENT_DATA_ENCRYPTED;
949 
950 		ret = fiemap_fill_next_extent(fieinfo, logical,
951 				phys, size, flags);
952 	}
953 
954 	if (start_blk > last_blk || ret)
955 		goto out;
956 
957 	logical = blk_to_logical(inode, start_blk);
958 	phys = blk_to_logical(inode, map_bh.b_blocknr);
959 	size = map_bh.b_size;
960 	flags = 0;
961 	if (buffer_unwritten(&map_bh))
962 		flags = FIEMAP_EXTENT_UNWRITTEN;
963 
964 	start_blk += logical_to_blk(inode, size);
965 
966 prep_next:
967 	cond_resched();
968 	if (fatal_signal_pending(current))
969 		ret = -EINTR;
970 	else
971 		goto next;
972 out:
973 	if (ret == 1)
974 		ret = 0;
975 
976 	inode_unlock(inode);
977 	return ret;
978 }
979 
980 static struct bio *f2fs_grab_bio(struct inode *inode, block_t blkaddr,
981 				 unsigned nr_pages)
982 {
983 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
984 	struct fscrypt_ctx *ctx = NULL;
985 	struct block_device *bdev = sbi->sb->s_bdev;
986 	struct bio *bio;
987 
988 	if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode)) {
989 		ctx = fscrypt_get_ctx(inode, GFP_NOFS);
990 		if (IS_ERR(ctx))
991 			return ERR_CAST(ctx);
992 
993 		/* wait the page to be moved by cleaning */
994 		f2fs_wait_on_encrypted_page_writeback(sbi, blkaddr);
995 	}
996 
997 	bio = bio_alloc(GFP_KERNEL, min_t(int, nr_pages, BIO_MAX_PAGES));
998 	if (!bio) {
999 		if (ctx)
1000 			fscrypt_release_ctx(ctx);
1001 		return ERR_PTR(-ENOMEM);
1002 	}
1003 	bio->bi_bdev = bdev;
1004 	bio->bi_iter.bi_sector = SECTOR_FROM_BLOCK(blkaddr);
1005 	bio->bi_end_io = f2fs_read_end_io;
1006 	bio->bi_private = ctx;
1007 
1008 	return bio;
1009 }
1010 
1011 /*
1012  * This function was originally taken from fs/mpage.c, and customized for f2fs.
1013  * Major change was from block_size == page_size in f2fs by default.
1014  */
1015 static int f2fs_mpage_readpages(struct address_space *mapping,
1016 			struct list_head *pages, struct page *page,
1017 			unsigned nr_pages)
1018 {
1019 	struct bio *bio = NULL;
1020 	unsigned page_idx;
1021 	sector_t last_block_in_bio = 0;
1022 	struct inode *inode = mapping->host;
1023 	const unsigned blkbits = inode->i_blkbits;
1024 	const unsigned blocksize = 1 << blkbits;
1025 	sector_t block_in_file;
1026 	sector_t last_block;
1027 	sector_t last_block_in_file;
1028 	sector_t block_nr;
1029 	struct f2fs_map_blocks map;
1030 
1031 	map.m_pblk = 0;
1032 	map.m_lblk = 0;
1033 	map.m_len = 0;
1034 	map.m_flags = 0;
1035 	map.m_next_pgofs = NULL;
1036 
1037 	for (page_idx = 0; nr_pages; page_idx++, nr_pages--) {
1038 
1039 		prefetchw(&page->flags);
1040 		if (pages) {
1041 			page = list_entry(pages->prev, struct page, lru);
1042 			list_del(&page->lru);
1043 			if (add_to_page_cache_lru(page, mapping,
1044 						  page->index,
1045 						  readahead_gfp_mask(mapping)))
1046 				goto next_page;
1047 		}
1048 
1049 		block_in_file = (sector_t)page->index;
1050 		last_block = block_in_file + nr_pages;
1051 		last_block_in_file = (i_size_read(inode) + blocksize - 1) >>
1052 								blkbits;
1053 		if (last_block > last_block_in_file)
1054 			last_block = last_block_in_file;
1055 
1056 		/*
1057 		 * Map blocks using the previous result first.
1058 		 */
1059 		if ((map.m_flags & F2FS_MAP_MAPPED) &&
1060 				block_in_file > map.m_lblk &&
1061 				block_in_file < (map.m_lblk + map.m_len))
1062 			goto got_it;
1063 
1064 		/*
1065 		 * Then do more f2fs_map_blocks() calls until we are
1066 		 * done with this page.
1067 		 */
1068 		map.m_flags = 0;
1069 
1070 		if (block_in_file < last_block) {
1071 			map.m_lblk = block_in_file;
1072 			map.m_len = last_block - block_in_file;
1073 
1074 			if (f2fs_map_blocks(inode, &map, 0,
1075 						F2FS_GET_BLOCK_READ))
1076 				goto set_error_page;
1077 		}
1078 got_it:
1079 		if ((map.m_flags & F2FS_MAP_MAPPED)) {
1080 			block_nr = map.m_pblk + block_in_file - map.m_lblk;
1081 			SetPageMappedToDisk(page);
1082 
1083 			if (!PageUptodate(page) && !cleancache_get_page(page)) {
1084 				SetPageUptodate(page);
1085 				goto confused;
1086 			}
1087 		} else {
1088 			zero_user_segment(page, 0, PAGE_SIZE);
1089 			if (!PageUptodate(page))
1090 				SetPageUptodate(page);
1091 			unlock_page(page);
1092 			goto next_page;
1093 		}
1094 
1095 		/*
1096 		 * This page will go to BIO.  Do we need to send this
1097 		 * BIO off first?
1098 		 */
1099 		if (bio && (last_block_in_bio != block_nr - 1)) {
1100 submit_and_realloc:
1101 			__submit_bio(F2FS_I_SB(inode), bio, DATA);
1102 			bio = NULL;
1103 		}
1104 		if (bio == NULL) {
1105 			bio = f2fs_grab_bio(inode, block_nr, nr_pages);
1106 			if (IS_ERR(bio)) {
1107 				bio = NULL;
1108 				goto set_error_page;
1109 			}
1110 			bio_set_op_attrs(bio, REQ_OP_READ, 0);
1111 		}
1112 
1113 		if (bio_add_page(bio, page, blocksize, 0) < blocksize)
1114 			goto submit_and_realloc;
1115 
1116 		last_block_in_bio = block_nr;
1117 		goto next_page;
1118 set_error_page:
1119 		SetPageError(page);
1120 		zero_user_segment(page, 0, PAGE_SIZE);
1121 		unlock_page(page);
1122 		goto next_page;
1123 confused:
1124 		if (bio) {
1125 			__submit_bio(F2FS_I_SB(inode), bio, DATA);
1126 			bio = NULL;
1127 		}
1128 		unlock_page(page);
1129 next_page:
1130 		if (pages)
1131 			put_page(page);
1132 	}
1133 	BUG_ON(pages && !list_empty(pages));
1134 	if (bio)
1135 		__submit_bio(F2FS_I_SB(inode), bio, DATA);
1136 	return 0;
1137 }
1138 
1139 static int f2fs_read_data_page(struct file *file, struct page *page)
1140 {
1141 	struct inode *inode = page->mapping->host;
1142 	int ret = -EAGAIN;
1143 
1144 	trace_f2fs_readpage(page, DATA);
1145 
1146 	/* If the file has inline data, try to read it directly */
1147 	if (f2fs_has_inline_data(inode))
1148 		ret = f2fs_read_inline_data(inode, page);
1149 	if (ret == -EAGAIN)
1150 		ret = f2fs_mpage_readpages(page->mapping, NULL, page, 1);
1151 	return ret;
1152 }
1153 
1154 static int f2fs_read_data_pages(struct file *file,
1155 			struct address_space *mapping,
1156 			struct list_head *pages, unsigned nr_pages)
1157 {
1158 	struct inode *inode = file->f_mapping->host;
1159 	struct page *page = list_entry(pages->prev, struct page, lru);
1160 
1161 	trace_f2fs_readpages(inode, page, nr_pages);
1162 
1163 	/* If the file has inline data, skip readpages */
1164 	if (f2fs_has_inline_data(inode))
1165 		return 0;
1166 
1167 	return f2fs_mpage_readpages(mapping, pages, NULL, nr_pages);
1168 }
1169 
1170 int do_write_data_page(struct f2fs_io_info *fio)
1171 {
1172 	struct page *page = fio->page;
1173 	struct inode *inode = page->mapping->host;
1174 	struct dnode_of_data dn;
1175 	int err = 0;
1176 
1177 	set_new_dnode(&dn, inode, NULL, NULL, 0);
1178 	err = get_dnode_of_data(&dn, page->index, LOOKUP_NODE);
1179 	if (err)
1180 		return err;
1181 
1182 	fio->old_blkaddr = dn.data_blkaddr;
1183 
1184 	/* This page is already truncated */
1185 	if (fio->old_blkaddr == NULL_ADDR) {
1186 		ClearPageUptodate(page);
1187 		goto out_writepage;
1188 	}
1189 
1190 	if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode)) {
1191 		gfp_t gfp_flags = GFP_NOFS;
1192 
1193 		/* wait for GCed encrypted page writeback */
1194 		f2fs_wait_on_encrypted_page_writeback(F2FS_I_SB(inode),
1195 							fio->old_blkaddr);
1196 retry_encrypt:
1197 		fio->encrypted_page = fscrypt_encrypt_page(inode, fio->page,
1198 								gfp_flags);
1199 		if (IS_ERR(fio->encrypted_page)) {
1200 			err = PTR_ERR(fio->encrypted_page);
1201 			if (err == -ENOMEM) {
1202 				/* flush pending ios and wait for a while */
1203 				f2fs_flush_merged_bios(F2FS_I_SB(inode));
1204 				congestion_wait(BLK_RW_ASYNC, HZ/50);
1205 				gfp_flags |= __GFP_NOFAIL;
1206 				err = 0;
1207 				goto retry_encrypt;
1208 			}
1209 			goto out_writepage;
1210 		}
1211 	}
1212 
1213 	set_page_writeback(page);
1214 
1215 	/*
1216 	 * If current allocation needs SSR,
1217 	 * it had better in-place writes for updated data.
1218 	 */
1219 	if (unlikely(fio->old_blkaddr != NEW_ADDR &&
1220 			!is_cold_data(page) &&
1221 			!IS_ATOMIC_WRITTEN_PAGE(page) &&
1222 			need_inplace_update(inode))) {
1223 		rewrite_data_page(fio);
1224 		set_inode_flag(inode, FI_UPDATE_WRITE);
1225 		trace_f2fs_do_write_data_page(page, IPU);
1226 	} else {
1227 		write_data_page(&dn, fio);
1228 		trace_f2fs_do_write_data_page(page, OPU);
1229 		set_inode_flag(inode, FI_APPEND_WRITE);
1230 		if (page->index == 0)
1231 			set_inode_flag(inode, FI_FIRST_BLOCK_WRITTEN);
1232 	}
1233 out_writepage:
1234 	f2fs_put_dnode(&dn);
1235 	return err;
1236 }
1237 
1238 static int f2fs_write_data_page(struct page *page,
1239 					struct writeback_control *wbc)
1240 {
1241 	struct inode *inode = page->mapping->host;
1242 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1243 	loff_t i_size = i_size_read(inode);
1244 	const pgoff_t end_index = ((unsigned long long) i_size)
1245 							>> PAGE_SHIFT;
1246 	loff_t psize = (page->index + 1) << PAGE_SHIFT;
1247 	unsigned offset = 0;
1248 	bool need_balance_fs = false;
1249 	int err = 0;
1250 	struct f2fs_io_info fio = {
1251 		.sbi = sbi,
1252 		.type = DATA,
1253 		.op = REQ_OP_WRITE,
1254 		.op_flags = (wbc->sync_mode == WB_SYNC_ALL) ? WRITE_SYNC : 0,
1255 		.page = page,
1256 		.encrypted_page = NULL,
1257 	};
1258 
1259 	trace_f2fs_writepage(page, DATA);
1260 
1261 	if (page->index < end_index)
1262 		goto write;
1263 
1264 	/*
1265 	 * If the offset is out-of-range of file size,
1266 	 * this page does not have to be written to disk.
1267 	 */
1268 	offset = i_size & (PAGE_SIZE - 1);
1269 	if ((page->index >= end_index + 1) || !offset)
1270 		goto out;
1271 
1272 	zero_user_segment(page, offset, PAGE_SIZE);
1273 write:
1274 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
1275 		goto redirty_out;
1276 	if (f2fs_is_drop_cache(inode))
1277 		goto out;
1278 	/* we should not write 0'th page having journal header */
1279 	if (f2fs_is_volatile_file(inode) && (!page->index ||
1280 			(!wbc->for_reclaim &&
1281 			available_free_memory(sbi, BASE_CHECK))))
1282 		goto redirty_out;
1283 
1284 	/* we should bypass data pages to proceed the kworkder jobs */
1285 	if (unlikely(f2fs_cp_error(sbi))) {
1286 		mapping_set_error(page->mapping, -EIO);
1287 		goto out;
1288 	}
1289 
1290 	/* Dentry blocks are controlled by checkpoint */
1291 	if (S_ISDIR(inode->i_mode)) {
1292 		err = do_write_data_page(&fio);
1293 		goto done;
1294 	}
1295 
1296 	if (!wbc->for_reclaim)
1297 		need_balance_fs = true;
1298 	else if (has_not_enough_free_secs(sbi, 0, 0))
1299 		goto redirty_out;
1300 
1301 	err = -EAGAIN;
1302 	f2fs_lock_op(sbi);
1303 	if (f2fs_has_inline_data(inode))
1304 		err = f2fs_write_inline_data(inode, page);
1305 	if (err == -EAGAIN)
1306 		err = do_write_data_page(&fio);
1307 	if (F2FS_I(inode)->last_disk_size < psize)
1308 		F2FS_I(inode)->last_disk_size = psize;
1309 	f2fs_unlock_op(sbi);
1310 done:
1311 	if (err && err != -ENOENT)
1312 		goto redirty_out;
1313 
1314 	clear_cold_data(page);
1315 out:
1316 	inode_dec_dirty_pages(inode);
1317 	if (err)
1318 		ClearPageUptodate(page);
1319 
1320 	if (wbc->for_reclaim) {
1321 		f2fs_submit_merged_bio_cond(sbi, NULL, page, 0, DATA, WRITE);
1322 		remove_dirty_inode(inode);
1323 	}
1324 
1325 	unlock_page(page);
1326 	f2fs_balance_fs(sbi, need_balance_fs);
1327 
1328 	if (unlikely(f2fs_cp_error(sbi)))
1329 		f2fs_submit_merged_bio(sbi, DATA, WRITE);
1330 
1331 	return 0;
1332 
1333 redirty_out:
1334 	redirty_page_for_writepage(wbc, page);
1335 	unlock_page(page);
1336 	return err;
1337 }
1338 
1339 /*
1340  * This function was copied from write_cche_pages from mm/page-writeback.c.
1341  * The major change is making write step of cold data page separately from
1342  * warm/hot data page.
1343  */
1344 static int f2fs_write_cache_pages(struct address_space *mapping,
1345 					struct writeback_control *wbc)
1346 {
1347 	int ret = 0;
1348 	int done = 0;
1349 	struct pagevec pvec;
1350 	int nr_pages;
1351 	pgoff_t uninitialized_var(writeback_index);
1352 	pgoff_t index;
1353 	pgoff_t end;		/* Inclusive */
1354 	pgoff_t done_index;
1355 	int cycled;
1356 	int range_whole = 0;
1357 	int tag;
1358 	int nwritten = 0;
1359 
1360 	pagevec_init(&pvec, 0);
1361 
1362 	if (wbc->range_cyclic) {
1363 		writeback_index = mapping->writeback_index; /* prev offset */
1364 		index = writeback_index;
1365 		if (index == 0)
1366 			cycled = 1;
1367 		else
1368 			cycled = 0;
1369 		end = -1;
1370 	} else {
1371 		index = wbc->range_start >> PAGE_SHIFT;
1372 		end = wbc->range_end >> PAGE_SHIFT;
1373 		if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
1374 			range_whole = 1;
1375 		cycled = 1; /* ignore range_cyclic tests */
1376 	}
1377 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
1378 		tag = PAGECACHE_TAG_TOWRITE;
1379 	else
1380 		tag = PAGECACHE_TAG_DIRTY;
1381 retry:
1382 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
1383 		tag_pages_for_writeback(mapping, index, end);
1384 	done_index = index;
1385 	while (!done && (index <= end)) {
1386 		int i;
1387 
1388 		nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
1389 			      min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1);
1390 		if (nr_pages == 0)
1391 			break;
1392 
1393 		for (i = 0; i < nr_pages; i++) {
1394 			struct page *page = pvec.pages[i];
1395 
1396 			if (page->index > end) {
1397 				done = 1;
1398 				break;
1399 			}
1400 
1401 			done_index = page->index;
1402 
1403 			lock_page(page);
1404 
1405 			if (unlikely(page->mapping != mapping)) {
1406 continue_unlock:
1407 				unlock_page(page);
1408 				continue;
1409 			}
1410 
1411 			if (!PageDirty(page)) {
1412 				/* someone wrote it for us */
1413 				goto continue_unlock;
1414 			}
1415 
1416 			if (PageWriteback(page)) {
1417 				if (wbc->sync_mode != WB_SYNC_NONE)
1418 					f2fs_wait_on_page_writeback(page,
1419 								DATA, true);
1420 				else
1421 					goto continue_unlock;
1422 			}
1423 
1424 			BUG_ON(PageWriteback(page));
1425 			if (!clear_page_dirty_for_io(page))
1426 				goto continue_unlock;
1427 
1428 			ret = mapping->a_ops->writepage(page, wbc);
1429 			if (unlikely(ret)) {
1430 				done_index = page->index + 1;
1431 				done = 1;
1432 				break;
1433 			} else {
1434 				nwritten++;
1435 			}
1436 
1437 			if (--wbc->nr_to_write <= 0 &&
1438 			    wbc->sync_mode == WB_SYNC_NONE) {
1439 				done = 1;
1440 				break;
1441 			}
1442 		}
1443 		pagevec_release(&pvec);
1444 		cond_resched();
1445 	}
1446 
1447 	if (!cycled && !done) {
1448 		cycled = 1;
1449 		index = 0;
1450 		end = writeback_index - 1;
1451 		goto retry;
1452 	}
1453 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1454 		mapping->writeback_index = done_index;
1455 
1456 	if (nwritten)
1457 		f2fs_submit_merged_bio_cond(F2FS_M_SB(mapping), mapping->host,
1458 							NULL, 0, DATA, WRITE);
1459 
1460 	return ret;
1461 }
1462 
1463 static int f2fs_write_data_pages(struct address_space *mapping,
1464 			    struct writeback_control *wbc)
1465 {
1466 	struct inode *inode = mapping->host;
1467 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1468 	struct blk_plug plug;
1469 	int ret;
1470 
1471 	/* deal with chardevs and other special file */
1472 	if (!mapping->a_ops->writepage)
1473 		return 0;
1474 
1475 	/* skip writing if there is no dirty page in this inode */
1476 	if (!get_dirty_pages(inode) && wbc->sync_mode == WB_SYNC_NONE)
1477 		return 0;
1478 
1479 	if (S_ISDIR(inode->i_mode) && wbc->sync_mode == WB_SYNC_NONE &&
1480 			get_dirty_pages(inode) < nr_pages_to_skip(sbi, DATA) &&
1481 			available_free_memory(sbi, DIRTY_DENTS))
1482 		goto skip_write;
1483 
1484 	/* skip writing during file defragment */
1485 	if (is_inode_flag_set(inode, FI_DO_DEFRAG))
1486 		goto skip_write;
1487 
1488 	/* during POR, we don't need to trigger writepage at all. */
1489 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
1490 		goto skip_write;
1491 
1492 	trace_f2fs_writepages(mapping->host, wbc, DATA);
1493 
1494 	blk_start_plug(&plug);
1495 	ret = f2fs_write_cache_pages(mapping, wbc);
1496 	blk_finish_plug(&plug);
1497 	/*
1498 	 * if some pages were truncated, we cannot guarantee its mapping->host
1499 	 * to detect pending bios.
1500 	 */
1501 
1502 	remove_dirty_inode(inode);
1503 	return ret;
1504 
1505 skip_write:
1506 	wbc->pages_skipped += get_dirty_pages(inode);
1507 	trace_f2fs_writepages(mapping->host, wbc, DATA);
1508 	return 0;
1509 }
1510 
1511 static void f2fs_write_failed(struct address_space *mapping, loff_t to)
1512 {
1513 	struct inode *inode = mapping->host;
1514 	loff_t i_size = i_size_read(inode);
1515 
1516 	if (to > i_size) {
1517 		truncate_pagecache(inode, i_size);
1518 		truncate_blocks(inode, i_size, true);
1519 	}
1520 }
1521 
1522 static int prepare_write_begin(struct f2fs_sb_info *sbi,
1523 			struct page *page, loff_t pos, unsigned len,
1524 			block_t *blk_addr, bool *node_changed)
1525 {
1526 	struct inode *inode = page->mapping->host;
1527 	pgoff_t index = page->index;
1528 	struct dnode_of_data dn;
1529 	struct page *ipage;
1530 	bool locked = false;
1531 	struct extent_info ei;
1532 	int err = 0;
1533 
1534 	/*
1535 	 * we already allocated all the blocks, so we don't need to get
1536 	 * the block addresses when there is no need to fill the page.
1537 	 */
1538 	if (!f2fs_has_inline_data(inode) && len == PAGE_SIZE)
1539 		return 0;
1540 
1541 	if (f2fs_has_inline_data(inode) ||
1542 			(pos & PAGE_MASK) >= i_size_read(inode)) {
1543 		f2fs_lock_op(sbi);
1544 		locked = true;
1545 	}
1546 restart:
1547 	/* check inline_data */
1548 	ipage = get_node_page(sbi, inode->i_ino);
1549 	if (IS_ERR(ipage)) {
1550 		err = PTR_ERR(ipage);
1551 		goto unlock_out;
1552 	}
1553 
1554 	set_new_dnode(&dn, inode, ipage, ipage, 0);
1555 
1556 	if (f2fs_has_inline_data(inode)) {
1557 		if (pos + len <= MAX_INLINE_DATA) {
1558 			read_inline_data(page, ipage);
1559 			set_inode_flag(inode, FI_DATA_EXIST);
1560 			if (inode->i_nlink)
1561 				set_inline_node(ipage);
1562 		} else {
1563 			err = f2fs_convert_inline_page(&dn, page);
1564 			if (err)
1565 				goto out;
1566 			if (dn.data_blkaddr == NULL_ADDR)
1567 				err = f2fs_get_block(&dn, index);
1568 		}
1569 	} else if (locked) {
1570 		err = f2fs_get_block(&dn, index);
1571 	} else {
1572 		if (f2fs_lookup_extent_cache(inode, index, &ei)) {
1573 			dn.data_blkaddr = ei.blk + index - ei.fofs;
1574 		} else {
1575 			/* hole case */
1576 			err = get_dnode_of_data(&dn, index, LOOKUP_NODE);
1577 			if (err || dn.data_blkaddr == NULL_ADDR) {
1578 				f2fs_put_dnode(&dn);
1579 				f2fs_lock_op(sbi);
1580 				locked = true;
1581 				goto restart;
1582 			}
1583 		}
1584 	}
1585 
1586 	/* convert_inline_page can make node_changed */
1587 	*blk_addr = dn.data_blkaddr;
1588 	*node_changed = dn.node_changed;
1589 out:
1590 	f2fs_put_dnode(&dn);
1591 unlock_out:
1592 	if (locked)
1593 		f2fs_unlock_op(sbi);
1594 	return err;
1595 }
1596 
1597 static int f2fs_write_begin(struct file *file, struct address_space *mapping,
1598 		loff_t pos, unsigned len, unsigned flags,
1599 		struct page **pagep, void **fsdata)
1600 {
1601 	struct inode *inode = mapping->host;
1602 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1603 	struct page *page = NULL;
1604 	pgoff_t index = ((unsigned long long) pos) >> PAGE_SHIFT;
1605 	bool need_balance = false;
1606 	block_t blkaddr = NULL_ADDR;
1607 	int err = 0;
1608 
1609 	trace_f2fs_write_begin(inode, pos, len, flags);
1610 
1611 	/*
1612 	 * We should check this at this moment to avoid deadlock on inode page
1613 	 * and #0 page. The locking rule for inline_data conversion should be:
1614 	 * lock_page(page #0) -> lock_page(inode_page)
1615 	 */
1616 	if (index != 0) {
1617 		err = f2fs_convert_inline_inode(inode);
1618 		if (err)
1619 			goto fail;
1620 	}
1621 repeat:
1622 	page = grab_cache_page_write_begin(mapping, index, flags);
1623 	if (!page) {
1624 		err = -ENOMEM;
1625 		goto fail;
1626 	}
1627 
1628 	*pagep = page;
1629 
1630 	err = prepare_write_begin(sbi, page, pos, len,
1631 					&blkaddr, &need_balance);
1632 	if (err)
1633 		goto fail;
1634 
1635 	if (need_balance && has_not_enough_free_secs(sbi, 0, 0)) {
1636 		unlock_page(page);
1637 		f2fs_balance_fs(sbi, true);
1638 		lock_page(page);
1639 		if (page->mapping != mapping) {
1640 			/* The page got truncated from under us */
1641 			f2fs_put_page(page, 1);
1642 			goto repeat;
1643 		}
1644 	}
1645 
1646 	f2fs_wait_on_page_writeback(page, DATA, false);
1647 
1648 	/* wait for GCed encrypted page writeback */
1649 	if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode))
1650 		f2fs_wait_on_encrypted_page_writeback(sbi, blkaddr);
1651 
1652 	if (len == PAGE_SIZE || PageUptodate(page))
1653 		return 0;
1654 
1655 	if (blkaddr == NEW_ADDR) {
1656 		zero_user_segment(page, 0, PAGE_SIZE);
1657 		SetPageUptodate(page);
1658 	} else {
1659 		struct bio *bio;
1660 
1661 		bio = f2fs_grab_bio(inode, blkaddr, 1);
1662 		if (IS_ERR(bio)) {
1663 			err = PTR_ERR(bio);
1664 			goto fail;
1665 		}
1666 		bio_set_op_attrs(bio, REQ_OP_READ, READ_SYNC);
1667 		if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE) {
1668 			bio_put(bio);
1669 			err = -EFAULT;
1670 			goto fail;
1671 		}
1672 
1673 		__submit_bio(sbi, bio, DATA);
1674 
1675 		lock_page(page);
1676 		if (unlikely(page->mapping != mapping)) {
1677 			f2fs_put_page(page, 1);
1678 			goto repeat;
1679 		}
1680 		if (unlikely(!PageUptodate(page))) {
1681 			err = -EIO;
1682 			goto fail;
1683 		}
1684 	}
1685 	return 0;
1686 
1687 fail:
1688 	f2fs_put_page(page, 1);
1689 	f2fs_write_failed(mapping, pos + len);
1690 	return err;
1691 }
1692 
1693 static int f2fs_write_end(struct file *file,
1694 			struct address_space *mapping,
1695 			loff_t pos, unsigned len, unsigned copied,
1696 			struct page *page, void *fsdata)
1697 {
1698 	struct inode *inode = page->mapping->host;
1699 
1700 	trace_f2fs_write_end(inode, pos, len, copied);
1701 
1702 	/*
1703 	 * This should be come from len == PAGE_SIZE, and we expect copied
1704 	 * should be PAGE_SIZE. Otherwise, we treat it with zero copied and
1705 	 * let generic_perform_write() try to copy data again through copied=0.
1706 	 */
1707 	if (!PageUptodate(page)) {
1708 		if (unlikely(copied != PAGE_SIZE))
1709 			copied = 0;
1710 		else
1711 			SetPageUptodate(page);
1712 	}
1713 	if (!copied)
1714 		goto unlock_out;
1715 
1716 	set_page_dirty(page);
1717 	clear_cold_data(page);
1718 
1719 	if (pos + copied > i_size_read(inode))
1720 		f2fs_i_size_write(inode, pos + copied);
1721 unlock_out:
1722 	f2fs_put_page(page, 1);
1723 	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1724 	return copied;
1725 }
1726 
1727 static int check_direct_IO(struct inode *inode, struct iov_iter *iter,
1728 			   loff_t offset)
1729 {
1730 	unsigned blocksize_mask = inode->i_sb->s_blocksize - 1;
1731 
1732 	if (offset & blocksize_mask)
1733 		return -EINVAL;
1734 
1735 	if (iov_iter_alignment(iter) & blocksize_mask)
1736 		return -EINVAL;
1737 
1738 	return 0;
1739 }
1740 
1741 static ssize_t f2fs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
1742 {
1743 	struct address_space *mapping = iocb->ki_filp->f_mapping;
1744 	struct inode *inode = mapping->host;
1745 	size_t count = iov_iter_count(iter);
1746 	loff_t offset = iocb->ki_pos;
1747 	int rw = iov_iter_rw(iter);
1748 	int err;
1749 
1750 	err = check_direct_IO(inode, iter, offset);
1751 	if (err)
1752 		return err;
1753 
1754 	if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode))
1755 		return 0;
1756 	if (test_opt(F2FS_I_SB(inode), LFS))
1757 		return 0;
1758 
1759 	trace_f2fs_direct_IO_enter(inode, offset, count, rw);
1760 
1761 	down_read(&F2FS_I(inode)->dio_rwsem[rw]);
1762 	err = blockdev_direct_IO(iocb, inode, iter, get_data_block_dio);
1763 	up_read(&F2FS_I(inode)->dio_rwsem[rw]);
1764 
1765 	if (rw == WRITE) {
1766 		if (err > 0)
1767 			set_inode_flag(inode, FI_UPDATE_WRITE);
1768 		else if (err < 0)
1769 			f2fs_write_failed(mapping, offset + count);
1770 	}
1771 
1772 	trace_f2fs_direct_IO_exit(inode, offset, count, rw, err);
1773 
1774 	return err;
1775 }
1776 
1777 void f2fs_invalidate_page(struct page *page, unsigned int offset,
1778 							unsigned int length)
1779 {
1780 	struct inode *inode = page->mapping->host;
1781 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1782 
1783 	if (inode->i_ino >= F2FS_ROOT_INO(sbi) &&
1784 		(offset % PAGE_SIZE || length != PAGE_SIZE))
1785 		return;
1786 
1787 	if (PageDirty(page)) {
1788 		if (inode->i_ino == F2FS_META_INO(sbi))
1789 			dec_page_count(sbi, F2FS_DIRTY_META);
1790 		else if (inode->i_ino == F2FS_NODE_INO(sbi))
1791 			dec_page_count(sbi, F2FS_DIRTY_NODES);
1792 		else
1793 			inode_dec_dirty_pages(inode);
1794 	}
1795 
1796 	/* This is atomic written page, keep Private */
1797 	if (IS_ATOMIC_WRITTEN_PAGE(page))
1798 		return;
1799 
1800 	set_page_private(page, 0);
1801 	ClearPagePrivate(page);
1802 }
1803 
1804 int f2fs_release_page(struct page *page, gfp_t wait)
1805 {
1806 	/* If this is dirty page, keep PagePrivate */
1807 	if (PageDirty(page))
1808 		return 0;
1809 
1810 	/* This is atomic written page, keep Private */
1811 	if (IS_ATOMIC_WRITTEN_PAGE(page))
1812 		return 0;
1813 
1814 	set_page_private(page, 0);
1815 	ClearPagePrivate(page);
1816 	return 1;
1817 }
1818 
1819 /*
1820  * This was copied from __set_page_dirty_buffers which gives higher performance
1821  * in very high speed storages. (e.g., pmem)
1822  */
1823 void f2fs_set_page_dirty_nobuffers(struct page *page)
1824 {
1825 	struct address_space *mapping = page->mapping;
1826 	unsigned long flags;
1827 
1828 	if (unlikely(!mapping))
1829 		return;
1830 
1831 	spin_lock(&mapping->private_lock);
1832 	lock_page_memcg(page);
1833 	SetPageDirty(page);
1834 	spin_unlock(&mapping->private_lock);
1835 
1836 	spin_lock_irqsave(&mapping->tree_lock, flags);
1837 	WARN_ON_ONCE(!PageUptodate(page));
1838 	account_page_dirtied(page, mapping);
1839 	radix_tree_tag_set(&mapping->page_tree,
1840 			page_index(page), PAGECACHE_TAG_DIRTY);
1841 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
1842 	unlock_page_memcg(page);
1843 
1844 	__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
1845 	return;
1846 }
1847 
1848 static int f2fs_set_data_page_dirty(struct page *page)
1849 {
1850 	struct address_space *mapping = page->mapping;
1851 	struct inode *inode = mapping->host;
1852 
1853 	trace_f2fs_set_page_dirty(page, DATA);
1854 
1855 	if (!PageUptodate(page))
1856 		SetPageUptodate(page);
1857 
1858 	if (f2fs_is_atomic_file(inode)) {
1859 		if (!IS_ATOMIC_WRITTEN_PAGE(page)) {
1860 			register_inmem_page(inode, page);
1861 			return 1;
1862 		}
1863 		/*
1864 		 * Previously, this page has been registered, we just
1865 		 * return here.
1866 		 */
1867 		return 0;
1868 	}
1869 
1870 	if (!PageDirty(page)) {
1871 		f2fs_set_page_dirty_nobuffers(page);
1872 		update_dirty_page(inode, page);
1873 		return 1;
1874 	}
1875 	return 0;
1876 }
1877 
1878 static sector_t f2fs_bmap(struct address_space *mapping, sector_t block)
1879 {
1880 	struct inode *inode = mapping->host;
1881 
1882 	if (f2fs_has_inline_data(inode))
1883 		return 0;
1884 
1885 	/* make sure allocating whole blocks */
1886 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
1887 		filemap_write_and_wait(mapping);
1888 
1889 	return generic_block_bmap(mapping, block, get_data_block_bmap);
1890 }
1891 
1892 #ifdef CONFIG_MIGRATION
1893 #include <linux/migrate.h>
1894 
1895 int f2fs_migrate_page(struct address_space *mapping,
1896 		struct page *newpage, struct page *page, enum migrate_mode mode)
1897 {
1898 	int rc, extra_count;
1899 	struct f2fs_inode_info *fi = F2FS_I(mapping->host);
1900 	bool atomic_written = IS_ATOMIC_WRITTEN_PAGE(page);
1901 
1902 	BUG_ON(PageWriteback(page));
1903 
1904 	/* migrating an atomic written page is safe with the inmem_lock hold */
1905 	if (atomic_written && !mutex_trylock(&fi->inmem_lock))
1906 		return -EAGAIN;
1907 
1908 	/*
1909 	 * A reference is expected if PagePrivate set when move mapping,
1910 	 * however F2FS breaks this for maintaining dirty page counts when
1911 	 * truncating pages. So here adjusting the 'extra_count' make it work.
1912 	 */
1913 	extra_count = (atomic_written ? 1 : 0) - page_has_private(page);
1914 	rc = migrate_page_move_mapping(mapping, newpage,
1915 				page, NULL, mode, extra_count);
1916 	if (rc != MIGRATEPAGE_SUCCESS) {
1917 		if (atomic_written)
1918 			mutex_unlock(&fi->inmem_lock);
1919 		return rc;
1920 	}
1921 
1922 	if (atomic_written) {
1923 		struct inmem_pages *cur;
1924 		list_for_each_entry(cur, &fi->inmem_pages, list)
1925 			if (cur->page == page) {
1926 				cur->page = newpage;
1927 				break;
1928 			}
1929 		mutex_unlock(&fi->inmem_lock);
1930 		put_page(page);
1931 		get_page(newpage);
1932 	}
1933 
1934 	if (PagePrivate(page))
1935 		SetPagePrivate(newpage);
1936 	set_page_private(newpage, page_private(page));
1937 
1938 	migrate_page_copy(newpage, page);
1939 
1940 	return MIGRATEPAGE_SUCCESS;
1941 }
1942 #endif
1943 
1944 const struct address_space_operations f2fs_dblock_aops = {
1945 	.readpage	= f2fs_read_data_page,
1946 	.readpages	= f2fs_read_data_pages,
1947 	.writepage	= f2fs_write_data_page,
1948 	.writepages	= f2fs_write_data_pages,
1949 	.write_begin	= f2fs_write_begin,
1950 	.write_end	= f2fs_write_end,
1951 	.set_page_dirty	= f2fs_set_data_page_dirty,
1952 	.invalidatepage	= f2fs_invalidate_page,
1953 	.releasepage	= f2fs_release_page,
1954 	.direct_IO	= f2fs_direct_IO,
1955 	.bmap		= f2fs_bmap,
1956 #ifdef CONFIG_MIGRATION
1957 	.migratepage    = f2fs_migrate_page,
1958 #endif
1959 };
1960