file.c 66 KB

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