UBIFS: add no_chk_data_crc mount option
[safe/jmp/linux-2.6] / fs / ubifs / io.c
1 /*
2  * This file is part of UBIFS.
3  *
4  * Copyright (C) 2006-2008 Nokia Corporation.
5  * Copyright (C) 2006, 2007 University of Szeged, Hungary
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License version 2 as published by
9  * the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, write to the Free Software Foundation, Inc., 51
18  * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19  *
20  * Authors: Artem Bityutskiy (Битюцкий Артём)
21  *          Adrian Hunter
22  *          Zoltan Sogor
23  */
24
25 /*
26  * This file implements UBIFS I/O subsystem which provides various I/O-related
27  * helper functions (reading/writing/checking/validating nodes) and implements
28  * write-buffering support. Write buffers help to save space which otherwise
29  * would have been wasted for padding to the nearest minimal I/O unit boundary.
30  * Instead, data first goes to the write-buffer and is flushed when the
31  * buffer is full or when it is not used for some time (by timer). This is
32  * similarto the mechanism is used by JFFS2.
33  *
34  * Write-buffers are defined by 'struct ubifs_wbuf' objects and protected by
35  * mutexes defined inside these objects. Since sometimes upper-level code
36  * has to lock the write-buffer (e.g. journal space reservation code), many
37  * functions related to write-buffers have "nolock" suffix which means that the
38  * caller has to lock the write-buffer before calling this function.
39  *
40  * UBIFS stores nodes at 64 bit-aligned addresses. If the node length is not
41  * aligned, UBIFS starts the next node from the aligned address, and the padded
42  * bytes may contain any rubbish. In other words, UBIFS does not put padding
43  * bytes in those small gaps. Common headers of nodes store real node lengths,
44  * not aligned lengths. Indexing nodes also store real lengths in branches.
45  *
46  * UBIFS uses padding when it pads to the next min. I/O unit. In this case it
47  * uses padding nodes or padding bytes, if the padding node does not fit.
48  *
49  * All UBIFS nodes are protected by CRC checksums and UBIFS checks all nodes
50  * every time they are read from the flash media.
51  */
52
53 #include <linux/crc32.h>
54 #include "ubifs.h"
55
56 /**
57  * ubifs_ro_mode - switch UBIFS to read read-only mode.
58  * @c: UBIFS file-system description object
59  * @err: error code which is the reason of switching to R/O mode
60  */
61 void ubifs_ro_mode(struct ubifs_info *c, int err)
62 {
63         if (!c->ro_media) {
64                 c->ro_media = 1;
65                 ubifs_warn("switched to read-only mode, error %d", err);
66                 dbg_dump_stack();
67         }
68 }
69
70 /**
71  * ubifs_check_node - check node.
72  * @c: UBIFS file-system description object
73  * @buf: node to check
74  * @lnum: logical eraseblock number
75  * @offs: offset within the logical eraseblock
76  * @quiet: print no messages
77  * @chk_crc: indicates whether to always check the CRC
78  *
79  * This function checks node magic number and CRC checksum. This function also
80  * validates node length to prevent UBIFS from becoming crazy when an attacker
81  * feeds it a file-system image with incorrect nodes. For example, too large
82  * node length in the common header could cause UBIFS to read memory outside of
83  * allocated buffer when checking the CRC checksum.
84  *
85  * This function returns zero in case of success %-EUCLEAN in case of bad CRC
86  * or magic.
87  */
88 int ubifs_check_node(const struct ubifs_info *c, const void *buf, int lnum,
89                      int offs, int quiet, int chk_crc)
90 {
91         int err = -EINVAL, type, node_len;
92         uint32_t crc, node_crc, magic;
93         const struct ubifs_ch *ch = buf;
94
95         ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
96         ubifs_assert(!(offs & 7) && offs < c->leb_size);
97
98         magic = le32_to_cpu(ch->magic);
99         if (magic != UBIFS_NODE_MAGIC) {
100                 if (!quiet)
101                         ubifs_err("bad magic %#08x, expected %#08x",
102                                   magic, UBIFS_NODE_MAGIC);
103                 err = -EUCLEAN;
104                 goto out;
105         }
106
107         type = ch->node_type;
108         if (type < 0 || type >= UBIFS_NODE_TYPES_CNT) {
109                 if (!quiet)
110                         ubifs_err("bad node type %d", type);
111                 goto out;
112         }
113
114         node_len = le32_to_cpu(ch->len);
115         if (node_len + offs > c->leb_size)
116                 goto out_len;
117
118         if (c->ranges[type].max_len == 0) {
119                 if (node_len != c->ranges[type].len)
120                         goto out_len;
121         } else if (node_len < c->ranges[type].min_len ||
122                    node_len > c->ranges[type].max_len)
123                 goto out_len;
124
125         if (!chk_crc && type == UBIFS_DATA_NODE && !c->always_chk_crc)
126                 if (c->no_chk_data_crc)
127                         return 0;
128
129         crc = crc32(UBIFS_CRC32_INIT, buf + 8, node_len - 8);
130         node_crc = le32_to_cpu(ch->crc);
131         if (crc != node_crc) {
132                 if (!quiet)
133                         ubifs_err("bad CRC: calculated %#08x, read %#08x",
134                                   crc, node_crc);
135                 err = -EUCLEAN;
136                 goto out;
137         }
138
139         return 0;
140
141 out_len:
142         if (!quiet)
143                 ubifs_err("bad node length %d", node_len);
144 out:
145         if (!quiet) {
146                 ubifs_err("bad node at LEB %d:%d", lnum, offs);
147                 dbg_dump_node(c, buf);
148                 dbg_dump_stack();
149         }
150         return err;
151 }
152
153 /**
154  * ubifs_pad - pad flash space.
155  * @c: UBIFS file-system description object
156  * @buf: buffer to put padding to
157  * @pad: how many bytes to pad
158  *
159  * The flash media obliges us to write only in chunks of %c->min_io_size and
160  * when we have to write less data we add padding node to the write-buffer and
161  * pad it to the next minimal I/O unit's boundary. Padding nodes help when the
162  * media is being scanned. If the amount of wasted space is not enough to fit a
163  * padding node which takes %UBIFS_PAD_NODE_SZ bytes, we write padding bytes
164  * pattern (%UBIFS_PADDING_BYTE).
165  *
166  * Padding nodes are also used to fill gaps when the "commit-in-gaps" method is
167  * used.
168  */
169 void ubifs_pad(const struct ubifs_info *c, void *buf, int pad)
170 {
171         uint32_t crc;
172
173         ubifs_assert(pad >= 0 && !(pad & 7));
174
175         if (pad >= UBIFS_PAD_NODE_SZ) {
176                 struct ubifs_ch *ch = buf;
177                 struct ubifs_pad_node *pad_node = buf;
178
179                 ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
180                 ch->node_type = UBIFS_PAD_NODE;
181                 ch->group_type = UBIFS_NO_NODE_GROUP;
182                 ch->padding[0] = ch->padding[1] = 0;
183                 ch->sqnum = 0;
184                 ch->len = cpu_to_le32(UBIFS_PAD_NODE_SZ);
185                 pad -= UBIFS_PAD_NODE_SZ;
186                 pad_node->pad_len = cpu_to_le32(pad);
187                 crc = crc32(UBIFS_CRC32_INIT, buf + 8, UBIFS_PAD_NODE_SZ - 8);
188                 ch->crc = cpu_to_le32(crc);
189                 memset(buf + UBIFS_PAD_NODE_SZ, 0, pad);
190         } else if (pad > 0)
191                 /* Too little space, padding node won't fit */
192                 memset(buf, UBIFS_PADDING_BYTE, pad);
193 }
194
195 /**
196  * next_sqnum - get next sequence number.
197  * @c: UBIFS file-system description object
198  */
199 static unsigned long long next_sqnum(struct ubifs_info *c)
200 {
201         unsigned long long sqnum;
202
203         spin_lock(&c->cnt_lock);
204         sqnum = ++c->max_sqnum;
205         spin_unlock(&c->cnt_lock);
206
207         if (unlikely(sqnum >= SQNUM_WARN_WATERMARK)) {
208                 if (sqnum >= SQNUM_WATERMARK) {
209                         ubifs_err("sequence number overflow %llu, end of life",
210                                   sqnum);
211                         ubifs_ro_mode(c, -EINVAL);
212                 }
213                 ubifs_warn("running out of sequence numbers, end of life soon");
214         }
215
216         return sqnum;
217 }
218
219 /**
220  * ubifs_prepare_node - prepare node to be written to flash.
221  * @c: UBIFS file-system description object
222  * @node: the node to pad
223  * @len: node length
224  * @pad: if the buffer has to be padded
225  *
226  * This function prepares node at @node to be written to the media - it
227  * calculates node CRC, fills the common header, and adds proper padding up to
228  * the next minimum I/O unit if @pad is not zero.
229  */
230 void ubifs_prepare_node(struct ubifs_info *c, void *node, int len, int pad)
231 {
232         uint32_t crc;
233         struct ubifs_ch *ch = node;
234         unsigned long long sqnum = next_sqnum(c);
235
236         ubifs_assert(len >= UBIFS_CH_SZ);
237
238         ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
239         ch->len = cpu_to_le32(len);
240         ch->group_type = UBIFS_NO_NODE_GROUP;
241         ch->sqnum = cpu_to_le64(sqnum);
242         ch->padding[0] = ch->padding[1] = 0;
243         crc = crc32(UBIFS_CRC32_INIT, node + 8, len - 8);
244         ch->crc = cpu_to_le32(crc);
245
246         if (pad) {
247                 len = ALIGN(len, 8);
248                 pad = ALIGN(len, c->min_io_size) - len;
249                 ubifs_pad(c, node + len, pad);
250         }
251 }
252
253 /**
254  * ubifs_prep_grp_node - prepare node of a group to be written to flash.
255  * @c: UBIFS file-system description object
256  * @node: the node to pad
257  * @len: node length
258  * @last: indicates the last node of the group
259  *
260  * This function prepares node at @node to be written to the media - it
261  * calculates node CRC and fills the common header.
262  */
263 void ubifs_prep_grp_node(struct ubifs_info *c, void *node, int len, int last)
264 {
265         uint32_t crc;
266         struct ubifs_ch *ch = node;
267         unsigned long long sqnum = next_sqnum(c);
268
269         ubifs_assert(len >= UBIFS_CH_SZ);
270
271         ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
272         ch->len = cpu_to_le32(len);
273         if (last)
274                 ch->group_type = UBIFS_LAST_OF_NODE_GROUP;
275         else
276                 ch->group_type = UBIFS_IN_NODE_GROUP;
277         ch->sqnum = cpu_to_le64(sqnum);
278         ch->padding[0] = ch->padding[1] = 0;
279         crc = crc32(UBIFS_CRC32_INIT, node + 8, len - 8);
280         ch->crc = cpu_to_le32(crc);
281 }
282
283 /**
284  * wbuf_timer_callback - write-buffer timer callback function.
285  * @data: timer data (write-buffer descriptor)
286  *
287  * This function is called when the write-buffer timer expires.
288  */
289 static void wbuf_timer_callback_nolock(unsigned long data)
290 {
291         struct ubifs_wbuf *wbuf = (struct ubifs_wbuf *)data;
292
293         wbuf->need_sync = 1;
294         wbuf->c->need_wbuf_sync = 1;
295         ubifs_wake_up_bgt(wbuf->c);
296 }
297
298 /**
299  * new_wbuf_timer - start new write-buffer timer.
300  * @wbuf: write-buffer descriptor
301  */
302 static void new_wbuf_timer_nolock(struct ubifs_wbuf *wbuf)
303 {
304         ubifs_assert(!timer_pending(&wbuf->timer));
305
306         if (!wbuf->timeout)
307                 return;
308
309         wbuf->timer.expires = jiffies + wbuf->timeout;
310         add_timer(&wbuf->timer);
311 }
312
313 /**
314  * cancel_wbuf_timer - cancel write-buffer timer.
315  * @wbuf: write-buffer descriptor
316  */
317 static void cancel_wbuf_timer_nolock(struct ubifs_wbuf *wbuf)
318 {
319         /*
320          * If the syncer is waiting for the lock (from the background thread's
321          * context) and another task is changing write-buffer then the syncing
322          * should be canceled.
323          */
324         wbuf->need_sync = 0;
325         del_timer(&wbuf->timer);
326 }
327
328 /**
329  * ubifs_wbuf_sync_nolock - synchronize write-buffer.
330  * @wbuf: write-buffer to synchronize
331  *
332  * This function synchronizes write-buffer @buf and returns zero in case of
333  * success or a negative error code in case of failure.
334  */
335 int ubifs_wbuf_sync_nolock(struct ubifs_wbuf *wbuf)
336 {
337         struct ubifs_info *c = wbuf->c;
338         int err, dirt;
339
340         cancel_wbuf_timer_nolock(wbuf);
341         if (!wbuf->used || wbuf->lnum == -1)
342                 /* Write-buffer is empty or not seeked */
343                 return 0;
344
345         dbg_io("LEB %d:%d, %d bytes",
346                wbuf->lnum, wbuf->offs, wbuf->used);
347         ubifs_assert(!(c->vfs_sb->s_flags & MS_RDONLY));
348         ubifs_assert(!(wbuf->avail & 7));
349         ubifs_assert(wbuf->offs + c->min_io_size <= c->leb_size);
350
351         if (c->ro_media)
352                 return -EROFS;
353
354         ubifs_pad(c, wbuf->buf + wbuf->used, wbuf->avail);
355         err = ubi_leb_write(c->ubi, wbuf->lnum, wbuf->buf, wbuf->offs,
356                             c->min_io_size, wbuf->dtype);
357         if (err) {
358                 ubifs_err("cannot write %d bytes to LEB %d:%d",
359                           c->min_io_size, wbuf->lnum, wbuf->offs);
360                 dbg_dump_stack();
361                 return err;
362         }
363
364         dirt = wbuf->avail;
365
366         spin_lock(&wbuf->lock);
367         wbuf->offs += c->min_io_size;
368         wbuf->avail = c->min_io_size;
369         wbuf->used = 0;
370         wbuf->next_ino = 0;
371         spin_unlock(&wbuf->lock);
372
373         if (wbuf->sync_callback)
374                 err = wbuf->sync_callback(c, wbuf->lnum,
375                                           c->leb_size - wbuf->offs, dirt);
376         return err;
377 }
378
379 /**
380  * ubifs_wbuf_seek_nolock - seek write-buffer.
381  * @wbuf: write-buffer
382  * @lnum: logical eraseblock number to seek to
383  * @offs: logical eraseblock offset to seek to
384  * @dtype: data type
385  *
386  * This function targets the write buffer to logical eraseblock @lnum:@offs.
387  * The write-buffer is synchronized if it is not empty. Returns zero in case of
388  * success and a negative error code in case of failure.
389  */
390 int ubifs_wbuf_seek_nolock(struct ubifs_wbuf *wbuf, int lnum, int offs,
391                            int dtype)
392 {
393         const struct ubifs_info *c = wbuf->c;
394
395         dbg_io("LEB %d:%d", lnum, offs);
396         ubifs_assert(lnum >= 0 && lnum < c->leb_cnt);
397         ubifs_assert(offs >= 0 && offs <= c->leb_size);
398         ubifs_assert(offs % c->min_io_size == 0 && !(offs & 7));
399         ubifs_assert(lnum != wbuf->lnum);
400
401         if (wbuf->used > 0) {
402                 int err = ubifs_wbuf_sync_nolock(wbuf);
403
404                 if (err)
405                         return err;
406         }
407
408         spin_lock(&wbuf->lock);
409         wbuf->lnum = lnum;
410         wbuf->offs = offs;
411         wbuf->avail = c->min_io_size;
412         wbuf->used = 0;
413         spin_unlock(&wbuf->lock);
414         wbuf->dtype = dtype;
415
416         return 0;
417 }
418
419 /**
420  * ubifs_bg_wbufs_sync - synchronize write-buffers.
421  * @c: UBIFS file-system description object
422  *
423  * This function is called by background thread to synchronize write-buffers.
424  * Returns zero in case of success and a negative error code in case of
425  * failure.
426  */
427 int ubifs_bg_wbufs_sync(struct ubifs_info *c)
428 {
429         int err, i;
430
431         if (!c->need_wbuf_sync)
432                 return 0;
433         c->need_wbuf_sync = 0;
434
435         if (c->ro_media) {
436                 err = -EROFS;
437                 goto out_timers;
438         }
439
440         dbg_io("synchronize");
441         for (i = 0; i < c->jhead_cnt; i++) {
442                 struct ubifs_wbuf *wbuf = &c->jheads[i].wbuf;
443
444                 cond_resched();
445
446                 /*
447                  * If the mutex is locked then wbuf is being changed, so
448                  * synchronization is not necessary.
449                  */
450                 if (mutex_is_locked(&wbuf->io_mutex))
451                         continue;
452
453                 mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
454                 if (!wbuf->need_sync) {
455                         mutex_unlock(&wbuf->io_mutex);
456                         continue;
457                 }
458
459                 err = ubifs_wbuf_sync_nolock(wbuf);
460                 mutex_unlock(&wbuf->io_mutex);
461                 if (err) {
462                         ubifs_err("cannot sync write-buffer, error %d", err);
463                         ubifs_ro_mode(c, err);
464                         goto out_timers;
465                 }
466         }
467
468         return 0;
469
470 out_timers:
471         /* Cancel all timers to prevent repeated errors */
472         for (i = 0; i < c->jhead_cnt; i++) {
473                 struct ubifs_wbuf *wbuf = &c->jheads[i].wbuf;
474
475                 mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
476                 cancel_wbuf_timer_nolock(wbuf);
477                 mutex_unlock(&wbuf->io_mutex);
478         }
479         return err;
480 }
481
482 /**
483  * ubifs_wbuf_write_nolock - write data to flash via write-buffer.
484  * @wbuf: write-buffer
485  * @buf: node to write
486  * @len: node length
487  *
488  * This function writes data to flash via write-buffer @wbuf. This means that
489  * the last piece of the node won't reach the flash media immediately if it
490  * does not take whole minimal I/O unit. Instead, the node will sit in RAM
491  * until the write-buffer is synchronized (e.g., by timer).
492  *
493  * This function returns zero in case of success and a negative error code in
494  * case of failure. If the node cannot be written because there is no more
495  * space in this logical eraseblock, %-ENOSPC is returned.
496  */
497 int ubifs_wbuf_write_nolock(struct ubifs_wbuf *wbuf, void *buf, int len)
498 {
499         struct ubifs_info *c = wbuf->c;
500         int err, written, n, aligned_len = ALIGN(len, 8), offs;
501
502         dbg_io("%d bytes (%s) to wbuf at LEB %d:%d", len,
503                dbg_ntype(((struct ubifs_ch *)buf)->node_type), wbuf->lnum,
504                wbuf->offs + wbuf->used);
505         ubifs_assert(len > 0 && wbuf->lnum >= 0 && wbuf->lnum < c->leb_cnt);
506         ubifs_assert(wbuf->offs >= 0 && wbuf->offs % c->min_io_size == 0);
507         ubifs_assert(!(wbuf->offs & 7) && wbuf->offs <= c->leb_size);
508         ubifs_assert(wbuf->avail > 0 && wbuf->avail <= c->min_io_size);
509         ubifs_assert(mutex_is_locked(&wbuf->io_mutex));
510
511         if (c->leb_size - wbuf->offs - wbuf->used < aligned_len) {
512                 err = -ENOSPC;
513                 goto out;
514         }
515
516         cancel_wbuf_timer_nolock(wbuf);
517
518         if (c->ro_media)
519                 return -EROFS;
520
521         if (aligned_len <= wbuf->avail) {
522                 /*
523                  * The node is not very large and fits entirely within
524                  * write-buffer.
525                  */
526                 memcpy(wbuf->buf + wbuf->used, buf, len);
527
528                 if (aligned_len == wbuf->avail) {
529                         dbg_io("flush wbuf to LEB %d:%d", wbuf->lnum,
530                                 wbuf->offs);
531                         err = ubi_leb_write(c->ubi, wbuf->lnum, wbuf->buf,
532                                             wbuf->offs, c->min_io_size,
533                                             wbuf->dtype);
534                         if (err)
535                                 goto out;
536
537                         spin_lock(&wbuf->lock);
538                         wbuf->offs += c->min_io_size;
539                         wbuf->avail = c->min_io_size;
540                         wbuf->used = 0;
541                         wbuf->next_ino = 0;
542                         spin_unlock(&wbuf->lock);
543                 } else {
544                         spin_lock(&wbuf->lock);
545                         wbuf->avail -= aligned_len;
546                         wbuf->used += aligned_len;
547                         spin_unlock(&wbuf->lock);
548                 }
549
550                 goto exit;
551         }
552
553         /*
554          * The node is large enough and does not fit entirely within current
555          * minimal I/O unit. We have to fill and flush write-buffer and switch
556          * to the next min. I/O unit.
557          */
558         dbg_io("flush wbuf to LEB %d:%d", wbuf->lnum, wbuf->offs);
559         memcpy(wbuf->buf + wbuf->used, buf, wbuf->avail);
560         err = ubi_leb_write(c->ubi, wbuf->lnum, wbuf->buf, wbuf->offs,
561                             c->min_io_size, wbuf->dtype);
562         if (err)
563                 goto out;
564
565         offs = wbuf->offs + c->min_io_size;
566         len -= wbuf->avail;
567         aligned_len -= wbuf->avail;
568         written = wbuf->avail;
569
570         /*
571          * The remaining data may take more whole min. I/O units, so write the
572          * remains multiple to min. I/O unit size directly to the flash media.
573          * We align node length to 8-byte boundary because we anyway flash wbuf
574          * if the remaining space is less than 8 bytes.
575          */
576         n = aligned_len >> c->min_io_shift;
577         if (n) {
578                 n <<= c->min_io_shift;
579                 dbg_io("write %d bytes to LEB %d:%d", n, wbuf->lnum, offs);
580                 err = ubi_leb_write(c->ubi, wbuf->lnum, buf + written, offs, n,
581                                     wbuf->dtype);
582                 if (err)
583                         goto out;
584                 offs += n;
585                 aligned_len -= n;
586                 len -= n;
587                 written += n;
588         }
589
590         spin_lock(&wbuf->lock);
591         if (aligned_len)
592                 /*
593                  * And now we have what's left and what does not take whole
594                  * min. I/O unit, so write it to the write-buffer and we are
595                  * done.
596                  */
597                 memcpy(wbuf->buf, buf + written, len);
598
599         wbuf->offs = offs;
600         wbuf->used = aligned_len;
601         wbuf->avail = c->min_io_size - aligned_len;
602         wbuf->next_ino = 0;
603         spin_unlock(&wbuf->lock);
604
605 exit:
606         if (wbuf->sync_callback) {
607                 int free = c->leb_size - wbuf->offs - wbuf->used;
608
609                 err = wbuf->sync_callback(c, wbuf->lnum, free, 0);
610                 if (err)
611                         goto out;
612         }
613
614         if (wbuf->used)
615                 new_wbuf_timer_nolock(wbuf);
616
617         return 0;
618
619 out:
620         ubifs_err("cannot write %d bytes to LEB %d:%d, error %d",
621                   len, wbuf->lnum, wbuf->offs, err);
622         dbg_dump_node(c, buf);
623         dbg_dump_stack();
624         dbg_dump_leb(c, wbuf->lnum);
625         return err;
626 }
627
628 /**
629  * ubifs_write_node - write node to the media.
630  * @c: UBIFS file-system description object
631  * @buf: the node to write
632  * @len: node length
633  * @lnum: logical eraseblock number
634  * @offs: offset within the logical eraseblock
635  * @dtype: node life-time hint (%UBI_LONGTERM, %UBI_SHORTTERM, %UBI_UNKNOWN)
636  *
637  * This function automatically fills node magic number, assigns sequence
638  * number, and calculates node CRC checksum. The length of the @buf buffer has
639  * to be aligned to the minimal I/O unit size. This function automatically
640  * appends padding node and padding bytes if needed. Returns zero in case of
641  * success and a negative error code in case of failure.
642  */
643 int ubifs_write_node(struct ubifs_info *c, void *buf, int len, int lnum,
644                      int offs, int dtype)
645 {
646         int err, buf_len = ALIGN(len, c->min_io_size);
647
648         dbg_io("LEB %d:%d, %s, length %d (aligned %d)",
649                lnum, offs, dbg_ntype(((struct ubifs_ch *)buf)->node_type), len,
650                buf_len);
651         ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
652         ubifs_assert(offs % c->min_io_size == 0 && offs < c->leb_size);
653
654         if (c->ro_media)
655                 return -EROFS;
656
657         ubifs_prepare_node(c, buf, len, 1);
658         err = ubi_leb_write(c->ubi, lnum, buf, offs, buf_len, dtype);
659         if (err) {
660                 ubifs_err("cannot write %d bytes to LEB %d:%d, error %d",
661                           buf_len, lnum, offs, err);
662                 dbg_dump_node(c, buf);
663                 dbg_dump_stack();
664         }
665
666         return err;
667 }
668
669 /**
670  * ubifs_read_node_wbuf - read node from the media or write-buffer.
671  * @wbuf: wbuf to check for un-written data
672  * @buf: buffer to read to
673  * @type: node type
674  * @len: node length
675  * @lnum: logical eraseblock number
676  * @offs: offset within the logical eraseblock
677  *
678  * This function reads a node of known type and length, checks it and stores
679  * in @buf. If the node partially or fully sits in the write-buffer, this
680  * function takes data from the buffer, otherwise it reads the flash media.
681  * Returns zero in case of success, %-EUCLEAN if CRC mismatched and a negative
682  * error code in case of failure.
683  */
684 int ubifs_read_node_wbuf(struct ubifs_wbuf *wbuf, void *buf, int type, int len,
685                          int lnum, int offs)
686 {
687         const struct ubifs_info *c = wbuf->c;
688         int err, rlen, overlap;
689         struct ubifs_ch *ch = buf;
690
691         dbg_io("LEB %d:%d, %s, length %d", lnum, offs, dbg_ntype(type), len);
692         ubifs_assert(wbuf && lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
693         ubifs_assert(!(offs & 7) && offs < c->leb_size);
694         ubifs_assert(type >= 0 && type < UBIFS_NODE_TYPES_CNT);
695
696         spin_lock(&wbuf->lock);
697         overlap = (lnum == wbuf->lnum && offs + len > wbuf->offs);
698         if (!overlap) {
699                 /* We may safely unlock the write-buffer and read the data */
700                 spin_unlock(&wbuf->lock);
701                 return ubifs_read_node(c, buf, type, len, lnum, offs);
702         }
703
704         /* Don't read under wbuf */
705         rlen = wbuf->offs - offs;
706         if (rlen < 0)
707                 rlen = 0;
708
709         /* Copy the rest from the write-buffer */
710         memcpy(buf + rlen, wbuf->buf + offs + rlen - wbuf->offs, len - rlen);
711         spin_unlock(&wbuf->lock);
712
713         if (rlen > 0) {
714                 /* Read everything that goes before write-buffer */
715                 err = ubi_read(c->ubi, lnum, buf, offs, rlen);
716                 if (err && err != -EBADMSG) {
717                         ubifs_err("failed to read node %d from LEB %d:%d, "
718                                   "error %d", type, lnum, offs, err);
719                         dbg_dump_stack();
720                         return err;
721                 }
722         }
723
724         if (type != ch->node_type) {
725                 ubifs_err("bad node type (%d but expected %d)",
726                           ch->node_type, type);
727                 goto out;
728         }
729
730         err = ubifs_check_node(c, buf, lnum, offs, 0, 0);
731         if (err) {
732                 ubifs_err("expected node type %d", type);
733                 return err;
734         }
735
736         rlen = le32_to_cpu(ch->len);
737         if (rlen != len) {
738                 ubifs_err("bad node length %d, expected %d", rlen, len);
739                 goto out;
740         }
741
742         return 0;
743
744 out:
745         ubifs_err("bad node at LEB %d:%d", lnum, offs);
746         dbg_dump_node(c, buf);
747         dbg_dump_stack();
748         return -EINVAL;
749 }
750
751 /**
752  * ubifs_read_node - read node.
753  * @c: UBIFS file-system description object
754  * @buf: buffer to read to
755  * @type: node type
756  * @len: node length (not aligned)
757  * @lnum: logical eraseblock number
758  * @offs: offset within the logical eraseblock
759  *
760  * This function reads a node of known type and and length, checks it and
761  * stores in @buf. Returns zero in case of success, %-EUCLEAN if CRC mismatched
762  * and a negative error code in case of failure.
763  */
764 int ubifs_read_node(const struct ubifs_info *c, void *buf, int type, int len,
765                     int lnum, int offs)
766 {
767         int err, l;
768         struct ubifs_ch *ch = buf;
769
770         dbg_io("LEB %d:%d, %s, length %d", lnum, offs, dbg_ntype(type), len);
771         ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
772         ubifs_assert(len >= UBIFS_CH_SZ && offs + len <= c->leb_size);
773         ubifs_assert(!(offs & 7) && offs < c->leb_size);
774         ubifs_assert(type >= 0 && type < UBIFS_NODE_TYPES_CNT);
775
776         err = ubi_read(c->ubi, lnum, buf, offs, len);
777         if (err && err != -EBADMSG) {
778                 ubifs_err("cannot read node %d from LEB %d:%d, error %d",
779                           type, lnum, offs, err);
780                 return err;
781         }
782
783         if (type != ch->node_type) {
784                 ubifs_err("bad node type (%d but expected %d)",
785                           ch->node_type, type);
786                 goto out;
787         }
788
789         err = ubifs_check_node(c, buf, lnum, offs, 0, 0);
790         if (err) {
791                 ubifs_err("expected node type %d", type);
792                 return err;
793         }
794
795         l = le32_to_cpu(ch->len);
796         if (l != len) {
797                 ubifs_err("bad node length %d, expected %d", l, len);
798                 goto out;
799         }
800
801         return 0;
802
803 out:
804         ubifs_err("bad node at LEB %d:%d", lnum, offs);
805         dbg_dump_node(c, buf);
806         dbg_dump_stack();
807         return -EINVAL;
808 }
809
810 /**
811  * ubifs_wbuf_init - initialize write-buffer.
812  * @c: UBIFS file-system description object
813  * @wbuf: write-buffer to initialize
814  *
815  * This function initializes write buffer. Returns zero in case of success
816  * %-ENOMEM in case of failure.
817  */
818 int ubifs_wbuf_init(struct ubifs_info *c, struct ubifs_wbuf *wbuf)
819 {
820         size_t size;
821
822         wbuf->buf = kmalloc(c->min_io_size, GFP_KERNEL);
823         if (!wbuf->buf)
824                 return -ENOMEM;
825
826         size = (c->min_io_size / UBIFS_CH_SZ + 1) * sizeof(ino_t);
827         wbuf->inodes = kmalloc(size, GFP_KERNEL);
828         if (!wbuf->inodes) {
829                 kfree(wbuf->buf);
830                 wbuf->buf = NULL;
831                 return -ENOMEM;
832         }
833
834         wbuf->used = 0;
835         wbuf->lnum = wbuf->offs = -1;
836         wbuf->avail = c->min_io_size;
837         wbuf->dtype = UBI_UNKNOWN;
838         wbuf->sync_callback = NULL;
839         mutex_init(&wbuf->io_mutex);
840         spin_lock_init(&wbuf->lock);
841
842         wbuf->c = c;
843         init_timer(&wbuf->timer);
844         wbuf->timer.function = wbuf_timer_callback_nolock;
845         wbuf->timer.data = (unsigned long)wbuf;
846         wbuf->timeout = DEFAULT_WBUF_TIMEOUT;
847         wbuf->next_ino = 0;
848
849         return 0;
850 }
851
852 /**
853  * ubifs_wbuf_add_ino_nolock - add an inode number into the wbuf inode array.
854  * @wbuf: the write-buffer whereto add
855  * @inum: the inode number
856  *
857  * This function adds an inode number to the inode array of the write-buffer.
858  */
859 void ubifs_wbuf_add_ino_nolock(struct ubifs_wbuf *wbuf, ino_t inum)
860 {
861         if (!wbuf->buf)
862                 /* NOR flash or something similar */
863                 return;
864
865         spin_lock(&wbuf->lock);
866         if (wbuf->used)
867                 wbuf->inodes[wbuf->next_ino++] = inum;
868         spin_unlock(&wbuf->lock);
869 }
870
871 /**
872  * wbuf_has_ino - returns if the wbuf contains data from the inode.
873  * @wbuf: the write-buffer
874  * @inum: the inode number
875  *
876  * This function returns with %1 if the write-buffer contains some data from the
877  * given inode otherwise it returns with %0.
878  */
879 static int wbuf_has_ino(struct ubifs_wbuf *wbuf, ino_t inum)
880 {
881         int i, ret = 0;
882
883         spin_lock(&wbuf->lock);
884         for (i = 0; i < wbuf->next_ino; i++)
885                 if (inum == wbuf->inodes[i]) {
886                         ret = 1;
887                         break;
888                 }
889         spin_unlock(&wbuf->lock);
890
891         return ret;
892 }
893
894 /**
895  * ubifs_sync_wbufs_by_inode - synchronize write-buffers for an inode.
896  * @c: UBIFS file-system description object
897  * @inode: inode to synchronize
898  *
899  * This function synchronizes write-buffers which contain nodes belonging to
900  * @inode. Returns zero in case of success and a negative error code in case of
901  * failure.
902  */
903 int ubifs_sync_wbufs_by_inode(struct ubifs_info *c, struct inode *inode)
904 {
905         int i, err = 0;
906
907         for (i = 0; i < c->jhead_cnt; i++) {
908                 struct ubifs_wbuf *wbuf = &c->jheads[i].wbuf;
909
910                 if (i == GCHD)
911                         /*
912                          * GC head is special, do not look at it. Even if the
913                          * head contains something related to this inode, it is
914                          * a _copy_ of corresponding on-flash node which sits
915                          * somewhere else.
916                          */
917                         continue;
918
919                 if (!wbuf_has_ino(wbuf, inode->i_ino))
920                         continue;
921
922                 mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
923                 if (wbuf_has_ino(wbuf, inode->i_ino))
924                         err = ubifs_wbuf_sync_nolock(wbuf);
925                 mutex_unlock(&wbuf->io_mutex);
926
927                 if (err) {
928                         ubifs_ro_mode(c, err);
929                         return err;
930                 }
931         }
932         return 0;
933 }