13c078bdf156e205bed67d7ca7c3bf692b3f884b
[linux-2.6-microblaze.git] / fs / ubifs / file.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This file is part of UBIFS.
4  *
5  * Copyright (C) 2006-2008 Nokia Corporation.
6  *
7  * Authors: Artem Bityutskiy (Битюцкий Артём)
8  *          Adrian Hunter
9  */
10
11 /*
12  * This file implements VFS file and inode operations for regular files, device
13  * nodes and symlinks as well as address space operations.
14  *
15  * UBIFS uses 2 page flags: @PG_private and @PG_checked. @PG_private is set if
16  * the page is dirty and is used for optimization purposes - dirty pages are
17  * not budgeted so the flag shows that 'ubifs_write_end()' should not release
18  * the budget for this page. The @PG_checked flag is set if full budgeting is
19  * required for the page e.g., when it corresponds to a file hole or it is
20  * beyond the file size. The budgeting is done in 'ubifs_write_begin()', because
21  * it is OK to fail in this function, and the budget is released in
22  * 'ubifs_write_end()'. So the @PG_private and @PG_checked flags carry
23  * information about how the page was budgeted, to make it possible to release
24  * the budget properly.
25  *
26  * A thing to keep in mind: inode @i_mutex is locked in most VFS operations we
27  * implement. However, this is not true for 'ubifs_writepage()', which may be
28  * called with @i_mutex unlocked. For example, when flusher thread is doing
29  * background write-back, it calls 'ubifs_writepage()' with unlocked @i_mutex.
30  * At "normal" work-paths the @i_mutex is locked in 'ubifs_writepage()', e.g.
31  * in the "sys_write -> alloc_pages -> direct reclaim path". So, in
32  * 'ubifs_writepage()' we are only guaranteed that the page is locked.
33  *
34  * Similarly, @i_mutex is not always locked in 'ubifs_read_folio()', e.g., the
35  * read-ahead path does not lock it ("sys_read -> generic_file_aio_read ->
36  * ondemand_readahead -> read_folio"). In case of readahead, @I_SYNC flag is not
37  * set as well. However, UBIFS disables readahead.
38  */
39
40 #include "ubifs.h"
41 #include <linux/mount.h>
42 #include <linux/slab.h>
43 #include <linux/migrate.h>
44
45 static int read_block(struct inode *inode, void *addr, unsigned int block,
46                       struct ubifs_data_node *dn)
47 {
48         struct ubifs_info *c = inode->i_sb->s_fs_info;
49         int err, len, out_len;
50         union ubifs_key key;
51         unsigned int dlen;
52
53         data_key_init(c, &key, inode->i_ino, block);
54         err = ubifs_tnc_lookup(c, &key, dn);
55         if (err) {
56                 if (err == -ENOENT)
57                         /* Not found, so it must be a hole */
58                         memset(addr, 0, UBIFS_BLOCK_SIZE);
59                 return err;
60         }
61
62         ubifs_assert(c, le64_to_cpu(dn->ch.sqnum) >
63                      ubifs_inode(inode)->creat_sqnum);
64         len = le32_to_cpu(dn->size);
65         if (len <= 0 || len > UBIFS_BLOCK_SIZE)
66                 goto dump;
67
68         dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
69
70         if (IS_ENCRYPTED(inode)) {
71                 err = ubifs_decrypt(inode, dn, &dlen, block);
72                 if (err)
73                         goto dump;
74         }
75
76         out_len = UBIFS_BLOCK_SIZE;
77         err = ubifs_decompress(c, &dn->data, dlen, addr, &out_len,
78                                le16_to_cpu(dn->compr_type));
79         if (err || len != out_len)
80                 goto dump;
81
82         /*
83          * Data length can be less than a full block, even for blocks that are
84          * not the last in the file (e.g., as a result of making a hole and
85          * appending data). Ensure that the remainder is zeroed out.
86          */
87         if (len < UBIFS_BLOCK_SIZE)
88                 memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
89
90         return 0;
91
92 dump:
93         ubifs_err(c, "bad data node (block %u, inode %lu)",
94                   block, inode->i_ino);
95         ubifs_dump_node(c, dn, UBIFS_MAX_DATA_NODE_SZ);
96         return -EINVAL;
97 }
98
99 static int do_readpage(struct page *page)
100 {
101         void *addr;
102         int err = 0, i;
103         unsigned int block, beyond;
104         struct ubifs_data_node *dn;
105         struct inode *inode = page->mapping->host;
106         struct ubifs_info *c = inode->i_sb->s_fs_info;
107         loff_t i_size = i_size_read(inode);
108
109         dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
110                 inode->i_ino, page->index, i_size, page->flags);
111         ubifs_assert(c, !PageChecked(page));
112         ubifs_assert(c, !PagePrivate(page));
113
114         addr = kmap(page);
115
116         block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
117         beyond = (i_size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT;
118         if (block >= beyond) {
119                 /* Reading beyond inode */
120                 SetPageChecked(page);
121                 memset(addr, 0, PAGE_SIZE);
122                 goto out;
123         }
124
125         dn = kmalloc(UBIFS_MAX_DATA_NODE_SZ, GFP_NOFS);
126         if (!dn) {
127                 err = -ENOMEM;
128                 goto error;
129         }
130
131         i = 0;
132         while (1) {
133                 int ret;
134
135                 if (block >= beyond) {
136                         /* Reading beyond inode */
137                         err = -ENOENT;
138                         memset(addr, 0, UBIFS_BLOCK_SIZE);
139                 } else {
140                         ret = read_block(inode, addr, block, dn);
141                         if (ret) {
142                                 err = ret;
143                                 if (err != -ENOENT)
144                                         break;
145                         } else if (block + 1 == beyond) {
146                                 int dlen = le32_to_cpu(dn->size);
147                                 int ilen = i_size & (UBIFS_BLOCK_SIZE - 1);
148
149                                 if (ilen && ilen < dlen)
150                                         memset(addr + ilen, 0, dlen - ilen);
151                         }
152                 }
153                 if (++i >= UBIFS_BLOCKS_PER_PAGE)
154                         break;
155                 block += 1;
156                 addr += UBIFS_BLOCK_SIZE;
157         }
158         if (err) {
159                 struct ubifs_info *c = inode->i_sb->s_fs_info;
160                 if (err == -ENOENT) {
161                         /* Not found, so it must be a hole */
162                         SetPageChecked(page);
163                         dbg_gen("hole");
164                         goto out_free;
165                 }
166                 ubifs_err(c, "cannot read page %lu of inode %lu, error %d",
167                           page->index, inode->i_ino, err);
168                 goto error;
169         }
170
171 out_free:
172         kfree(dn);
173 out:
174         SetPageUptodate(page);
175         ClearPageError(page);
176         flush_dcache_page(page);
177         kunmap(page);
178         return 0;
179
180 error:
181         kfree(dn);
182         ClearPageUptodate(page);
183         SetPageError(page);
184         flush_dcache_page(page);
185         kunmap(page);
186         return err;
187 }
188
189 /**
190  * release_new_page_budget - release budget of a new page.
191  * @c: UBIFS file-system description object
192  *
193  * This is a helper function which releases budget corresponding to the budget
194  * of one new page of data.
195  */
196 static void release_new_page_budget(struct ubifs_info *c)
197 {
198         struct ubifs_budget_req req = { .recalculate = 1, .new_page = 1 };
199
200         ubifs_release_budget(c, &req);
201 }
202
203 /**
204  * release_existing_page_budget - release budget of an existing page.
205  * @c: UBIFS file-system description object
206  *
207  * This is a helper function which releases budget corresponding to the budget
208  * of changing one page of data which already exists on the flash media.
209  */
210 static void release_existing_page_budget(struct ubifs_info *c)
211 {
212         struct ubifs_budget_req req = { .dd_growth = c->bi.page_budget};
213
214         ubifs_release_budget(c, &req);
215 }
216
217 static int write_begin_slow(struct address_space *mapping,
218                             loff_t pos, unsigned len, struct page **pagep)
219 {
220         struct inode *inode = mapping->host;
221         struct ubifs_info *c = inode->i_sb->s_fs_info;
222         pgoff_t index = pos >> PAGE_SHIFT;
223         struct ubifs_budget_req req = { .new_page = 1 };
224         int err, appending = !!(pos + len > inode->i_size);
225         struct folio *folio;
226
227         dbg_gen("ino %lu, pos %llu, len %u, i_size %lld",
228                 inode->i_ino, pos, len, inode->i_size);
229
230         /*
231          * At the slow path we have to budget before locking the folio, because
232          * budgeting may force write-back, which would wait on locked folios and
233          * deadlock if we had the folio locked. At this point we do not know
234          * anything about the folio, so assume that this is a new folio which is
235          * written to a hole. This corresponds to largest budget. Later the
236          * budget will be amended if this is not true.
237          */
238         if (appending)
239                 /* We are appending data, budget for inode change */
240                 req.dirtied_ino = 1;
241
242         err = ubifs_budget_space(c, &req);
243         if (unlikely(err))
244                 return err;
245
246         folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
247                         mapping_gfp_mask(mapping));
248         if (IS_ERR(folio)) {
249                 ubifs_release_budget(c, &req);
250                 return PTR_ERR(folio);
251         }
252
253         if (!folio_test_uptodate(folio)) {
254                 if (pos == folio_pos(folio) && len >= folio_size(folio))
255                         folio_set_checked(folio);
256                 else {
257                         err = do_readpage(&folio->page);
258                         if (err) {
259                                 folio_unlock(folio);
260                                 folio_put(folio);
261                                 ubifs_release_budget(c, &req);
262                                 return err;
263                         }
264                 }
265         }
266
267         if (folio->private)
268                 /*
269                  * The folio is dirty, which means it was budgeted twice:
270                  *   o first time the budget was allocated by the task which
271                  *     made the folio dirty and set the private field;
272                  *   o and then we budgeted for it for the second time at the
273                  *     very beginning of this function.
274                  *
275                  * So what we have to do is to release the folio budget we
276                  * allocated.
277                  */
278                 release_new_page_budget(c);
279         else if (!folio_test_checked(folio))
280                 /*
281                  * We are changing a folio which already exists on the media.
282                  * This means that changing the folio does not make the amount
283                  * of indexing information larger, and this part of the budget
284                  * which we have already acquired may be released.
285                  */
286                 ubifs_convert_page_budget(c);
287
288         if (appending) {
289                 struct ubifs_inode *ui = ubifs_inode(inode);
290
291                 /*
292                  * 'ubifs_write_end()' is optimized from the fast-path part of
293                  * 'ubifs_write_begin()' and expects the @ui_mutex to be locked
294                  * if data is appended.
295                  */
296                 mutex_lock(&ui->ui_mutex);
297                 if (ui->dirty)
298                         /*
299                          * The inode is dirty already, so we may free the
300                          * budget we allocated.
301                          */
302                         ubifs_release_dirty_inode_budget(c, ui);
303         }
304
305         *pagep = &folio->page;
306         return 0;
307 }
308
309 /**
310  * allocate_budget - allocate budget for 'ubifs_write_begin()'.
311  * @c: UBIFS file-system description object
312  * @page: page to allocate budget for
313  * @ui: UBIFS inode object the page belongs to
314  * @appending: non-zero if the page is appended
315  *
316  * This is a helper function for 'ubifs_write_begin()' which allocates budget
317  * for the operation. The budget is allocated differently depending on whether
318  * this is appending, whether the page is dirty or not, and so on. This
319  * function leaves the @ui->ui_mutex locked in case of appending.
320  *
321  * Returns: %0 in case of success and %-ENOSPC in case of failure.
322  */
323 static int allocate_budget(struct ubifs_info *c, struct page *page,
324                            struct ubifs_inode *ui, int appending)
325 {
326         struct ubifs_budget_req req = { .fast = 1 };
327
328         if (PagePrivate(page)) {
329                 if (!appending)
330                         /*
331                          * The page is dirty and we are not appending, which
332                          * means no budget is needed at all.
333                          */
334                         return 0;
335
336                 mutex_lock(&ui->ui_mutex);
337                 if (ui->dirty)
338                         /*
339                          * The page is dirty and we are appending, so the inode
340                          * has to be marked as dirty. However, it is already
341                          * dirty, so we do not need any budget. We may return,
342                          * but @ui->ui_mutex hast to be left locked because we
343                          * should prevent write-back from flushing the inode
344                          * and freeing the budget. The lock will be released in
345                          * 'ubifs_write_end()'.
346                          */
347                         return 0;
348
349                 /*
350                  * The page is dirty, we are appending, the inode is clean, so
351                  * we need to budget the inode change.
352                  */
353                 req.dirtied_ino = 1;
354         } else {
355                 if (PageChecked(page))
356                         /*
357                          * The page corresponds to a hole and does not
358                          * exist on the media. So changing it makes
359                          * make the amount of indexing information
360                          * larger, and we have to budget for a new
361                          * page.
362                          */
363                         req.new_page = 1;
364                 else
365                         /*
366                          * Not a hole, the change will not add any new
367                          * indexing information, budget for page
368                          * change.
369                          */
370                         req.dirtied_page = 1;
371
372                 if (appending) {
373                         mutex_lock(&ui->ui_mutex);
374                         if (!ui->dirty)
375                                 /*
376                                  * The inode is clean but we will have to mark
377                                  * it as dirty because we are appending. This
378                                  * needs a budget.
379                                  */
380                                 req.dirtied_ino = 1;
381                 }
382         }
383
384         return ubifs_budget_space(c, &req);
385 }
386
387 /*
388  * This function is called when a page of data is going to be written. Since
389  * the page of data will not necessarily go to the flash straight away, UBIFS
390  * has to reserve space on the media for it, which is done by means of
391  * budgeting.
392  *
393  * This is the hot-path of the file-system and we are trying to optimize it as
394  * much as possible. For this reasons it is split on 2 parts - slow and fast.
395  *
396  * There many budgeting cases:
397  *     o a new page is appended - we have to budget for a new page and for
398  *       changing the inode; however, if the inode is already dirty, there is
399  *       no need to budget for it;
400  *     o an existing clean page is changed - we have budget for it; if the page
401  *       does not exist on the media (a hole), we have to budget for a new
402  *       page; otherwise, we may budget for changing an existing page; the
403  *       difference between these cases is that changing an existing page does
404  *       not introduce anything new to the FS indexing information, so it does
405  *       not grow, and smaller budget is acquired in this case;
406  *     o an existing dirty page is changed - no need to budget at all, because
407  *       the page budget has been acquired by earlier, when the page has been
408  *       marked dirty.
409  *
410  * UBIFS budgeting sub-system may force write-back if it thinks there is no
411  * space to reserve. This imposes some locking restrictions and makes it
412  * impossible to take into account the above cases, and makes it impossible to
413  * optimize budgeting.
414  *
415  * The solution for this is that the fast path of 'ubifs_write_begin()' assumes
416  * there is a plenty of flash space and the budget will be acquired quickly,
417  * without forcing write-back. The slow path does not make this assumption.
418  */
419 static int ubifs_write_begin(struct file *file, struct address_space *mapping,
420                              loff_t pos, unsigned len,
421                              struct page **pagep, void **fsdata)
422 {
423         struct inode *inode = mapping->host;
424         struct ubifs_info *c = inode->i_sb->s_fs_info;
425         struct ubifs_inode *ui = ubifs_inode(inode);
426         pgoff_t index = pos >> PAGE_SHIFT;
427         int err, appending = !!(pos + len > inode->i_size);
428         int skipped_read = 0;
429         struct folio *folio;
430
431         ubifs_assert(c, ubifs_inode(inode)->ui_size == inode->i_size);
432         ubifs_assert(c, !c->ro_media && !c->ro_mount);
433
434         if (unlikely(c->ro_error))
435                 return -EROFS;
436
437         /* Try out the fast-path part first */
438         folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
439                         mapping_gfp_mask(mapping));
440         if (IS_ERR(folio))
441                 return PTR_ERR(folio);
442
443         if (!folio_test_uptodate(folio)) {
444                 /* The page is not loaded from the flash */
445                 if (pos == folio_pos(folio) && len >= folio_size(folio)) {
446                         /*
447                          * We change whole page so no need to load it. But we
448                          * do not know whether this page exists on the media or
449                          * not, so we assume the latter because it requires
450                          * larger budget. The assumption is that it is better
451                          * to budget a bit more than to read the page from the
452                          * media. Thus, we are setting the @PG_checked flag
453                          * here.
454                          */
455                         folio_set_checked(folio);
456                         skipped_read = 1;
457                 } else {
458                         err = do_readpage(&folio->page);
459                         if (err) {
460                                 folio_unlock(folio);
461                                 folio_put(folio);
462                                 return err;
463                         }
464                 }
465         }
466
467         err = allocate_budget(c, &folio->page, ui, appending);
468         if (unlikely(err)) {
469                 ubifs_assert(c, err == -ENOSPC);
470                 /*
471                  * If we skipped reading the page because we were going to
472                  * write all of it, then it is not up to date.
473                  */
474                 if (skipped_read)
475                         folio_clear_checked(folio);
476                 /*
477                  * Budgeting failed which means it would have to force
478                  * write-back but didn't, because we set the @fast flag in the
479                  * request. Write-back cannot be done now, while we have the
480                  * page locked, because it would deadlock. Unlock and free
481                  * everything and fall-back to slow-path.
482                  */
483                 if (appending) {
484                         ubifs_assert(c, mutex_is_locked(&ui->ui_mutex));
485                         mutex_unlock(&ui->ui_mutex);
486                 }
487                 folio_unlock(folio);
488                 folio_put(folio);
489
490                 return write_begin_slow(mapping, pos, len, pagep);
491         }
492
493         /*
494          * Whee, we acquired budgeting quickly - without involving
495          * garbage-collection, committing or forcing write-back. We return
496          * with @ui->ui_mutex locked if we are appending pages, and unlocked
497          * otherwise. This is an optimization (slightly hacky though).
498          */
499         *pagep = &folio->page;
500         return 0;
501 }
502
503 /**
504  * cancel_budget - cancel budget.
505  * @c: UBIFS file-system description object
506  * @page: page to cancel budget for
507  * @ui: UBIFS inode object the page belongs to
508  * @appending: non-zero if the page is appended
509  *
510  * This is a helper function for a page write operation. It unlocks the
511  * @ui->ui_mutex in case of appending.
512  */
513 static void cancel_budget(struct ubifs_info *c, struct page *page,
514                           struct ubifs_inode *ui, int appending)
515 {
516         if (appending) {
517                 if (!ui->dirty)
518                         ubifs_release_dirty_inode_budget(c, ui);
519                 mutex_unlock(&ui->ui_mutex);
520         }
521         if (!PagePrivate(page)) {
522                 if (PageChecked(page))
523                         release_new_page_budget(c);
524                 else
525                         release_existing_page_budget(c);
526         }
527 }
528
529 static int ubifs_write_end(struct file *file, struct address_space *mapping,
530                            loff_t pos, unsigned len, unsigned copied,
531                            struct page *page, void *fsdata)
532 {
533         struct inode *inode = mapping->host;
534         struct ubifs_inode *ui = ubifs_inode(inode);
535         struct ubifs_info *c = inode->i_sb->s_fs_info;
536         loff_t end_pos = pos + len;
537         int appending = !!(end_pos > inode->i_size);
538
539         dbg_gen("ino %lu, pos %llu, pg %lu, len %u, copied %d, i_size %lld",
540                 inode->i_ino, pos, page->index, len, copied, inode->i_size);
541
542         if (unlikely(copied < len && len == PAGE_SIZE)) {
543                 /*
544                  * VFS copied less data to the page that it intended and
545                  * declared in its '->write_begin()' call via the @len
546                  * argument. If the page was not up-to-date, and @len was
547                  * @PAGE_SIZE, the 'ubifs_write_begin()' function did
548                  * not load it from the media (for optimization reasons). This
549                  * means that part of the page contains garbage. So read the
550                  * page now.
551                  */
552                 dbg_gen("copied %d instead of %d, read page and repeat",
553                         copied, len);
554                 cancel_budget(c, page, ui, appending);
555                 ClearPageChecked(page);
556
557                 /*
558                  * Return 0 to force VFS to repeat the whole operation, or the
559                  * error code if 'do_readpage()' fails.
560                  */
561                 copied = do_readpage(page);
562                 goto out;
563         }
564
565         if (len == PAGE_SIZE)
566                 SetPageUptodate(page);
567
568         if (!PagePrivate(page)) {
569                 attach_page_private(page, (void *)1);
570                 atomic_long_inc(&c->dirty_pg_cnt);
571                 __set_page_dirty_nobuffers(page);
572         }
573
574         if (appending) {
575                 i_size_write(inode, end_pos);
576                 ui->ui_size = end_pos;
577                 /*
578                  * Note, we do not set @I_DIRTY_PAGES (which means that the
579                  * inode has dirty pages), this has been done in
580                  * '__set_page_dirty_nobuffers()'.
581                  */
582                 __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
583                 ubifs_assert(c, mutex_is_locked(&ui->ui_mutex));
584                 mutex_unlock(&ui->ui_mutex);
585         }
586
587 out:
588         unlock_page(page);
589         put_page(page);
590         return copied;
591 }
592
593 /**
594  * populate_page - copy data nodes into a page for bulk-read.
595  * @c: UBIFS file-system description object
596  * @page: page
597  * @bu: bulk-read information
598  * @n: next zbranch slot
599  *
600  * Returns: %0 on success and a negative error code on failure.
601  */
602 static int populate_page(struct ubifs_info *c, struct page *page,
603                          struct bu_info *bu, int *n)
604 {
605         int i = 0, nn = *n, offs = bu->zbranch[0].offs, hole = 0, read = 0;
606         struct inode *inode = page->mapping->host;
607         loff_t i_size = i_size_read(inode);
608         unsigned int page_block;
609         void *addr, *zaddr;
610         pgoff_t end_index;
611
612         dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
613                 inode->i_ino, page->index, i_size, page->flags);
614
615         addr = zaddr = kmap(page);
616
617         end_index = (i_size - 1) >> PAGE_SHIFT;
618         if (!i_size || page->index > end_index) {
619                 hole = 1;
620                 memset(addr, 0, PAGE_SIZE);
621                 goto out_hole;
622         }
623
624         page_block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
625         while (1) {
626                 int err, len, out_len, dlen;
627
628                 if (nn >= bu->cnt) {
629                         hole = 1;
630                         memset(addr, 0, UBIFS_BLOCK_SIZE);
631                 } else if (key_block(c, &bu->zbranch[nn].key) == page_block) {
632                         struct ubifs_data_node *dn;
633
634                         dn = bu->buf + (bu->zbranch[nn].offs - offs);
635
636                         ubifs_assert(c, le64_to_cpu(dn->ch.sqnum) >
637                                      ubifs_inode(inode)->creat_sqnum);
638
639                         len = le32_to_cpu(dn->size);
640                         if (len <= 0 || len > UBIFS_BLOCK_SIZE)
641                                 goto out_err;
642
643                         dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
644                         out_len = UBIFS_BLOCK_SIZE;
645
646                         if (IS_ENCRYPTED(inode)) {
647                                 err = ubifs_decrypt(inode, dn, &dlen, page_block);
648                                 if (err)
649                                         goto out_err;
650                         }
651
652                         err = ubifs_decompress(c, &dn->data, dlen, addr, &out_len,
653                                                le16_to_cpu(dn->compr_type));
654                         if (err || len != out_len)
655                                 goto out_err;
656
657                         if (len < UBIFS_BLOCK_SIZE)
658                                 memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
659
660                         nn += 1;
661                         read = (i << UBIFS_BLOCK_SHIFT) + len;
662                 } else if (key_block(c, &bu->zbranch[nn].key) < page_block) {
663                         nn += 1;
664                         continue;
665                 } else {
666                         hole = 1;
667                         memset(addr, 0, UBIFS_BLOCK_SIZE);
668                 }
669                 if (++i >= UBIFS_BLOCKS_PER_PAGE)
670                         break;
671                 addr += UBIFS_BLOCK_SIZE;
672                 page_block += 1;
673         }
674
675         if (end_index == page->index) {
676                 int len = i_size & (PAGE_SIZE - 1);
677
678                 if (len && len < read)
679                         memset(zaddr + len, 0, read - len);
680         }
681
682 out_hole:
683         if (hole) {
684                 SetPageChecked(page);
685                 dbg_gen("hole");
686         }
687
688         SetPageUptodate(page);
689         ClearPageError(page);
690         flush_dcache_page(page);
691         kunmap(page);
692         *n = nn;
693         return 0;
694
695 out_err:
696         ClearPageUptodate(page);
697         SetPageError(page);
698         flush_dcache_page(page);
699         kunmap(page);
700         ubifs_err(c, "bad data node (block %u, inode %lu)",
701                   page_block, inode->i_ino);
702         return -EINVAL;
703 }
704
705 /**
706  * ubifs_do_bulk_read - do bulk-read.
707  * @c: UBIFS file-system description object
708  * @bu: bulk-read information
709  * @page1: first page to read
710  *
711  * Returns: %1 if the bulk-read is done, otherwise %0 is returned.
712  */
713 static int ubifs_do_bulk_read(struct ubifs_info *c, struct bu_info *bu,
714                               struct page *page1)
715 {
716         pgoff_t offset = page1->index, end_index;
717         struct address_space *mapping = page1->mapping;
718         struct inode *inode = mapping->host;
719         struct ubifs_inode *ui = ubifs_inode(inode);
720         int err, page_idx, page_cnt, ret = 0, n = 0;
721         int allocate = bu->buf ? 0 : 1;
722         loff_t isize;
723         gfp_t ra_gfp_mask = readahead_gfp_mask(mapping) & ~__GFP_FS;
724
725         err = ubifs_tnc_get_bu_keys(c, bu);
726         if (err)
727                 goto out_warn;
728
729         if (bu->eof) {
730                 /* Turn off bulk-read at the end of the file */
731                 ui->read_in_a_row = 1;
732                 ui->bulk_read = 0;
733         }
734
735         page_cnt = bu->blk_cnt >> UBIFS_BLOCKS_PER_PAGE_SHIFT;
736         if (!page_cnt) {
737                 /*
738                  * This happens when there are multiple blocks per page and the
739                  * blocks for the first page we are looking for, are not
740                  * together. If all the pages were like this, bulk-read would
741                  * reduce performance, so we turn it off for a while.
742                  */
743                 goto out_bu_off;
744         }
745
746         if (bu->cnt) {
747                 if (allocate) {
748                         /*
749                          * Allocate bulk-read buffer depending on how many data
750                          * nodes we are going to read.
751                          */
752                         bu->buf_len = bu->zbranch[bu->cnt - 1].offs +
753                                       bu->zbranch[bu->cnt - 1].len -
754                                       bu->zbranch[0].offs;
755                         ubifs_assert(c, bu->buf_len > 0);
756                         ubifs_assert(c, bu->buf_len <= c->leb_size);
757                         bu->buf = kmalloc(bu->buf_len, GFP_NOFS | __GFP_NOWARN);
758                         if (!bu->buf)
759                                 goto out_bu_off;
760                 }
761
762                 err = ubifs_tnc_bulk_read(c, bu);
763                 if (err)
764                         goto out_warn;
765         }
766
767         err = populate_page(c, page1, bu, &n);
768         if (err)
769                 goto out_warn;
770
771         unlock_page(page1);
772         ret = 1;
773
774         isize = i_size_read(inode);
775         if (isize == 0)
776                 goto out_free;
777         end_index = ((isize - 1) >> PAGE_SHIFT);
778
779         for (page_idx = 1; page_idx < page_cnt; page_idx++) {
780                 pgoff_t page_offset = offset + page_idx;
781                 struct page *page;
782
783                 if (page_offset > end_index)
784                         break;
785                 page = pagecache_get_page(mapping, page_offset,
786                                  FGP_LOCK|FGP_ACCESSED|FGP_CREAT|FGP_NOWAIT,
787                                  ra_gfp_mask);
788                 if (!page)
789                         break;
790                 if (!PageUptodate(page))
791                         err = populate_page(c, page, bu, &n);
792                 unlock_page(page);
793                 put_page(page);
794                 if (err)
795                         break;
796         }
797
798         ui->last_page_read = offset + page_idx - 1;
799
800 out_free:
801         if (allocate)
802                 kfree(bu->buf);
803         return ret;
804
805 out_warn:
806         ubifs_warn(c, "ignoring error %d and skipping bulk-read", err);
807         goto out_free;
808
809 out_bu_off:
810         ui->read_in_a_row = ui->bulk_read = 0;
811         goto out_free;
812 }
813
814 /**
815  * ubifs_bulk_read - determine whether to bulk-read and, if so, do it.
816  * @page: page from which to start bulk-read.
817  *
818  * Some flash media are capable of reading sequentially at faster rates. UBIFS
819  * bulk-read facility is designed to take advantage of that, by reading in one
820  * go consecutive data nodes that are also located consecutively in the same
821  * LEB.
822  *
823  * Returns: %1 if a bulk-read is done and %0 otherwise.
824  */
825 static int ubifs_bulk_read(struct page *page)
826 {
827         struct inode *inode = page->mapping->host;
828         struct ubifs_info *c = inode->i_sb->s_fs_info;
829         struct ubifs_inode *ui = ubifs_inode(inode);
830         pgoff_t index = page->index, last_page_read = ui->last_page_read;
831         struct bu_info *bu;
832         int err = 0, allocated = 0;
833
834         ui->last_page_read = index;
835         if (!c->bulk_read)
836                 return 0;
837
838         /*
839          * Bulk-read is protected by @ui->ui_mutex, but it is an optimization,
840          * so don't bother if we cannot lock the mutex.
841          */
842         if (!mutex_trylock(&ui->ui_mutex))
843                 return 0;
844
845         if (index != last_page_read + 1) {
846                 /* Turn off bulk-read if we stop reading sequentially */
847                 ui->read_in_a_row = 1;
848                 if (ui->bulk_read)
849                         ui->bulk_read = 0;
850                 goto out_unlock;
851         }
852
853         if (!ui->bulk_read) {
854                 ui->read_in_a_row += 1;
855                 if (ui->read_in_a_row < 3)
856                         goto out_unlock;
857                 /* Three reads in a row, so switch on bulk-read */
858                 ui->bulk_read = 1;
859         }
860
861         /*
862          * If possible, try to use pre-allocated bulk-read information, which
863          * is protected by @c->bu_mutex.
864          */
865         if (mutex_trylock(&c->bu_mutex))
866                 bu = &c->bu;
867         else {
868                 bu = kmalloc(sizeof(struct bu_info), GFP_NOFS | __GFP_NOWARN);
869                 if (!bu)
870                         goto out_unlock;
871
872                 bu->buf = NULL;
873                 allocated = 1;
874         }
875
876         bu->buf_len = c->max_bu_buf_len;
877         data_key_init(c, &bu->key, inode->i_ino,
878                       page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT);
879         err = ubifs_do_bulk_read(c, bu, page);
880
881         if (!allocated)
882                 mutex_unlock(&c->bu_mutex);
883         else
884                 kfree(bu);
885
886 out_unlock:
887         mutex_unlock(&ui->ui_mutex);
888         return err;
889 }
890
891 static int ubifs_read_folio(struct file *file, struct folio *folio)
892 {
893         struct page *page = &folio->page;
894
895         if (ubifs_bulk_read(page))
896                 return 0;
897         do_readpage(page);
898         folio_unlock(folio);
899         return 0;
900 }
901
902 static int do_writepage(struct folio *folio, size_t len)
903 {
904         int err = 0, blen;
905         unsigned int block;
906         void *addr;
907         size_t offset = 0;
908         union ubifs_key key;
909         struct inode *inode = folio->mapping->host;
910         struct ubifs_info *c = inode->i_sb->s_fs_info;
911
912 #ifdef UBIFS_DEBUG
913         struct ubifs_inode *ui = ubifs_inode(inode);
914         spin_lock(&ui->ui_lock);
915         ubifs_assert(c, folio->index <= ui->synced_i_size >> PAGE_SHIFT);
916         spin_unlock(&ui->ui_lock);
917 #endif
918
919         folio_start_writeback(folio);
920
921         addr = kmap_local_folio(folio, offset);
922         block = folio->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
923         for (;;) {
924                 blen = min_t(size_t, len, UBIFS_BLOCK_SIZE);
925                 data_key_init(c, &key, inode->i_ino, block);
926                 err = ubifs_jnl_write_data(c, inode, &key, addr, blen);
927                 if (err)
928                         break;
929                 len -= blen;
930                 if (!len)
931                         break;
932                 block += 1;
933                 addr += blen;
934                 if (folio_test_highmem(folio) && !offset_in_page(addr)) {
935                         kunmap_local(addr - blen);
936                         offset += PAGE_SIZE;
937                         addr = kmap_local_folio(folio, offset);
938                 }
939         }
940         kunmap_local(addr);
941         if (err) {
942                 mapping_set_error(folio->mapping, err);
943                 ubifs_err(c, "cannot write folio %lu of inode %lu, error %d",
944                           folio->index, inode->i_ino, err);
945                 ubifs_ro_mode(c, err);
946         }
947
948         ubifs_assert(c, folio->private != NULL);
949         if (folio_test_checked(folio))
950                 release_new_page_budget(c);
951         else
952                 release_existing_page_budget(c);
953
954         atomic_long_dec(&c->dirty_pg_cnt);
955         folio_detach_private(folio);
956         folio_clear_checked(folio);
957
958         folio_unlock(folio);
959         folio_end_writeback(folio);
960         return err;
961 }
962
963 /*
964  * When writing-back dirty inodes, VFS first writes-back pages belonging to the
965  * inode, then the inode itself. For UBIFS this may cause a problem. Consider a
966  * situation when a we have an inode with size 0, then a megabyte of data is
967  * appended to the inode, then write-back starts and flushes some amount of the
968  * dirty pages, the journal becomes full, commit happens and finishes, and then
969  * an unclean reboot happens. When the file system is mounted next time, the
970  * inode size would still be 0, but there would be many pages which are beyond
971  * the inode size, they would be indexed and consume flash space. Because the
972  * journal has been committed, the replay would not be able to detect this
973  * situation and correct the inode size. This means UBIFS would have to scan
974  * whole index and correct all inode sizes, which is long an unacceptable.
975  *
976  * To prevent situations like this, UBIFS writes pages back only if they are
977  * within the last synchronized inode size, i.e. the size which has been
978  * written to the flash media last time. Otherwise, UBIFS forces inode
979  * write-back, thus making sure the on-flash inode contains current inode size,
980  * and then keeps writing pages back.
981  *
982  * Some locking issues explanation. 'ubifs_writepage()' first is called with
983  * the page locked, and it locks @ui_mutex. However, write-back does take inode
984  * @i_mutex, which means other VFS operations may be run on this inode at the
985  * same time. And the problematic one is truncation to smaller size, from where
986  * we have to call 'truncate_setsize()', which first changes @inode->i_size,
987  * then drops the truncated pages. And while dropping the pages, it takes the
988  * page lock. This means that 'do_truncation()' cannot call 'truncate_setsize()'
989  * with @ui_mutex locked, because it would deadlock with 'ubifs_writepage()'.
990  * This means that @inode->i_size is changed while @ui_mutex is unlocked.
991  *
992  * XXX(truncate): with the new truncate sequence this is not true anymore,
993  * and the calls to truncate_setsize can be move around freely.  They should
994  * be moved to the very end of the truncate sequence.
995  *
996  * But in 'ubifs_writepage()' we have to guarantee that we do not write beyond
997  * inode size. How do we do this if @inode->i_size may became smaller while we
998  * are in the middle of 'ubifs_writepage()'? The UBIFS solution is the
999  * @ui->ui_isize "shadow" field which UBIFS uses instead of @inode->i_size
1000  * internally and updates it under @ui_mutex.
1001  *
1002  * Q: why we do not worry that if we race with truncation, we may end up with a
1003  * situation when the inode is truncated while we are in the middle of
1004  * 'do_writepage()', so we do write beyond inode size?
1005  * A: If we are in the middle of 'do_writepage()', truncation would be locked
1006  * on the page lock and it would not write the truncated inode node to the
1007  * journal before we have finished.
1008  */
1009 static int ubifs_writepage(struct folio *folio, struct writeback_control *wbc,
1010                 void *data)
1011 {
1012         struct inode *inode = folio->mapping->host;
1013         struct ubifs_info *c = inode->i_sb->s_fs_info;
1014         struct ubifs_inode *ui = ubifs_inode(inode);
1015         loff_t i_size =  i_size_read(inode), synced_i_size;
1016         int err, len = folio_size(folio);
1017
1018         dbg_gen("ino %lu, pg %lu, pg flags %#lx",
1019                 inode->i_ino, folio->index, folio->flags);
1020         ubifs_assert(c, folio->private != NULL);
1021
1022         /* Is the folio fully outside @i_size? (truncate in progress) */
1023         if (folio_pos(folio) >= i_size) {
1024                 err = 0;
1025                 goto out_unlock;
1026         }
1027
1028         spin_lock(&ui->ui_lock);
1029         synced_i_size = ui->synced_i_size;
1030         spin_unlock(&ui->ui_lock);
1031
1032         /* Is the folio fully inside i_size? */
1033         if (folio_pos(folio) + len <= i_size) {
1034                 if (folio_pos(folio) >= synced_i_size) {
1035                         err = inode->i_sb->s_op->write_inode(inode, NULL);
1036                         if (err)
1037                                 goto out_redirty;
1038                         /*
1039                          * The inode has been written, but the write-buffer has
1040                          * not been synchronized, so in case of an unclean
1041                          * reboot we may end up with some pages beyond inode
1042                          * size, but they would be in the journal (because
1043                          * commit flushes write buffers) and recovery would deal
1044                          * with this.
1045                          */
1046                 }
1047                 return do_writepage(folio, len);
1048         }
1049
1050         /*
1051          * The folio straddles @i_size. It must be zeroed out on each and every
1052          * writepage invocation because it may be mmapped. "A file is mapped
1053          * in multiples of the page size. For a file that is not a multiple of
1054          * the page size, the remaining memory is zeroed when mapped, and
1055          * writes to that region are not written out to the file."
1056          */
1057         len = i_size - folio_pos(folio);
1058         folio_zero_segment(folio, len, folio_size(folio));
1059
1060         if (i_size > synced_i_size) {
1061                 err = inode->i_sb->s_op->write_inode(inode, NULL);
1062                 if (err)
1063                         goto out_redirty;
1064         }
1065
1066         return do_writepage(folio, len);
1067 out_redirty:
1068         /*
1069          * folio_redirty_for_writepage() won't call ubifs_dirty_inode() because
1070          * it passes I_DIRTY_PAGES flag while calling __mark_inode_dirty(), so
1071          * there is no need to do space budget for dirty inode.
1072          */
1073         folio_redirty_for_writepage(wbc, folio);
1074 out_unlock:
1075         folio_unlock(folio);
1076         return err;
1077 }
1078
1079 static int ubifs_writepages(struct address_space *mapping,
1080                 struct writeback_control *wbc)
1081 {
1082         return write_cache_pages(mapping, wbc, ubifs_writepage, NULL);
1083 }
1084
1085 /**
1086  * do_attr_changes - change inode attributes.
1087  * @inode: inode to change attributes for
1088  * @attr: describes attributes to change
1089  */
1090 static void do_attr_changes(struct inode *inode, const struct iattr *attr)
1091 {
1092         if (attr->ia_valid & ATTR_UID)
1093                 inode->i_uid = attr->ia_uid;
1094         if (attr->ia_valid & ATTR_GID)
1095                 inode->i_gid = attr->ia_gid;
1096         if (attr->ia_valid & ATTR_ATIME)
1097                 inode_set_atime_to_ts(inode, attr->ia_atime);
1098         if (attr->ia_valid & ATTR_MTIME)
1099                 inode_set_mtime_to_ts(inode, attr->ia_mtime);
1100         if (attr->ia_valid & ATTR_CTIME)
1101                 inode_set_ctime_to_ts(inode, attr->ia_ctime);
1102         if (attr->ia_valid & ATTR_MODE) {
1103                 umode_t mode = attr->ia_mode;
1104
1105                 if (!in_group_p(inode->i_gid) && !capable(CAP_FSETID))
1106                         mode &= ~S_ISGID;
1107                 inode->i_mode = mode;
1108         }
1109 }
1110
1111 /**
1112  * do_truncation - truncate an inode.
1113  * @c: UBIFS file-system description object
1114  * @inode: inode to truncate
1115  * @attr: inode attribute changes description
1116  *
1117  * This function implements VFS '->setattr()' call when the inode is truncated
1118  * to a smaller size.
1119  *
1120  * Returns: %0 in case of success and a negative error code
1121  * in case of failure.
1122  */
1123 static int do_truncation(struct ubifs_info *c, struct inode *inode,
1124                          const struct iattr *attr)
1125 {
1126         int err;
1127         struct ubifs_budget_req req;
1128         loff_t old_size = inode->i_size, new_size = attr->ia_size;
1129         int offset = new_size & (UBIFS_BLOCK_SIZE - 1), budgeted = 1;
1130         struct ubifs_inode *ui = ubifs_inode(inode);
1131
1132         dbg_gen("ino %lu, size %lld -> %lld", inode->i_ino, old_size, new_size);
1133         memset(&req, 0, sizeof(struct ubifs_budget_req));
1134
1135         /*
1136          * If this is truncation to a smaller size, and we do not truncate on a
1137          * block boundary, budget for changing one data block, because the last
1138          * block will be re-written.
1139          */
1140         if (new_size & (UBIFS_BLOCK_SIZE - 1))
1141                 req.dirtied_page = 1;
1142
1143         req.dirtied_ino = 1;
1144         /* A funny way to budget for truncation node */
1145         req.dirtied_ino_d = UBIFS_TRUN_NODE_SZ;
1146         err = ubifs_budget_space(c, &req);
1147         if (err) {
1148                 /*
1149                  * Treat truncations to zero as deletion and always allow them,
1150                  * just like we do for '->unlink()'.
1151                  */
1152                 if (new_size || err != -ENOSPC)
1153                         return err;
1154                 budgeted = 0;
1155         }
1156
1157         truncate_setsize(inode, new_size);
1158
1159         if (offset) {
1160                 pgoff_t index = new_size >> PAGE_SHIFT;
1161                 struct folio *folio;
1162
1163                 folio = filemap_lock_folio(inode->i_mapping, index);
1164                 if (!IS_ERR(folio)) {
1165                         if (folio_test_dirty(folio)) {
1166                                 /*
1167                                  * 'ubifs_jnl_truncate()' will try to truncate
1168                                  * the last data node, but it contains
1169                                  * out-of-date data because the page is dirty.
1170                                  * Write the page now, so that
1171                                  * 'ubifs_jnl_truncate()' will see an already
1172                                  * truncated (and up to date) data node.
1173                                  */
1174                                 ubifs_assert(c, folio->private != NULL);
1175
1176                                 folio_clear_dirty_for_io(folio);
1177                                 if (UBIFS_BLOCKS_PER_PAGE_SHIFT)
1178                                         offset = offset_in_folio(folio,
1179                                                         new_size);
1180                                 err = do_writepage(folio, offset);
1181                                 folio_put(folio);
1182                                 if (err)
1183                                         goto out_budg;
1184                                 /*
1185                                  * We could now tell 'ubifs_jnl_truncate()' not
1186                                  * to read the last block.
1187                                  */
1188                         } else {
1189                                 /*
1190                                  * We could 'kmap()' the page and pass the data
1191                                  * to 'ubifs_jnl_truncate()' to save it from
1192                                  * having to read it.
1193                                  */
1194                                 folio_unlock(folio);
1195                                 folio_put(folio);
1196                         }
1197                 }
1198         }
1199
1200         mutex_lock(&ui->ui_mutex);
1201         ui->ui_size = inode->i_size;
1202         /* Truncation changes inode [mc]time */
1203         inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1204         /* Other attributes may be changed at the same time as well */
1205         do_attr_changes(inode, attr);
1206         err = ubifs_jnl_truncate(c, inode, old_size, new_size);
1207         mutex_unlock(&ui->ui_mutex);
1208
1209 out_budg:
1210         if (budgeted)
1211                 ubifs_release_budget(c, &req);
1212         else {
1213                 c->bi.nospace = c->bi.nospace_rp = 0;
1214                 smp_wmb();
1215         }
1216         return err;
1217 }
1218
1219 /**
1220  * do_setattr - change inode attributes.
1221  * @c: UBIFS file-system description object
1222  * @inode: inode to change attributes for
1223  * @attr: inode attribute changes description
1224  *
1225  * This function implements VFS '->setattr()' call for all cases except
1226  * truncations to smaller size.
1227  *
1228  * Returns: %0 in case of success and a negative
1229  * error code in case of failure.
1230  */
1231 static int do_setattr(struct ubifs_info *c, struct inode *inode,
1232                       const struct iattr *attr)
1233 {
1234         int err, release;
1235         loff_t new_size = attr->ia_size;
1236         struct ubifs_inode *ui = ubifs_inode(inode);
1237         struct ubifs_budget_req req = { .dirtied_ino = 1,
1238                                 .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1239
1240         err = ubifs_budget_space(c, &req);
1241         if (err)
1242                 return err;
1243
1244         if (attr->ia_valid & ATTR_SIZE) {
1245                 dbg_gen("size %lld -> %lld", inode->i_size, new_size);
1246                 truncate_setsize(inode, new_size);
1247         }
1248
1249         mutex_lock(&ui->ui_mutex);
1250         if (attr->ia_valid & ATTR_SIZE) {
1251                 /* Truncation changes inode [mc]time */
1252                 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1253                 /* 'truncate_setsize()' changed @i_size, update @ui_size */
1254                 ui->ui_size = inode->i_size;
1255         }
1256
1257         do_attr_changes(inode, attr);
1258
1259         release = ui->dirty;
1260         if (attr->ia_valid & ATTR_SIZE)
1261                 /*
1262                  * Inode length changed, so we have to make sure
1263                  * @I_DIRTY_DATASYNC is set.
1264                  */
1265                  __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1266         else
1267                 mark_inode_dirty_sync(inode);
1268         mutex_unlock(&ui->ui_mutex);
1269
1270         if (release)
1271                 ubifs_release_budget(c, &req);
1272         if (IS_SYNC(inode))
1273                 err = inode->i_sb->s_op->write_inode(inode, NULL);
1274         return err;
1275 }
1276
1277 int ubifs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
1278                   struct iattr *attr)
1279 {
1280         int err;
1281         struct inode *inode = d_inode(dentry);
1282         struct ubifs_info *c = inode->i_sb->s_fs_info;
1283
1284         dbg_gen("ino %lu, mode %#x, ia_valid %#x",
1285                 inode->i_ino, inode->i_mode, attr->ia_valid);
1286         err = setattr_prepare(&nop_mnt_idmap, dentry, attr);
1287         if (err)
1288                 return err;
1289
1290         err = dbg_check_synced_i_size(c, inode);
1291         if (err)
1292                 return err;
1293
1294         err = fscrypt_prepare_setattr(dentry, attr);
1295         if (err)
1296                 return err;
1297
1298         if ((attr->ia_valid & ATTR_SIZE) && attr->ia_size < inode->i_size)
1299                 /* Truncation to a smaller size */
1300                 err = do_truncation(c, inode, attr);
1301         else
1302                 err = do_setattr(c, inode, attr);
1303
1304         return err;
1305 }
1306
1307 static void ubifs_invalidate_folio(struct folio *folio, size_t offset,
1308                                  size_t length)
1309 {
1310         struct inode *inode = folio->mapping->host;
1311         struct ubifs_info *c = inode->i_sb->s_fs_info;
1312
1313         ubifs_assert(c, folio_test_private(folio));
1314         if (offset || length < folio_size(folio))
1315                 /* Partial folio remains dirty */
1316                 return;
1317
1318         if (folio_test_checked(folio))
1319                 release_new_page_budget(c);
1320         else
1321                 release_existing_page_budget(c);
1322
1323         atomic_long_dec(&c->dirty_pg_cnt);
1324         folio_detach_private(folio);
1325         folio_clear_checked(folio);
1326 }
1327
1328 int ubifs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
1329 {
1330         struct inode *inode = file->f_mapping->host;
1331         struct ubifs_info *c = inode->i_sb->s_fs_info;
1332         int err;
1333
1334         dbg_gen("syncing inode %lu", inode->i_ino);
1335
1336         if (c->ro_mount)
1337                 /*
1338                  * For some really strange reasons VFS does not filter out
1339                  * 'fsync()' for R/O mounted file-systems as per 2.6.39.
1340                  */
1341                 return 0;
1342
1343         err = file_write_and_wait_range(file, start, end);
1344         if (err)
1345                 return err;
1346         inode_lock(inode);
1347
1348         /* Synchronize the inode unless this is a 'datasync()' call. */
1349         if (!datasync || (inode->i_state & I_DIRTY_DATASYNC)) {
1350                 err = inode->i_sb->s_op->write_inode(inode, NULL);
1351                 if (err)
1352                         goto out;
1353         }
1354
1355         /*
1356          * Nodes related to this inode may still sit in a write-buffer. Flush
1357          * them.
1358          */
1359         err = ubifs_sync_wbufs_by_inode(c, inode);
1360 out:
1361         inode_unlock(inode);
1362         return err;
1363 }
1364
1365 /**
1366  * mctime_update_needed - check if mtime or ctime update is needed.
1367  * @inode: the inode to do the check for
1368  * @now: current time
1369  *
1370  * This helper function checks if the inode mtime/ctime should be updated or
1371  * not. If current values of the time-stamps are within the UBIFS inode time
1372  * granularity, they are not updated. This is an optimization.
1373  *
1374  * Returns: %1 if time update is needed, %0 if not
1375  */
1376 static inline int mctime_update_needed(const struct inode *inode,
1377                                        const struct timespec64 *now)
1378 {
1379         struct timespec64 ctime = inode_get_ctime(inode);
1380         struct timespec64 mtime = inode_get_mtime(inode);
1381
1382         if (!timespec64_equal(&mtime, now) || !timespec64_equal(&ctime, now))
1383                 return 1;
1384         return 0;
1385 }
1386
1387 /**
1388  * ubifs_update_time - update time of inode.
1389  * @inode: inode to update
1390  * @flags: time updating control flag determines updating
1391  *          which time fields of @inode
1392  *
1393  * This function updates time of the inode.
1394  *
1395  * Returns: %0 for success or a negative error code otherwise.
1396  */
1397 int ubifs_update_time(struct inode *inode, int flags)
1398 {
1399         struct ubifs_inode *ui = ubifs_inode(inode);
1400         struct ubifs_info *c = inode->i_sb->s_fs_info;
1401         struct ubifs_budget_req req = { .dirtied_ino = 1,
1402                         .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1403         int err, release;
1404
1405         if (!IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT)) {
1406                 generic_update_time(inode, flags);
1407                 return 0;
1408         }
1409
1410         err = ubifs_budget_space(c, &req);
1411         if (err)
1412                 return err;
1413
1414         mutex_lock(&ui->ui_mutex);
1415         inode_update_timestamps(inode, flags);
1416         release = ui->dirty;
1417         __mark_inode_dirty(inode, I_DIRTY_SYNC);
1418         mutex_unlock(&ui->ui_mutex);
1419         if (release)
1420                 ubifs_release_budget(c, &req);
1421         return 0;
1422 }
1423
1424 /**
1425  * update_mctime - update mtime and ctime of an inode.
1426  * @inode: inode to update
1427  *
1428  * This function updates mtime and ctime of the inode if it is not equivalent to
1429  * current time.
1430  *
1431  * Returns: %0 in case of success and a negative error code in
1432  * case of failure.
1433  */
1434 static int update_mctime(struct inode *inode)
1435 {
1436         struct timespec64 now = current_time(inode);
1437         struct ubifs_inode *ui = ubifs_inode(inode);
1438         struct ubifs_info *c = inode->i_sb->s_fs_info;
1439
1440         if (mctime_update_needed(inode, &now)) {
1441                 int err, release;
1442                 struct ubifs_budget_req req = { .dirtied_ino = 1,
1443                                 .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1444
1445                 err = ubifs_budget_space(c, &req);
1446                 if (err)
1447                         return err;
1448
1449                 mutex_lock(&ui->ui_mutex);
1450                 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1451                 release = ui->dirty;
1452                 mark_inode_dirty_sync(inode);
1453                 mutex_unlock(&ui->ui_mutex);
1454                 if (release)
1455                         ubifs_release_budget(c, &req);
1456         }
1457
1458         return 0;
1459 }
1460
1461 static ssize_t ubifs_write_iter(struct kiocb *iocb, struct iov_iter *from)
1462 {
1463         int err = update_mctime(file_inode(iocb->ki_filp));
1464         if (err)
1465                 return err;
1466
1467         return generic_file_write_iter(iocb, from);
1468 }
1469
1470 static bool ubifs_dirty_folio(struct address_space *mapping,
1471                 struct folio *folio)
1472 {
1473         bool ret;
1474         struct ubifs_info *c = mapping->host->i_sb->s_fs_info;
1475
1476         ret = filemap_dirty_folio(mapping, folio);
1477         /*
1478          * An attempt to dirty a page without budgeting for it - should not
1479          * happen.
1480          */
1481         ubifs_assert(c, ret == false);
1482         return ret;
1483 }
1484
1485 static bool ubifs_release_folio(struct folio *folio, gfp_t unused_gfp_flags)
1486 {
1487         struct inode *inode = folio->mapping->host;
1488         struct ubifs_info *c = inode->i_sb->s_fs_info;
1489
1490         if (folio_test_writeback(folio))
1491                 return false;
1492
1493         /*
1494          * Page is private but not dirty, weird? There is one condition
1495          * making it happened. ubifs_writepage skipped the page because
1496          * page index beyonds isize (for example. truncated by other
1497          * process named A), then the page is invalidated by fadvise64
1498          * syscall before being truncated by process A.
1499          */
1500         ubifs_assert(c, folio_test_private(folio));
1501         if (folio_test_checked(folio))
1502                 release_new_page_budget(c);
1503         else
1504                 release_existing_page_budget(c);
1505
1506         atomic_long_dec(&c->dirty_pg_cnt);
1507         folio_detach_private(folio);
1508         folio_clear_checked(folio);
1509         return true;
1510 }
1511
1512 /*
1513  * mmap()d file has taken write protection fault and is being made writable.
1514  * UBIFS must ensure page is budgeted for.
1515  */
1516 static vm_fault_t ubifs_vm_page_mkwrite(struct vm_fault *vmf)
1517 {
1518         struct folio *folio = page_folio(vmf->page);
1519         struct inode *inode = file_inode(vmf->vma->vm_file);
1520         struct ubifs_info *c = inode->i_sb->s_fs_info;
1521         struct timespec64 now = current_time(inode);
1522         struct ubifs_budget_req req = { .new_page = 1 };
1523         int err, update_time;
1524
1525         dbg_gen("ino %lu, pg %lu, i_size %lld", inode->i_ino, folio->index,
1526                 i_size_read(inode));
1527         ubifs_assert(c, !c->ro_media && !c->ro_mount);
1528
1529         if (unlikely(c->ro_error))
1530                 return VM_FAULT_SIGBUS; /* -EROFS */
1531
1532         /*
1533          * We have not locked @folio so far so we may budget for changing the
1534          * folio. Note, we cannot do this after we locked the folio, because
1535          * budgeting may cause write-back which would cause deadlock.
1536          *
1537          * At the moment we do not know whether the folio is dirty or not, so we
1538          * assume that it is not and budget for a new folio. We could look at
1539          * the @PG_private flag and figure this out, but we may race with write
1540          * back and the folio state may change by the time we lock it, so this
1541          * would need additional care. We do not bother with this at the
1542          * moment, although it might be good idea to do. Instead, we allocate
1543          * budget for a new folio and amend it later on if the folio was in fact
1544          * dirty.
1545          *
1546          * The budgeting-related logic of this function is similar to what we
1547          * do in 'ubifs_write_begin()' and 'ubifs_write_end()'. Glance there
1548          * for more comments.
1549          */
1550         update_time = mctime_update_needed(inode, &now);
1551         if (update_time)
1552                 /*
1553                  * We have to change inode time stamp which requires extra
1554                  * budgeting.
1555                  */
1556                 req.dirtied_ino = 1;
1557
1558         err = ubifs_budget_space(c, &req);
1559         if (unlikely(err)) {
1560                 if (err == -ENOSPC)
1561                         ubifs_warn(c, "out of space for mmapped file (inode number %lu)",
1562                                    inode->i_ino);
1563                 return VM_FAULT_SIGBUS;
1564         }
1565
1566         folio_lock(folio);
1567         if (unlikely(folio->mapping != inode->i_mapping ||
1568                      folio_pos(folio) >= i_size_read(inode))) {
1569                 /* Folio got truncated out from underneath us */
1570                 goto sigbus;
1571         }
1572
1573         if (folio->private)
1574                 release_new_page_budget(c);
1575         else {
1576                 if (!folio_test_checked(folio))
1577                         ubifs_convert_page_budget(c);
1578                 folio_attach_private(folio, (void *)1);
1579                 atomic_long_inc(&c->dirty_pg_cnt);
1580                 filemap_dirty_folio(folio->mapping, folio);
1581         }
1582
1583         if (update_time) {
1584                 int release;
1585                 struct ubifs_inode *ui = ubifs_inode(inode);
1586
1587                 mutex_lock(&ui->ui_mutex);
1588                 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1589                 release = ui->dirty;
1590                 mark_inode_dirty_sync(inode);
1591                 mutex_unlock(&ui->ui_mutex);
1592                 if (release)
1593                         ubifs_release_dirty_inode_budget(c, ui);
1594         }
1595
1596         folio_wait_stable(folio);
1597         return VM_FAULT_LOCKED;
1598
1599 sigbus:
1600         folio_unlock(folio);
1601         ubifs_release_budget(c, &req);
1602         return VM_FAULT_SIGBUS;
1603 }
1604
1605 static const struct vm_operations_struct ubifs_file_vm_ops = {
1606         .fault        = filemap_fault,
1607         .map_pages = filemap_map_pages,
1608         .page_mkwrite = ubifs_vm_page_mkwrite,
1609 };
1610
1611 static int ubifs_file_mmap(struct file *file, struct vm_area_struct *vma)
1612 {
1613         int err;
1614
1615         err = generic_file_mmap(file, vma);
1616         if (err)
1617                 return err;
1618         vma->vm_ops = &ubifs_file_vm_ops;
1619
1620         if (IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT))
1621                 file_accessed(file);
1622
1623         return 0;
1624 }
1625
1626 static const char *ubifs_get_link(struct dentry *dentry,
1627                                             struct inode *inode,
1628                                             struct delayed_call *done)
1629 {
1630         struct ubifs_inode *ui = ubifs_inode(inode);
1631
1632         if (!IS_ENCRYPTED(inode))
1633                 return ui->data;
1634
1635         if (!dentry)
1636                 return ERR_PTR(-ECHILD);
1637
1638         return fscrypt_get_symlink(inode, ui->data, ui->data_len, done);
1639 }
1640
1641 static int ubifs_symlink_getattr(struct mnt_idmap *idmap,
1642                                  const struct path *path, struct kstat *stat,
1643                                  u32 request_mask, unsigned int query_flags)
1644 {
1645         ubifs_getattr(idmap, path, stat, request_mask, query_flags);
1646
1647         if (IS_ENCRYPTED(d_inode(path->dentry)))
1648                 return fscrypt_symlink_getattr(path, stat);
1649         return 0;
1650 }
1651
1652 const struct address_space_operations ubifs_file_address_operations = {
1653         .read_folio     = ubifs_read_folio,
1654         .writepages     = ubifs_writepages,
1655         .write_begin    = ubifs_write_begin,
1656         .write_end      = ubifs_write_end,
1657         .invalidate_folio = ubifs_invalidate_folio,
1658         .dirty_folio    = ubifs_dirty_folio,
1659         .migrate_folio  = filemap_migrate_folio,
1660         .release_folio  = ubifs_release_folio,
1661 };
1662
1663 const struct inode_operations ubifs_file_inode_operations = {
1664         .setattr     = ubifs_setattr,
1665         .getattr     = ubifs_getattr,
1666         .listxattr   = ubifs_listxattr,
1667         .update_time = ubifs_update_time,
1668         .fileattr_get = ubifs_fileattr_get,
1669         .fileattr_set = ubifs_fileattr_set,
1670 };
1671
1672 const struct inode_operations ubifs_symlink_inode_operations = {
1673         .get_link    = ubifs_get_link,
1674         .setattr     = ubifs_setattr,
1675         .getattr     = ubifs_symlink_getattr,
1676         .listxattr   = ubifs_listxattr,
1677         .update_time = ubifs_update_time,
1678 };
1679
1680 const struct file_operations ubifs_file_operations = {
1681         .llseek         = generic_file_llseek,
1682         .read_iter      = generic_file_read_iter,
1683         .write_iter     = ubifs_write_iter,
1684         .mmap           = ubifs_file_mmap,
1685         .fsync          = ubifs_fsync,
1686         .unlocked_ioctl = ubifs_ioctl,
1687         .splice_read    = filemap_splice_read,
1688         .splice_write   = iter_file_splice_write,
1689         .open           = fscrypt_file_open,
1690 #ifdef CONFIG_COMPAT
1691         .compat_ioctl   = ubifs_compat_ioctl,
1692 #endif
1693 };