file.c 66 KB

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