[PATCH] aoe: update to version 14
[linux-2.6] / fs / ntfs / aops.c
1 /**
2  * aops.c - NTFS kernel address space operations and page cache handling.
3  *          Part of the Linux-NTFS project.
4  *
5  * Copyright (c) 2001-2005 Anton Altaparmakov
6  * Copyright (c) 2002 Richard Russon
7  *
8  * This program/include file is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as published
10  * by the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program/include file is distributed in the hope that it will be
14  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program (in the main directory of the Linux-NTFS
20  * distribution in the file COPYING); if not, write to the Free Software
21  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include <linux/errno.h>
25 #include <linux/mm.h>
26 #include <linux/pagemap.h>
27 #include <linux/swap.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/bit_spinlock.h>
31
32 #include "aops.h"
33 #include "attrib.h"
34 #include "debug.h"
35 #include "inode.h"
36 #include "mft.h"
37 #include "runlist.h"
38 #include "types.h"
39 #include "ntfs.h"
40
41 /**
42  * ntfs_end_buffer_async_read - async io completion for reading attributes
43  * @bh:         buffer head on which io is completed
44  * @uptodate:   whether @bh is now uptodate or not
45  *
46  * Asynchronous I/O completion handler for reading pages belonging to the
47  * attribute address space of an inode.  The inodes can either be files or
48  * directories or they can be fake inodes describing some attribute.
49  *
50  * If NInoMstProtected(), perform the post read mst fixups when all IO on the
51  * page has been completed and mark the page uptodate or set the error bit on
52  * the page.  To determine the size of the records that need fixing up, we
53  * cheat a little bit by setting the index_block_size in ntfs_inode to the ntfs
54  * record size, and index_block_size_bits, to the log(base 2) of the ntfs
55  * record size.
56  */
57 static void ntfs_end_buffer_async_read(struct buffer_head *bh, int uptodate)
58 {
59         unsigned long flags;
60         struct buffer_head *first, *tmp;
61         struct page *page;
62         struct inode *vi;
63         ntfs_inode *ni;
64         int page_uptodate = 1;
65
66         page = bh->b_page;
67         vi = page->mapping->host;
68         ni = NTFS_I(vi);
69
70         if (likely(uptodate)) {
71                 loff_t i_size;
72                 s64 file_ofs, init_size;
73
74                 set_buffer_uptodate(bh);
75
76                 file_ofs = ((s64)page->index << PAGE_CACHE_SHIFT) +
77                                 bh_offset(bh);
78                 read_lock_irqsave(&ni->size_lock, flags);
79                 init_size = ni->initialized_size;
80                 i_size = i_size_read(vi);
81                 read_unlock_irqrestore(&ni->size_lock, flags);
82                 if (unlikely(init_size > i_size)) {
83                         /* Race with shrinking truncate. */
84                         init_size = i_size;
85                 }
86                 /* Check for the current buffer head overflowing. */
87                 if (unlikely(file_ofs + bh->b_size > init_size)) {
88                         u8 *kaddr;
89                         int ofs;
90
91                         ofs = 0;
92                         if (file_ofs < init_size)
93                                 ofs = init_size - file_ofs;
94                         kaddr = kmap_atomic(page, KM_BIO_SRC_IRQ);
95                         memset(kaddr + bh_offset(bh) + ofs, 0,
96                                         bh->b_size - ofs);
97                         kunmap_atomic(kaddr, KM_BIO_SRC_IRQ);
98                         flush_dcache_page(page);
99                 }
100         } else {
101                 clear_buffer_uptodate(bh);
102                 SetPageError(page);
103                 ntfs_error(ni->vol->sb, "Buffer I/O error, logical block "
104                                 "0x%llx.", (unsigned long long)bh->b_blocknr);
105         }
106         first = page_buffers(page);
107         local_irq_save(flags);
108         bit_spin_lock(BH_Uptodate_Lock, &first->b_state);
109         clear_buffer_async_read(bh);
110         unlock_buffer(bh);
111         tmp = bh;
112         do {
113                 if (!buffer_uptodate(tmp))
114                         page_uptodate = 0;
115                 if (buffer_async_read(tmp)) {
116                         if (likely(buffer_locked(tmp)))
117                                 goto still_busy;
118                         /* Async buffers must be locked. */
119                         BUG();
120                 }
121                 tmp = tmp->b_this_page;
122         } while (tmp != bh);
123         bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
124         local_irq_restore(flags);
125         /*
126          * If none of the buffers had errors then we can set the page uptodate,
127          * but we first have to perform the post read mst fixups, if the
128          * attribute is mst protected, i.e. if NInoMstProteced(ni) is true.
129          * Note we ignore fixup errors as those are detected when
130          * map_mft_record() is called which gives us per record granularity
131          * rather than per page granularity.
132          */
133         if (!NInoMstProtected(ni)) {
134                 if (likely(page_uptodate && !PageError(page)))
135                         SetPageUptodate(page);
136         } else {
137                 u8 *kaddr;
138                 unsigned int i, recs;
139                 u32 rec_size;
140
141                 rec_size = ni->itype.index.block_size;
142                 recs = PAGE_CACHE_SIZE / rec_size;
143                 /* Should have been verified before we got here... */
144                 BUG_ON(!recs);
145                 kaddr = kmap_atomic(page, KM_BIO_SRC_IRQ);
146                 for (i = 0; i < recs; i++)
147                         post_read_mst_fixup((NTFS_RECORD*)(kaddr +
148                                         i * rec_size), rec_size);
149                 kunmap_atomic(kaddr, KM_BIO_SRC_IRQ);
150                 flush_dcache_page(page);
151                 if (likely(page_uptodate && !PageError(page)))
152                         SetPageUptodate(page);
153         }
154         unlock_page(page);
155         return;
156 still_busy:
157         bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
158         local_irq_restore(flags);
159         return;
160 }
161
162 /**
163  * ntfs_read_block - fill a @page of an address space with data
164  * @page:       page cache page to fill with data
165  *
166  * Fill the page @page of the address space belonging to the @page->host inode.
167  * We read each buffer asynchronously and when all buffers are read in, our io
168  * completion handler ntfs_end_buffer_read_async(), if required, automatically
169  * applies the mst fixups to the page before finally marking it uptodate and
170  * unlocking it.
171  *
172  * We only enforce allocated_size limit because i_size is checked for in
173  * generic_file_read().
174  *
175  * Return 0 on success and -errno on error.
176  *
177  * Contains an adapted version of fs/buffer.c::block_read_full_page().
178  */
179 static int ntfs_read_block(struct page *page)
180 {
181         loff_t i_size;
182         VCN vcn;
183         LCN lcn;
184         s64 init_size;
185         struct inode *vi;
186         ntfs_inode *ni;
187         ntfs_volume *vol;
188         runlist_element *rl;
189         struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
190         sector_t iblock, lblock, zblock;
191         unsigned long flags;
192         unsigned int blocksize, vcn_ofs;
193         int i, nr;
194         unsigned char blocksize_bits;
195
196         vi = page->mapping->host;
197         ni = NTFS_I(vi);
198         vol = ni->vol;
199
200         /* $MFT/$DATA must have its complete runlist in memory at all times. */
201         BUG_ON(!ni->runlist.rl && !ni->mft_no && !NInoAttr(ni));
202
203         blocksize_bits = VFS_I(ni)->i_blkbits;
204         blocksize = 1 << blocksize_bits;
205
206         if (!page_has_buffers(page)) {
207                 create_empty_buffers(page, blocksize, 0);
208                 if (unlikely(!page_has_buffers(page))) {
209                         unlock_page(page);
210                         return -ENOMEM;
211                 }
212         }
213         bh = head = page_buffers(page);
214         BUG_ON(!bh);
215
216         /*
217          * We may be racing with truncate.  To avoid some of the problems we
218          * now take a snapshot of the various sizes and use those for the whole
219          * of the function.  In case of an extending truncate it just means we
220          * may leave some buffers unmapped which are now allocated.  This is
221          * not a problem since these buffers will just get mapped when a write
222          * occurs.  In case of a shrinking truncate, we will detect this later
223          * on due to the runlist being incomplete and if the page is being
224          * fully truncated, truncate will throw it away as soon as we unlock
225          * it so no need to worry what we do with it.
226          */
227         iblock = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
228         read_lock_irqsave(&ni->size_lock, flags);
229         lblock = (ni->allocated_size + blocksize - 1) >> blocksize_bits;
230         init_size = ni->initialized_size;
231         i_size = i_size_read(vi);
232         read_unlock_irqrestore(&ni->size_lock, flags);
233         if (unlikely(init_size > i_size)) {
234                 /* Race with shrinking truncate. */
235                 init_size = i_size;
236         }
237         zblock = (init_size + blocksize - 1) >> blocksize_bits;
238
239         /* Loop through all the buffers in the page. */
240         rl = NULL;
241         nr = i = 0;
242         do {
243                 u8 *kaddr;
244                 int err;
245
246                 if (unlikely(buffer_uptodate(bh)))
247                         continue;
248                 if (unlikely(buffer_mapped(bh))) {
249                         arr[nr++] = bh;
250                         continue;
251                 }
252                 err = 0;
253                 bh->b_bdev = vol->sb->s_bdev;
254                 /* Is the block within the allowed limits? */
255                 if (iblock < lblock) {
256                         BOOL is_retry = FALSE;
257
258                         /* Convert iblock into corresponding vcn and offset. */
259                         vcn = (VCN)iblock << blocksize_bits >>
260                                         vol->cluster_size_bits;
261                         vcn_ofs = ((VCN)iblock << blocksize_bits) &
262                                         vol->cluster_size_mask;
263                         if (!rl) {
264 lock_retry_remap:
265                                 down_read(&ni->runlist.lock);
266                                 rl = ni->runlist.rl;
267                         }
268                         if (likely(rl != NULL)) {
269                                 /* Seek to element containing target vcn. */
270                                 while (rl->length && rl[1].vcn <= vcn)
271                                         rl++;
272                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
273                         } else
274                                 lcn = LCN_RL_NOT_MAPPED;
275                         /* Successful remap. */
276                         if (lcn >= 0) {
277                                 /* Setup buffer head to correct block. */
278                                 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
279                                                 + vcn_ofs) >> blocksize_bits;
280                                 set_buffer_mapped(bh);
281                                 /* Only read initialized data blocks. */
282                                 if (iblock < zblock) {
283                                         arr[nr++] = bh;
284                                         continue;
285                                 }
286                                 /* Fully non-initialized data block, zero it. */
287                                 goto handle_zblock;
288                         }
289                         /* It is a hole, need to zero it. */
290                         if (lcn == LCN_HOLE)
291                                 goto handle_hole;
292                         /* If first try and runlist unmapped, map and retry. */
293                         if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
294                                 is_retry = TRUE;
295                                 /*
296                                  * Attempt to map runlist, dropping lock for
297                                  * the duration.
298                                  */
299                                 up_read(&ni->runlist.lock);
300                                 err = ntfs_map_runlist(ni, vcn);
301                                 if (likely(!err))
302                                         goto lock_retry_remap;
303                                 rl = NULL;
304                         } else if (!rl)
305                                 up_read(&ni->runlist.lock);
306                         /*
307                          * If buffer is outside the runlist, treat it as a
308                          * hole.  This can happen due to concurrent truncate
309                          * for example.
310                          */
311                         if (err == -ENOENT || lcn == LCN_ENOENT) {
312                                 err = 0;
313                                 goto handle_hole;
314                         }
315                         /* Hard error, zero out region. */
316                         if (!err)
317                                 err = -EIO;
318                         bh->b_blocknr = -1;
319                         SetPageError(page);
320                         ntfs_error(vol->sb, "Failed to read from inode 0x%lx, "
321                                         "attribute type 0x%x, vcn 0x%llx, "
322                                         "offset 0x%x because its location on "
323                                         "disk could not be determined%s "
324                                         "(error code %i).", ni->mft_no,
325                                         ni->type, (unsigned long long)vcn,
326                                         vcn_ofs, is_retry ? " even after "
327                                         "retrying" : "", err);
328                 }
329                 /*
330                  * Either iblock was outside lblock limits or
331                  * ntfs_rl_vcn_to_lcn() returned error.  Just zero that portion
332                  * of the page and set the buffer uptodate.
333                  */
334 handle_hole:
335                 bh->b_blocknr = -1UL;
336                 clear_buffer_mapped(bh);
337 handle_zblock:
338                 kaddr = kmap_atomic(page, KM_USER0);
339                 memset(kaddr + i * blocksize, 0, blocksize);
340                 kunmap_atomic(kaddr, KM_USER0);
341                 flush_dcache_page(page);
342                 if (likely(!err))
343                         set_buffer_uptodate(bh);
344         } while (i++, iblock++, (bh = bh->b_this_page) != head);
345
346         /* Release the lock if we took it. */
347         if (rl)
348                 up_read(&ni->runlist.lock);
349
350         /* Check we have at least one buffer ready for i/o. */
351         if (nr) {
352                 struct buffer_head *tbh;
353
354                 /* Lock the buffers. */
355                 for (i = 0; i < nr; i++) {
356                         tbh = arr[i];
357                         lock_buffer(tbh);
358                         tbh->b_end_io = ntfs_end_buffer_async_read;
359                         set_buffer_async_read(tbh);
360                 }
361                 /* Finally, start i/o on the buffers. */
362                 for (i = 0; i < nr; i++) {
363                         tbh = arr[i];
364                         if (likely(!buffer_uptodate(tbh)))
365                                 submit_bh(READ, tbh);
366                         else
367                                 ntfs_end_buffer_async_read(tbh, 1);
368                 }
369                 return 0;
370         }
371         /* No i/o was scheduled on any of the buffers. */
372         if (likely(!PageError(page)))
373                 SetPageUptodate(page);
374         else /* Signal synchronous i/o error. */
375                 nr = -EIO;
376         unlock_page(page);
377         return nr;
378 }
379
380 /**
381  * ntfs_readpage - fill a @page of a @file with data from the device
382  * @file:       open file to which the page @page belongs or NULL
383  * @page:       page cache page to fill with data
384  *
385  * For non-resident attributes, ntfs_readpage() fills the @page of the open
386  * file @file by calling the ntfs version of the generic block_read_full_page()
387  * function, ntfs_read_block(), which in turn creates and reads in the buffers
388  * associated with the page asynchronously.
389  *
390  * For resident attributes, OTOH, ntfs_readpage() fills @page by copying the
391  * data from the mft record (which at this stage is most likely in memory) and
392  * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
393  * even if the mft record is not cached at this point in time, we need to wait
394  * for it to be read in before we can do the copy.
395  *
396  * Return 0 on success and -errno on error.
397  */
398 static int ntfs_readpage(struct file *file, struct page *page)
399 {
400         loff_t i_size;
401         struct inode *vi;
402         ntfs_inode *ni, *base_ni;
403         u8 *kaddr;
404         ntfs_attr_search_ctx *ctx;
405         MFT_RECORD *mrec;
406         unsigned long flags;
407         u32 attr_len;
408         int err = 0;
409
410 retry_readpage:
411         BUG_ON(!PageLocked(page));
412         /*
413          * This can potentially happen because we clear PageUptodate() during
414          * ntfs_writepage() of MstProtected() attributes.
415          */
416         if (PageUptodate(page)) {
417                 unlock_page(page);
418                 return 0;
419         }
420         vi = page->mapping->host;
421         ni = NTFS_I(vi);
422         /*
423          * Only $DATA attributes can be encrypted and only unnamed $DATA
424          * attributes can be compressed.  Index root can have the flags set but
425          * this means to create compressed/encrypted files, not that the
426          * attribute is compressed/encrypted.  Note we need to check for
427          * AT_INDEX_ALLOCATION since this is the type of both directory and
428          * index inodes.
429          */
430         if (ni->type != AT_INDEX_ALLOCATION) {
431                 /* If attribute is encrypted, deny access, just like NT4. */
432                 if (NInoEncrypted(ni)) {
433                         BUG_ON(ni->type != AT_DATA);
434                         err = -EACCES;
435                         goto err_out;
436                 }
437                 /* Compressed data streams are handled in compress.c. */
438                 if (NInoNonResident(ni) && NInoCompressed(ni)) {
439                         BUG_ON(ni->type != AT_DATA);
440                         BUG_ON(ni->name_len);
441                         return ntfs_read_compressed_block(page);
442                 }
443         }
444         /* NInoNonResident() == NInoIndexAllocPresent() */
445         if (NInoNonResident(ni)) {
446                 /* Normal, non-resident data stream. */
447                 return ntfs_read_block(page);
448         }
449         /*
450          * Attribute is resident, implying it is not compressed or encrypted.
451          * This also means the attribute is smaller than an mft record and
452          * hence smaller than a page, so can simply zero out any pages with
453          * index above 0.  Note the attribute can actually be marked compressed
454          * but if it is resident the actual data is not compressed so we are
455          * ok to ignore the compressed flag here.
456          */
457         if (unlikely(page->index > 0)) {
458                 kaddr = kmap_atomic(page, KM_USER0);
459                 memset(kaddr, 0, PAGE_CACHE_SIZE);
460                 flush_dcache_page(page);
461                 kunmap_atomic(kaddr, KM_USER0);
462                 goto done;
463         }
464         if (!NInoAttr(ni))
465                 base_ni = ni;
466         else
467                 base_ni = ni->ext.base_ntfs_ino;
468         /* Map, pin, and lock the mft record. */
469         mrec = map_mft_record(base_ni);
470         if (IS_ERR(mrec)) {
471                 err = PTR_ERR(mrec);
472                 goto err_out;
473         }
474         /*
475          * If a parallel write made the attribute non-resident, drop the mft
476          * record and retry the readpage.
477          */
478         if (unlikely(NInoNonResident(ni))) {
479                 unmap_mft_record(base_ni);
480                 goto retry_readpage;
481         }
482         ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
483         if (unlikely(!ctx)) {
484                 err = -ENOMEM;
485                 goto unm_err_out;
486         }
487         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
488                         CASE_SENSITIVE, 0, NULL, 0, ctx);
489         if (unlikely(err))
490                 goto put_unm_err_out;
491         attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
492         read_lock_irqsave(&ni->size_lock, flags);
493         if (unlikely(attr_len > ni->initialized_size))
494                 attr_len = ni->initialized_size;
495         i_size = i_size_read(vi);
496         read_unlock_irqrestore(&ni->size_lock, flags);
497         if (unlikely(attr_len > i_size)) {
498                 /* Race with shrinking truncate. */
499                 attr_len = i_size;
500         }
501         kaddr = kmap_atomic(page, KM_USER0);
502         /* Copy the data to the page. */
503         memcpy(kaddr, (u8*)ctx->attr +
504                         le16_to_cpu(ctx->attr->data.resident.value_offset),
505                         attr_len);
506         /* Zero the remainder of the page. */
507         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
508         flush_dcache_page(page);
509         kunmap_atomic(kaddr, KM_USER0);
510 put_unm_err_out:
511         ntfs_attr_put_search_ctx(ctx);
512 unm_err_out:
513         unmap_mft_record(base_ni);
514 done:
515         SetPageUptodate(page);
516 err_out:
517         unlock_page(page);
518         return err;
519 }
520
521 #ifdef NTFS_RW
522
523 /**
524  * ntfs_write_block - write a @page to the backing store
525  * @page:       page cache page to write out
526  * @wbc:        writeback control structure
527  *
528  * This function is for writing pages belonging to non-resident, non-mst
529  * protected attributes to their backing store.
530  *
531  * For a page with buffers, map and write the dirty buffers asynchronously
532  * under page writeback. For a page without buffers, create buffers for the
533  * page, then proceed as above.
534  *
535  * If a page doesn't have buffers the page dirty state is definitive. If a page
536  * does have buffers, the page dirty state is just a hint, and the buffer dirty
537  * state is definitive. (A hint which has rules: dirty buffers against a clean
538  * page is illegal. Other combinations are legal and need to be handled. In
539  * particular a dirty page containing clean buffers for example.)
540  *
541  * Return 0 on success and -errno on error.
542  *
543  * Based on ntfs_read_block() and __block_write_full_page().
544  */
545 static int ntfs_write_block(struct page *page, struct writeback_control *wbc)
546 {
547         VCN vcn;
548         LCN lcn;
549         s64 initialized_size;
550         loff_t i_size;
551         sector_t block, dblock, iblock;
552         struct inode *vi;
553         ntfs_inode *ni;
554         ntfs_volume *vol;
555         runlist_element *rl;
556         struct buffer_head *bh, *head;
557         unsigned long flags;
558         unsigned int blocksize, vcn_ofs;
559         int err;
560         BOOL need_end_writeback;
561         unsigned char blocksize_bits;
562
563         vi = page->mapping->host;
564         ni = NTFS_I(vi);
565         vol = ni->vol;
566
567         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
568                         "0x%lx.", ni->mft_no, ni->type, page->index);
569
570         BUG_ON(!NInoNonResident(ni));
571         BUG_ON(NInoMstProtected(ni));
572
573         blocksize_bits = vi->i_blkbits;
574         blocksize = 1 << blocksize_bits;
575
576         if (!page_has_buffers(page)) {
577                 BUG_ON(!PageUptodate(page));
578                 create_empty_buffers(page, blocksize,
579                                 (1 << BH_Uptodate) | (1 << BH_Dirty));
580                 if (unlikely(!page_has_buffers(page))) {
581                         ntfs_warning(vol->sb, "Error allocating page "
582                                         "buffers.  Redirtying page so we try "
583                                         "again later.");
584                         /*
585                          * Put the page back on mapping->dirty_pages, but leave
586                          * its buffers' dirty state as-is.
587                          */
588                         redirty_page_for_writepage(wbc, page);
589                         unlock_page(page);
590                         return 0;
591                 }
592         }
593         bh = head = page_buffers(page);
594         BUG_ON(!bh);
595
596         /* NOTE: Different naming scheme to ntfs_read_block()! */
597
598         /* The first block in the page. */
599         block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
600
601         read_lock_irqsave(&ni->size_lock, flags);
602         i_size = i_size_read(vi);
603         initialized_size = ni->initialized_size;
604         read_unlock_irqrestore(&ni->size_lock, flags);
605
606         /* The first out of bounds block for the data size. */
607         dblock = (i_size + blocksize - 1) >> blocksize_bits;
608
609         /* The last (fully or partially) initialized block. */
610         iblock = initialized_size >> blocksize_bits;
611
612         /*
613          * Be very careful.  We have no exclusion from __set_page_dirty_buffers
614          * here, and the (potentially unmapped) buffers may become dirty at
615          * any time.  If a buffer becomes dirty here after we've inspected it
616          * then we just miss that fact, and the page stays dirty.
617          *
618          * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
619          * handle that here by just cleaning them.
620          */
621
622         /*
623          * Loop through all the buffers in the page, mapping all the dirty
624          * buffers to disk addresses and handling any aliases from the
625          * underlying block device's mapping.
626          */
627         rl = NULL;
628         err = 0;
629         do {
630                 BOOL is_retry = FALSE;
631
632                 if (unlikely(block >= dblock)) {
633                         /*
634                          * Mapped buffers outside i_size will occur, because
635                          * this page can be outside i_size when there is a
636                          * truncate in progress. The contents of such buffers
637                          * were zeroed by ntfs_writepage().
638                          *
639                          * FIXME: What about the small race window where
640                          * ntfs_writepage() has not done any clearing because
641                          * the page was within i_size but before we get here,
642                          * vmtruncate() modifies i_size?
643                          */
644                         clear_buffer_dirty(bh);
645                         set_buffer_uptodate(bh);
646                         continue;
647                 }
648
649                 /* Clean buffers are not written out, so no need to map them. */
650                 if (!buffer_dirty(bh))
651                         continue;
652
653                 /* Make sure we have enough initialized size. */
654                 if (unlikely((block >= iblock) &&
655                                 (initialized_size < i_size))) {
656                         /*
657                          * If this page is fully outside initialized size, zero
658                          * out all pages between the current initialized size
659                          * and the current page. Just use ntfs_readpage() to do
660                          * the zeroing transparently.
661                          */
662                         if (block > iblock) {
663                                 // TODO:
664                                 // For each page do:
665                                 // - read_cache_page()
666                                 // Again for each page do:
667                                 // - wait_on_page_locked()
668                                 // - Check (PageUptodate(page) &&
669                                 //                      !PageError(page))
670                                 // Update initialized size in the attribute and
671                                 // in the inode.
672                                 // Again, for each page do:
673                                 //      __set_page_dirty_buffers();
674                                 // page_cache_release()
675                                 // We don't need to wait on the writes.
676                                 // Update iblock.
677                         }
678                         /*
679                          * The current page straddles initialized size. Zero
680                          * all non-uptodate buffers and set them uptodate (and
681                          * dirty?). Note, there aren't any non-uptodate buffers
682                          * if the page is uptodate.
683                          * FIXME: For an uptodate page, the buffers may need to
684                          * be written out because they were not initialized on
685                          * disk before.
686                          */
687                         if (!PageUptodate(page)) {
688                                 // TODO:
689                                 // Zero any non-uptodate buffers up to i_size.
690                                 // Set them uptodate and dirty.
691                         }
692                         // TODO:
693                         // Update initialized size in the attribute and in the
694                         // inode (up to i_size).
695                         // Update iblock.
696                         // FIXME: This is inefficient. Try to batch the two
697                         // size changes to happen in one go.
698                         ntfs_error(vol->sb, "Writing beyond initialized size "
699                                         "is not supported yet. Sorry.");
700                         err = -EOPNOTSUPP;
701                         break;
702                         // Do NOT set_buffer_new() BUT DO clear buffer range
703                         // outside write request range.
704                         // set_buffer_uptodate() on complete buffers as well as
705                         // set_buffer_dirty().
706                 }
707
708                 /* No need to map buffers that are already mapped. */
709                 if (buffer_mapped(bh))
710                         continue;
711
712                 /* Unmapped, dirty buffer. Need to map it. */
713                 bh->b_bdev = vol->sb->s_bdev;
714
715                 /* Convert block into corresponding vcn and offset. */
716                 vcn = (VCN)block << blocksize_bits;
717                 vcn_ofs = vcn & vol->cluster_size_mask;
718                 vcn >>= vol->cluster_size_bits;
719                 if (!rl) {
720 lock_retry_remap:
721                         down_read(&ni->runlist.lock);
722                         rl = ni->runlist.rl;
723                 }
724                 if (likely(rl != NULL)) {
725                         /* Seek to element containing target vcn. */
726                         while (rl->length && rl[1].vcn <= vcn)
727                                 rl++;
728                         lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
729                 } else
730                         lcn = LCN_RL_NOT_MAPPED;
731                 /* Successful remap. */
732                 if (lcn >= 0) {
733                         /* Setup buffer head to point to correct block. */
734                         bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
735                                         vcn_ofs) >> blocksize_bits;
736                         set_buffer_mapped(bh);
737                         continue;
738                 }
739                 /* It is a hole, need to instantiate it. */
740                 if (lcn == LCN_HOLE) {
741                         u8 *kaddr;
742                         unsigned long *bpos, *bend;
743
744                         /* Check if the buffer is zero. */
745                         kaddr = kmap_atomic(page, KM_USER0);
746                         bpos = (unsigned long *)(kaddr + bh_offset(bh));
747                         bend = (unsigned long *)((u8*)bpos + blocksize);
748                         do {
749                                 if (unlikely(*bpos))
750                                         break;
751                         } while (likely(++bpos < bend));
752                         kunmap_atomic(kaddr, KM_USER0);
753                         if (bpos == bend) {
754                                 /*
755                                  * Buffer is zero and sparse, no need to write
756                                  * it.
757                                  */
758                                 bh->b_blocknr = -1;
759                                 clear_buffer_dirty(bh);
760                                 continue;
761                         }
762                         // TODO: Instantiate the hole.
763                         // clear_buffer_new(bh);
764                         // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
765                         ntfs_error(vol->sb, "Writing into sparse regions is "
766                                         "not supported yet. Sorry.");
767                         err = -EOPNOTSUPP;
768                         break;
769                 }
770                 /* If first try and runlist unmapped, map and retry. */
771                 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
772                         is_retry = TRUE;
773                         /*
774                          * Attempt to map runlist, dropping lock for
775                          * the duration.
776                          */
777                         up_read(&ni->runlist.lock);
778                         err = ntfs_map_runlist(ni, vcn);
779                         if (likely(!err))
780                                 goto lock_retry_remap;
781                         rl = NULL;
782                 } else if (!rl)
783                         up_read(&ni->runlist.lock);
784                 /*
785                  * If buffer is outside the runlist, truncate has cut it out
786                  * of the runlist.  Just clean and clear the buffer and set it
787                  * uptodate so it can get discarded by the VM.
788                  */
789                 if (err == -ENOENT || lcn == LCN_ENOENT) {
790                         u8 *kaddr;
791
792                         bh->b_blocknr = -1;
793                         clear_buffer_dirty(bh);
794                         kaddr = kmap_atomic(page, KM_USER0);
795                         memset(kaddr + bh_offset(bh), 0, blocksize);
796                         kunmap_atomic(kaddr, KM_USER0);
797                         flush_dcache_page(page);
798                         set_buffer_uptodate(bh);
799                         err = 0;
800                         continue;
801                 }
802                 /* Failed to map the buffer, even after retrying. */
803                 if (!err)
804                         err = -EIO;
805                 bh->b_blocknr = -1;
806                 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
807                                 "attribute type 0x%x, vcn 0x%llx, offset 0x%x "
808                                 "because its location on disk could not be "
809                                 "determined%s (error code %i).", ni->mft_no,
810                                 ni->type, (unsigned long long)vcn,
811                                 vcn_ofs, is_retry ? " even after "
812                                 "retrying" : "", err);
813                 break;
814         } while (block++, (bh = bh->b_this_page) != head);
815
816         /* Release the lock if we took it. */
817         if (rl)
818                 up_read(&ni->runlist.lock);
819
820         /* For the error case, need to reset bh to the beginning. */
821         bh = head;
822
823         /* Just an optimization, so ->readpage() is not called later. */
824         if (unlikely(!PageUptodate(page))) {
825                 int uptodate = 1;
826                 do {
827                         if (!buffer_uptodate(bh)) {
828                                 uptodate = 0;
829                                 bh = head;
830                                 break;
831                         }
832                 } while ((bh = bh->b_this_page) != head);
833                 if (uptodate)
834                         SetPageUptodate(page);
835         }
836
837         /* Setup all mapped, dirty buffers for async write i/o. */
838         do {
839                 if (buffer_mapped(bh) && buffer_dirty(bh)) {
840                         lock_buffer(bh);
841                         if (test_clear_buffer_dirty(bh)) {
842                                 BUG_ON(!buffer_uptodate(bh));
843                                 mark_buffer_async_write(bh);
844                         } else
845                                 unlock_buffer(bh);
846                 } else if (unlikely(err)) {
847                         /*
848                          * For the error case. The buffer may have been set
849                          * dirty during attachment to a dirty page.
850                          */
851                         if (err != -ENOMEM)
852                                 clear_buffer_dirty(bh);
853                 }
854         } while ((bh = bh->b_this_page) != head);
855
856         if (unlikely(err)) {
857                 // TODO: Remove the -EOPNOTSUPP check later on...
858                 if (unlikely(err == -EOPNOTSUPP))
859                         err = 0;
860                 else if (err == -ENOMEM) {
861                         ntfs_warning(vol->sb, "Error allocating memory. "
862                                         "Redirtying page so we try again "
863                                         "later.");
864                         /*
865                          * Put the page back on mapping->dirty_pages, but
866                          * leave its buffer's dirty state as-is.
867                          */
868                         redirty_page_for_writepage(wbc, page);
869                         err = 0;
870                 } else
871                         SetPageError(page);
872         }
873
874         BUG_ON(PageWriteback(page));
875         set_page_writeback(page);       /* Keeps try_to_free_buffers() away. */
876
877         /* Submit the prepared buffers for i/o. */
878         need_end_writeback = TRUE;
879         do {
880                 struct buffer_head *next = bh->b_this_page;
881                 if (buffer_async_write(bh)) {
882                         submit_bh(WRITE, bh);
883                         need_end_writeback = FALSE;
884                 }
885                 bh = next;
886         } while (bh != head);
887         unlock_page(page);
888
889         /* If no i/o was started, need to end_page_writeback(). */
890         if (unlikely(need_end_writeback))
891                 end_page_writeback(page);
892
893         ntfs_debug("Done.");
894         return err;
895 }
896
897 /**
898  * ntfs_write_mst_block - write a @page to the backing store
899  * @page:       page cache page to write out
900  * @wbc:        writeback control structure
901  *
902  * This function is for writing pages belonging to non-resident, mst protected
903  * attributes to their backing store.  The only supported attributes are index
904  * allocation and $MFT/$DATA.  Both directory inodes and index inodes are
905  * supported for the index allocation case.
906  *
907  * The page must remain locked for the duration of the write because we apply
908  * the mst fixups, write, and then undo the fixups, so if we were to unlock the
909  * page before undoing the fixups, any other user of the page will see the
910  * page contents as corrupt.
911  *
912  * We clear the page uptodate flag for the duration of the function to ensure
913  * exclusion for the $MFT/$DATA case against someone mapping an mft record we
914  * are about to apply the mst fixups to.
915  *
916  * Return 0 on success and -errno on error.
917  *
918  * Based on ntfs_write_block(), ntfs_mft_writepage(), and
919  * write_mft_record_nolock().
920  */
921 static int ntfs_write_mst_block(struct page *page,
922                 struct writeback_control *wbc)
923 {
924         sector_t block, dblock, rec_block;
925         struct inode *vi = page->mapping->host;
926         ntfs_inode *ni = NTFS_I(vi);
927         ntfs_volume *vol = ni->vol;
928         u8 *kaddr;
929         unsigned int rec_size = ni->itype.index.block_size;
930         ntfs_inode *locked_nis[PAGE_CACHE_SIZE / rec_size];
931         struct buffer_head *bh, *head, *tbh, *rec_start_bh;
932         struct buffer_head *bhs[MAX_BUF_PER_PAGE];
933         runlist_element *rl;
934         int i, nr_locked_nis, nr_recs, nr_bhs, max_bhs, bhs_per_rec, err, err2;
935         unsigned bh_size, rec_size_bits;
936         BOOL sync, is_mft, page_is_dirty, rec_is_dirty;
937         unsigned char bh_size_bits;
938
939         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
940                         "0x%lx.", vi->i_ino, ni->type, page->index);
941         BUG_ON(!NInoNonResident(ni));
942         BUG_ON(!NInoMstProtected(ni));
943         is_mft = (S_ISREG(vi->i_mode) && !vi->i_ino);
944         /*
945          * NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page
946          * in its page cache were to be marked dirty.  However this should
947          * never happen with the current driver and considering we do not
948          * handle this case here we do want to BUG(), at least for now.
949          */
950         BUG_ON(!(is_mft || S_ISDIR(vi->i_mode) ||
951                         (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
952         bh_size_bits = vi->i_blkbits;
953         bh_size = 1 << bh_size_bits;
954         max_bhs = PAGE_CACHE_SIZE / bh_size;
955         BUG_ON(!max_bhs);
956         BUG_ON(max_bhs > MAX_BUF_PER_PAGE);
957
958         /* Were we called for sync purposes? */
959         sync = (wbc->sync_mode == WB_SYNC_ALL);
960
961         /* Make sure we have mapped buffers. */
962         bh = head = page_buffers(page);
963         BUG_ON(!bh);
964
965         rec_size_bits = ni->itype.index.block_size_bits;
966         BUG_ON(!(PAGE_CACHE_SIZE >> rec_size_bits));
967         bhs_per_rec = rec_size >> bh_size_bits;
968         BUG_ON(!bhs_per_rec);
969
970         /* The first block in the page. */
971         rec_block = block = (sector_t)page->index <<
972                         (PAGE_CACHE_SHIFT - bh_size_bits);
973
974         /* The first out of bounds block for the data size. */
975         dblock = (i_size_read(vi) + bh_size - 1) >> bh_size_bits;
976
977         rl = NULL;
978         err = err2 = nr_bhs = nr_recs = nr_locked_nis = 0;
979         page_is_dirty = rec_is_dirty = FALSE;
980         rec_start_bh = NULL;
981         do {
982                 BOOL is_retry = FALSE;
983
984                 if (likely(block < rec_block)) {
985                         if (unlikely(block >= dblock)) {
986                                 clear_buffer_dirty(bh);
987                                 set_buffer_uptodate(bh);
988                                 continue;
989                         }
990                         /*
991                          * This block is not the first one in the record.  We
992                          * ignore the buffer's dirty state because we could
993                          * have raced with a parallel mark_ntfs_record_dirty().
994                          */
995                         if (!rec_is_dirty)
996                                 continue;
997                         if (unlikely(err2)) {
998                                 if (err2 != -ENOMEM)
999                                         clear_buffer_dirty(bh);
1000                                 continue;
1001                         }
1002                 } else /* if (block == rec_block) */ {
1003                         BUG_ON(block > rec_block);
1004                         /* This block is the first one in the record. */
1005                         rec_block += bhs_per_rec;
1006                         err2 = 0;
1007                         if (unlikely(block >= dblock)) {
1008                                 clear_buffer_dirty(bh);
1009                                 continue;
1010                         }
1011                         if (!buffer_dirty(bh)) {
1012                                 /* Clean records are not written out. */
1013                                 rec_is_dirty = FALSE;
1014                                 continue;
1015                         }
1016                         rec_is_dirty = TRUE;
1017                         rec_start_bh = bh;
1018                 }
1019                 /* Need to map the buffer if it is not mapped already. */
1020                 if (unlikely(!buffer_mapped(bh))) {
1021                         VCN vcn;
1022                         LCN lcn;
1023                         unsigned int vcn_ofs;
1024
1025                         bh->b_bdev = vol->sb->s_bdev;
1026                         /* Obtain the vcn and offset of the current block. */
1027                         vcn = (VCN)block << bh_size_bits;
1028                         vcn_ofs = vcn & vol->cluster_size_mask;
1029                         vcn >>= vol->cluster_size_bits;
1030                         if (!rl) {
1031 lock_retry_remap:
1032                                 down_read(&ni->runlist.lock);
1033                                 rl = ni->runlist.rl;
1034                         }
1035                         if (likely(rl != NULL)) {
1036                                 /* Seek to element containing target vcn. */
1037                                 while (rl->length && rl[1].vcn <= vcn)
1038                                         rl++;
1039                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1040                         } else
1041                                 lcn = LCN_RL_NOT_MAPPED;
1042                         /* Successful remap. */
1043                         if (likely(lcn >= 0)) {
1044                                 /* Setup buffer head to correct block. */
1045                                 bh->b_blocknr = ((lcn <<
1046                                                 vol->cluster_size_bits) +
1047                                                 vcn_ofs) >> bh_size_bits;
1048                                 set_buffer_mapped(bh);
1049                         } else {
1050                                 /*
1051                                  * Remap failed.  Retry to map the runlist once
1052                                  * unless we are working on $MFT which always
1053                                  * has the whole of its runlist in memory.
1054                                  */
1055                                 if (!is_mft && !is_retry &&
1056                                                 lcn == LCN_RL_NOT_MAPPED) {
1057                                         is_retry = TRUE;
1058                                         /*
1059                                          * Attempt to map runlist, dropping
1060                                          * lock for the duration.
1061                                          */
1062                                         up_read(&ni->runlist.lock);
1063                                         err2 = ntfs_map_runlist(ni, vcn);
1064                                         if (likely(!err2))
1065                                                 goto lock_retry_remap;
1066                                         if (err2 == -ENOMEM)
1067                                                 page_is_dirty = TRUE;
1068                                         lcn = err2;
1069                                 } else {
1070                                         err2 = -EIO;
1071                                         if (!rl)
1072                                                 up_read(&ni->runlist.lock);
1073                                 }
1074                                 /* Hard error.  Abort writing this record. */
1075                                 if (!err || err == -ENOMEM)
1076                                         err = err2;
1077                                 bh->b_blocknr = -1;
1078                                 ntfs_error(vol->sb, "Cannot write ntfs record "
1079                                                 "0x%llx (inode 0x%lx, "
1080                                                 "attribute type 0x%x) because "
1081                                                 "its location on disk could "
1082                                                 "not be determined (error "
1083                                                 "code %lli).",
1084                                                 (long long)block <<
1085                                                 bh_size_bits >>
1086                                                 vol->mft_record_size_bits,
1087                                                 ni->mft_no, ni->type,
1088                                                 (long long)lcn);
1089                                 /*
1090                                  * If this is not the first buffer, remove the
1091                                  * buffers in this record from the list of
1092                                  * buffers to write and clear their dirty bit
1093                                  * if not error -ENOMEM.
1094                                  */
1095                                 if (rec_start_bh != bh) {
1096                                         while (bhs[--nr_bhs] != rec_start_bh)
1097                                                 ;
1098                                         if (err2 != -ENOMEM) {
1099                                                 do {
1100                                                         clear_buffer_dirty(
1101                                                                 rec_start_bh);
1102                                                 } while ((rec_start_bh =
1103                                                                 rec_start_bh->
1104                                                                 b_this_page) !=
1105                                                                 bh);
1106                                         }
1107                                 }
1108                                 continue;
1109                         }
1110                 }
1111                 BUG_ON(!buffer_uptodate(bh));
1112                 BUG_ON(nr_bhs >= max_bhs);
1113                 bhs[nr_bhs++] = bh;
1114         } while (block++, (bh = bh->b_this_page) != head);
1115         if (unlikely(rl))
1116                 up_read(&ni->runlist.lock);
1117         /* If there were no dirty buffers, we are done. */
1118         if (!nr_bhs)
1119                 goto done;
1120         /* Map the page so we can access its contents. */
1121         kaddr = kmap(page);
1122         /* Clear the page uptodate flag whilst the mst fixups are applied. */
1123         BUG_ON(!PageUptodate(page));
1124         ClearPageUptodate(page);
1125         for (i = 0; i < nr_bhs; i++) {
1126                 unsigned int ofs;
1127
1128                 /* Skip buffers which are not at the beginning of records. */
1129                 if (i % bhs_per_rec)
1130                         continue;
1131                 tbh = bhs[i];
1132                 ofs = bh_offset(tbh);
1133                 if (is_mft) {
1134                         ntfs_inode *tni;
1135                         unsigned long mft_no;
1136
1137                         /* Get the mft record number. */
1138                         mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1139                                         >> rec_size_bits;
1140                         /* Check whether to write this mft record. */
1141                         tni = NULL;
1142                         if (!ntfs_may_write_mft_record(vol, mft_no,
1143                                         (MFT_RECORD*)(kaddr + ofs), &tni)) {
1144                                 /*
1145                                  * The record should not be written.  This
1146                                  * means we need to redirty the page before
1147                                  * returning.
1148                                  */
1149                                 page_is_dirty = TRUE;
1150                                 /*
1151                                  * Remove the buffers in this mft record from
1152                                  * the list of buffers to write.
1153                                  */
1154                                 do {
1155                                         bhs[i] = NULL;
1156                                 } while (++i % bhs_per_rec);
1157                                 continue;
1158                         }
1159                         /*
1160                          * The record should be written.  If a locked ntfs
1161                          * inode was returned, add it to the array of locked
1162                          * ntfs inodes.
1163                          */
1164                         if (tni)
1165                                 locked_nis[nr_locked_nis++] = tni;
1166                 }
1167                 /* Apply the mst protection fixups. */
1168                 err2 = pre_write_mst_fixup((NTFS_RECORD*)(kaddr + ofs),
1169                                 rec_size);
1170                 if (unlikely(err2)) {
1171                         if (!err || err == -ENOMEM)
1172                                 err = -EIO;
1173                         ntfs_error(vol->sb, "Failed to apply mst fixups "
1174                                         "(inode 0x%lx, attribute type 0x%x, "
1175                                         "page index 0x%lx, page offset 0x%x)!"
1176                                         "  Unmount and run chkdsk.", vi->i_ino,
1177                                         ni->type, page->index, ofs);
1178                         /*
1179                          * Mark all the buffers in this record clean as we do
1180                          * not want to write corrupt data to disk.
1181                          */
1182                         do {
1183                                 clear_buffer_dirty(bhs[i]);
1184                                 bhs[i] = NULL;
1185                         } while (++i % bhs_per_rec);
1186                         continue;
1187                 }
1188                 nr_recs++;
1189         }
1190         /* If no records are to be written out, we are done. */
1191         if (!nr_recs)
1192                 goto unm_done;
1193         flush_dcache_page(page);
1194         /* Lock buffers and start synchronous write i/o on them. */
1195         for (i = 0; i < nr_bhs; i++) {
1196                 tbh = bhs[i];
1197                 if (!tbh)
1198                         continue;
1199                 if (unlikely(test_set_buffer_locked(tbh)))
1200                         BUG();
1201                 /* The buffer dirty state is now irrelevant, just clean it. */
1202                 clear_buffer_dirty(tbh);
1203                 BUG_ON(!buffer_uptodate(tbh));
1204                 BUG_ON(!buffer_mapped(tbh));
1205                 get_bh(tbh);
1206                 tbh->b_end_io = end_buffer_write_sync;
1207                 submit_bh(WRITE, tbh);
1208         }
1209         /* Synchronize the mft mirror now if not @sync. */
1210         if (is_mft && !sync)
1211                 goto do_mirror;
1212 do_wait:
1213         /* Wait on i/o completion of buffers. */
1214         for (i = 0; i < nr_bhs; i++) {
1215                 tbh = bhs[i];
1216                 if (!tbh)
1217                         continue;
1218                 wait_on_buffer(tbh);
1219                 if (unlikely(!buffer_uptodate(tbh))) {
1220                         ntfs_error(vol->sb, "I/O error while writing ntfs "
1221                                         "record buffer (inode 0x%lx, "
1222                                         "attribute type 0x%x, page index "
1223                                         "0x%lx, page offset 0x%lx)!  Unmount "
1224                                         "and run chkdsk.", vi->i_ino, ni->type,
1225                                         page->index, bh_offset(tbh));
1226                         if (!err || err == -ENOMEM)
1227                                 err = -EIO;
1228                         /*
1229                          * Set the buffer uptodate so the page and buffer
1230                          * states do not become out of sync.
1231                          */
1232                         set_buffer_uptodate(tbh);
1233                 }
1234         }
1235         /* If @sync, now synchronize the mft mirror. */
1236         if (is_mft && sync) {
1237 do_mirror:
1238                 for (i = 0; i < nr_bhs; i++) {
1239                         unsigned long mft_no;
1240                         unsigned int ofs;
1241
1242                         /*
1243                          * Skip buffers which are not at the beginning of
1244                          * records.
1245                          */
1246                         if (i % bhs_per_rec)
1247                                 continue;
1248                         tbh = bhs[i];
1249                         /* Skip removed buffers (and hence records). */
1250                         if (!tbh)
1251                                 continue;
1252                         ofs = bh_offset(tbh);
1253                         /* Get the mft record number. */
1254                         mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1255                                         >> rec_size_bits;
1256                         if (mft_no < vol->mftmirr_size)
1257                                 ntfs_sync_mft_mirror(vol, mft_no,
1258                                                 (MFT_RECORD*)(kaddr + ofs),
1259                                                 sync);
1260                 }
1261                 if (!sync)
1262                         goto do_wait;
1263         }
1264         /* Remove the mst protection fixups again. */
1265         for (i = 0; i < nr_bhs; i++) {
1266                 if (!(i % bhs_per_rec)) {
1267                         tbh = bhs[i];
1268                         if (!tbh)
1269                                 continue;
1270                         post_write_mst_fixup((NTFS_RECORD*)(kaddr +
1271                                         bh_offset(tbh)));
1272                 }
1273         }
1274         flush_dcache_page(page);
1275 unm_done:
1276         /* Unlock any locked inodes. */
1277         while (nr_locked_nis-- > 0) {
1278                 ntfs_inode *tni, *base_tni;
1279                 
1280                 tni = locked_nis[nr_locked_nis];
1281                 /* Get the base inode. */
1282                 down(&tni->extent_lock);
1283                 if (tni->nr_extents >= 0)
1284                         base_tni = tni;
1285                 else {
1286                         base_tni = tni->ext.base_ntfs_ino;
1287                         BUG_ON(!base_tni);
1288                 }
1289                 up(&tni->extent_lock);
1290                 ntfs_debug("Unlocking %s inode 0x%lx.",
1291                                 tni == base_tni ? "base" : "extent",
1292                                 tni->mft_no);
1293                 up(&tni->mrec_lock);
1294                 atomic_dec(&tni->count);
1295                 iput(VFS_I(base_tni));
1296         }
1297         SetPageUptodate(page);
1298         kunmap(page);
1299 done:
1300         if (unlikely(err && err != -ENOMEM)) {
1301                 /*
1302                  * Set page error if there is only one ntfs record in the page.
1303                  * Otherwise we would loose per-record granularity.
1304                  */
1305                 if (ni->itype.index.block_size == PAGE_CACHE_SIZE)
1306                         SetPageError(page);
1307                 NVolSetErrors(vol);
1308         }
1309         if (page_is_dirty) {
1310                 ntfs_debug("Page still contains one or more dirty ntfs "
1311                                 "records.  Redirtying the page starting at "
1312                                 "record 0x%lx.", page->index <<
1313                                 (PAGE_CACHE_SHIFT - rec_size_bits));
1314                 redirty_page_for_writepage(wbc, page);
1315                 unlock_page(page);
1316         } else {
1317                 /*
1318                  * Keep the VM happy.  This must be done otherwise the
1319                  * radix-tree tag PAGECACHE_TAG_DIRTY remains set even though
1320                  * the page is clean.
1321                  */
1322                 BUG_ON(PageWriteback(page));
1323                 set_page_writeback(page);
1324                 unlock_page(page);
1325                 end_page_writeback(page);
1326         }
1327         if (likely(!err))
1328                 ntfs_debug("Done.");
1329         return err;
1330 }
1331
1332 /**
1333  * ntfs_writepage - write a @page to the backing store
1334  * @page:       page cache page to write out
1335  * @wbc:        writeback control structure
1336  *
1337  * This is called from the VM when it wants to have a dirty ntfs page cache
1338  * page cleaned.  The VM has already locked the page and marked it clean.
1339  *
1340  * For non-resident attributes, ntfs_writepage() writes the @page by calling
1341  * the ntfs version of the generic block_write_full_page() function,
1342  * ntfs_write_block(), which in turn if necessary creates and writes the
1343  * buffers associated with the page asynchronously.
1344  *
1345  * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1346  * the data to the mft record (which at this stage is most likely in memory).
1347  * The mft record is then marked dirty and written out asynchronously via the
1348  * vfs inode dirty code path for the inode the mft record belongs to or via the
1349  * vm page dirty code path for the page the mft record is in.
1350  *
1351  * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1352  *
1353  * Return 0 on success and -errno on error.
1354  */
1355 static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1356 {
1357         loff_t i_size;
1358         struct inode *vi = page->mapping->host;
1359         ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1360         char *kaddr;
1361         ntfs_attr_search_ctx *ctx = NULL;
1362         MFT_RECORD *m = NULL;
1363         u32 attr_len;
1364         int err;
1365
1366 retry_writepage:
1367         BUG_ON(!PageLocked(page));
1368         i_size = i_size_read(vi);
1369         /* Is the page fully outside i_size? (truncate in progress) */
1370         if (unlikely(page->index >= (i_size + PAGE_CACHE_SIZE - 1) >>
1371                         PAGE_CACHE_SHIFT)) {
1372                 /*
1373                  * The page may have dirty, unmapped buffers.  Make them
1374                  * freeable here, so the page does not leak.
1375                  */
1376                 block_invalidatepage(page, 0);
1377                 unlock_page(page);
1378                 ntfs_debug("Write outside i_size - truncated?");
1379                 return 0;
1380         }
1381         /*
1382          * Only $DATA attributes can be encrypted and only unnamed $DATA
1383          * attributes can be compressed.  Index root can have the flags set but
1384          * this means to create compressed/encrypted files, not that the
1385          * attribute is compressed/encrypted.  Note we need to check for
1386          * AT_INDEX_ALLOCATION since this is the type of both directory and
1387          * index inodes.
1388          */
1389         if (ni->type != AT_INDEX_ALLOCATION) {
1390                 /* If file is encrypted, deny access, just like NT4. */
1391                 if (NInoEncrypted(ni)) {
1392                         unlock_page(page);
1393                         BUG_ON(ni->type != AT_DATA);
1394                         ntfs_debug("Denying write access to encrypted "
1395                                         "file.");
1396                         return -EACCES;
1397                 }
1398                 /* Compressed data streams are handled in compress.c. */
1399                 if (NInoNonResident(ni) && NInoCompressed(ni)) {
1400                         BUG_ON(ni->type != AT_DATA);
1401                         BUG_ON(ni->name_len);
1402                         // TODO: Implement and replace this with
1403                         // return ntfs_write_compressed_block(page);
1404                         unlock_page(page);
1405                         ntfs_error(vi->i_sb, "Writing to compressed files is "
1406                                         "not supported yet.  Sorry.");
1407                         return -EOPNOTSUPP;
1408                 }
1409                 // TODO: Implement and remove this check.
1410                 if (NInoNonResident(ni) && NInoSparse(ni)) {
1411                         unlock_page(page);
1412                         ntfs_error(vi->i_sb, "Writing to sparse files is not "
1413                                         "supported yet.  Sorry.");
1414                         return -EOPNOTSUPP;
1415                 }
1416         }
1417         /* NInoNonResident() == NInoIndexAllocPresent() */
1418         if (NInoNonResident(ni)) {
1419                 /* We have to zero every time due to mmap-at-end-of-file. */
1420                 if (page->index >= (i_size >> PAGE_CACHE_SHIFT)) {
1421                         /* The page straddles i_size. */
1422                         unsigned int ofs = i_size & ~PAGE_CACHE_MASK;
1423                         kaddr = kmap_atomic(page, KM_USER0);
1424                         memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1425                         kunmap_atomic(kaddr, KM_USER0);
1426                         flush_dcache_page(page);
1427                 }
1428                 /* Handle mst protected attributes. */
1429                 if (NInoMstProtected(ni))
1430                         return ntfs_write_mst_block(page, wbc);
1431                 /* Normal, non-resident data stream. */
1432                 return ntfs_write_block(page, wbc);
1433         }
1434         /*
1435          * Attribute is resident, implying it is not compressed, encrypted, or
1436          * mst protected.  This also means the attribute is smaller than an mft
1437          * record and hence smaller than a page, so can simply return error on
1438          * any pages with index above 0.  Note the attribute can actually be
1439          * marked compressed but if it is resident the actual data is not
1440          * compressed so we are ok to ignore the compressed flag here.
1441          */
1442         BUG_ON(page_has_buffers(page));
1443         BUG_ON(!PageUptodate(page));
1444         if (unlikely(page->index > 0)) {
1445                 ntfs_error(vi->i_sb, "BUG()! page->index (0x%lx) > 0.  "
1446                                 "Aborting write.", page->index);
1447                 BUG_ON(PageWriteback(page));
1448                 set_page_writeback(page);
1449                 unlock_page(page);
1450                 end_page_writeback(page);
1451                 return -EIO;
1452         }
1453         if (!NInoAttr(ni))
1454                 base_ni = ni;
1455         else
1456                 base_ni = ni->ext.base_ntfs_ino;
1457         /* Map, pin, and lock the mft record. */
1458         m = map_mft_record(base_ni);
1459         if (IS_ERR(m)) {
1460                 err = PTR_ERR(m);
1461                 m = NULL;
1462                 ctx = NULL;
1463                 goto err_out;
1464         }
1465         /*
1466          * If a parallel write made the attribute non-resident, drop the mft
1467          * record and retry the writepage.
1468          */
1469         if (unlikely(NInoNonResident(ni))) {
1470                 unmap_mft_record(base_ni);
1471                 goto retry_writepage;
1472         }
1473         ctx = ntfs_attr_get_search_ctx(base_ni, m);
1474         if (unlikely(!ctx)) {
1475                 err = -ENOMEM;
1476                 goto err_out;
1477         }
1478         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1479                         CASE_SENSITIVE, 0, NULL, 0, ctx);
1480         if (unlikely(err))
1481                 goto err_out;
1482         /*
1483          * Keep the VM happy.  This must be done otherwise the radix-tree tag
1484          * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1485          */
1486         BUG_ON(PageWriteback(page));
1487         set_page_writeback(page);
1488         unlock_page(page);
1489         attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
1490         i_size = i_size_read(vi);
1491         if (unlikely(attr_len > i_size)) {
1492                 /* Race with shrinking truncate or a failed truncate. */
1493                 attr_len = i_size;
1494                 /*
1495                  * If the truncate failed, fix it up now.  If a concurrent
1496                  * truncate, we do its job, so it does not have to do anything.
1497                  */
1498                 err = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr,
1499                                 attr_len);
1500                 /* Shrinking cannot fail. */
1501                 BUG_ON(err);
1502         }
1503         kaddr = kmap_atomic(page, KM_USER0);
1504         /* Copy the data from the page to the mft record. */
1505         memcpy((u8*)ctx->attr +
1506                         le16_to_cpu(ctx->attr->data.resident.value_offset),
1507                         kaddr, attr_len);
1508         /* Zero out of bounds area in the page cache page. */
1509         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1510         kunmap_atomic(kaddr, KM_USER0);
1511         flush_dcache_mft_record_page(ctx->ntfs_ino);
1512         flush_dcache_page(page);
1513         /* We are done with the page. */
1514         end_page_writeback(page);
1515         /* Finally, mark the mft record dirty, so it gets written back. */
1516         mark_mft_record_dirty(ctx->ntfs_ino);
1517         ntfs_attr_put_search_ctx(ctx);
1518         unmap_mft_record(base_ni);
1519         return 0;
1520 err_out:
1521         if (err == -ENOMEM) {
1522                 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1523                                 "page so we try again later.");
1524                 /*
1525                  * Put the page back on mapping->dirty_pages, but leave its
1526                  * buffers' dirty state as-is.
1527                  */
1528                 redirty_page_for_writepage(wbc, page);
1529                 err = 0;
1530         } else {
1531                 ntfs_error(vi->i_sb, "Resident attribute write failed with "
1532                                 "error %i.", err);
1533                 SetPageError(page);
1534                 NVolSetErrors(ni->vol);
1535                 make_bad_inode(vi);
1536         }
1537         unlock_page(page);
1538         if (ctx)
1539                 ntfs_attr_put_search_ctx(ctx);
1540         if (m)
1541                 unmap_mft_record(base_ni);
1542         return err;
1543 }
1544
1545 /**
1546  * ntfs_prepare_nonresident_write -
1547  *
1548  */
1549 static int ntfs_prepare_nonresident_write(struct page *page,
1550                 unsigned from, unsigned to)
1551 {
1552         VCN vcn;
1553         LCN lcn;
1554         s64 initialized_size;
1555         loff_t i_size;
1556         sector_t block, ablock, iblock;
1557         struct inode *vi;
1558         ntfs_inode *ni;
1559         ntfs_volume *vol;
1560         runlist_element *rl;
1561         struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1562         unsigned long flags;
1563         unsigned int vcn_ofs, block_start, block_end, blocksize;
1564         int err;
1565         BOOL is_retry;
1566         unsigned char blocksize_bits;
1567
1568         vi = page->mapping->host;
1569         ni = NTFS_I(vi);
1570         vol = ni->vol;
1571
1572         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1573                         "0x%lx, from = %u, to = %u.", ni->mft_no, ni->type,
1574                         page->index, from, to);
1575
1576         BUG_ON(!NInoNonResident(ni));
1577
1578         blocksize_bits = vi->i_blkbits;
1579         blocksize = 1 << blocksize_bits;
1580
1581         /*
1582          * create_empty_buffers() will create uptodate/dirty buffers if the
1583          * page is uptodate/dirty.
1584          */
1585         if (!page_has_buffers(page))
1586                 create_empty_buffers(page, blocksize, 0);
1587         bh = head = page_buffers(page);
1588         if (unlikely(!bh))
1589                 return -ENOMEM;
1590
1591         /* The first block in the page. */
1592         block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
1593
1594         read_lock_irqsave(&ni->size_lock, flags);
1595         /*
1596          * The first out of bounds block for the allocated size.  No need to
1597          * round up as allocated_size is in multiples of cluster size and the
1598          * minimum cluster size is 512 bytes, which is equal to the smallest
1599          * blocksize.
1600          */
1601         ablock = ni->allocated_size >> blocksize_bits;
1602         i_size = i_size_read(vi);
1603         initialized_size = ni->initialized_size;
1604         read_unlock_irqrestore(&ni->size_lock, flags);
1605
1606         /* The last (fully or partially) initialized block. */
1607         iblock = initialized_size >> blocksize_bits;
1608
1609         /* Loop through all the buffers in the page. */
1610         block_start = 0;
1611         rl = NULL;
1612         err = 0;
1613         do {
1614                 block_end = block_start + blocksize;
1615                 /*
1616                  * If buffer @bh is outside the write, just mark it uptodate
1617                  * if the page is uptodate and continue with the next buffer.
1618                  */
1619                 if (block_end <= from || block_start >= to) {
1620                         if (PageUptodate(page)) {
1621                                 if (!buffer_uptodate(bh))
1622                                         set_buffer_uptodate(bh);
1623                         }
1624                         continue;
1625                 }
1626                 /*
1627                  * @bh is at least partially being written to.
1628                  * Make sure it is not marked as new.
1629                  */
1630                 //if (buffer_new(bh))
1631                 //      clear_buffer_new(bh);
1632
1633                 if (block >= ablock) {
1634                         // TODO: block is above allocated_size, need to
1635                         // allocate it. Best done in one go to accommodate not
1636                         // only block but all above blocks up to and including:
1637                         // ((page->index << PAGE_CACHE_SHIFT) + to + blocksize
1638                         // - 1) >> blobksize_bits. Obviously will need to round
1639                         // up to next cluster boundary, too. This should be
1640                         // done with a helper function, so it can be reused.
1641                         ntfs_error(vol->sb, "Writing beyond allocated size "
1642                                         "is not supported yet. Sorry.");
1643                         err = -EOPNOTSUPP;
1644                         goto err_out;
1645                         // Need to update ablock.
1646                         // Need to set_buffer_new() on all block bhs that are
1647                         // newly allocated.
1648                 }
1649                 /*
1650                  * Now we have enough allocated size to fulfill the whole
1651                  * request, i.e. block < ablock is true.
1652                  */
1653                 if (unlikely((block >= iblock) &&
1654                                 (initialized_size < i_size))) {
1655                         /*
1656                          * If this page is fully outside initialized size, zero
1657                          * out all pages between the current initialized size
1658                          * and the current page. Just use ntfs_readpage() to do
1659                          * the zeroing transparently.
1660                          */
1661                         if (block > iblock) {
1662                                 // TODO:
1663                                 // For each page do:
1664                                 // - read_cache_page()
1665                                 // Again for each page do:
1666                                 // - wait_on_page_locked()
1667                                 // - Check (PageUptodate(page) &&
1668                                 //                      !PageError(page))
1669                                 // Update initialized size in the attribute and
1670                                 // in the inode.
1671                                 // Again, for each page do:
1672                                 //      __set_page_dirty_buffers();
1673                                 // page_cache_release()
1674                                 // We don't need to wait on the writes.
1675                                 // Update iblock.
1676                         }
1677                         /*
1678                          * The current page straddles initialized size. Zero
1679                          * all non-uptodate buffers and set them uptodate (and
1680                          * dirty?). Note, there aren't any non-uptodate buffers
1681                          * if the page is uptodate.
1682                          * FIXME: For an uptodate page, the buffers may need to
1683                          * be written out because they were not initialized on
1684                          * disk before.
1685                          */
1686                         if (!PageUptodate(page)) {
1687                                 // TODO:
1688                                 // Zero any non-uptodate buffers up to i_size.
1689                                 // Set them uptodate and dirty.
1690                         }
1691                         // TODO:
1692                         // Update initialized size in the attribute and in the
1693                         // inode (up to i_size).
1694                         // Update iblock.
1695                         // FIXME: This is inefficient. Try to batch the two
1696                         // size changes to happen in one go.
1697                         ntfs_error(vol->sb, "Writing beyond initialized size "
1698                                         "is not supported yet. Sorry.");
1699                         err = -EOPNOTSUPP;
1700                         goto err_out;
1701                         // Do NOT set_buffer_new() BUT DO clear buffer range
1702                         // outside write request range.
1703                         // set_buffer_uptodate() on complete buffers as well as
1704                         // set_buffer_dirty().
1705                 }
1706
1707                 /* Need to map unmapped buffers. */
1708                 if (!buffer_mapped(bh)) {
1709                         /* Unmapped buffer. Need to map it. */
1710                         bh->b_bdev = vol->sb->s_bdev;
1711
1712                         /* Convert block into corresponding vcn and offset. */
1713                         vcn = (VCN)block << blocksize_bits >>
1714                                         vol->cluster_size_bits;
1715                         vcn_ofs = ((VCN)block << blocksize_bits) &
1716                                         vol->cluster_size_mask;
1717
1718                         is_retry = FALSE;
1719                         if (!rl) {
1720 lock_retry_remap:
1721                                 down_read(&ni->runlist.lock);
1722                                 rl = ni->runlist.rl;
1723                         }
1724                         if (likely(rl != NULL)) {
1725                                 /* Seek to element containing target vcn. */
1726                                 while (rl->length && rl[1].vcn <= vcn)
1727                                         rl++;
1728                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1729                         } else
1730                                 lcn = LCN_RL_NOT_MAPPED;
1731                         if (unlikely(lcn < 0)) {
1732                                 /*
1733                                  * We extended the attribute allocation above.
1734                                  * If we hit an ENOENT here it means that the
1735                                  * allocation was insufficient which is a bug.
1736                                  */
1737                                 BUG_ON(lcn == LCN_ENOENT);
1738
1739                                 /* It is a hole, need to instantiate it. */
1740                                 if (lcn == LCN_HOLE) {
1741                                         // TODO: Instantiate the hole.
1742                                         // clear_buffer_new(bh);
1743                                         // unmap_underlying_metadata(bh->b_bdev,
1744                                         //              bh->b_blocknr);
1745                                         // For non-uptodate buffers, need to
1746                                         // zero out the region outside the
1747                                         // request in this bh or all bhs,
1748                                         // depending on what we implemented
1749                                         // above.
1750                                         // Need to flush_dcache_page().
1751                                         // Or could use set_buffer_new()
1752                                         // instead?
1753                                         ntfs_error(vol->sb, "Writing into "
1754                                                         "sparse regions is "
1755                                                         "not supported yet. "
1756                                                         "Sorry.");
1757                                         err = -EOPNOTSUPP;
1758                                         if (!rl)
1759                                                 up_read(&ni->runlist.lock);
1760                                         goto err_out;
1761                                 } else if (!is_retry &&
1762                                                 lcn == LCN_RL_NOT_MAPPED) {
1763                                         is_retry = TRUE;
1764                                         /*
1765                                          * Attempt to map runlist, dropping
1766                                          * lock for the duration.
1767                                          */
1768                                         up_read(&ni->runlist.lock);
1769                                         err = ntfs_map_runlist(ni, vcn);
1770                                         if (likely(!err))
1771                                                 goto lock_retry_remap;
1772                                         rl = NULL;
1773                                 } else if (!rl)
1774                                         up_read(&ni->runlist.lock);
1775                                 /*
1776                                  * Failed to map the buffer, even after
1777                                  * retrying.
1778                                  */
1779                                 if (!err)
1780                                         err = -EIO;
1781                                 bh->b_blocknr = -1;
1782                                 ntfs_error(vol->sb, "Failed to write to inode "
1783                                                 "0x%lx, attribute type 0x%x, "
1784                                                 "vcn 0x%llx, offset 0x%x "
1785                                                 "because its location on disk "
1786                                                 "could not be determined%s "
1787                                                 "(error code %i).",
1788                                                 ni->mft_no, ni->type,
1789                                                 (unsigned long long)vcn,
1790                                                 vcn_ofs, is_retry ? " even "
1791                                                 "after retrying" : "", err);
1792                                 goto err_out;
1793                         }
1794                         /* We now have a successful remap, i.e. lcn >= 0. */
1795
1796                         /* Setup buffer head to correct block. */
1797                         bh->b_blocknr = ((lcn << vol->cluster_size_bits)
1798                                         + vcn_ofs) >> blocksize_bits;
1799                         set_buffer_mapped(bh);
1800
1801                         // FIXME: Something analogous to this is needed for
1802                         // each newly allocated block, i.e. BH_New.
1803                         // FIXME: Might need to take this out of the
1804                         // if (!buffer_mapped(bh)) {}, depending on how we
1805                         // implement things during the allocated_size and
1806                         // initialized_size extension code above.
1807                         if (buffer_new(bh)) {
1808                                 clear_buffer_new(bh);
1809                                 unmap_underlying_metadata(bh->b_bdev,
1810                                                 bh->b_blocknr);
1811                                 if (PageUptodate(page)) {
1812                                         set_buffer_uptodate(bh);
1813                                         continue;
1814                                 }
1815                                 /*
1816                                  * Page is _not_ uptodate, zero surrounding
1817                                  * region. NOTE: This is how we decide if to
1818                                  * zero or not!
1819                                  */
1820                                 if (block_end > to || block_start < from) {
1821                                         void *kaddr;
1822
1823                                         kaddr = kmap_atomic(page, KM_USER0);
1824                                         if (block_end > to)
1825                                                 memset(kaddr + to, 0,
1826                                                                 block_end - to);
1827                                         if (block_start < from)
1828                                                 memset(kaddr + block_start, 0,
1829                                                                 from -
1830                                                                 block_start);
1831                                         flush_dcache_page(page);
1832                                         kunmap_atomic(kaddr, KM_USER0);
1833                                 }
1834                                 continue;
1835                         }
1836                 }
1837                 /* @bh is mapped, set it uptodate if the page is uptodate. */
1838                 if (PageUptodate(page)) {
1839                         if (!buffer_uptodate(bh))
1840                                 set_buffer_uptodate(bh);
1841                         continue;
1842                 }
1843                 /*
1844                  * The page is not uptodate. The buffer is mapped. If it is not
1845                  * uptodate, and it is only partially being written to, we need
1846                  * to read the buffer in before the write, i.e. right now.
1847                  */
1848                 if (!buffer_uptodate(bh) &&
1849                                 (block_start < from || block_end > to)) {
1850                         ll_rw_block(READ, 1, &bh);
1851                         *wait_bh++ = bh;
1852                 }
1853         } while (block++, block_start = block_end,
1854                         (bh = bh->b_this_page) != head);
1855
1856         /* Release the lock if we took it. */
1857         if (rl) {
1858                 up_read(&ni->runlist.lock);
1859                 rl = NULL;
1860         }
1861
1862         /* If we issued read requests, let them complete. */
1863         while (wait_bh > wait) {
1864                 wait_on_buffer(*--wait_bh);
1865                 if (!buffer_uptodate(*wait_bh))
1866                         return -EIO;
1867         }
1868
1869         ntfs_debug("Done.");
1870         return 0;
1871 err_out:
1872         /*
1873          * Zero out any newly allocated blocks to avoid exposing stale data.
1874          * If BH_New is set, we know that the block was newly allocated in the
1875          * above loop.
1876          * FIXME: What about initialized_size increments? Have we done all the
1877          * required zeroing above? If not this error handling is broken, and
1878          * in particular the if (block_end <= from) check is completely bogus.
1879          */
1880         bh = head;
1881         block_start = 0;
1882         is_retry = FALSE;
1883         do {
1884                 block_end = block_start + blocksize;
1885                 if (block_end <= from)
1886                         continue;
1887                 if (block_start >= to)
1888                         break;
1889                 if (buffer_new(bh)) {
1890                         void *kaddr;
1891
1892                         clear_buffer_new(bh);
1893                         kaddr = kmap_atomic(page, KM_USER0);
1894                         memset(kaddr + block_start, 0, bh->b_size);
1895                         kunmap_atomic(kaddr, KM_USER0);
1896                         set_buffer_uptodate(bh);
1897                         mark_buffer_dirty(bh);
1898                         is_retry = TRUE;
1899                 }
1900         } while (block_start = block_end, (bh = bh->b_this_page) != head);
1901         if (is_retry)
1902                 flush_dcache_page(page);
1903         if (rl)
1904                 up_read(&ni->runlist.lock);
1905         return err;
1906 }
1907
1908 /**
1909  * ntfs_prepare_write - prepare a page for receiving data
1910  *
1911  * This is called from generic_file_write() with i_sem held on the inode
1912  * (@page->mapping->host).  The @page is locked but not kmap()ped.  The source
1913  * data has not yet been copied into the @page.
1914  *
1915  * Need to extend the attribute/fill in holes if necessary, create blocks and
1916  * make partially overwritten blocks uptodate,
1917  *
1918  * i_size is not to be modified yet.
1919  *
1920  * Return 0 on success or -errno on error.
1921  *
1922  * Should be using block_prepare_write() [support for sparse files] or
1923  * cont_prepare_write() [no support for sparse files].  Cannot do that due to
1924  * ntfs specifics but can look at them for implementation guidance.
1925  *
1926  * Note: In the range, @from is inclusive and @to is exclusive, i.e. @from is
1927  * the first byte in the page that will be written to and @to is the first byte
1928  * after the last byte that will be written to.
1929  */
1930 static int ntfs_prepare_write(struct file *file, struct page *page,
1931                 unsigned from, unsigned to)
1932 {
1933         s64 new_size;
1934         loff_t i_size;
1935         struct inode *vi = page->mapping->host;
1936         ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1937         ntfs_volume *vol = ni->vol;
1938         ntfs_attr_search_ctx *ctx = NULL;
1939         MFT_RECORD *m = NULL;
1940         ATTR_RECORD *a;
1941         u8 *kaddr;
1942         u32 attr_len;
1943         int err;
1944
1945         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1946                         "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1947                         page->index, from, to);
1948         BUG_ON(!PageLocked(page));
1949         BUG_ON(from > PAGE_CACHE_SIZE);
1950         BUG_ON(to > PAGE_CACHE_SIZE);
1951         BUG_ON(from > to);
1952         BUG_ON(NInoMstProtected(ni));
1953         /*
1954          * If a previous ntfs_truncate() failed, repeat it and abort if it
1955          * fails again.
1956          */
1957         if (unlikely(NInoTruncateFailed(ni))) {
1958                 down_write(&vi->i_alloc_sem);
1959                 err = ntfs_truncate(vi);
1960                 up_write(&vi->i_alloc_sem);
1961                 if (err || NInoTruncateFailed(ni)) {
1962                         if (!err)
1963                                 err = -EIO;
1964                         goto err_out;
1965                 }
1966         }
1967         /* If the attribute is not resident, deal with it elsewhere. */
1968         if (NInoNonResident(ni)) {
1969                 /*
1970                  * Only unnamed $DATA attributes can be compressed, encrypted,
1971                  * and/or sparse.
1972                  */
1973                 if (ni->type == AT_DATA && !ni->name_len) {
1974                         /* If file is encrypted, deny access, just like NT4. */
1975                         if (NInoEncrypted(ni)) {
1976                                 ntfs_debug("Denying write access to encrypted "
1977                                                 "file.");
1978                                 return -EACCES;
1979                         }
1980                         /* Compressed data streams are handled in compress.c. */
1981                         if (NInoCompressed(ni)) {
1982                                 // TODO: Implement and replace this check with
1983                                 // return ntfs_write_compressed_block(page);
1984                                 ntfs_error(vi->i_sb, "Writing to compressed "
1985                                                 "files is not supported yet. "
1986                                                 "Sorry.");
1987                                 return -EOPNOTSUPP;
1988                         }
1989                         // TODO: Implement and remove this check.
1990                         if (NInoSparse(ni)) {
1991                                 ntfs_error(vi->i_sb, "Writing to sparse files "
1992                                                 "is not supported yet. Sorry.");
1993                                 return -EOPNOTSUPP;
1994                         }
1995                 }
1996                 /* Normal data stream. */
1997                 return ntfs_prepare_nonresident_write(page, from, to);
1998         }
1999         /*
2000          * Attribute is resident, implying it is not compressed, encrypted, or
2001          * sparse.
2002          */
2003         BUG_ON(page_has_buffers(page));
2004         new_size = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
2005         /* If we do not need to resize the attribute allocation we are done. */
2006         if (new_size <= i_size_read(vi))
2007                 goto done;
2008         /* Map, pin, and lock the (base) mft record. */
2009         if (!NInoAttr(ni))
2010                 base_ni = ni;
2011         else
2012                 base_ni = ni->ext.base_ntfs_ino;
2013         m = map_mft_record(base_ni);
2014         if (IS_ERR(m)) {
2015                 err = PTR_ERR(m);
2016                 m = NULL;
2017                 ctx = NULL;
2018                 goto err_out;
2019         }
2020         ctx = ntfs_attr_get_search_ctx(base_ni, m);
2021         if (unlikely(!ctx)) {
2022                 err = -ENOMEM;
2023                 goto err_out;
2024         }
2025         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2026                         CASE_SENSITIVE, 0, NULL, 0, ctx);
2027         if (unlikely(err)) {
2028                 if (err == -ENOENT)
2029                         err = -EIO;
2030                 goto err_out;
2031         }
2032         m = ctx->mrec;
2033         a = ctx->attr;
2034         /* The total length of the attribute value. */
2035         attr_len = le32_to_cpu(a->data.resident.value_length);
2036         /* Fix an eventual previous failure of ntfs_commit_write(). */
2037         i_size = i_size_read(vi);
2038         if (unlikely(attr_len > i_size)) {
2039                 attr_len = i_size;
2040                 a->data.resident.value_length = cpu_to_le32(attr_len);
2041         }
2042         /* If we do not need to resize the attribute allocation we are done. */
2043         if (new_size <= attr_len)
2044                 goto done_unm;
2045         /* Check if new size is allowed in $AttrDef. */
2046         err = ntfs_attr_size_bounds_check(vol, ni->type, new_size);
2047         if (unlikely(err)) {
2048                 if (err == -ERANGE) {
2049                         ntfs_error(vol->sb, "Write would cause the inode "
2050                                         "0x%lx to exceed the maximum size for "
2051                                         "its attribute type (0x%x).  Aborting "
2052                                         "write.", vi->i_ino,
2053                                         le32_to_cpu(ni->type));
2054                 } else {
2055                         ntfs_error(vol->sb, "Inode 0x%lx has unknown "
2056                                         "attribute type 0x%x.  Aborting "
2057                                         "write.", vi->i_ino,
2058                                         le32_to_cpu(ni->type));
2059                         err = -EIO;
2060                 }
2061                 goto err_out2;
2062         }
2063         /*
2064          * Extend the attribute record to be able to store the new attribute
2065          * size.
2066          */
2067         if (new_size >= vol->mft_record_size || ntfs_attr_record_resize(m, a,
2068                         le16_to_cpu(a->data.resident.value_offset) +
2069                         new_size)) {
2070                 /* Not enough space in the mft record. */
2071                 ntfs_error(vol->sb, "Not enough space in the mft record for "
2072                                 "the resized attribute value.  This is not "
2073                                 "supported yet.  Aborting write.");
2074                 err = -EOPNOTSUPP;
2075                 goto err_out2;
2076         }
2077         /*
2078          * We have enough space in the mft record to fit the write.  This
2079          * implies the attribute is smaller than the mft record and hence the
2080          * attribute must be in a single page and hence page->index must be 0.
2081          */
2082         BUG_ON(page->index);
2083         /*
2084          * If the beginning of the write is past the old size, enlarge the
2085          * attribute value up to the beginning of the write and fill it with
2086          * zeroes.
2087          */
2088         if (from > attr_len) {
2089                 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
2090                                 attr_len, 0, from - attr_len);
2091                 a->data.resident.value_length = cpu_to_le32(from);
2092                 /* Zero the corresponding area in the page as well. */
2093                 if (PageUptodate(page)) {
2094                         kaddr = kmap_atomic(page, KM_USER0);
2095                         memset(kaddr + attr_len, 0, from - attr_len);
2096                         kunmap_atomic(kaddr, KM_USER0);
2097                         flush_dcache_page(page);
2098                 }
2099         }
2100         flush_dcache_mft_record_page(ctx->ntfs_ino);
2101         mark_mft_record_dirty(ctx->ntfs_ino);
2102 done_unm:
2103         ntfs_attr_put_search_ctx(ctx);
2104         unmap_mft_record(base_ni);
2105         /*
2106          * Because resident attributes are handled by memcpy() to/from the
2107          * corresponding MFT record, and because this form of i/o is byte
2108          * aligned rather than block aligned, there is no need to bring the
2109          * page uptodate here as in the non-resident case where we need to
2110          * bring the buffers straddled by the write uptodate before
2111          * generic_file_write() does the copying from userspace.
2112          *
2113          * We thus defer the uptodate bringing of the page region outside the
2114          * region written to to ntfs_commit_write(), which makes the code
2115          * simpler and saves one atomic kmap which is good.
2116          */
2117 done:
2118         ntfs_debug("Done.");
2119         return 0;
2120 err_out:
2121         if (err == -ENOMEM)
2122                 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2123                                 "prepare the write.");
2124         else {
2125                 ntfs_error(vi->i_sb, "Resident attribute prepare write failed "
2126                                 "with error %i.", err);
2127                 NVolSetErrors(vol);
2128                 make_bad_inode(vi);
2129         }
2130 err_out2:
2131         if (ctx)
2132                 ntfs_attr_put_search_ctx(ctx);
2133         if (m)
2134                 unmap_mft_record(base_ni);
2135         return err;
2136 }
2137
2138 /**
2139  * ntfs_commit_nonresident_write -
2140  *
2141  */
2142 static int ntfs_commit_nonresident_write(struct page *page,
2143                 unsigned from, unsigned to)
2144 {
2145         s64 pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
2146         struct inode *vi = page->mapping->host;
2147         struct buffer_head *bh, *head;
2148         unsigned int block_start, block_end, blocksize;
2149         BOOL partial;
2150
2151         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2152                         "0x%lx, from = %u, to = %u.", vi->i_ino,
2153                         NTFS_I(vi)->type, page->index, from, to);
2154         blocksize = 1 << vi->i_blkbits;
2155
2156         // FIXME: We need a whole slew of special cases in here for compressed
2157         // files for example...
2158         // For now, we know ntfs_prepare_write() would have failed so we can't
2159         // get here in any of the cases which we have to special case, so we
2160         // are just a ripped off, unrolled generic_commit_write().
2161
2162         bh = head = page_buffers(page);
2163         block_start = 0;
2164         partial = FALSE;
2165         do {
2166                 block_end = block_start + blocksize;
2167                 if (block_end <= from || block_start >= to) {
2168                         if (!buffer_uptodate(bh))
2169                                 partial = TRUE;
2170                 } else {
2171                         set_buffer_uptodate(bh);
2172                         mark_buffer_dirty(bh);
2173                 }
2174         } while (block_start = block_end, (bh = bh->b_this_page) != head);
2175         /*
2176          * If this is a partial write which happened to make all buffers
2177          * uptodate then we can optimize away a bogus ->readpage() for the next
2178          * read().  Here we 'discover' whether the page went uptodate as a
2179          * result of this (potentially partial) write.
2180          */
2181         if (!partial)
2182                 SetPageUptodate(page);
2183         /*
2184          * Not convinced about this at all.  See disparity comment above.  For
2185          * now we know ntfs_prepare_write() would have failed in the write
2186          * exceeds i_size case, so this will never trigger which is fine.
2187          */
2188         if (pos > i_size_read(vi)) {
2189                 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
2190                                 "not supported yet.  Sorry.");
2191                 return -EOPNOTSUPP;
2192                 // vi->i_size = pos;
2193                 // mark_inode_dirty(vi);
2194         }
2195         ntfs_debug("Done.");
2196         return 0;
2197 }
2198
2199 /**
2200  * ntfs_commit_write - commit the received data
2201  *
2202  * This is called from generic_file_write() with i_sem held on the inode
2203  * (@page->mapping->host).  The @page is locked but not kmap()ped.  The source
2204  * data has already been copied into the @page.  ntfs_prepare_write() has been
2205  * called before the data copied and it returned success so we can take the
2206  * results of various BUG checks and some error handling for granted.
2207  *
2208  * Need to mark modified blocks dirty so they get written out later when
2209  * ntfs_writepage() is invoked by the VM.
2210  *
2211  * Return 0 on success or -errno on error.
2212  *
2213  * Should be using generic_commit_write().  This marks buffers uptodate and
2214  * dirty, sets the page uptodate if all buffers in the page are uptodate, and
2215  * updates i_size if the end of io is beyond i_size.  In that case, it also
2216  * marks the inode dirty.
2217  *
2218  * Cannot use generic_commit_write() due to ntfs specialities but can look at
2219  * it for implementation guidance.
2220  *
2221  * If things have gone as outlined in ntfs_prepare_write(), then we do not
2222  * need to do any page content modifications here at all, except in the write
2223  * to resident attribute case, where we need to do the uptodate bringing here
2224  * which we combine with the copying into the mft record which means we save
2225  * one atomic kmap.
2226  */
2227 static int ntfs_commit_write(struct file *file, struct page *page,
2228                 unsigned from, unsigned to)
2229 {
2230         struct inode *vi = page->mapping->host;
2231         ntfs_inode *base_ni, *ni = NTFS_I(vi);
2232         char *kaddr, *kattr;
2233         ntfs_attr_search_ctx *ctx;
2234         MFT_RECORD *m;
2235         ATTR_RECORD *a;
2236         u32 attr_len;
2237         int err;
2238
2239         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2240                         "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
2241                         page->index, from, to);
2242         /* If the attribute is not resident, deal with it elsewhere. */
2243         if (NInoNonResident(ni)) {
2244                 /* Only unnamed $DATA attributes can be compressed/encrypted. */
2245                 if (ni->type == AT_DATA && !ni->name_len) {
2246                         /* Encrypted files need separate handling. */
2247                         if (NInoEncrypted(ni)) {
2248                                 // We never get here at present!
2249                                 BUG();
2250                         }
2251                         /* Compressed data streams are handled in compress.c. */
2252                         if (NInoCompressed(ni)) {
2253                                 // TODO: Implement this!
2254                                 // return ntfs_write_compressed_block(page);
2255                                 // We never get here at present!
2256                                 BUG();
2257                         }
2258                 }
2259                 /* Normal data stream. */
2260                 return ntfs_commit_nonresident_write(page, from, to);
2261         }
2262         /*
2263          * Attribute is resident, implying it is not compressed, encrypted, or
2264          * sparse.
2265          */
2266         if (!NInoAttr(ni))
2267                 base_ni = ni;
2268         else
2269                 base_ni = ni->ext.base_ntfs_ino;
2270         /* Map, pin, and lock the mft record. */
2271         m = map_mft_record(base_ni);
2272         if (IS_ERR(m)) {
2273                 err = PTR_ERR(m);
2274                 m = NULL;
2275                 ctx = NULL;
2276                 goto err_out;
2277         }
2278         ctx = ntfs_attr_get_search_ctx(base_ni, m);
2279         if (unlikely(!ctx)) {
2280                 err = -ENOMEM;
2281                 goto err_out;
2282         }
2283         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2284                         CASE_SENSITIVE, 0, NULL, 0, ctx);
2285         if (unlikely(err)) {
2286                 if (err == -ENOENT)
2287                         err = -EIO;
2288                 goto err_out;
2289         }
2290         a = ctx->attr;
2291         /* The total length of the attribute value. */
2292         attr_len = le32_to_cpu(a->data.resident.value_length);
2293         BUG_ON(from > attr_len);
2294         kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
2295         kaddr = kmap_atomic(page, KM_USER0);
2296         /* Copy the received data from the page to the mft record. */
2297         memcpy(kattr + from, kaddr + from, to - from);
2298         /* Update the attribute length if necessary. */
2299         if (to > attr_len) {
2300                 attr_len = to;
2301                 a->data.resident.value_length = cpu_to_le32(attr_len);
2302         }
2303         /*
2304          * If the page is not uptodate, bring the out of bounds area(s)
2305          * uptodate by copying data from the mft record to the page.
2306          */
2307         if (!PageUptodate(page)) {
2308                 if (from > 0)
2309                         memcpy(kaddr, kattr, from);
2310                 if (to < attr_len)
2311                         memcpy(kaddr + to, kattr + to, attr_len - to);
2312                 /* Zero the region outside the end of the attribute value. */
2313                 if (attr_len < PAGE_CACHE_SIZE)
2314                         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
2315                 /*
2316                  * The probability of not having done any of the above is
2317                  * extremely small, so we just flush unconditionally.
2318                  */
2319                 flush_dcache_page(page);
2320                 SetPageUptodate(page);
2321         }
2322         kunmap_atomic(kaddr, KM_USER0);
2323         /* Update i_size if necessary. */
2324         if (i_size_read(vi) < attr_len) {
2325                 unsigned long flags;
2326
2327                 write_lock_irqsave(&ni->size_lock, flags);
2328                 ni->allocated_size = ni->initialized_size = attr_len;
2329                 i_size_write(vi, attr_len);
2330                 write_unlock_irqrestore(&ni->size_lock, flags);
2331         }
2332         /* Mark the mft record dirty, so it gets written back. */
2333         flush_dcache_mft_record_page(ctx->ntfs_ino);
2334         mark_mft_record_dirty(ctx->ntfs_ino);
2335         ntfs_attr_put_search_ctx(ctx);
2336         unmap_mft_record(base_ni);
2337         ntfs_debug("Done.");
2338         return 0;
2339 err_out:
2340         if (err == -ENOMEM) {
2341                 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2342                                 "commit the write.");
2343                 if (PageUptodate(page)) {
2344                         ntfs_warning(vi->i_sb, "Page is uptodate, setting "
2345                                         "dirty so the write will be retried "
2346                                         "later on by the VM.");
2347                         /*
2348                          * Put the page on mapping->dirty_pages, but leave its
2349                          * buffers' dirty state as-is.
2350                          */
2351                         __set_page_dirty_nobuffers(page);
2352                         err = 0;
2353                 } else
2354                         ntfs_error(vi->i_sb, "Page is not uptodate.  Written "
2355                                         "data has been lost.");
2356         } else {
2357                 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
2358                                 "with error %i.", err);
2359                 NVolSetErrors(ni->vol);
2360                 make_bad_inode(vi);
2361         }
2362         if (ctx)
2363                 ntfs_attr_put_search_ctx(ctx);
2364         if (m)
2365                 unmap_mft_record(base_ni);
2366         return err;
2367 }
2368
2369 #endif  /* NTFS_RW */
2370
2371 /**
2372  * ntfs_aops - general address space operations for inodes and attributes
2373  */
2374 struct address_space_operations ntfs_aops = {
2375         .readpage       = ntfs_readpage,        /* Fill page with data. */
2376         .sync_page      = block_sync_page,      /* Currently, just unplugs the
2377                                                    disk request queue. */
2378 #ifdef NTFS_RW
2379         .writepage      = ntfs_writepage,       /* Write dirty page to disk. */
2380         .prepare_write  = ntfs_prepare_write,   /* Prepare page and buffers
2381                                                    ready to receive data. */
2382         .commit_write   = ntfs_commit_write,    /* Commit received data. */
2383 #endif /* NTFS_RW */
2384 };
2385
2386 /**
2387  * ntfs_mst_aops - general address space operations for mst protecteed inodes
2388  *                 and attributes
2389  */
2390 struct address_space_operations ntfs_mst_aops = {
2391         .readpage       = ntfs_readpage,        /* Fill page with data. */
2392         .sync_page      = block_sync_page,      /* Currently, just unplugs the
2393                                                    disk request queue. */
2394 #ifdef NTFS_RW
2395         .writepage      = ntfs_writepage,       /* Write dirty page to disk. */
2396         .set_page_dirty = __set_page_dirty_nobuffers,   /* Set the page dirty
2397                                                    without touching the buffers
2398                                                    belonging to the page. */
2399 #endif /* NTFS_RW */
2400 };
2401
2402 #ifdef NTFS_RW
2403
2404 /**
2405  * mark_ntfs_record_dirty - mark an ntfs record dirty
2406  * @page:       page containing the ntfs record to mark dirty
2407  * @ofs:        byte offset within @page at which the ntfs record begins
2408  *
2409  * Set the buffers and the page in which the ntfs record is located dirty.
2410  *
2411  * The latter also marks the vfs inode the ntfs record belongs to dirty
2412  * (I_DIRTY_PAGES only).
2413  *
2414  * If the page does not have buffers, we create them and set them uptodate.
2415  * The page may not be locked which is why we need to handle the buffers under
2416  * the mapping->private_lock.  Once the buffers are marked dirty we no longer
2417  * need the lock since try_to_free_buffers() does not free dirty buffers.
2418  */
2419 void mark_ntfs_record_dirty(struct page *page, const unsigned int ofs) {
2420         struct address_space *mapping = page->mapping;
2421         ntfs_inode *ni = NTFS_I(mapping->host);
2422         struct buffer_head *bh, *head, *buffers_to_free = NULL;
2423         unsigned int end, bh_size, bh_ofs;
2424
2425         BUG_ON(!PageUptodate(page));
2426         end = ofs + ni->itype.index.block_size;
2427         bh_size = 1 << VFS_I(ni)->i_blkbits;
2428         spin_lock(&mapping->private_lock);
2429         if (unlikely(!page_has_buffers(page))) {
2430                 spin_unlock(&mapping->private_lock);
2431                 bh = head = alloc_page_buffers(page, bh_size, 1);
2432                 spin_lock(&mapping->private_lock);
2433                 if (likely(!page_has_buffers(page))) {
2434                         struct buffer_head *tail;
2435
2436                         do {
2437                                 set_buffer_uptodate(bh);
2438                                 tail = bh;
2439                                 bh = bh->b_this_page;
2440                         } while (bh);
2441                         tail->b_this_page = head;
2442                         attach_page_buffers(page, head);
2443                 } else
2444                         buffers_to_free = bh;
2445         }
2446         bh = head = page_buffers(page);
2447         BUG_ON(!bh);
2448         do {
2449                 bh_ofs = bh_offset(bh);
2450                 if (bh_ofs + bh_size <= ofs)
2451                         continue;
2452                 if (unlikely(bh_ofs >= end))
2453                         break;
2454                 set_buffer_dirty(bh);
2455         } while ((bh = bh->b_this_page) != head);
2456         spin_unlock(&mapping->private_lock);
2457         __set_page_dirty_nobuffers(page);
2458         if (unlikely(buffers_to_free)) {
2459                 do {
2460                         bh = buffers_to_free->b_this_page;
2461                         free_buffer_head(buffers_to_free);
2462                         buffers_to_free = bh;
2463                 } while (buffers_to_free);
2464         }
2465 }
2466
2467 #endif /* NTFS_RW */