file.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * file.c - NTFS kernel file operations. Part of the Linux-NTFS project.
  4. *
  5. * Copyright (c) 2001-2015 Anton Altaparmakov and Tuxera Inc.
  6. */
  7. #include <linux/blkdev.h>
  8. #include <linux/backing-dev.h>
  9. #include <linux/buffer_head.h>
  10. #include <linux/gfp.h>
  11. #include <linux/pagemap.h>
  12. #include <linux/pagevec.h>
  13. #include <linux/sched/signal.h>
  14. #include <linux/swap.h>
  15. #include <linux/uio.h>
  16. #include <linux/writeback.h>
  17. #include <asm/page.h>
  18. #include <linux/uaccess.h>
  19. #include "attrib.h"
  20. #include "bitmap.h"
  21. #include "inode.h"
  22. #include "debug.h"
  23. #include "lcnalloc.h"
  24. #include "malloc.h"
  25. #include "mft.h"
  26. #include "ntfs.h"
  27. /**
  28. * ntfs_file_open - called when an inode is about to be opened
  29. * @vi: inode to be opened
  30. * @filp: file structure describing the inode
  31. *
  32. * Limit file size to the page cache limit on architectures where unsigned long
  33. * is 32-bits. This is the most we can do for now without overflowing the page
  34. * cache page index. Doing it this way means we don't run into problems because
  35. * of existing too large files. It would be better to allow the user to read
  36. * the beginning of the file but I doubt very much anyone is going to hit this
  37. * check on a 32-bit architecture, so there is no point in adding the extra
  38. * complexity required to support this.
  39. *
  40. * On 64-bit architectures, the check is hopefully optimized away by the
  41. * compiler.
  42. *
  43. * After the check passes, just call generic_file_open() to do its work.
  44. */
  45. static int ntfs_file_open(struct inode *vi, struct file *filp)
  46. {
  47. if (sizeof(unsigned long) < 8) {
  48. if (i_size_read(vi) > MAX_LFS_FILESIZE)
  49. return -EOVERFLOW;
  50. }
  51. return generic_file_open(vi, filp);
  52. }
  53. #ifdef NTFS_RW
  54. /**
  55. * ntfs_attr_extend_initialized - extend the initialized size of an attribute
  56. * @ni: ntfs inode of the attribute to extend
  57. * @new_init_size: requested new initialized size in bytes
  58. *
  59. * Extend the initialized size of an attribute described by the ntfs inode @ni
  60. * to @new_init_size bytes. This involves zeroing any non-sparse space between
  61. * the old initialized size and @new_init_size both in the page cache and on
  62. * disk (if relevant complete pages are already uptodate in the page cache then
  63. * these are simply marked dirty).
  64. *
  65. * As a side-effect, the file size (vfs inode->i_size) may be incremented as,
  66. * in the resident attribute case, it is tied to the initialized size and, in
  67. * the non-resident attribute case, it may not fall below the initialized size.
  68. *
  69. * Note that if the attribute is resident, we do not need to touch the page
  70. * cache at all. This is because if the page cache page is not uptodate we
  71. * bring it uptodate later, when doing the write to the mft record since we
  72. * then already have the page mapped. And if the page is uptodate, the
  73. * non-initialized region will already have been zeroed when the page was
  74. * brought uptodate and the region may in fact already have been overwritten
  75. * with new data via mmap() based writes, so we cannot just zero it. And since
  76. * POSIX specifies that the behaviour of resizing a file whilst it is mmap()ped
  77. * is unspecified, we choose not to do zeroing and thus we do not need to touch
  78. * the page at all. For a more detailed explanation see ntfs_truncate() in
  79. * fs/ntfs/inode.c.
  80. *
  81. * Return 0 on success and -errno on error. In the case that an error is
  82. * encountered it is possible that the initialized size will already have been
  83. * incremented some way towards @new_init_size but it is guaranteed that if
  84. * this is the case, the necessary zeroing will also have happened and that all
  85. * metadata is self-consistent.
  86. *
  87. * Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be
  88. * held by the caller.
  89. */
  90. static int ntfs_attr_extend_initialized(ntfs_inode *ni, const s64 new_init_size)
  91. {
  92. s64 old_init_size;
  93. loff_t old_i_size;
  94. pgoff_t index, end_index;
  95. unsigned long flags;
  96. struct inode *vi = VFS_I(ni);
  97. ntfs_inode *base_ni;
  98. MFT_RECORD *m = NULL;
  99. ATTR_RECORD *a;
  100. ntfs_attr_search_ctx *ctx = NULL;
  101. struct address_space *mapping;
  102. struct page *page = NULL;
  103. u8 *kattr;
  104. int err;
  105. u32 attr_len;
  106. read_lock_irqsave(&ni->size_lock, flags);
  107. old_init_size = ni->initialized_size;
  108. old_i_size = i_size_read(vi);
  109. BUG_ON(new_init_size > ni->allocated_size);
  110. read_unlock_irqrestore(&ni->size_lock, flags);
  111. ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
  112. "old_initialized_size 0x%llx, "
  113. "new_initialized_size 0x%llx, i_size 0x%llx.",
  114. vi->i_ino, (unsigned)le32_to_cpu(ni->type),
  115. (unsigned long long)old_init_size,
  116. (unsigned long long)new_init_size, old_i_size);
  117. if (!NInoAttr(ni))
  118. base_ni = ni;
  119. else
  120. base_ni = ni->ext.base_ntfs_ino;
  121. /* Use goto to reduce indentation and we need the label below anyway. */
  122. if (NInoNonResident(ni))
  123. goto do_non_resident_extend;
  124. BUG_ON(old_init_size != old_i_size);
  125. m = map_mft_record(base_ni);
  126. if (IS_ERR(m)) {
  127. err = PTR_ERR(m);
  128. m = NULL;
  129. goto err_out;
  130. }
  131. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  132. if (unlikely(!ctx)) {
  133. err = -ENOMEM;
  134. goto err_out;
  135. }
  136. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  137. CASE_SENSITIVE, 0, NULL, 0, ctx);
  138. if (unlikely(err)) {
  139. if (err == -ENOENT)
  140. err = -EIO;
  141. goto err_out;
  142. }
  143. m = ctx->mrec;
  144. a = ctx->attr;
  145. BUG_ON(a->non_resident);
  146. /* The total length of the attribute value. */
  147. attr_len = le32_to_cpu(a->data.resident.value_length);
  148. BUG_ON(old_i_size != (loff_t)attr_len);
  149. /*
  150. * Do the zeroing in the mft record and update the attribute size in
  151. * the mft record.
  152. */
  153. kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
  154. memset(kattr + attr_len, 0, new_init_size - attr_len);
  155. a->data.resident.value_length = cpu_to_le32((u32)new_init_size);
  156. /* Finally, update the sizes in the vfs and ntfs inodes. */
  157. write_lock_irqsave(&ni->size_lock, flags);
  158. i_size_write(vi, new_init_size);
  159. ni->initialized_size = new_init_size;
  160. write_unlock_irqrestore(&ni->size_lock, flags);
  161. goto done;
  162. do_non_resident_extend:
  163. /*
  164. * If the new initialized size @new_init_size exceeds the current file
  165. * size (vfs inode->i_size), we need to extend the file size to the
  166. * new initialized size.
  167. */
  168. if (new_init_size > old_i_size) {
  169. m = map_mft_record(base_ni);
  170. if (IS_ERR(m)) {
  171. err = PTR_ERR(m);
  172. m = NULL;
  173. goto err_out;
  174. }
  175. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  176. if (unlikely(!ctx)) {
  177. err = -ENOMEM;
  178. goto err_out;
  179. }
  180. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  181. CASE_SENSITIVE, 0, NULL, 0, ctx);
  182. if (unlikely(err)) {
  183. if (err == -ENOENT)
  184. err = -EIO;
  185. goto err_out;
  186. }
  187. m = ctx->mrec;
  188. a = ctx->attr;
  189. BUG_ON(!a->non_resident);
  190. BUG_ON(old_i_size != (loff_t)
  191. sle64_to_cpu(a->data.non_resident.data_size));
  192. a->data.non_resident.data_size = cpu_to_sle64(new_init_size);
  193. flush_dcache_mft_record_page(ctx->ntfs_ino);
  194. mark_mft_record_dirty(ctx->ntfs_ino);
  195. /* Update the file size in the vfs inode. */
  196. i_size_write(vi, new_init_size);
  197. ntfs_attr_put_search_ctx(ctx);
  198. ctx = NULL;
  199. unmap_mft_record(base_ni);
  200. m = NULL;
  201. }
  202. mapping = vi->i_mapping;
  203. index = old_init_size >> PAGE_SHIFT;
  204. end_index = (new_init_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  205. do {
  206. /*
  207. * Read the page. If the page is not present, this will zero
  208. * the uninitialized regions for us.
  209. */
  210. page = read_mapping_page(mapping, index, NULL);
  211. if (IS_ERR(page)) {
  212. err = PTR_ERR(page);
  213. goto init_err_out;
  214. }
  215. /*
  216. * Update the initialized size in the ntfs inode. This is
  217. * enough to make ntfs_writepage() work.
  218. */
  219. write_lock_irqsave(&ni->size_lock, flags);
  220. ni->initialized_size = (s64)(index + 1) << PAGE_SHIFT;
  221. if (ni->initialized_size > new_init_size)
  222. ni->initialized_size = new_init_size;
  223. write_unlock_irqrestore(&ni->size_lock, flags);
  224. /* Set the page dirty so it gets written out. */
  225. set_page_dirty(page);
  226. put_page(page);
  227. /*
  228. * Play nice with the vm and the rest of the system. This is
  229. * very much needed as we can potentially be modifying the
  230. * initialised size from a very small value to a really huge
  231. * value, e.g.
  232. * f = open(somefile, O_TRUNC);
  233. * truncate(f, 10GiB);
  234. * seek(f, 10GiB);
  235. * write(f, 1);
  236. * And this would mean we would be marking dirty hundreds of
  237. * thousands of pages or as in the above example more than
  238. * two and a half million pages!
  239. *
  240. * TODO: For sparse pages could optimize this workload by using
  241. * the FsMisc / MiscFs page bit as a "PageIsSparse" bit. This
  242. * would be set in read_folio for sparse pages and here we would
  243. * not need to mark dirty any pages which have this bit set.
  244. * The only caveat is that we have to clear the bit everywhere
  245. * where we allocate any clusters that lie in the page or that
  246. * contain the page.
  247. *
  248. * TODO: An even greater optimization would be for us to only
  249. * call read_folio() on pages which are not in sparse regions as
  250. * determined from the runlist. This would greatly reduce the
  251. * number of pages we read and make dirty in the case of sparse
  252. * files.
  253. */
  254. balance_dirty_pages_ratelimited(mapping);
  255. cond_resched();
  256. } while (++index < end_index);
  257. read_lock_irqsave(&ni->size_lock, flags);
  258. BUG_ON(ni->initialized_size != new_init_size);
  259. read_unlock_irqrestore(&ni->size_lock, flags);
  260. /* Now bring in sync the initialized_size in the mft record. */
  261. m = map_mft_record(base_ni);
  262. if (IS_ERR(m)) {
  263. err = PTR_ERR(m);
  264. m = NULL;
  265. goto init_err_out;
  266. }
  267. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  268. if (unlikely(!ctx)) {
  269. err = -ENOMEM;
  270. goto init_err_out;
  271. }
  272. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  273. CASE_SENSITIVE, 0, NULL, 0, ctx);
  274. if (unlikely(err)) {
  275. if (err == -ENOENT)
  276. err = -EIO;
  277. goto init_err_out;
  278. }
  279. m = ctx->mrec;
  280. a = ctx->attr;
  281. BUG_ON(!a->non_resident);
  282. a->data.non_resident.initialized_size = cpu_to_sle64(new_init_size);
  283. done:
  284. flush_dcache_mft_record_page(ctx->ntfs_ino);
  285. mark_mft_record_dirty(ctx->ntfs_ino);
  286. if (ctx)
  287. ntfs_attr_put_search_ctx(ctx);
  288. if (m)
  289. unmap_mft_record(base_ni);
  290. ntfs_debug("Done, initialized_size 0x%llx, i_size 0x%llx.",
  291. (unsigned long long)new_init_size, i_size_read(vi));
  292. return 0;
  293. init_err_out:
  294. write_lock_irqsave(&ni->size_lock, flags);
  295. ni->initialized_size = old_init_size;
  296. write_unlock_irqrestore(&ni->size_lock, flags);
  297. err_out:
  298. if (ctx)
  299. ntfs_attr_put_search_ctx(ctx);
  300. if (m)
  301. unmap_mft_record(base_ni);
  302. ntfs_debug("Failed. Returning error code %i.", err);
  303. return err;
  304. }
  305. static ssize_t ntfs_prepare_file_for_write(struct kiocb *iocb,
  306. struct iov_iter *from)
  307. {
  308. loff_t pos;
  309. s64 end, ll;
  310. ssize_t err;
  311. unsigned long flags;
  312. struct file *file = iocb->ki_filp;
  313. struct inode *vi = file_inode(file);
  314. ntfs_inode *ni = NTFS_I(vi);
  315. ntfs_volume *vol = ni->vol;
  316. ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
  317. "0x%llx, count 0x%zx.", vi->i_ino,
  318. (unsigned)le32_to_cpu(ni->type),
  319. (unsigned long long)iocb->ki_pos,
  320. iov_iter_count(from));
  321. err = generic_write_checks(iocb, from);
  322. if (unlikely(err <= 0))
  323. goto out;
  324. /*
  325. * All checks have passed. Before we start doing any writing we want
  326. * to abort any totally illegal writes.
  327. */
  328. BUG_ON(NInoMstProtected(ni));
  329. BUG_ON(ni->type != AT_DATA);
  330. /* If file is encrypted, deny access, just like NT4. */
  331. if (NInoEncrypted(ni)) {
  332. /* Only $DATA attributes can be encrypted. */
  333. /*
  334. * Reminder for later: Encrypted files are _always_
  335. * non-resident so that the content can always be encrypted.
  336. */
  337. ntfs_debug("Denying write access to encrypted file.");
  338. err = -EACCES;
  339. goto out;
  340. }
  341. if (NInoCompressed(ni)) {
  342. /* Only unnamed $DATA attribute can be compressed. */
  343. BUG_ON(ni->name_len);
  344. /*
  345. * Reminder for later: If resident, the data is not actually
  346. * compressed. Only on the switch to non-resident does
  347. * compression kick in. This is in contrast to encrypted files
  348. * (see above).
  349. */
  350. ntfs_error(vi->i_sb, "Writing to compressed files is not "
  351. "implemented yet. Sorry.");
  352. err = -EOPNOTSUPP;
  353. goto out;
  354. }
  355. err = file_remove_privs(file);
  356. if (unlikely(err))
  357. goto out;
  358. /*
  359. * Our ->update_time method always succeeds thus file_update_time()
  360. * cannot fail either so there is no need to check the return code.
  361. */
  362. file_update_time(file);
  363. pos = iocb->ki_pos;
  364. /* The first byte after the last cluster being written to. */
  365. end = (pos + iov_iter_count(from) + vol->cluster_size_mask) &
  366. ~(u64)vol->cluster_size_mask;
  367. /*
  368. * If the write goes beyond the allocated size, extend the allocation
  369. * to cover the whole of the write, rounded up to the nearest cluster.
  370. */
  371. read_lock_irqsave(&ni->size_lock, flags);
  372. ll = ni->allocated_size;
  373. read_unlock_irqrestore(&ni->size_lock, flags);
  374. if (end > ll) {
  375. /*
  376. * Extend the allocation without changing the data size.
  377. *
  378. * Note we ensure the allocation is big enough to at least
  379. * write some data but we do not require the allocation to be
  380. * complete, i.e. it may be partial.
  381. */
  382. ll = ntfs_attr_extend_allocation(ni, end, -1, pos);
  383. if (likely(ll >= 0)) {
  384. BUG_ON(pos >= ll);
  385. /* If the extension was partial truncate the write. */
  386. if (end > ll) {
  387. ntfs_debug("Truncating write to inode 0x%lx, "
  388. "attribute type 0x%x, because "
  389. "the allocation was only "
  390. "partially extended.",
  391. vi->i_ino, (unsigned)
  392. le32_to_cpu(ni->type));
  393. iov_iter_truncate(from, ll - pos);
  394. }
  395. } else {
  396. err = ll;
  397. read_lock_irqsave(&ni->size_lock, flags);
  398. ll = ni->allocated_size;
  399. read_unlock_irqrestore(&ni->size_lock, flags);
  400. /* Perform a partial write if possible or fail. */
  401. if (pos < ll) {
  402. ntfs_debug("Truncating write to inode 0x%lx "
  403. "attribute type 0x%x, because "
  404. "extending the allocation "
  405. "failed (error %d).",
  406. vi->i_ino, (unsigned)
  407. le32_to_cpu(ni->type),
  408. (int)-err);
  409. iov_iter_truncate(from, ll - pos);
  410. } else {
  411. if (err != -ENOSPC)
  412. ntfs_error(vi->i_sb, "Cannot perform "
  413. "write to inode "
  414. "0x%lx, attribute "
  415. "type 0x%x, because "
  416. "extending the "
  417. "allocation failed "
  418. "(error %ld).",
  419. vi->i_ino, (unsigned)
  420. le32_to_cpu(ni->type),
  421. (long)-err);
  422. else
  423. ntfs_debug("Cannot perform write to "
  424. "inode 0x%lx, "
  425. "attribute type 0x%x, "
  426. "because there is not "
  427. "space left.",
  428. vi->i_ino, (unsigned)
  429. le32_to_cpu(ni->type));
  430. goto out;
  431. }
  432. }
  433. }
  434. /*
  435. * If the write starts beyond the initialized size, extend it up to the
  436. * beginning of the write and initialize all non-sparse space between
  437. * the old initialized size and the new one. This automatically also
  438. * increments the vfs inode->i_size to keep it above or equal to the
  439. * initialized_size.
  440. */
  441. read_lock_irqsave(&ni->size_lock, flags);
  442. ll = ni->initialized_size;
  443. read_unlock_irqrestore(&ni->size_lock, flags);
  444. if (pos > ll) {
  445. /*
  446. * Wait for ongoing direct i/o to complete before proceeding.
  447. * New direct i/o cannot start as we hold i_mutex.
  448. */
  449. inode_dio_wait(vi);
  450. err = ntfs_attr_extend_initialized(ni, pos);
  451. if (unlikely(err < 0))
  452. ntfs_error(vi->i_sb, "Cannot perform write to inode "
  453. "0x%lx, attribute type 0x%x, because "
  454. "extending the initialized size "
  455. "failed (error %d).", vi->i_ino,
  456. (unsigned)le32_to_cpu(ni->type),
  457. (int)-err);
  458. }
  459. out:
  460. return err;
  461. }
  462. /**
  463. * __ntfs_grab_cache_pages - obtain a number of locked pages
  464. * @mapping: address space mapping from which to obtain page cache pages
  465. * @index: starting index in @mapping at which to begin obtaining pages
  466. * @nr_pages: number of page cache pages to obtain
  467. * @pages: array of pages in which to return the obtained page cache pages
  468. * @cached_page: allocated but as yet unused page
  469. *
  470. * Obtain @nr_pages locked page cache pages from the mapping @mapping and
  471. * starting at index @index.
  472. *
  473. * If a page is newly created, add it to lru list
  474. *
  475. * Note, the page locks are obtained in ascending page index order.
  476. */
  477. static inline int __ntfs_grab_cache_pages(struct address_space *mapping,
  478. pgoff_t index, const unsigned nr_pages, struct page **pages,
  479. struct page **cached_page)
  480. {
  481. int err, nr;
  482. BUG_ON(!nr_pages);
  483. err = nr = 0;
  484. do {
  485. pages[nr] = find_get_page_flags(mapping, index, FGP_LOCK |
  486. FGP_ACCESSED);
  487. if (!pages[nr]) {
  488. if (!*cached_page) {
  489. *cached_page = page_cache_alloc(mapping);
  490. if (unlikely(!*cached_page)) {
  491. err = -ENOMEM;
  492. goto err_out;
  493. }
  494. }
  495. err = add_to_page_cache_lru(*cached_page, mapping,
  496. index,
  497. mapping_gfp_constraint(mapping, GFP_KERNEL));
  498. if (unlikely(err)) {
  499. if (err == -EEXIST)
  500. continue;
  501. goto err_out;
  502. }
  503. pages[nr] = *cached_page;
  504. *cached_page = NULL;
  505. }
  506. index++;
  507. nr++;
  508. } while (nr < nr_pages);
  509. out:
  510. return err;
  511. err_out:
  512. while (nr > 0) {
  513. unlock_page(pages[--nr]);
  514. put_page(pages[nr]);
  515. }
  516. goto out;
  517. }
  518. static inline void ntfs_submit_bh_for_read(struct buffer_head *bh)
  519. {
  520. lock_buffer(bh);
  521. get_bh(bh);
  522. bh->b_end_io = end_buffer_read_sync;
  523. submit_bh(REQ_OP_READ, bh);
  524. }
  525. /**
  526. * ntfs_prepare_pages_for_non_resident_write - prepare pages for receiving data
  527. * @pages: array of destination pages
  528. * @nr_pages: number of pages in @pages
  529. * @pos: byte position in file at which the write begins
  530. * @bytes: number of bytes to be written
  531. *
  532. * This is called for non-resident attributes from ntfs_file_buffered_write()
  533. * with i_mutex held on the inode (@pages[0]->mapping->host). There are
  534. * @nr_pages pages in @pages which are locked but not kmap()ped. The source
  535. * data has not yet been copied into the @pages.
  536. *
  537. * Need to fill any holes with actual clusters, allocate buffers if necessary,
  538. * ensure all the buffers are mapped, and bring uptodate any buffers that are
  539. * only partially being written to.
  540. *
  541. * If @nr_pages is greater than one, we are guaranteed that the cluster size is
  542. * greater than PAGE_SIZE, that all pages in @pages are entirely inside
  543. * the same cluster and that they are the entirety of that cluster, and that
  544. * the cluster is sparse, i.e. we need to allocate a cluster to fill the hole.
  545. *
  546. * i_size is not to be modified yet.
  547. *
  548. * Return 0 on success or -errno on error.
  549. */
  550. static int ntfs_prepare_pages_for_non_resident_write(struct page **pages,
  551. unsigned nr_pages, s64 pos, size_t bytes)
  552. {
  553. VCN vcn, highest_vcn = 0, cpos, cend, bh_cpos, bh_cend;
  554. LCN lcn;
  555. s64 bh_pos, vcn_len, end, initialized_size;
  556. sector_t lcn_block;
  557. struct page *page;
  558. struct inode *vi;
  559. ntfs_inode *ni, *base_ni = NULL;
  560. ntfs_volume *vol;
  561. runlist_element *rl, *rl2;
  562. struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
  563. ntfs_attr_search_ctx *ctx = NULL;
  564. MFT_RECORD *m = NULL;
  565. ATTR_RECORD *a = NULL;
  566. unsigned long flags;
  567. u32 attr_rec_len = 0;
  568. unsigned blocksize, u;
  569. int err, mp_size;
  570. bool rl_write_locked, was_hole, is_retry;
  571. unsigned char blocksize_bits;
  572. struct {
  573. u8 runlist_merged:1;
  574. u8 mft_attr_mapped:1;
  575. u8 mp_rebuilt:1;
  576. u8 attr_switched:1;
  577. } status = { 0, 0, 0, 0 };
  578. BUG_ON(!nr_pages);
  579. BUG_ON(!pages);
  580. BUG_ON(!*pages);
  581. vi = pages[0]->mapping->host;
  582. ni = NTFS_I(vi);
  583. vol = ni->vol;
  584. ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
  585. "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
  586. vi->i_ino, ni->type, pages[0]->index, nr_pages,
  587. (long long)pos, bytes);
  588. blocksize = vol->sb->s_blocksize;
  589. blocksize_bits = vol->sb->s_blocksize_bits;
  590. u = 0;
  591. do {
  592. page = pages[u];
  593. BUG_ON(!page);
  594. /*
  595. * create_empty_buffers() will create uptodate/dirty buffers if
  596. * the page is uptodate/dirty.
  597. */
  598. if (!page_has_buffers(page)) {
  599. create_empty_buffers(page, blocksize, 0);
  600. if (unlikely(!page_has_buffers(page)))
  601. return -ENOMEM;
  602. }
  603. } while (++u < nr_pages);
  604. rl_write_locked = false;
  605. rl = NULL;
  606. err = 0;
  607. vcn = lcn = -1;
  608. vcn_len = 0;
  609. lcn_block = -1;
  610. was_hole = false;
  611. cpos = pos >> vol->cluster_size_bits;
  612. end = pos + bytes;
  613. cend = (end + vol->cluster_size - 1) >> vol->cluster_size_bits;
  614. /*
  615. * Loop over each page and for each page over each buffer. Use goto to
  616. * reduce indentation.
  617. */
  618. u = 0;
  619. do_next_page:
  620. page = pages[u];
  621. bh_pos = (s64)page->index << PAGE_SHIFT;
  622. bh = head = page_buffers(page);
  623. do {
  624. VCN cdelta;
  625. s64 bh_end;
  626. unsigned bh_cofs;
  627. /* Clear buffer_new on all buffers to reinitialise state. */
  628. if (buffer_new(bh))
  629. clear_buffer_new(bh);
  630. bh_end = bh_pos + blocksize;
  631. bh_cpos = bh_pos >> vol->cluster_size_bits;
  632. bh_cofs = bh_pos & vol->cluster_size_mask;
  633. if (buffer_mapped(bh)) {
  634. /*
  635. * The buffer is already mapped. If it is uptodate,
  636. * ignore it.
  637. */
  638. if (buffer_uptodate(bh))
  639. continue;
  640. /*
  641. * The buffer is not uptodate. If the page is uptodate
  642. * set the buffer uptodate and otherwise ignore it.
  643. */
  644. if (PageUptodate(page)) {
  645. set_buffer_uptodate(bh);
  646. continue;
  647. }
  648. /*
  649. * Neither the page nor the buffer are uptodate. If
  650. * the buffer is only partially being written to, we
  651. * need to read it in before the write, i.e. now.
  652. */
  653. if ((bh_pos < pos && bh_end > pos) ||
  654. (bh_pos < end && bh_end > end)) {
  655. /*
  656. * If the buffer is fully or partially within
  657. * the initialized size, do an actual read.
  658. * Otherwise, simply zero the buffer.
  659. */
  660. read_lock_irqsave(&ni->size_lock, flags);
  661. initialized_size = ni->initialized_size;
  662. read_unlock_irqrestore(&ni->size_lock, flags);
  663. if (bh_pos < initialized_size) {
  664. ntfs_submit_bh_for_read(bh);
  665. *wait_bh++ = bh;
  666. } else {
  667. zero_user(page, bh_offset(bh),
  668. blocksize);
  669. set_buffer_uptodate(bh);
  670. }
  671. }
  672. continue;
  673. }
  674. /* Unmapped buffer. Need to map it. */
  675. bh->b_bdev = vol->sb->s_bdev;
  676. /*
  677. * If the current buffer is in the same clusters as the map
  678. * cache, there is no need to check the runlist again. The
  679. * map cache is made up of @vcn, which is the first cached file
  680. * cluster, @vcn_len which is the number of cached file
  681. * clusters, @lcn is the device cluster corresponding to @vcn,
  682. * and @lcn_block is the block number corresponding to @lcn.
  683. */
  684. cdelta = bh_cpos - vcn;
  685. if (likely(!cdelta || (cdelta > 0 && cdelta < vcn_len))) {
  686. map_buffer_cached:
  687. BUG_ON(lcn < 0);
  688. bh->b_blocknr = lcn_block +
  689. (cdelta << (vol->cluster_size_bits -
  690. blocksize_bits)) +
  691. (bh_cofs >> blocksize_bits);
  692. set_buffer_mapped(bh);
  693. /*
  694. * If the page is uptodate so is the buffer. If the
  695. * buffer is fully outside the write, we ignore it if
  696. * it was already allocated and we mark it dirty so it
  697. * gets written out if we allocated it. On the other
  698. * hand, if we allocated the buffer but we are not
  699. * marking it dirty we set buffer_new so we can do
  700. * error recovery.
  701. */
  702. if (PageUptodate(page)) {
  703. if (!buffer_uptodate(bh))
  704. set_buffer_uptodate(bh);
  705. if (unlikely(was_hole)) {
  706. /* We allocated the buffer. */
  707. clean_bdev_bh_alias(bh);
  708. if (bh_end <= pos || bh_pos >= end)
  709. mark_buffer_dirty(bh);
  710. else
  711. set_buffer_new(bh);
  712. }
  713. continue;
  714. }
  715. /* Page is _not_ uptodate. */
  716. if (likely(!was_hole)) {
  717. /*
  718. * Buffer was already allocated. If it is not
  719. * uptodate and is only partially being written
  720. * to, we need to read it in before the write,
  721. * i.e. now.
  722. */
  723. if (!buffer_uptodate(bh) && bh_pos < end &&
  724. bh_end > pos &&
  725. (bh_pos < pos ||
  726. bh_end > end)) {
  727. /*
  728. * If the buffer is fully or partially
  729. * within the initialized size, do an
  730. * actual read. Otherwise, simply zero
  731. * the buffer.
  732. */
  733. read_lock_irqsave(&ni->size_lock,
  734. flags);
  735. initialized_size = ni->initialized_size;
  736. read_unlock_irqrestore(&ni->size_lock,
  737. flags);
  738. if (bh_pos < initialized_size) {
  739. ntfs_submit_bh_for_read(bh);
  740. *wait_bh++ = bh;
  741. } else {
  742. zero_user(page, bh_offset(bh),
  743. blocksize);
  744. set_buffer_uptodate(bh);
  745. }
  746. }
  747. continue;
  748. }
  749. /* We allocated the buffer. */
  750. clean_bdev_bh_alias(bh);
  751. /*
  752. * If the buffer is fully outside the write, zero it,
  753. * set it uptodate, and mark it dirty so it gets
  754. * written out. If it is partially being written to,
  755. * zero region surrounding the write but leave it to
  756. * commit write to do anything else. Finally, if the
  757. * buffer is fully being overwritten, do nothing.
  758. */
  759. if (bh_end <= pos || bh_pos >= end) {
  760. if (!buffer_uptodate(bh)) {
  761. zero_user(page, bh_offset(bh),
  762. blocksize);
  763. set_buffer_uptodate(bh);
  764. }
  765. mark_buffer_dirty(bh);
  766. continue;
  767. }
  768. set_buffer_new(bh);
  769. if (!buffer_uptodate(bh) &&
  770. (bh_pos < pos || bh_end > end)) {
  771. u8 *kaddr;
  772. unsigned pofs;
  773. kaddr = kmap_atomic(page);
  774. if (bh_pos < pos) {
  775. pofs = bh_pos & ~PAGE_MASK;
  776. memset(kaddr + pofs, 0, pos - bh_pos);
  777. }
  778. if (bh_end > end) {
  779. pofs = end & ~PAGE_MASK;
  780. memset(kaddr + pofs, 0, bh_end - end);
  781. }
  782. kunmap_atomic(kaddr);
  783. flush_dcache_page(page);
  784. }
  785. continue;
  786. }
  787. /*
  788. * Slow path: this is the first buffer in the cluster. If it
  789. * is outside allocated size and is not uptodate, zero it and
  790. * set it uptodate.
  791. */
  792. read_lock_irqsave(&ni->size_lock, flags);
  793. initialized_size = ni->allocated_size;
  794. read_unlock_irqrestore(&ni->size_lock, flags);
  795. if (bh_pos > initialized_size) {
  796. if (PageUptodate(page)) {
  797. if (!buffer_uptodate(bh))
  798. set_buffer_uptodate(bh);
  799. } else if (!buffer_uptodate(bh)) {
  800. zero_user(page, bh_offset(bh), blocksize);
  801. set_buffer_uptodate(bh);
  802. }
  803. continue;
  804. }
  805. is_retry = false;
  806. if (!rl) {
  807. down_read(&ni->runlist.lock);
  808. retry_remap:
  809. rl = ni->runlist.rl;
  810. }
  811. if (likely(rl != NULL)) {
  812. /* Seek to element containing target cluster. */
  813. while (rl->length && rl[1].vcn <= bh_cpos)
  814. rl++;
  815. lcn = ntfs_rl_vcn_to_lcn(rl, bh_cpos);
  816. if (likely(lcn >= 0)) {
  817. /*
  818. * Successful remap, setup the map cache and
  819. * use that to deal with the buffer.
  820. */
  821. was_hole = false;
  822. vcn = bh_cpos;
  823. vcn_len = rl[1].vcn - vcn;
  824. lcn_block = lcn << (vol->cluster_size_bits -
  825. blocksize_bits);
  826. cdelta = 0;
  827. /*
  828. * If the number of remaining clusters touched
  829. * by the write is smaller or equal to the
  830. * number of cached clusters, unlock the
  831. * runlist as the map cache will be used from
  832. * now on.
  833. */
  834. if (likely(vcn + vcn_len >= cend)) {
  835. if (rl_write_locked) {
  836. up_write(&ni->runlist.lock);
  837. rl_write_locked = false;
  838. } else
  839. up_read(&ni->runlist.lock);
  840. rl = NULL;
  841. }
  842. goto map_buffer_cached;
  843. }
  844. } else
  845. lcn = LCN_RL_NOT_MAPPED;
  846. /*
  847. * If it is not a hole and not out of bounds, the runlist is
  848. * probably unmapped so try to map it now.
  849. */
  850. if (unlikely(lcn != LCN_HOLE && lcn != LCN_ENOENT)) {
  851. if (likely(!is_retry && lcn == LCN_RL_NOT_MAPPED)) {
  852. /* Attempt to map runlist. */
  853. if (!rl_write_locked) {
  854. /*
  855. * We need the runlist locked for
  856. * writing, so if it is locked for
  857. * reading relock it now and retry in
  858. * case it changed whilst we dropped
  859. * the lock.
  860. */
  861. up_read(&ni->runlist.lock);
  862. down_write(&ni->runlist.lock);
  863. rl_write_locked = true;
  864. goto retry_remap;
  865. }
  866. err = ntfs_map_runlist_nolock(ni, bh_cpos,
  867. NULL);
  868. if (likely(!err)) {
  869. is_retry = true;
  870. goto retry_remap;
  871. }
  872. /*
  873. * If @vcn is out of bounds, pretend @lcn is
  874. * LCN_ENOENT. As long as the buffer is out
  875. * of bounds this will work fine.
  876. */
  877. if (err == -ENOENT) {
  878. lcn = LCN_ENOENT;
  879. err = 0;
  880. goto rl_not_mapped_enoent;
  881. }
  882. } else
  883. err = -EIO;
  884. /* Failed to map the buffer, even after retrying. */
  885. bh->b_blocknr = -1;
  886. ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
  887. "attribute type 0x%x, vcn 0x%llx, "
  888. "vcn offset 0x%x, because its "
  889. "location on disk could not be "
  890. "determined%s (error code %i).",
  891. ni->mft_no, ni->type,
  892. (unsigned long long)bh_cpos,
  893. (unsigned)bh_pos &
  894. vol->cluster_size_mask,
  895. is_retry ? " even after retrying" : "",
  896. err);
  897. break;
  898. }
  899. rl_not_mapped_enoent:
  900. /*
  901. * The buffer is in a hole or out of bounds. We need to fill
  902. * the hole, unless the buffer is in a cluster which is not
  903. * touched by the write, in which case we just leave the buffer
  904. * unmapped. This can only happen when the cluster size is
  905. * less than the page cache size.
  906. */
  907. if (unlikely(vol->cluster_size < PAGE_SIZE)) {
  908. bh_cend = (bh_end + vol->cluster_size - 1) >>
  909. vol->cluster_size_bits;
  910. if ((bh_cend <= cpos || bh_cpos >= cend)) {
  911. bh->b_blocknr = -1;
  912. /*
  913. * If the buffer is uptodate we skip it. If it
  914. * is not but the page is uptodate, we can set
  915. * the buffer uptodate. If the page is not
  916. * uptodate, we can clear the buffer and set it
  917. * uptodate. Whether this is worthwhile is
  918. * debatable and this could be removed.
  919. */
  920. if (PageUptodate(page)) {
  921. if (!buffer_uptodate(bh))
  922. set_buffer_uptodate(bh);
  923. } else if (!buffer_uptodate(bh)) {
  924. zero_user(page, bh_offset(bh),
  925. blocksize);
  926. set_buffer_uptodate(bh);
  927. }
  928. continue;
  929. }
  930. }
  931. /*
  932. * Out of bounds buffer is invalid if it was not really out of
  933. * bounds.
  934. */
  935. BUG_ON(lcn != LCN_HOLE);
  936. /*
  937. * We need the runlist locked for writing, so if it is locked
  938. * for reading relock it now and retry in case it changed
  939. * whilst we dropped the lock.
  940. */
  941. BUG_ON(!rl);
  942. if (!rl_write_locked) {
  943. up_read(&ni->runlist.lock);
  944. down_write(&ni->runlist.lock);
  945. rl_write_locked = true;
  946. goto retry_remap;
  947. }
  948. /* Find the previous last allocated cluster. */
  949. BUG_ON(rl->lcn != LCN_HOLE);
  950. lcn = -1;
  951. rl2 = rl;
  952. while (--rl2 >= ni->runlist.rl) {
  953. if (rl2->lcn >= 0) {
  954. lcn = rl2->lcn + rl2->length;
  955. break;
  956. }
  957. }
  958. rl2 = ntfs_cluster_alloc(vol, bh_cpos, 1, lcn, DATA_ZONE,
  959. false);
  960. if (IS_ERR(rl2)) {
  961. err = PTR_ERR(rl2);
  962. ntfs_debug("Failed to allocate cluster, error code %i.",
  963. err);
  964. break;
  965. }
  966. lcn = rl2->lcn;
  967. rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
  968. if (IS_ERR(rl)) {
  969. err = PTR_ERR(rl);
  970. if (err != -ENOMEM)
  971. err = -EIO;
  972. if (ntfs_cluster_free_from_rl(vol, rl2)) {
  973. ntfs_error(vol->sb, "Failed to release "
  974. "allocated cluster in error "
  975. "code path. Run chkdsk to "
  976. "recover the lost cluster.");
  977. NVolSetErrors(vol);
  978. }
  979. ntfs_free(rl2);
  980. break;
  981. }
  982. ni->runlist.rl = rl;
  983. status.runlist_merged = 1;
  984. ntfs_debug("Allocated cluster, lcn 0x%llx.",
  985. (unsigned long long)lcn);
  986. /* Map and lock the mft record and get the attribute record. */
  987. if (!NInoAttr(ni))
  988. base_ni = ni;
  989. else
  990. base_ni = ni->ext.base_ntfs_ino;
  991. m = map_mft_record(base_ni);
  992. if (IS_ERR(m)) {
  993. err = PTR_ERR(m);
  994. break;
  995. }
  996. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  997. if (unlikely(!ctx)) {
  998. err = -ENOMEM;
  999. unmap_mft_record(base_ni);
  1000. break;
  1001. }
  1002. status.mft_attr_mapped = 1;
  1003. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1004. CASE_SENSITIVE, bh_cpos, NULL, 0, ctx);
  1005. if (unlikely(err)) {
  1006. if (err == -ENOENT)
  1007. err = -EIO;
  1008. break;
  1009. }
  1010. m = ctx->mrec;
  1011. a = ctx->attr;
  1012. /*
  1013. * Find the runlist element with which the attribute extent
  1014. * starts. Note, we cannot use the _attr_ version because we
  1015. * have mapped the mft record. That is ok because we know the
  1016. * runlist fragment must be mapped already to have ever gotten
  1017. * here, so we can just use the _rl_ version.
  1018. */
  1019. vcn = sle64_to_cpu(a->data.non_resident.lowest_vcn);
  1020. rl2 = ntfs_rl_find_vcn_nolock(rl, vcn);
  1021. BUG_ON(!rl2);
  1022. BUG_ON(!rl2->length);
  1023. BUG_ON(rl2->lcn < LCN_HOLE);
  1024. highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
  1025. /*
  1026. * If @highest_vcn is zero, calculate the real highest_vcn
  1027. * (which can really be zero).
  1028. */
  1029. if (!highest_vcn)
  1030. highest_vcn = (sle64_to_cpu(
  1031. a->data.non_resident.allocated_size) >>
  1032. vol->cluster_size_bits) - 1;
  1033. /*
  1034. * Determine the size of the mapping pairs array for the new
  1035. * extent, i.e. the old extent with the hole filled.
  1036. */
  1037. mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, vcn,
  1038. highest_vcn);
  1039. if (unlikely(mp_size <= 0)) {
  1040. if (!(err = mp_size))
  1041. err = -EIO;
  1042. ntfs_debug("Failed to get size for mapping pairs "
  1043. "array, error code %i.", err);
  1044. break;
  1045. }
  1046. /*
  1047. * Resize the attribute record to fit the new mapping pairs
  1048. * array.
  1049. */
  1050. attr_rec_len = le32_to_cpu(a->length);
  1051. err = ntfs_attr_record_resize(m, a, mp_size + le16_to_cpu(
  1052. a->data.non_resident.mapping_pairs_offset));
  1053. if (unlikely(err)) {
  1054. BUG_ON(err != -ENOSPC);
  1055. // TODO: Deal with this by using the current attribute
  1056. // and fill it with as much of the mapping pairs
  1057. // array as possible. Then loop over each attribute
  1058. // extent rewriting the mapping pairs arrays as we go
  1059. // along and if when we reach the end we have not
  1060. // enough space, try to resize the last attribute
  1061. // extent and if even that fails, add a new attribute
  1062. // extent.
  1063. // We could also try to resize at each step in the hope
  1064. // that we will not need to rewrite every single extent.
  1065. // Note, we may need to decompress some extents to fill
  1066. // the runlist as we are walking the extents...
  1067. ntfs_error(vol->sb, "Not enough space in the mft "
  1068. "record for the extended attribute "
  1069. "record. This case is not "
  1070. "implemented yet.");
  1071. err = -EOPNOTSUPP;
  1072. break ;
  1073. }
  1074. status.mp_rebuilt = 1;
  1075. /*
  1076. * Generate the mapping pairs array directly into the attribute
  1077. * record.
  1078. */
  1079. err = ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
  1080. a->data.non_resident.mapping_pairs_offset),
  1081. mp_size, rl2, vcn, highest_vcn, NULL);
  1082. if (unlikely(err)) {
  1083. ntfs_error(vol->sb, "Cannot fill hole in inode 0x%lx, "
  1084. "attribute type 0x%x, because building "
  1085. "the mapping pairs failed with error "
  1086. "code %i.", vi->i_ino,
  1087. (unsigned)le32_to_cpu(ni->type), err);
  1088. err = -EIO;
  1089. break;
  1090. }
  1091. /* Update the highest_vcn but only if it was not set. */
  1092. if (unlikely(!a->data.non_resident.highest_vcn))
  1093. a->data.non_resident.highest_vcn =
  1094. cpu_to_sle64(highest_vcn);
  1095. /*
  1096. * If the attribute is sparse/compressed, update the compressed
  1097. * size in the ntfs_inode structure and the attribute record.
  1098. */
  1099. if (likely(NInoSparse(ni) || NInoCompressed(ni))) {
  1100. /*
  1101. * If we are not in the first attribute extent, switch
  1102. * to it, but first ensure the changes will make it to
  1103. * disk later.
  1104. */
  1105. if (a->data.non_resident.lowest_vcn) {
  1106. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1107. mark_mft_record_dirty(ctx->ntfs_ino);
  1108. ntfs_attr_reinit_search_ctx(ctx);
  1109. err = ntfs_attr_lookup(ni->type, ni->name,
  1110. ni->name_len, CASE_SENSITIVE,
  1111. 0, NULL, 0, ctx);
  1112. if (unlikely(err)) {
  1113. status.attr_switched = 1;
  1114. break;
  1115. }
  1116. /* @m is not used any more so do not set it. */
  1117. a = ctx->attr;
  1118. }
  1119. write_lock_irqsave(&ni->size_lock, flags);
  1120. ni->itype.compressed.size += vol->cluster_size;
  1121. a->data.non_resident.compressed_size =
  1122. cpu_to_sle64(ni->itype.compressed.size);
  1123. write_unlock_irqrestore(&ni->size_lock, flags);
  1124. }
  1125. /* Ensure the changes make it to disk. */
  1126. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1127. mark_mft_record_dirty(ctx->ntfs_ino);
  1128. ntfs_attr_put_search_ctx(ctx);
  1129. unmap_mft_record(base_ni);
  1130. /* Successfully filled the hole. */
  1131. status.runlist_merged = 0;
  1132. status.mft_attr_mapped = 0;
  1133. status.mp_rebuilt = 0;
  1134. /* Setup the map cache and use that to deal with the buffer. */
  1135. was_hole = true;
  1136. vcn = bh_cpos;
  1137. vcn_len = 1;
  1138. lcn_block = lcn << (vol->cluster_size_bits - blocksize_bits);
  1139. cdelta = 0;
  1140. /*
  1141. * If the number of remaining clusters in the @pages is smaller
  1142. * or equal to the number of cached clusters, unlock the
  1143. * runlist as the map cache will be used from now on.
  1144. */
  1145. if (likely(vcn + vcn_len >= cend)) {
  1146. up_write(&ni->runlist.lock);
  1147. rl_write_locked = false;
  1148. rl = NULL;
  1149. }
  1150. goto map_buffer_cached;
  1151. } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
  1152. /* If there are no errors, do the next page. */
  1153. if (likely(!err && ++u < nr_pages))
  1154. goto do_next_page;
  1155. /* If there are no errors, release the runlist lock if we took it. */
  1156. if (likely(!err)) {
  1157. if (unlikely(rl_write_locked)) {
  1158. up_write(&ni->runlist.lock);
  1159. rl_write_locked = false;
  1160. } else if (unlikely(rl))
  1161. up_read(&ni->runlist.lock);
  1162. rl = NULL;
  1163. }
  1164. /* If we issued read requests, let them complete. */
  1165. read_lock_irqsave(&ni->size_lock, flags);
  1166. initialized_size = ni->initialized_size;
  1167. read_unlock_irqrestore(&ni->size_lock, flags);
  1168. while (wait_bh > wait) {
  1169. bh = *--wait_bh;
  1170. wait_on_buffer(bh);
  1171. if (likely(buffer_uptodate(bh))) {
  1172. page = bh->b_page;
  1173. bh_pos = ((s64)page->index << PAGE_SHIFT) +
  1174. bh_offset(bh);
  1175. /*
  1176. * If the buffer overflows the initialized size, need
  1177. * to zero the overflowing region.
  1178. */
  1179. if (unlikely(bh_pos + blocksize > initialized_size)) {
  1180. int ofs = 0;
  1181. if (likely(bh_pos < initialized_size))
  1182. ofs = initialized_size - bh_pos;
  1183. zero_user_segment(page, bh_offset(bh) + ofs,
  1184. blocksize);
  1185. }
  1186. } else /* if (unlikely(!buffer_uptodate(bh))) */
  1187. err = -EIO;
  1188. }
  1189. if (likely(!err)) {
  1190. /* Clear buffer_new on all buffers. */
  1191. u = 0;
  1192. do {
  1193. bh = head = page_buffers(pages[u]);
  1194. do {
  1195. if (buffer_new(bh))
  1196. clear_buffer_new(bh);
  1197. } while ((bh = bh->b_this_page) != head);
  1198. } while (++u < nr_pages);
  1199. ntfs_debug("Done.");
  1200. return err;
  1201. }
  1202. if (status.attr_switched) {
  1203. /* Get back to the attribute extent we modified. */
  1204. ntfs_attr_reinit_search_ctx(ctx);
  1205. if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1206. CASE_SENSITIVE, bh_cpos, NULL, 0, ctx)) {
  1207. ntfs_error(vol->sb, "Failed to find required "
  1208. "attribute extent of attribute in "
  1209. "error code path. Run chkdsk to "
  1210. "recover.");
  1211. write_lock_irqsave(&ni->size_lock, flags);
  1212. ni->itype.compressed.size += vol->cluster_size;
  1213. write_unlock_irqrestore(&ni->size_lock, flags);
  1214. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1215. mark_mft_record_dirty(ctx->ntfs_ino);
  1216. /*
  1217. * The only thing that is now wrong is the compressed
  1218. * size of the base attribute extent which chkdsk
  1219. * should be able to fix.
  1220. */
  1221. NVolSetErrors(vol);
  1222. } else {
  1223. m = ctx->mrec;
  1224. a = ctx->attr;
  1225. status.attr_switched = 0;
  1226. }
  1227. }
  1228. /*
  1229. * If the runlist has been modified, need to restore it by punching a
  1230. * hole into it and we then need to deallocate the on-disk cluster as
  1231. * well. Note, we only modify the runlist if we are able to generate a
  1232. * new mapping pairs array, i.e. only when the mapped attribute extent
  1233. * is not switched.
  1234. */
  1235. if (status.runlist_merged && !status.attr_switched) {
  1236. BUG_ON(!rl_write_locked);
  1237. /* Make the file cluster we allocated sparse in the runlist. */
  1238. if (ntfs_rl_punch_nolock(vol, &ni->runlist, bh_cpos, 1)) {
  1239. ntfs_error(vol->sb, "Failed to punch hole into "
  1240. "attribute runlist in error code "
  1241. "path. Run chkdsk to recover the "
  1242. "lost cluster.");
  1243. NVolSetErrors(vol);
  1244. } else /* if (success) */ {
  1245. status.runlist_merged = 0;
  1246. /*
  1247. * Deallocate the on-disk cluster we allocated but only
  1248. * if we succeeded in punching its vcn out of the
  1249. * runlist.
  1250. */
  1251. down_write(&vol->lcnbmp_lock);
  1252. if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
  1253. ntfs_error(vol->sb, "Failed to release "
  1254. "allocated cluster in error "
  1255. "code path. Run chkdsk to "
  1256. "recover the lost cluster.");
  1257. NVolSetErrors(vol);
  1258. }
  1259. up_write(&vol->lcnbmp_lock);
  1260. }
  1261. }
  1262. /*
  1263. * Resize the attribute record to its old size and rebuild the mapping
  1264. * pairs array. Note, we only can do this if the runlist has been
  1265. * restored to its old state which also implies that the mapped
  1266. * attribute extent is not switched.
  1267. */
  1268. if (status.mp_rebuilt && !status.runlist_merged) {
  1269. if (ntfs_attr_record_resize(m, a, attr_rec_len)) {
  1270. ntfs_error(vol->sb, "Failed to restore attribute "
  1271. "record in error code path. Run "
  1272. "chkdsk to recover.");
  1273. NVolSetErrors(vol);
  1274. } else /* if (success) */ {
  1275. if (ntfs_mapping_pairs_build(vol, (u8*)a +
  1276. le16_to_cpu(a->data.non_resident.
  1277. mapping_pairs_offset), attr_rec_len -
  1278. le16_to_cpu(a->data.non_resident.
  1279. mapping_pairs_offset), ni->runlist.rl,
  1280. vcn, highest_vcn, NULL)) {
  1281. ntfs_error(vol->sb, "Failed to restore "
  1282. "mapping pairs array in error "
  1283. "code path. Run chkdsk to "
  1284. "recover.");
  1285. NVolSetErrors(vol);
  1286. }
  1287. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1288. mark_mft_record_dirty(ctx->ntfs_ino);
  1289. }
  1290. }
  1291. /* Release the mft record and the attribute. */
  1292. if (status.mft_attr_mapped) {
  1293. ntfs_attr_put_search_ctx(ctx);
  1294. unmap_mft_record(base_ni);
  1295. }
  1296. /* Release the runlist lock. */
  1297. if (rl_write_locked)
  1298. up_write(&ni->runlist.lock);
  1299. else if (rl)
  1300. up_read(&ni->runlist.lock);
  1301. /*
  1302. * Zero out any newly allocated blocks to avoid exposing stale data.
  1303. * If BH_New is set, we know that the block was newly allocated above
  1304. * and that it has not been fully zeroed and marked dirty yet.
  1305. */
  1306. nr_pages = u;
  1307. u = 0;
  1308. end = bh_cpos << vol->cluster_size_bits;
  1309. do {
  1310. page = pages[u];
  1311. bh = head = page_buffers(page);
  1312. do {
  1313. if (u == nr_pages &&
  1314. ((s64)page->index << PAGE_SHIFT) +
  1315. bh_offset(bh) >= end)
  1316. break;
  1317. if (!buffer_new(bh))
  1318. continue;
  1319. clear_buffer_new(bh);
  1320. if (!buffer_uptodate(bh)) {
  1321. if (PageUptodate(page))
  1322. set_buffer_uptodate(bh);
  1323. else {
  1324. zero_user(page, bh_offset(bh),
  1325. blocksize);
  1326. set_buffer_uptodate(bh);
  1327. }
  1328. }
  1329. mark_buffer_dirty(bh);
  1330. } while ((bh = bh->b_this_page) != head);
  1331. } while (++u <= nr_pages);
  1332. ntfs_error(vol->sb, "Failed. Returning error code %i.", err);
  1333. return err;
  1334. }
  1335. static inline void ntfs_flush_dcache_pages(struct page **pages,
  1336. unsigned nr_pages)
  1337. {
  1338. BUG_ON(!nr_pages);
  1339. /*
  1340. * Warning: Do not do the decrement at the same time as the call to
  1341. * flush_dcache_page() because it is a NULL macro on i386 and hence the
  1342. * decrement never happens so the loop never terminates.
  1343. */
  1344. do {
  1345. --nr_pages;
  1346. flush_dcache_page(pages[nr_pages]);
  1347. } while (nr_pages > 0);
  1348. }
  1349. /**
  1350. * ntfs_commit_pages_after_non_resident_write - commit the received data
  1351. * @pages: array of destination pages
  1352. * @nr_pages: number of pages in @pages
  1353. * @pos: byte position in file at which the write begins
  1354. * @bytes: number of bytes to be written
  1355. *
  1356. * See description of ntfs_commit_pages_after_write(), below.
  1357. */
  1358. static inline int ntfs_commit_pages_after_non_resident_write(
  1359. struct page **pages, const unsigned nr_pages,
  1360. s64 pos, size_t bytes)
  1361. {
  1362. s64 end, initialized_size;
  1363. struct inode *vi;
  1364. ntfs_inode *ni, *base_ni;
  1365. struct buffer_head *bh, *head;
  1366. ntfs_attr_search_ctx *ctx;
  1367. MFT_RECORD *m;
  1368. ATTR_RECORD *a;
  1369. unsigned long flags;
  1370. unsigned blocksize, u;
  1371. int err;
  1372. vi = pages[0]->mapping->host;
  1373. ni = NTFS_I(vi);
  1374. blocksize = vi->i_sb->s_blocksize;
  1375. end = pos + bytes;
  1376. u = 0;
  1377. do {
  1378. s64 bh_pos;
  1379. struct page *page;
  1380. bool partial;
  1381. page = pages[u];
  1382. bh_pos = (s64)page->index << PAGE_SHIFT;
  1383. bh = head = page_buffers(page);
  1384. partial = false;
  1385. do {
  1386. s64 bh_end;
  1387. bh_end = bh_pos + blocksize;
  1388. if (bh_end <= pos || bh_pos >= end) {
  1389. if (!buffer_uptodate(bh))
  1390. partial = true;
  1391. } else {
  1392. set_buffer_uptodate(bh);
  1393. mark_buffer_dirty(bh);
  1394. }
  1395. } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
  1396. /*
  1397. * If all buffers are now uptodate but the page is not, set the
  1398. * page uptodate.
  1399. */
  1400. if (!partial && !PageUptodate(page))
  1401. SetPageUptodate(page);
  1402. } while (++u < nr_pages);
  1403. /*
  1404. * Finally, if we do not need to update initialized_size or i_size we
  1405. * are finished.
  1406. */
  1407. read_lock_irqsave(&ni->size_lock, flags);
  1408. initialized_size = ni->initialized_size;
  1409. read_unlock_irqrestore(&ni->size_lock, flags);
  1410. if (end <= initialized_size) {
  1411. ntfs_debug("Done.");
  1412. return 0;
  1413. }
  1414. /*
  1415. * Update initialized_size/i_size as appropriate, both in the inode and
  1416. * the mft record.
  1417. */
  1418. if (!NInoAttr(ni))
  1419. base_ni = ni;
  1420. else
  1421. base_ni = ni->ext.base_ntfs_ino;
  1422. /* Map, pin, and lock the mft record. */
  1423. m = map_mft_record(base_ni);
  1424. if (IS_ERR(m)) {
  1425. err = PTR_ERR(m);
  1426. m = NULL;
  1427. ctx = NULL;
  1428. goto err_out;
  1429. }
  1430. BUG_ON(!NInoNonResident(ni));
  1431. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  1432. if (unlikely(!ctx)) {
  1433. err = -ENOMEM;
  1434. goto err_out;
  1435. }
  1436. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1437. CASE_SENSITIVE, 0, NULL, 0, ctx);
  1438. if (unlikely(err)) {
  1439. if (err == -ENOENT)
  1440. err = -EIO;
  1441. goto err_out;
  1442. }
  1443. a = ctx->attr;
  1444. BUG_ON(!a->non_resident);
  1445. write_lock_irqsave(&ni->size_lock, flags);
  1446. BUG_ON(end > ni->allocated_size);
  1447. ni->initialized_size = end;
  1448. a->data.non_resident.initialized_size = cpu_to_sle64(end);
  1449. if (end > i_size_read(vi)) {
  1450. i_size_write(vi, end);
  1451. a->data.non_resident.data_size =
  1452. a->data.non_resident.initialized_size;
  1453. }
  1454. write_unlock_irqrestore(&ni->size_lock, flags);
  1455. /* Mark the mft record dirty, so it gets written back. */
  1456. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1457. mark_mft_record_dirty(ctx->ntfs_ino);
  1458. ntfs_attr_put_search_ctx(ctx);
  1459. unmap_mft_record(base_ni);
  1460. ntfs_debug("Done.");
  1461. return 0;
  1462. err_out:
  1463. if (ctx)
  1464. ntfs_attr_put_search_ctx(ctx);
  1465. if (m)
  1466. unmap_mft_record(base_ni);
  1467. ntfs_error(vi->i_sb, "Failed to update initialized_size/i_size (error "
  1468. "code %i).", err);
  1469. if (err != -ENOMEM)
  1470. NVolSetErrors(ni->vol);
  1471. return err;
  1472. }
  1473. /**
  1474. * ntfs_commit_pages_after_write - commit the received data
  1475. * @pages: array of destination pages
  1476. * @nr_pages: number of pages in @pages
  1477. * @pos: byte position in file at which the write begins
  1478. * @bytes: number of bytes to be written
  1479. *
  1480. * This is called from ntfs_file_buffered_write() with i_mutex held on the inode
  1481. * (@pages[0]->mapping->host). There are @nr_pages pages in @pages which are
  1482. * locked but not kmap()ped. The source data has already been copied into the
  1483. * @page. ntfs_prepare_pages_for_non_resident_write() has been called before
  1484. * the data was copied (for non-resident attributes only) and it returned
  1485. * success.
  1486. *
  1487. * Need to set uptodate and mark dirty all buffers within the boundary of the
  1488. * write. If all buffers in a page are uptodate we set the page uptodate, too.
  1489. *
  1490. * Setting the buffers dirty ensures that they get written out later when
  1491. * ntfs_writepage() is invoked by the VM.
  1492. *
  1493. * Finally, we need to update i_size and initialized_size as appropriate both
  1494. * in the inode and the mft record.
  1495. *
  1496. * This is modelled after fs/buffer.c::generic_commit_write(), which marks
  1497. * buffers uptodate and dirty, sets the page uptodate if all buffers in the
  1498. * page are uptodate, and updates i_size if the end of io is beyond i_size. In
  1499. * that case, it also marks the inode dirty.
  1500. *
  1501. * If things have gone as outlined in
  1502. * ntfs_prepare_pages_for_non_resident_write(), we do not need to do any page
  1503. * content modifications here for non-resident attributes. For resident
  1504. * attributes we need to do the uptodate bringing here which we combine with
  1505. * the copying into the mft record which means we save one atomic kmap.
  1506. *
  1507. * Return 0 on success or -errno on error.
  1508. */
  1509. static int ntfs_commit_pages_after_write(struct page **pages,
  1510. const unsigned nr_pages, s64 pos, size_t bytes)
  1511. {
  1512. s64 end, initialized_size;
  1513. loff_t i_size;
  1514. struct inode *vi;
  1515. ntfs_inode *ni, *base_ni;
  1516. struct page *page;
  1517. ntfs_attr_search_ctx *ctx;
  1518. MFT_RECORD *m;
  1519. ATTR_RECORD *a;
  1520. char *kattr, *kaddr;
  1521. unsigned long flags;
  1522. u32 attr_len;
  1523. int err;
  1524. BUG_ON(!nr_pages);
  1525. BUG_ON(!pages);
  1526. page = pages[0];
  1527. BUG_ON(!page);
  1528. vi = page->mapping->host;
  1529. ni = NTFS_I(vi);
  1530. ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
  1531. "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
  1532. vi->i_ino, ni->type, page->index, nr_pages,
  1533. (long long)pos, bytes);
  1534. if (NInoNonResident(ni))
  1535. return ntfs_commit_pages_after_non_resident_write(pages,
  1536. nr_pages, pos, bytes);
  1537. BUG_ON(nr_pages > 1);
  1538. /*
  1539. * Attribute is resident, implying it is not compressed, encrypted, or
  1540. * sparse.
  1541. */
  1542. if (!NInoAttr(ni))
  1543. base_ni = ni;
  1544. else
  1545. base_ni = ni->ext.base_ntfs_ino;
  1546. BUG_ON(NInoNonResident(ni));
  1547. /* Map, pin, and lock the mft record. */
  1548. m = map_mft_record(base_ni);
  1549. if (IS_ERR(m)) {
  1550. err = PTR_ERR(m);
  1551. m = NULL;
  1552. ctx = NULL;
  1553. goto err_out;
  1554. }
  1555. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  1556. if (unlikely(!ctx)) {
  1557. err = -ENOMEM;
  1558. goto err_out;
  1559. }
  1560. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1561. CASE_SENSITIVE, 0, NULL, 0, ctx);
  1562. if (unlikely(err)) {
  1563. if (err == -ENOENT)
  1564. err = -EIO;
  1565. goto err_out;
  1566. }
  1567. a = ctx->attr;
  1568. BUG_ON(a->non_resident);
  1569. /* The total length of the attribute value. */
  1570. attr_len = le32_to_cpu(a->data.resident.value_length);
  1571. i_size = i_size_read(vi);
  1572. BUG_ON(attr_len != i_size);
  1573. BUG_ON(pos > attr_len);
  1574. end = pos + bytes;
  1575. BUG_ON(end > le32_to_cpu(a->length) -
  1576. le16_to_cpu(a->data.resident.value_offset));
  1577. kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
  1578. kaddr = kmap_atomic(page);
  1579. /* Copy the received data from the page to the mft record. */
  1580. memcpy(kattr + pos, kaddr + pos, bytes);
  1581. /* Update the attribute length if necessary. */
  1582. if (end > attr_len) {
  1583. attr_len = end;
  1584. a->data.resident.value_length = cpu_to_le32(attr_len);
  1585. }
  1586. /*
  1587. * If the page is not uptodate, bring the out of bounds area(s)
  1588. * uptodate by copying data from the mft record to the page.
  1589. */
  1590. if (!PageUptodate(page)) {
  1591. if (pos > 0)
  1592. memcpy(kaddr, kattr, pos);
  1593. if (end < attr_len)
  1594. memcpy(kaddr + end, kattr + end, attr_len - end);
  1595. /* Zero the region outside the end of the attribute value. */
  1596. memset(kaddr + attr_len, 0, PAGE_SIZE - attr_len);
  1597. flush_dcache_page(page);
  1598. SetPageUptodate(page);
  1599. }
  1600. kunmap_atomic(kaddr);
  1601. /* Update initialized_size/i_size if necessary. */
  1602. read_lock_irqsave(&ni->size_lock, flags);
  1603. initialized_size = ni->initialized_size;
  1604. BUG_ON(end > ni->allocated_size);
  1605. read_unlock_irqrestore(&ni->size_lock, flags);
  1606. BUG_ON(initialized_size != i_size);
  1607. if (end > initialized_size) {
  1608. write_lock_irqsave(&ni->size_lock, flags);
  1609. ni->initialized_size = end;
  1610. i_size_write(vi, end);
  1611. write_unlock_irqrestore(&ni->size_lock, flags);
  1612. }
  1613. /* Mark the mft record dirty, so it gets written back. */
  1614. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1615. mark_mft_record_dirty(ctx->ntfs_ino);
  1616. ntfs_attr_put_search_ctx(ctx);
  1617. unmap_mft_record(base_ni);
  1618. ntfs_debug("Done.");
  1619. return 0;
  1620. err_out:
  1621. if (err == -ENOMEM) {
  1622. ntfs_warning(vi->i_sb, "Error allocating memory required to "
  1623. "commit the write.");
  1624. if (PageUptodate(page)) {
  1625. ntfs_warning(vi->i_sb, "Page is uptodate, setting "
  1626. "dirty so the write will be retried "
  1627. "later on by the VM.");
  1628. /*
  1629. * Put the page on mapping->dirty_pages, but leave its
  1630. * buffers' dirty state as-is.
  1631. */
  1632. __set_page_dirty_nobuffers(page);
  1633. err = 0;
  1634. } else
  1635. ntfs_error(vi->i_sb, "Page is not uptodate. Written "
  1636. "data has been lost.");
  1637. } else {
  1638. ntfs_error(vi->i_sb, "Resident attribute commit write failed "
  1639. "with error %i.", err);
  1640. NVolSetErrors(ni->vol);
  1641. }
  1642. if (ctx)
  1643. ntfs_attr_put_search_ctx(ctx);
  1644. if (m)
  1645. unmap_mft_record(base_ni);
  1646. return err;
  1647. }
  1648. /*
  1649. * Copy as much as we can into the pages and return the number of bytes which
  1650. * were successfully copied. If a fault is encountered then clear the pages
  1651. * out to (ofs + bytes) and return the number of bytes which were copied.
  1652. */
  1653. static size_t ntfs_copy_from_user_iter(struct page **pages, unsigned nr_pages,
  1654. unsigned ofs, struct iov_iter *i, size_t bytes)
  1655. {
  1656. struct page **last_page = pages + nr_pages;
  1657. size_t total = 0;
  1658. unsigned len, copied;
  1659. do {
  1660. len = PAGE_SIZE - ofs;
  1661. if (len > bytes)
  1662. len = bytes;
  1663. copied = copy_page_from_iter_atomic(*pages, ofs, len, i);
  1664. total += copied;
  1665. bytes -= copied;
  1666. if (!bytes)
  1667. break;
  1668. if (copied < len)
  1669. goto err;
  1670. ofs = 0;
  1671. } while (++pages < last_page);
  1672. out:
  1673. return total;
  1674. err:
  1675. /* Zero the rest of the target like __copy_from_user(). */
  1676. len = PAGE_SIZE - copied;
  1677. do {
  1678. if (len > bytes)
  1679. len = bytes;
  1680. zero_user(*pages, copied, len);
  1681. bytes -= len;
  1682. copied = 0;
  1683. len = PAGE_SIZE;
  1684. } while (++pages < last_page);
  1685. goto out;
  1686. }
  1687. /**
  1688. * ntfs_perform_write - perform buffered write to a file
  1689. * @file: file to write to
  1690. * @i: iov_iter with data to write
  1691. * @pos: byte offset in file at which to begin writing to
  1692. */
  1693. static ssize_t ntfs_perform_write(struct file *file, struct iov_iter *i,
  1694. loff_t pos)
  1695. {
  1696. struct address_space *mapping = file->f_mapping;
  1697. struct inode *vi = mapping->host;
  1698. ntfs_inode *ni = NTFS_I(vi);
  1699. ntfs_volume *vol = ni->vol;
  1700. struct page *pages[NTFS_MAX_PAGES_PER_CLUSTER];
  1701. struct page *cached_page = NULL;
  1702. VCN last_vcn;
  1703. LCN lcn;
  1704. size_t bytes;
  1705. ssize_t status, written = 0;
  1706. unsigned nr_pages;
  1707. ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
  1708. "0x%llx, count 0x%lx.", vi->i_ino,
  1709. (unsigned)le32_to_cpu(ni->type),
  1710. (unsigned long long)pos,
  1711. (unsigned long)iov_iter_count(i));
  1712. /*
  1713. * If a previous ntfs_truncate() failed, repeat it and abort if it
  1714. * fails again.
  1715. */
  1716. if (unlikely(NInoTruncateFailed(ni))) {
  1717. int err;
  1718. inode_dio_wait(vi);
  1719. err = ntfs_truncate(vi);
  1720. if (err || NInoTruncateFailed(ni)) {
  1721. if (!err)
  1722. err = -EIO;
  1723. ntfs_error(vol->sb, "Cannot perform write to inode "
  1724. "0x%lx, attribute type 0x%x, because "
  1725. "ntfs_truncate() failed (error code "
  1726. "%i).", vi->i_ino,
  1727. (unsigned)le32_to_cpu(ni->type), err);
  1728. return err;
  1729. }
  1730. }
  1731. /*
  1732. * Determine the number of pages per cluster for non-resident
  1733. * attributes.
  1734. */
  1735. nr_pages = 1;
  1736. if (vol->cluster_size > PAGE_SIZE && NInoNonResident(ni))
  1737. nr_pages = vol->cluster_size >> PAGE_SHIFT;
  1738. last_vcn = -1;
  1739. do {
  1740. VCN vcn;
  1741. pgoff_t start_idx;
  1742. unsigned ofs, do_pages, u;
  1743. size_t copied;
  1744. start_idx = pos >> PAGE_SHIFT;
  1745. ofs = pos & ~PAGE_MASK;
  1746. bytes = PAGE_SIZE - ofs;
  1747. do_pages = 1;
  1748. if (nr_pages > 1) {
  1749. vcn = pos >> vol->cluster_size_bits;
  1750. if (vcn != last_vcn) {
  1751. last_vcn = vcn;
  1752. /*
  1753. * Get the lcn of the vcn the write is in. If
  1754. * it is a hole, need to lock down all pages in
  1755. * the cluster.
  1756. */
  1757. down_read(&ni->runlist.lock);
  1758. lcn = ntfs_attr_vcn_to_lcn_nolock(ni, pos >>
  1759. vol->cluster_size_bits, false);
  1760. up_read(&ni->runlist.lock);
  1761. if (unlikely(lcn < LCN_HOLE)) {
  1762. if (lcn == LCN_ENOMEM)
  1763. status = -ENOMEM;
  1764. else {
  1765. status = -EIO;
  1766. ntfs_error(vol->sb, "Cannot "
  1767. "perform write to "
  1768. "inode 0x%lx, "
  1769. "attribute type 0x%x, "
  1770. "because the attribute "
  1771. "is corrupt.",
  1772. vi->i_ino, (unsigned)
  1773. le32_to_cpu(ni->type));
  1774. }
  1775. break;
  1776. }
  1777. if (lcn == LCN_HOLE) {
  1778. start_idx = (pos & ~(s64)
  1779. vol->cluster_size_mask)
  1780. >> PAGE_SHIFT;
  1781. bytes = vol->cluster_size - (pos &
  1782. vol->cluster_size_mask);
  1783. do_pages = nr_pages;
  1784. }
  1785. }
  1786. }
  1787. if (bytes > iov_iter_count(i))
  1788. bytes = iov_iter_count(i);
  1789. again:
  1790. /*
  1791. * Bring in the user page(s) that we will copy from _first_.
  1792. * Otherwise there is a nasty deadlock on copying from the same
  1793. * page(s) as we are writing to, without it/them being marked
  1794. * up-to-date. Note, at present there is nothing to stop the
  1795. * pages being swapped out between us bringing them into memory
  1796. * and doing the actual copying.
  1797. */
  1798. if (unlikely(fault_in_iov_iter_readable(i, bytes))) {
  1799. status = -EFAULT;
  1800. break;
  1801. }
  1802. /* Get and lock @do_pages starting at index @start_idx. */
  1803. status = __ntfs_grab_cache_pages(mapping, start_idx, do_pages,
  1804. pages, &cached_page);
  1805. if (unlikely(status))
  1806. break;
  1807. /*
  1808. * For non-resident attributes, we need to fill any holes with
  1809. * actual clusters and ensure all bufferes are mapped. We also
  1810. * need to bring uptodate any buffers that are only partially
  1811. * being written to.
  1812. */
  1813. if (NInoNonResident(ni)) {
  1814. status = ntfs_prepare_pages_for_non_resident_write(
  1815. pages, do_pages, pos, bytes);
  1816. if (unlikely(status)) {
  1817. do {
  1818. unlock_page(pages[--do_pages]);
  1819. put_page(pages[do_pages]);
  1820. } while (do_pages);
  1821. break;
  1822. }
  1823. }
  1824. u = (pos >> PAGE_SHIFT) - pages[0]->index;
  1825. copied = ntfs_copy_from_user_iter(pages + u, do_pages - u, ofs,
  1826. i, bytes);
  1827. ntfs_flush_dcache_pages(pages + u, do_pages - u);
  1828. status = 0;
  1829. if (likely(copied == bytes)) {
  1830. status = ntfs_commit_pages_after_write(pages, do_pages,
  1831. pos, bytes);
  1832. }
  1833. do {
  1834. unlock_page(pages[--do_pages]);
  1835. put_page(pages[do_pages]);
  1836. } while (do_pages);
  1837. if (unlikely(status < 0)) {
  1838. iov_iter_revert(i, copied);
  1839. break;
  1840. }
  1841. cond_resched();
  1842. if (unlikely(copied < bytes)) {
  1843. iov_iter_revert(i, copied);
  1844. if (copied)
  1845. bytes = copied;
  1846. else if (bytes > PAGE_SIZE - ofs)
  1847. bytes = PAGE_SIZE - ofs;
  1848. goto again;
  1849. }
  1850. pos += copied;
  1851. written += copied;
  1852. balance_dirty_pages_ratelimited(mapping);
  1853. if (fatal_signal_pending(current)) {
  1854. status = -EINTR;
  1855. break;
  1856. }
  1857. } while (iov_iter_count(i));
  1858. if (cached_page)
  1859. put_page(cached_page);
  1860. ntfs_debug("Done. Returning %s (written 0x%lx, status %li).",
  1861. written ? "written" : "status", (unsigned long)written,
  1862. (long)status);
  1863. return written ? written : status;
  1864. }
  1865. /**
  1866. * ntfs_file_write_iter - simple wrapper for ntfs_file_write_iter_nolock()
  1867. * @iocb: IO state structure
  1868. * @from: iov_iter with data to write
  1869. *
  1870. * Basically the same as generic_file_write_iter() except that it ends up
  1871. * up calling ntfs_perform_write() instead of generic_perform_write() and that
  1872. * O_DIRECT is not implemented.
  1873. */
  1874. static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  1875. {
  1876. struct file *file = iocb->ki_filp;
  1877. struct inode *vi = file_inode(file);
  1878. ssize_t written = 0;
  1879. ssize_t err;
  1880. inode_lock(vi);
  1881. /* We can write back this queue in page reclaim. */
  1882. current->backing_dev_info = inode_to_bdi(vi);
  1883. err = ntfs_prepare_file_for_write(iocb, from);
  1884. if (iov_iter_count(from) && !err)
  1885. written = ntfs_perform_write(file, from, iocb->ki_pos);
  1886. current->backing_dev_info = NULL;
  1887. inode_unlock(vi);
  1888. iocb->ki_pos += written;
  1889. if (likely(written > 0))
  1890. written = generic_write_sync(iocb, written);
  1891. return written ? written : err;
  1892. }
  1893. /**
  1894. * ntfs_file_fsync - sync a file to disk
  1895. * @filp: file to be synced
  1896. * @datasync: if non-zero only flush user data and not metadata
  1897. *
  1898. * Data integrity sync of a file to disk. Used for fsync, fdatasync, and msync
  1899. * system calls. This function is inspired by fs/buffer.c::file_fsync().
  1900. *
  1901. * If @datasync is false, write the mft record and all associated extent mft
  1902. * records as well as the $DATA attribute and then sync the block device.
  1903. *
  1904. * If @datasync is true and the attribute is non-resident, we skip the writing
  1905. * of the mft record and all associated extent mft records (this might still
  1906. * happen due to the write_inode_now() call).
  1907. *
  1908. * Also, if @datasync is true, we do not wait on the inode to be written out
  1909. * but we always wait on the page cache pages to be written out.
  1910. *
  1911. * Locking: Caller must hold i_mutex on the inode.
  1912. *
  1913. * TODO: We should probably also write all attribute/index inodes associated
  1914. * with this inode but since we have no simple way of getting to them we ignore
  1915. * this problem for now.
  1916. */
  1917. static int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end,
  1918. int datasync)
  1919. {
  1920. struct inode *vi = filp->f_mapping->host;
  1921. int err, ret = 0;
  1922. ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
  1923. err = file_write_and_wait_range(filp, start, end);
  1924. if (err)
  1925. return err;
  1926. inode_lock(vi);
  1927. BUG_ON(S_ISDIR(vi->i_mode));
  1928. if (!datasync || !NInoNonResident(NTFS_I(vi)))
  1929. ret = __ntfs_write_inode(vi, 1);
  1930. write_inode_now(vi, !datasync);
  1931. /*
  1932. * NOTE: If we were to use mapping->private_list (see ext2 and
  1933. * fs/buffer.c) for dirty blocks then we could optimize the below to be
  1934. * sync_mapping_buffers(vi->i_mapping).
  1935. */
  1936. err = sync_blockdev(vi->i_sb->s_bdev);
  1937. if (unlikely(err && !ret))
  1938. ret = err;
  1939. if (likely(!ret))
  1940. ntfs_debug("Done.");
  1941. else
  1942. ntfs_warning(vi->i_sb, "Failed to f%ssync inode 0x%lx. Error "
  1943. "%u.", datasync ? "data" : "", vi->i_ino, -ret);
  1944. inode_unlock(vi);
  1945. return ret;
  1946. }
  1947. #endif /* NTFS_RW */
  1948. const struct file_operations ntfs_file_ops = {
  1949. .llseek = generic_file_llseek,
  1950. .read_iter = generic_file_read_iter,
  1951. #ifdef NTFS_RW
  1952. .write_iter = ntfs_file_write_iter,
  1953. .fsync = ntfs_file_fsync,
  1954. #endif /* NTFS_RW */
  1955. .mmap = generic_file_mmap,
  1956. .open = ntfs_file_open,
  1957. .splice_read = generic_file_splice_read,
  1958. };
  1959. const struct inode_operations ntfs_file_inode_ops = {
  1960. #ifdef NTFS_RW
  1961. .setattr = ntfs_setattr,
  1962. #endif /* NTFS_RW */
  1963. };
  1964. const struct file_operations ntfs_empty_file_ops = {};
  1965. const struct inode_operations ntfs_empty_inode_ops = {};