mft.c 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /**
  3. * mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
  4. *
  5. * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
  6. * Copyright (c) 2002 Richard Russon
  7. */
  8. #include <linux/buffer_head.h>
  9. #include <linux/slab.h>
  10. #include <linux/swap.h>
  11. #include <linux/bio.h>
  12. #include "attrib.h"
  13. #include "aops.h"
  14. #include "bitmap.h"
  15. #include "debug.h"
  16. #include "dir.h"
  17. #include "lcnalloc.h"
  18. #include "malloc.h"
  19. #include "mft.h"
  20. #include "ntfs.h"
  21. #define MAX_BHS (PAGE_SIZE / NTFS_BLOCK_SIZE)
  22. /**
  23. * map_mft_record_page - map the page in which a specific mft record resides
  24. * @ni: ntfs inode whose mft record page to map
  25. *
  26. * This maps the page in which the mft record of the ntfs inode @ni is situated
  27. * and returns a pointer to the mft record within the mapped page.
  28. *
  29. * Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
  30. * contains the negative error code returned.
  31. */
  32. static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
  33. {
  34. loff_t i_size;
  35. ntfs_volume *vol = ni->vol;
  36. struct inode *mft_vi = vol->mft_ino;
  37. struct page *page;
  38. unsigned long index, end_index;
  39. unsigned ofs;
  40. BUG_ON(ni->page);
  41. /*
  42. * The index into the page cache and the offset within the page cache
  43. * page of the wanted mft record. FIXME: We need to check for
  44. * overflowing the unsigned long, but I don't think we would ever get
  45. * here if the volume was that big...
  46. */
  47. index = (u64)ni->mft_no << vol->mft_record_size_bits >>
  48. PAGE_SHIFT;
  49. ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_MASK;
  50. i_size = i_size_read(mft_vi);
  51. /* The maximum valid index into the page cache for $MFT's data. */
  52. end_index = i_size >> PAGE_SHIFT;
  53. /* If the wanted index is out of bounds the mft record doesn't exist. */
  54. if (unlikely(index >= end_index)) {
  55. if (index > end_index || (i_size & ~PAGE_MASK) < ofs +
  56. vol->mft_record_size) {
  57. page = ERR_PTR(-ENOENT);
  58. ntfs_error(vol->sb, "Attempt to read mft record 0x%lx, "
  59. "which is beyond the end of the mft. "
  60. "This is probably a bug in the ntfs "
  61. "driver.", ni->mft_no);
  62. goto err_out;
  63. }
  64. }
  65. /* Read, map, and pin the page. */
  66. page = ntfs_map_page(mft_vi->i_mapping, index);
  67. if (!IS_ERR(page)) {
  68. /* Catch multi sector transfer fixup errors. */
  69. if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
  70. ofs)))) {
  71. ni->page = page;
  72. ni->page_ofs = ofs;
  73. return page_address(page) + ofs;
  74. }
  75. ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
  76. "Run chkdsk.", ni->mft_no);
  77. ntfs_unmap_page(page);
  78. page = ERR_PTR(-EIO);
  79. NVolSetErrors(vol);
  80. }
  81. err_out:
  82. ni->page = NULL;
  83. ni->page_ofs = 0;
  84. return (void*)page;
  85. }
  86. /**
  87. * map_mft_record - map, pin and lock an mft record
  88. * @ni: ntfs inode whose MFT record to map
  89. *
  90. * First, take the mrec_lock mutex. We might now be sleeping, while waiting
  91. * for the mutex if it was already locked by someone else.
  92. *
  93. * The page of the record is mapped using map_mft_record_page() before being
  94. * returned to the caller.
  95. *
  96. * This in turn uses ntfs_map_page() to get the page containing the wanted mft
  97. * record (it in turn calls read_cache_page() which reads it in from disk if
  98. * necessary, increments the use count on the page so that it cannot disappear
  99. * under us and returns a reference to the page cache page).
  100. *
  101. * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
  102. * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
  103. * and the post-read mst fixups on each mft record in the page have been
  104. * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
  105. * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
  106. * ntfs_map_page() waits for PG_locked to become clear and checks if
  107. * PG_uptodate is set and returns an error code if not. This provides
  108. * sufficient protection against races when reading/using the page.
  109. *
  110. * However there is the write mapping to think about. Doing the above described
  111. * checking here will be fine, because when initiating the write we will set
  112. * PG_locked and clear PG_uptodate making sure nobody is touching the page
  113. * contents. Doing the locking this way means that the commit to disk code in
  114. * the page cache code paths is automatically sufficiently locked with us as
  115. * we will not touch a page that has been locked or is not uptodate. The only
  116. * locking problem then is them locking the page while we are accessing it.
  117. *
  118. * So that code will end up having to own the mrec_lock of all mft
  119. * records/inodes present in the page before I/O can proceed. In that case we
  120. * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
  121. * accessing anything without owning the mrec_lock mutex. But we do need to
  122. * use them because of the read_cache_page() invocation and the code becomes so
  123. * much simpler this way that it is well worth it.
  124. *
  125. * The mft record is now ours and we return a pointer to it. You need to check
  126. * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
  127. * the error code.
  128. *
  129. * NOTE: Caller is responsible for setting the mft record dirty before calling
  130. * unmap_mft_record(). This is obviously only necessary if the caller really
  131. * modified the mft record...
  132. * Q: Do we want to recycle one of the VFS inode state bits instead?
  133. * A: No, the inode ones mean we want to change the mft record, not we want to
  134. * write it out.
  135. */
  136. MFT_RECORD *map_mft_record(ntfs_inode *ni)
  137. {
  138. MFT_RECORD *m;
  139. ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
  140. /* Make sure the ntfs inode doesn't go away. */
  141. atomic_inc(&ni->count);
  142. /* Serialize access to this mft record. */
  143. mutex_lock(&ni->mrec_lock);
  144. m = map_mft_record_page(ni);
  145. if (!IS_ERR(m))
  146. return m;
  147. mutex_unlock(&ni->mrec_lock);
  148. atomic_dec(&ni->count);
  149. ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
  150. return m;
  151. }
  152. /**
  153. * unmap_mft_record_page - unmap the page in which a specific mft record resides
  154. * @ni: ntfs inode whose mft record page to unmap
  155. *
  156. * This unmaps the page in which the mft record of the ntfs inode @ni is
  157. * situated and returns. This is a NOOP if highmem is not configured.
  158. *
  159. * The unmap happens via ntfs_unmap_page() which in turn decrements the use
  160. * count on the page thus releasing it from the pinned state.
  161. *
  162. * We do not actually unmap the page from memory of course, as that will be
  163. * done by the page cache code itself when memory pressure increases or
  164. * whatever.
  165. */
  166. static inline void unmap_mft_record_page(ntfs_inode *ni)
  167. {
  168. BUG_ON(!ni->page);
  169. // TODO: If dirty, blah...
  170. ntfs_unmap_page(ni->page);
  171. ni->page = NULL;
  172. ni->page_ofs = 0;
  173. return;
  174. }
  175. /**
  176. * unmap_mft_record - release a mapped mft record
  177. * @ni: ntfs inode whose MFT record to unmap
  178. *
  179. * We release the page mapping and the mrec_lock mutex which unmaps the mft
  180. * record and releases it for others to get hold of. We also release the ntfs
  181. * inode by decrementing the ntfs inode reference count.
  182. *
  183. * NOTE: If caller has modified the mft record, it is imperative to set the mft
  184. * record dirty BEFORE calling unmap_mft_record().
  185. */
  186. void unmap_mft_record(ntfs_inode *ni)
  187. {
  188. struct page *page = ni->page;
  189. BUG_ON(!page);
  190. ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
  191. unmap_mft_record_page(ni);
  192. mutex_unlock(&ni->mrec_lock);
  193. atomic_dec(&ni->count);
  194. /*
  195. * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
  196. * ntfs_clear_extent_inode() in the extent inode case, and to the
  197. * caller in the non-extent, yet pure ntfs inode case, to do the actual
  198. * tear down of all structures and freeing of all allocated memory.
  199. */
  200. return;
  201. }
  202. /**
  203. * map_extent_mft_record - load an extent inode and attach it to its base
  204. * @base_ni: base ntfs inode
  205. * @mref: mft reference of the extent inode to load
  206. * @ntfs_ino: on successful return, pointer to the ntfs_inode structure
  207. *
  208. * Load the extent mft record @mref and attach it to its base inode @base_ni.
  209. * Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
  210. * PTR_ERR(result) gives the negative error code.
  211. *
  212. * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
  213. * structure of the mapped extent inode.
  214. */
  215. MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
  216. ntfs_inode **ntfs_ino)
  217. {
  218. MFT_RECORD *m;
  219. ntfs_inode *ni = NULL;
  220. ntfs_inode **extent_nis = NULL;
  221. int i;
  222. unsigned long mft_no = MREF(mref);
  223. u16 seq_no = MSEQNO(mref);
  224. bool destroy_ni = false;
  225. ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
  226. mft_no, base_ni->mft_no);
  227. /* Make sure the base ntfs inode doesn't go away. */
  228. atomic_inc(&base_ni->count);
  229. /*
  230. * Check if this extent inode has already been added to the base inode,
  231. * in which case just return it. If not found, add it to the base
  232. * inode before returning it.
  233. */
  234. mutex_lock(&base_ni->extent_lock);
  235. if (base_ni->nr_extents > 0) {
  236. extent_nis = base_ni->ext.extent_ntfs_inos;
  237. for (i = 0; i < base_ni->nr_extents; i++) {
  238. if (mft_no != extent_nis[i]->mft_no)
  239. continue;
  240. ni = extent_nis[i];
  241. /* Make sure the ntfs inode doesn't go away. */
  242. atomic_inc(&ni->count);
  243. break;
  244. }
  245. }
  246. if (likely(ni != NULL)) {
  247. mutex_unlock(&base_ni->extent_lock);
  248. atomic_dec(&base_ni->count);
  249. /* We found the record; just have to map and return it. */
  250. m = map_mft_record(ni);
  251. /* map_mft_record() has incremented this on success. */
  252. atomic_dec(&ni->count);
  253. if (!IS_ERR(m)) {
  254. /* Verify the sequence number. */
  255. if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
  256. ntfs_debug("Done 1.");
  257. *ntfs_ino = ni;
  258. return m;
  259. }
  260. unmap_mft_record(ni);
  261. ntfs_error(base_ni->vol->sb, "Found stale extent mft "
  262. "reference! Corrupt filesystem. "
  263. "Run chkdsk.");
  264. return ERR_PTR(-EIO);
  265. }
  266. map_err_out:
  267. ntfs_error(base_ni->vol->sb, "Failed to map extent "
  268. "mft record, error code %ld.", -PTR_ERR(m));
  269. return m;
  270. }
  271. /* Record wasn't there. Get a new ntfs inode and initialize it. */
  272. ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
  273. if (unlikely(!ni)) {
  274. mutex_unlock(&base_ni->extent_lock);
  275. atomic_dec(&base_ni->count);
  276. return ERR_PTR(-ENOMEM);
  277. }
  278. ni->vol = base_ni->vol;
  279. ni->seq_no = seq_no;
  280. ni->nr_extents = -1;
  281. ni->ext.base_ntfs_ino = base_ni;
  282. /* Now map the record. */
  283. m = map_mft_record(ni);
  284. if (IS_ERR(m)) {
  285. mutex_unlock(&base_ni->extent_lock);
  286. atomic_dec(&base_ni->count);
  287. ntfs_clear_extent_inode(ni);
  288. goto map_err_out;
  289. }
  290. /* Verify the sequence number if it is present. */
  291. if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
  292. ntfs_error(base_ni->vol->sb, "Found stale extent mft "
  293. "reference! Corrupt filesystem. Run chkdsk.");
  294. destroy_ni = true;
  295. m = ERR_PTR(-EIO);
  296. goto unm_err_out;
  297. }
  298. /* Attach extent inode to base inode, reallocating memory if needed. */
  299. if (!(base_ni->nr_extents & 3)) {
  300. ntfs_inode **tmp;
  301. int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
  302. tmp = kmalloc(new_size, GFP_NOFS);
  303. if (unlikely(!tmp)) {
  304. ntfs_error(base_ni->vol->sb, "Failed to allocate "
  305. "internal buffer.");
  306. destroy_ni = true;
  307. m = ERR_PTR(-ENOMEM);
  308. goto unm_err_out;
  309. }
  310. if (base_ni->nr_extents) {
  311. BUG_ON(!base_ni->ext.extent_ntfs_inos);
  312. memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
  313. 4 * sizeof(ntfs_inode *));
  314. kfree(base_ni->ext.extent_ntfs_inos);
  315. }
  316. base_ni->ext.extent_ntfs_inos = tmp;
  317. }
  318. base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
  319. mutex_unlock(&base_ni->extent_lock);
  320. atomic_dec(&base_ni->count);
  321. ntfs_debug("Done 2.");
  322. *ntfs_ino = ni;
  323. return m;
  324. unm_err_out:
  325. unmap_mft_record(ni);
  326. mutex_unlock(&base_ni->extent_lock);
  327. atomic_dec(&base_ni->count);
  328. /*
  329. * If the extent inode was not attached to the base inode we need to
  330. * release it or we will leak memory.
  331. */
  332. if (destroy_ni)
  333. ntfs_clear_extent_inode(ni);
  334. return m;
  335. }
  336. #ifdef NTFS_RW
  337. /**
  338. * __mark_mft_record_dirty - set the mft record and the page containing it dirty
  339. * @ni: ntfs inode describing the mapped mft record
  340. *
  341. * Internal function. Users should call mark_mft_record_dirty() instead.
  342. *
  343. * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
  344. * as well as the page containing the mft record, dirty. Also, mark the base
  345. * vfs inode dirty. This ensures that any changes to the mft record are
  346. * written out to disk.
  347. *
  348. * NOTE: We only set I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
  349. * on the base vfs inode, because even though file data may have been modified,
  350. * it is dirty in the inode meta data rather than the data page cache of the
  351. * inode, and thus there are no data pages that need writing out. Therefore, a
  352. * full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
  353. * other hand, is not sufficient, because ->write_inode needs to be called even
  354. * in case of fdatasync. This needs to happen or the file data would not
  355. * necessarily hit the device synchronously, even though the vfs inode has the
  356. * O_SYNC flag set. Also, I_DIRTY_DATASYNC simply "feels" better than just
  357. * I_DIRTY_SYNC, since the file data has not actually hit the block device yet,
  358. * which is not what I_DIRTY_SYNC on its own would suggest.
  359. */
  360. void __mark_mft_record_dirty(ntfs_inode *ni)
  361. {
  362. ntfs_inode *base_ni;
  363. ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
  364. BUG_ON(NInoAttr(ni));
  365. mark_ntfs_record_dirty(ni->page, ni->page_ofs);
  366. /* Determine the base vfs inode and mark it dirty, too. */
  367. mutex_lock(&ni->extent_lock);
  368. if (likely(ni->nr_extents >= 0))
  369. base_ni = ni;
  370. else
  371. base_ni = ni->ext.base_ntfs_ino;
  372. mutex_unlock(&ni->extent_lock);
  373. __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_DATASYNC);
  374. }
  375. static const char *ntfs_please_email = "Please email "
  376. "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
  377. "this message. Thank you.";
  378. /**
  379. * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
  380. * @vol: ntfs volume on which the mft record to synchronize resides
  381. * @mft_no: mft record number of mft record to synchronize
  382. * @m: mapped, mst protected (extent) mft record to synchronize
  383. *
  384. * Write the mapped, mst protected (extent) mft record @m with mft record
  385. * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
  386. * bypassing the page cache and the $MFTMirr inode itself.
  387. *
  388. * This function is only for use at umount time when the mft mirror inode has
  389. * already been disposed off. We BUG() if we are called while the mft mirror
  390. * inode is still attached to the volume.
  391. *
  392. * On success return 0. On error return -errno.
  393. *
  394. * NOTE: This function is not implemented yet as I am not convinced it can
  395. * actually be triggered considering the sequence of commits we do in super.c::
  396. * ntfs_put_super(). But just in case we provide this place holder as the
  397. * alternative would be either to BUG() or to get a NULL pointer dereference
  398. * and Oops.
  399. */
  400. static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
  401. const unsigned long mft_no, MFT_RECORD *m)
  402. {
  403. BUG_ON(vol->mftmirr_ino);
  404. ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
  405. "implemented yet. %s", ntfs_please_email);
  406. return -EOPNOTSUPP;
  407. }
  408. /**
  409. * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
  410. * @vol: ntfs volume on which the mft record to synchronize resides
  411. * @mft_no: mft record number of mft record to synchronize
  412. * @m: mapped, mst protected (extent) mft record to synchronize
  413. * @sync: if true, wait for i/o completion
  414. *
  415. * Write the mapped, mst protected (extent) mft record @m with mft record
  416. * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
  417. *
  418. * On success return 0. On error return -errno and set the volume errors flag
  419. * in the ntfs volume @vol.
  420. *
  421. * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
  422. *
  423. * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
  424. * schedule i/o via ->writepage or do it via kntfsd or whatever.
  425. */
  426. int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
  427. MFT_RECORD *m, int sync)
  428. {
  429. struct page *page;
  430. unsigned int blocksize = vol->sb->s_blocksize;
  431. int max_bhs = vol->mft_record_size / blocksize;
  432. struct buffer_head *bhs[MAX_BHS];
  433. struct buffer_head *bh, *head;
  434. u8 *kmirr;
  435. runlist_element *rl;
  436. unsigned int block_start, block_end, m_start, m_end, page_ofs;
  437. int i_bhs, nr_bhs, err = 0;
  438. unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
  439. ntfs_debug("Entering for inode 0x%lx.", mft_no);
  440. BUG_ON(!max_bhs);
  441. if (WARN_ON(max_bhs > MAX_BHS))
  442. return -EINVAL;
  443. if (unlikely(!vol->mftmirr_ino)) {
  444. /* This could happen during umount... */
  445. err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
  446. if (likely(!err))
  447. return err;
  448. goto err_out;
  449. }
  450. /* Get the page containing the mirror copy of the mft record @m. */
  451. page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
  452. (PAGE_SHIFT - vol->mft_record_size_bits));
  453. if (IS_ERR(page)) {
  454. ntfs_error(vol->sb, "Failed to map mft mirror page.");
  455. err = PTR_ERR(page);
  456. goto err_out;
  457. }
  458. lock_page(page);
  459. BUG_ON(!PageUptodate(page));
  460. ClearPageUptodate(page);
  461. /* Offset of the mft mirror record inside the page. */
  462. page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_MASK;
  463. /* The address in the page of the mirror copy of the mft record @m. */
  464. kmirr = page_address(page) + page_ofs;
  465. /* Copy the mst protected mft record to the mirror. */
  466. memcpy(kmirr, m, vol->mft_record_size);
  467. /* Create uptodate buffers if not present. */
  468. if (unlikely(!page_has_buffers(page))) {
  469. struct buffer_head *tail;
  470. bh = head = alloc_page_buffers(page, blocksize, true);
  471. do {
  472. set_buffer_uptodate(bh);
  473. tail = bh;
  474. bh = bh->b_this_page;
  475. } while (bh);
  476. tail->b_this_page = head;
  477. attach_page_private(page, head);
  478. }
  479. bh = head = page_buffers(page);
  480. BUG_ON(!bh);
  481. rl = NULL;
  482. nr_bhs = 0;
  483. block_start = 0;
  484. m_start = kmirr - (u8*)page_address(page);
  485. m_end = m_start + vol->mft_record_size;
  486. do {
  487. block_end = block_start + blocksize;
  488. /* If the buffer is outside the mft record, skip it. */
  489. if (block_end <= m_start)
  490. continue;
  491. if (unlikely(block_start >= m_end))
  492. break;
  493. /* Need to map the buffer if it is not mapped already. */
  494. if (unlikely(!buffer_mapped(bh))) {
  495. VCN vcn;
  496. LCN lcn;
  497. unsigned int vcn_ofs;
  498. bh->b_bdev = vol->sb->s_bdev;
  499. /* Obtain the vcn and offset of the current block. */
  500. vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
  501. (block_start - m_start);
  502. vcn_ofs = vcn & vol->cluster_size_mask;
  503. vcn >>= vol->cluster_size_bits;
  504. if (!rl) {
  505. down_read(&NTFS_I(vol->mftmirr_ino)->
  506. runlist.lock);
  507. rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
  508. /*
  509. * $MFTMirr always has the whole of its runlist
  510. * in memory.
  511. */
  512. BUG_ON(!rl);
  513. }
  514. /* Seek to element containing target vcn. */
  515. while (rl->length && rl[1].vcn <= vcn)
  516. rl++;
  517. lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
  518. /* For $MFTMirr, only lcn >= 0 is a successful remap. */
  519. if (likely(lcn >= 0)) {
  520. /* Setup buffer head to correct block. */
  521. bh->b_blocknr = ((lcn <<
  522. vol->cluster_size_bits) +
  523. vcn_ofs) >> blocksize_bits;
  524. set_buffer_mapped(bh);
  525. } else {
  526. bh->b_blocknr = -1;
  527. ntfs_error(vol->sb, "Cannot write mft mirror "
  528. "record 0x%lx because its "
  529. "location on disk could not "
  530. "be determined (error code "
  531. "%lli).", mft_no,
  532. (long long)lcn);
  533. err = -EIO;
  534. }
  535. }
  536. BUG_ON(!buffer_uptodate(bh));
  537. BUG_ON(!nr_bhs && (m_start != block_start));
  538. BUG_ON(nr_bhs >= max_bhs);
  539. bhs[nr_bhs++] = bh;
  540. BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
  541. } while (block_start = block_end, (bh = bh->b_this_page) != head);
  542. if (unlikely(rl))
  543. up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
  544. if (likely(!err)) {
  545. /* Lock buffers and start synchronous write i/o on them. */
  546. for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
  547. struct buffer_head *tbh = bhs[i_bhs];
  548. if (!trylock_buffer(tbh))
  549. BUG();
  550. BUG_ON(!buffer_uptodate(tbh));
  551. clear_buffer_dirty(tbh);
  552. get_bh(tbh);
  553. tbh->b_end_io = end_buffer_write_sync;
  554. submit_bh(REQ_OP_WRITE, 0, tbh);
  555. }
  556. /* Wait on i/o completion of buffers. */
  557. for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
  558. struct buffer_head *tbh = bhs[i_bhs];
  559. wait_on_buffer(tbh);
  560. if (unlikely(!buffer_uptodate(tbh))) {
  561. err = -EIO;
  562. /*
  563. * Set the buffer uptodate so the page and
  564. * buffer states do not become out of sync.
  565. */
  566. set_buffer_uptodate(tbh);
  567. }
  568. }
  569. } else /* if (unlikely(err)) */ {
  570. /* Clean the buffers. */
  571. for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
  572. clear_buffer_dirty(bhs[i_bhs]);
  573. }
  574. /* Current state: all buffers are clean, unlocked, and uptodate. */
  575. /* Remove the mst protection fixups again. */
  576. post_write_mst_fixup((NTFS_RECORD*)kmirr);
  577. flush_dcache_page(page);
  578. SetPageUptodate(page);
  579. unlock_page(page);
  580. ntfs_unmap_page(page);
  581. if (likely(!err)) {
  582. ntfs_debug("Done.");
  583. } else {
  584. ntfs_error(vol->sb, "I/O error while writing mft mirror "
  585. "record 0x%lx!", mft_no);
  586. err_out:
  587. ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
  588. "code %i). Volume will be left marked dirty "
  589. "on umount. Run ntfsfix on the partition "
  590. "after umounting to correct this.", -err);
  591. NVolSetErrors(vol);
  592. }
  593. return err;
  594. }
  595. /**
  596. * write_mft_record_nolock - write out a mapped (extent) mft record
  597. * @ni: ntfs inode describing the mapped (extent) mft record
  598. * @m: mapped (extent) mft record to write
  599. * @sync: if true, wait for i/o completion
  600. *
  601. * Write the mapped (extent) mft record @m described by the (regular or extent)
  602. * ntfs inode @ni to backing store. If the mft record @m has a counterpart in
  603. * the mft mirror, that is also updated.
  604. *
  605. * We only write the mft record if the ntfs inode @ni is dirty and the first
  606. * buffer belonging to its mft record is dirty, too. We ignore the dirty state
  607. * of subsequent buffers because we could have raced with
  608. * fs/ntfs/aops.c::mark_ntfs_record_dirty().
  609. *
  610. * On success, clean the mft record and return 0. On error, leave the mft
  611. * record dirty and return -errno.
  612. *
  613. * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
  614. * However, if the mft record has a counterpart in the mft mirror and @sync is
  615. * true, we write the mft record, wait for i/o completion, and only then write
  616. * the mft mirror copy. This ensures that if the system crashes either the mft
  617. * or the mft mirror will contain a self-consistent mft record @m. If @sync is
  618. * false on the other hand, we start i/o on both and then wait for completion
  619. * on them. This provides a speedup but no longer guarantees that you will end
  620. * up with a self-consistent mft record in the case of a crash but if you asked
  621. * for asynchronous writing you probably do not care about that anyway.
  622. *
  623. * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
  624. * schedule i/o via ->writepage or do it via kntfsd or whatever.
  625. */
  626. int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
  627. {
  628. ntfs_volume *vol = ni->vol;
  629. struct page *page = ni->page;
  630. unsigned int blocksize = vol->sb->s_blocksize;
  631. unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
  632. int max_bhs = vol->mft_record_size / blocksize;
  633. struct buffer_head *bhs[MAX_BHS];
  634. struct buffer_head *bh, *head;
  635. runlist_element *rl;
  636. unsigned int block_start, block_end, m_start, m_end;
  637. int i_bhs, nr_bhs, err = 0;
  638. ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
  639. BUG_ON(NInoAttr(ni));
  640. BUG_ON(!max_bhs);
  641. BUG_ON(!PageLocked(page));
  642. if (WARN_ON(max_bhs > MAX_BHS)) {
  643. err = -EINVAL;
  644. goto err_out;
  645. }
  646. /*
  647. * If the ntfs_inode is clean no need to do anything. If it is dirty,
  648. * mark it as clean now so that it can be redirtied later on if needed.
  649. * There is no danger of races since the caller is holding the locks
  650. * for the mft record @m and the page it is in.
  651. */
  652. if (!NInoTestClearDirty(ni))
  653. goto done;
  654. bh = head = page_buffers(page);
  655. BUG_ON(!bh);
  656. rl = NULL;
  657. nr_bhs = 0;
  658. block_start = 0;
  659. m_start = ni->page_ofs;
  660. m_end = m_start + vol->mft_record_size;
  661. do {
  662. block_end = block_start + blocksize;
  663. /* If the buffer is outside the mft record, skip it. */
  664. if (block_end <= m_start)
  665. continue;
  666. if (unlikely(block_start >= m_end))
  667. break;
  668. /*
  669. * If this block is not the first one in the record, we ignore
  670. * the buffer's dirty state because we could have raced with a
  671. * parallel mark_ntfs_record_dirty().
  672. */
  673. if (block_start == m_start) {
  674. /* This block is the first one in the record. */
  675. if (!buffer_dirty(bh)) {
  676. BUG_ON(nr_bhs);
  677. /* Clean records are not written out. */
  678. break;
  679. }
  680. }
  681. /* Need to map the buffer if it is not mapped already. */
  682. if (unlikely(!buffer_mapped(bh))) {
  683. VCN vcn;
  684. LCN lcn;
  685. unsigned int vcn_ofs;
  686. bh->b_bdev = vol->sb->s_bdev;
  687. /* Obtain the vcn and offset of the current block. */
  688. vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
  689. (block_start - m_start);
  690. vcn_ofs = vcn & vol->cluster_size_mask;
  691. vcn >>= vol->cluster_size_bits;
  692. if (!rl) {
  693. down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
  694. rl = NTFS_I(vol->mft_ino)->runlist.rl;
  695. BUG_ON(!rl);
  696. }
  697. /* Seek to element containing target vcn. */
  698. while (rl->length && rl[1].vcn <= vcn)
  699. rl++;
  700. lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
  701. /* For $MFT, only lcn >= 0 is a successful remap. */
  702. if (likely(lcn >= 0)) {
  703. /* Setup buffer head to correct block. */
  704. bh->b_blocknr = ((lcn <<
  705. vol->cluster_size_bits) +
  706. vcn_ofs) >> blocksize_bits;
  707. set_buffer_mapped(bh);
  708. } else {
  709. bh->b_blocknr = -1;
  710. ntfs_error(vol->sb, "Cannot write mft record "
  711. "0x%lx because its location "
  712. "on disk could not be "
  713. "determined (error code %lli).",
  714. ni->mft_no, (long long)lcn);
  715. err = -EIO;
  716. }
  717. }
  718. BUG_ON(!buffer_uptodate(bh));
  719. BUG_ON(!nr_bhs && (m_start != block_start));
  720. BUG_ON(nr_bhs >= max_bhs);
  721. bhs[nr_bhs++] = bh;
  722. BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
  723. } while (block_start = block_end, (bh = bh->b_this_page) != head);
  724. if (unlikely(rl))
  725. up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
  726. if (!nr_bhs)
  727. goto done;
  728. if (unlikely(err))
  729. goto cleanup_out;
  730. /* Apply the mst protection fixups. */
  731. err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
  732. if (err) {
  733. ntfs_error(vol->sb, "Failed to apply mst fixups!");
  734. goto cleanup_out;
  735. }
  736. flush_dcache_mft_record_page(ni);
  737. /* Lock buffers and start synchronous write i/o on them. */
  738. for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
  739. struct buffer_head *tbh = bhs[i_bhs];
  740. if (!trylock_buffer(tbh))
  741. BUG();
  742. BUG_ON(!buffer_uptodate(tbh));
  743. clear_buffer_dirty(tbh);
  744. get_bh(tbh);
  745. tbh->b_end_io = end_buffer_write_sync;
  746. submit_bh(REQ_OP_WRITE, 0, tbh);
  747. }
  748. /* Synchronize the mft mirror now if not @sync. */
  749. if (!sync && ni->mft_no < vol->mftmirr_size)
  750. ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
  751. /* Wait on i/o completion of buffers. */
  752. for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
  753. struct buffer_head *tbh = bhs[i_bhs];
  754. wait_on_buffer(tbh);
  755. if (unlikely(!buffer_uptodate(tbh))) {
  756. err = -EIO;
  757. /*
  758. * Set the buffer uptodate so the page and buffer
  759. * states do not become out of sync.
  760. */
  761. if (PageUptodate(page))
  762. set_buffer_uptodate(tbh);
  763. }
  764. }
  765. /* If @sync, now synchronize the mft mirror. */
  766. if (sync && ni->mft_no < vol->mftmirr_size)
  767. ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
  768. /* Remove the mst protection fixups again. */
  769. post_write_mst_fixup((NTFS_RECORD*)m);
  770. flush_dcache_mft_record_page(ni);
  771. if (unlikely(err)) {
  772. /* I/O error during writing. This is really bad! */
  773. ntfs_error(vol->sb, "I/O error while writing mft record "
  774. "0x%lx! Marking base inode as bad. You "
  775. "should unmount the volume and run chkdsk.",
  776. ni->mft_no);
  777. goto err_out;
  778. }
  779. done:
  780. ntfs_debug("Done.");
  781. return 0;
  782. cleanup_out:
  783. /* Clean the buffers. */
  784. for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
  785. clear_buffer_dirty(bhs[i_bhs]);
  786. err_out:
  787. /*
  788. * Current state: all buffers are clean, unlocked, and uptodate.
  789. * The caller should mark the base inode as bad so that no more i/o
  790. * happens. ->clear_inode() will still be invoked so all extent inodes
  791. * and other allocated memory will be freed.
  792. */
  793. if (err == -ENOMEM) {
  794. ntfs_error(vol->sb, "Not enough memory to write mft record. "
  795. "Redirtying so the write is retried later.");
  796. mark_mft_record_dirty(ni);
  797. err = 0;
  798. } else
  799. NVolSetErrors(vol);
  800. return err;
  801. }
  802. /**
  803. * ntfs_may_write_mft_record - check if an mft record may be written out
  804. * @vol: [IN] ntfs volume on which the mft record to check resides
  805. * @mft_no: [IN] mft record number of the mft record to check
  806. * @m: [IN] mapped mft record to check
  807. * @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
  808. *
  809. * Check if the mapped (base or extent) mft record @m with mft record number
  810. * @mft_no belonging to the ntfs volume @vol may be written out. If necessary
  811. * and possible the ntfs inode of the mft record is locked and the base vfs
  812. * inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
  813. * caller is responsible for unlocking the ntfs inode and unpinning the base
  814. * vfs inode.
  815. *
  816. * Return 'true' if the mft record may be written out and 'false' if not.
  817. *
  818. * The caller has locked the page and cleared the uptodate flag on it which
  819. * means that we can safely write out any dirty mft records that do not have
  820. * their inodes in icache as determined by ilookup5() as anyone
  821. * opening/creating such an inode would block when attempting to map the mft
  822. * record in read_cache_page() until we are finished with the write out.
  823. *
  824. * Here is a description of the tests we perform:
  825. *
  826. * If the inode is found in icache we know the mft record must be a base mft
  827. * record. If it is dirty, we do not write it and return 'false' as the vfs
  828. * inode write paths will result in the access times being updated which would
  829. * cause the base mft record to be redirtied and written out again. (We know
  830. * the access time update will modify the base mft record because Windows
  831. * chkdsk complains if the standard information attribute is not in the base
  832. * mft record.)
  833. *
  834. * If the inode is in icache and not dirty, we attempt to lock the mft record
  835. * and if we find the lock was already taken, it is not safe to write the mft
  836. * record and we return 'false'.
  837. *
  838. * If we manage to obtain the lock we have exclusive access to the mft record,
  839. * which also allows us safe writeout of the mft record. We then set
  840. * @locked_ni to the locked ntfs inode and return 'true'.
  841. *
  842. * Note we cannot just lock the mft record and sleep while waiting for the lock
  843. * because this would deadlock due to lock reversal (normally the mft record is
  844. * locked before the page is locked but we already have the page locked here
  845. * when we try to lock the mft record).
  846. *
  847. * If the inode is not in icache we need to perform further checks.
  848. *
  849. * If the mft record is not a FILE record or it is a base mft record, we can
  850. * safely write it and return 'true'.
  851. *
  852. * We now know the mft record is an extent mft record. We check if the inode
  853. * corresponding to its base mft record is in icache and obtain a reference to
  854. * it if it is. If it is not, we can safely write it and return 'true'.
  855. *
  856. * We now have the base inode for the extent mft record. We check if it has an
  857. * ntfs inode for the extent mft record attached and if not it is safe to write
  858. * the extent mft record and we return 'true'.
  859. *
  860. * The ntfs inode for the extent mft record is attached to the base inode so we
  861. * attempt to lock the extent mft record and if we find the lock was already
  862. * taken, it is not safe to write the extent mft record and we return 'false'.
  863. *
  864. * If we manage to obtain the lock we have exclusive access to the extent mft
  865. * record, which also allows us safe writeout of the extent mft record. We
  866. * set the ntfs inode of the extent mft record clean and then set @locked_ni to
  867. * the now locked ntfs inode and return 'true'.
  868. *
  869. * Note, the reason for actually writing dirty mft records here and not just
  870. * relying on the vfs inode dirty code paths is that we can have mft records
  871. * modified without them ever having actual inodes in memory. Also we can have
  872. * dirty mft records with clean ntfs inodes in memory. None of the described
  873. * cases would result in the dirty mft records being written out if we only
  874. * relied on the vfs inode dirty code paths. And these cases can really occur
  875. * during allocation of new mft records and in particular when the
  876. * initialized_size of the $MFT/$DATA attribute is extended and the new space
  877. * is initialized using ntfs_mft_record_format(). The clean inode can then
  878. * appear if the mft record is reused for a new inode before it got written
  879. * out.
  880. */
  881. bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
  882. const MFT_RECORD *m, ntfs_inode **locked_ni)
  883. {
  884. struct super_block *sb = vol->sb;
  885. struct inode *mft_vi = vol->mft_ino;
  886. struct inode *vi;
  887. ntfs_inode *ni, *eni, **extent_nis;
  888. int i;
  889. ntfs_attr na;
  890. ntfs_debug("Entering for inode 0x%lx.", mft_no);
  891. /*
  892. * Normally we do not return a locked inode so set @locked_ni to NULL.
  893. */
  894. BUG_ON(!locked_ni);
  895. *locked_ni = NULL;
  896. /*
  897. * Check if the inode corresponding to this mft record is in the VFS
  898. * inode cache and obtain a reference to it if it is.
  899. */
  900. ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
  901. na.mft_no = mft_no;
  902. na.name = NULL;
  903. na.name_len = 0;
  904. na.type = AT_UNUSED;
  905. /*
  906. * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
  907. * we get here for it rather often.
  908. */
  909. if (!mft_no) {
  910. /* Balance the below iput(). */
  911. vi = igrab(mft_vi);
  912. BUG_ON(vi != mft_vi);
  913. } else {
  914. /*
  915. * Have to use ilookup5_nowait() since ilookup5() waits for the
  916. * inode lock which causes ntfs to deadlock when a concurrent
  917. * inode write via the inode dirty code paths and the page
  918. * dirty code path of the inode dirty code path when writing
  919. * $MFT occurs.
  920. */
  921. vi = ilookup5_nowait(sb, mft_no, ntfs_test_inode, &na);
  922. }
  923. if (vi) {
  924. ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
  925. /* The inode is in icache. */
  926. ni = NTFS_I(vi);
  927. /* Take a reference to the ntfs inode. */
  928. atomic_inc(&ni->count);
  929. /* If the inode is dirty, do not write this record. */
  930. if (NInoDirty(ni)) {
  931. ntfs_debug("Inode 0x%lx is dirty, do not write it.",
  932. mft_no);
  933. atomic_dec(&ni->count);
  934. iput(vi);
  935. return false;
  936. }
  937. ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
  938. /* The inode is not dirty, try to take the mft record lock. */
  939. if (unlikely(!mutex_trylock(&ni->mrec_lock))) {
  940. ntfs_debug("Mft record 0x%lx is already locked, do "
  941. "not write it.", mft_no);
  942. atomic_dec(&ni->count);
  943. iput(vi);
  944. return false;
  945. }
  946. ntfs_debug("Managed to lock mft record 0x%lx, write it.",
  947. mft_no);
  948. /*
  949. * The write has to occur while we hold the mft record lock so
  950. * return the locked ntfs inode.
  951. */
  952. *locked_ni = ni;
  953. return true;
  954. }
  955. ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
  956. /* The inode is not in icache. */
  957. /* Write the record if it is not a mft record (type "FILE"). */
  958. if (!ntfs_is_mft_record(m->magic)) {
  959. ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
  960. mft_no);
  961. return true;
  962. }
  963. /* Write the mft record if it is a base inode. */
  964. if (!m->base_mft_record) {
  965. ntfs_debug("Mft record 0x%lx is a base record, write it.",
  966. mft_no);
  967. return true;
  968. }
  969. /*
  970. * This is an extent mft record. Check if the inode corresponding to
  971. * its base mft record is in icache and obtain a reference to it if it
  972. * is.
  973. */
  974. na.mft_no = MREF_LE(m->base_mft_record);
  975. ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
  976. "inode 0x%lx in icache.", mft_no, na.mft_no);
  977. if (!na.mft_no) {
  978. /* Balance the below iput(). */
  979. vi = igrab(mft_vi);
  980. BUG_ON(vi != mft_vi);
  981. } else
  982. vi = ilookup5_nowait(sb, na.mft_no, ntfs_test_inode,
  983. &na);
  984. if (!vi) {
  985. /*
  986. * The base inode is not in icache, write this extent mft
  987. * record.
  988. */
  989. ntfs_debug("Base inode 0x%lx is not in icache, write the "
  990. "extent record.", na.mft_no);
  991. return true;
  992. }
  993. ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
  994. /*
  995. * The base inode is in icache. Check if it has the extent inode
  996. * corresponding to this extent mft record attached.
  997. */
  998. ni = NTFS_I(vi);
  999. mutex_lock(&ni->extent_lock);
  1000. if (ni->nr_extents <= 0) {
  1001. /*
  1002. * The base inode has no attached extent inodes, write this
  1003. * extent mft record.
  1004. */
  1005. mutex_unlock(&ni->extent_lock);
  1006. iput(vi);
  1007. ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
  1008. "write the extent record.", na.mft_no);
  1009. return true;
  1010. }
  1011. /* Iterate over the attached extent inodes. */
  1012. extent_nis = ni->ext.extent_ntfs_inos;
  1013. for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
  1014. if (mft_no == extent_nis[i]->mft_no) {
  1015. /*
  1016. * Found the extent inode corresponding to this extent
  1017. * mft record.
  1018. */
  1019. eni = extent_nis[i];
  1020. break;
  1021. }
  1022. }
  1023. /*
  1024. * If the extent inode was not attached to the base inode, write this
  1025. * extent mft record.
  1026. */
  1027. if (!eni) {
  1028. mutex_unlock(&ni->extent_lock);
  1029. iput(vi);
  1030. ntfs_debug("Extent inode 0x%lx is not attached to its base "
  1031. "inode 0x%lx, write the extent record.",
  1032. mft_no, na.mft_no);
  1033. return true;
  1034. }
  1035. ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
  1036. mft_no, na.mft_no);
  1037. /* Take a reference to the extent ntfs inode. */
  1038. atomic_inc(&eni->count);
  1039. mutex_unlock(&ni->extent_lock);
  1040. /*
  1041. * Found the extent inode coresponding to this extent mft record.
  1042. * Try to take the mft record lock.
  1043. */
  1044. if (unlikely(!mutex_trylock(&eni->mrec_lock))) {
  1045. atomic_dec(&eni->count);
  1046. iput(vi);
  1047. ntfs_debug("Extent mft record 0x%lx is already locked, do "
  1048. "not write it.", mft_no);
  1049. return false;
  1050. }
  1051. ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
  1052. mft_no);
  1053. if (NInoTestClearDirty(eni))
  1054. ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
  1055. mft_no);
  1056. /*
  1057. * The write has to occur while we hold the mft record lock so return
  1058. * the locked extent ntfs inode.
  1059. */
  1060. *locked_ni = eni;
  1061. return true;
  1062. }
  1063. static const char *es = " Leaving inconsistent metadata. Unmount and run "
  1064. "chkdsk.";
  1065. /**
  1066. * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
  1067. * @vol: volume on which to search for a free mft record
  1068. * @base_ni: open base inode if allocating an extent mft record or NULL
  1069. *
  1070. * Search for a free mft record in the mft bitmap attribute on the ntfs volume
  1071. * @vol.
  1072. *
  1073. * If @base_ni is NULL start the search at the default allocator position.
  1074. *
  1075. * If @base_ni is not NULL start the search at the mft record after the base
  1076. * mft record @base_ni.
  1077. *
  1078. * Return the free mft record on success and -errno on error. An error code of
  1079. * -ENOSPC means that there are no free mft records in the currently
  1080. * initialized mft bitmap.
  1081. *
  1082. * Locking: Caller must hold vol->mftbmp_lock for writing.
  1083. */
  1084. static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
  1085. ntfs_inode *base_ni)
  1086. {
  1087. s64 pass_end, ll, data_pos, pass_start, ofs, bit;
  1088. unsigned long flags;
  1089. struct address_space *mftbmp_mapping;
  1090. u8 *buf, *byte;
  1091. struct page *page;
  1092. unsigned int page_ofs, size;
  1093. u8 pass, b;
  1094. ntfs_debug("Searching for free mft record in the currently "
  1095. "initialized mft bitmap.");
  1096. mftbmp_mapping = vol->mftbmp_ino->i_mapping;
  1097. /*
  1098. * Set the end of the pass making sure we do not overflow the mft
  1099. * bitmap.
  1100. */
  1101. read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
  1102. pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
  1103. vol->mft_record_size_bits;
  1104. read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
  1105. read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
  1106. ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
  1107. read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
  1108. if (pass_end > ll)
  1109. pass_end = ll;
  1110. pass = 1;
  1111. if (!base_ni)
  1112. data_pos = vol->mft_data_pos;
  1113. else
  1114. data_pos = base_ni->mft_no + 1;
  1115. if (data_pos < 24)
  1116. data_pos = 24;
  1117. if (data_pos >= pass_end) {
  1118. data_pos = 24;
  1119. pass = 2;
  1120. /* This happens on a freshly formatted volume. */
  1121. if (data_pos >= pass_end)
  1122. return -ENOSPC;
  1123. }
  1124. pass_start = data_pos;
  1125. ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
  1126. "pass_end 0x%llx, data_pos 0x%llx.", pass,
  1127. (long long)pass_start, (long long)pass_end,
  1128. (long long)data_pos);
  1129. /* Loop until a free mft record is found. */
  1130. for (; pass <= 2;) {
  1131. /* Cap size to pass_end. */
  1132. ofs = data_pos >> 3;
  1133. page_ofs = ofs & ~PAGE_MASK;
  1134. size = PAGE_SIZE - page_ofs;
  1135. ll = ((pass_end + 7) >> 3) - ofs;
  1136. if (size > ll)
  1137. size = ll;
  1138. size <<= 3;
  1139. /*
  1140. * If we are still within the active pass, search the next page
  1141. * for a zero bit.
  1142. */
  1143. if (size) {
  1144. page = ntfs_map_page(mftbmp_mapping,
  1145. ofs >> PAGE_SHIFT);
  1146. if (IS_ERR(page)) {
  1147. ntfs_error(vol->sb, "Failed to read mft "
  1148. "bitmap, aborting.");
  1149. return PTR_ERR(page);
  1150. }
  1151. buf = (u8*)page_address(page) + page_ofs;
  1152. bit = data_pos & 7;
  1153. data_pos &= ~7ull;
  1154. ntfs_debug("Before inner for loop: size 0x%x, "
  1155. "data_pos 0x%llx, bit 0x%llx", size,
  1156. (long long)data_pos, (long long)bit);
  1157. for (; bit < size && data_pos + bit < pass_end;
  1158. bit &= ~7ull, bit += 8) {
  1159. byte = buf + (bit >> 3);
  1160. if (*byte == 0xff)
  1161. continue;
  1162. b = ffz((unsigned long)*byte);
  1163. if (b < 8 && b >= (bit & 7)) {
  1164. ll = data_pos + (bit & ~7ull) + b;
  1165. if (unlikely(ll > (1ll << 32))) {
  1166. ntfs_unmap_page(page);
  1167. return -ENOSPC;
  1168. }
  1169. *byte |= 1 << b;
  1170. flush_dcache_page(page);
  1171. set_page_dirty(page);
  1172. ntfs_unmap_page(page);
  1173. ntfs_debug("Done. (Found and "
  1174. "allocated mft record "
  1175. "0x%llx.)",
  1176. (long long)ll);
  1177. return ll;
  1178. }
  1179. }
  1180. ntfs_debug("After inner for loop: size 0x%x, "
  1181. "data_pos 0x%llx, bit 0x%llx", size,
  1182. (long long)data_pos, (long long)bit);
  1183. data_pos += size;
  1184. ntfs_unmap_page(page);
  1185. /*
  1186. * If the end of the pass has not been reached yet,
  1187. * continue searching the mft bitmap for a zero bit.
  1188. */
  1189. if (data_pos < pass_end)
  1190. continue;
  1191. }
  1192. /* Do the next pass. */
  1193. if (++pass == 2) {
  1194. /*
  1195. * Starting the second pass, in which we scan the first
  1196. * part of the zone which we omitted earlier.
  1197. */
  1198. pass_end = pass_start;
  1199. data_pos = pass_start = 24;
  1200. ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
  1201. "0x%llx.", pass, (long long)pass_start,
  1202. (long long)pass_end);
  1203. if (data_pos >= pass_end)
  1204. break;
  1205. }
  1206. }
  1207. /* No free mft records in currently initialized mft bitmap. */
  1208. ntfs_debug("Done. (No free mft records left in currently initialized "
  1209. "mft bitmap.)");
  1210. return -ENOSPC;
  1211. }
  1212. /**
  1213. * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
  1214. * @vol: volume on which to extend the mft bitmap attribute
  1215. *
  1216. * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
  1217. *
  1218. * Note: Only changes allocated_size, i.e. does not touch initialized_size or
  1219. * data_size.
  1220. *
  1221. * Return 0 on success and -errno on error.
  1222. *
  1223. * Locking: - Caller must hold vol->mftbmp_lock for writing.
  1224. * - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
  1225. * writing and releases it before returning.
  1226. * - This function takes vol->lcnbmp_lock for writing and releases it
  1227. * before returning.
  1228. */
  1229. static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
  1230. {
  1231. LCN lcn;
  1232. s64 ll;
  1233. unsigned long flags;
  1234. struct page *page;
  1235. ntfs_inode *mft_ni, *mftbmp_ni;
  1236. runlist_element *rl, *rl2 = NULL;
  1237. ntfs_attr_search_ctx *ctx = NULL;
  1238. MFT_RECORD *mrec;
  1239. ATTR_RECORD *a = NULL;
  1240. int ret, mp_size;
  1241. u32 old_alen = 0;
  1242. u8 *b, tb;
  1243. struct {
  1244. u8 added_cluster:1;
  1245. u8 added_run:1;
  1246. u8 mp_rebuilt:1;
  1247. } status = { 0, 0, 0 };
  1248. ntfs_debug("Extending mft bitmap allocation.");
  1249. mft_ni = NTFS_I(vol->mft_ino);
  1250. mftbmp_ni = NTFS_I(vol->mftbmp_ino);
  1251. /*
  1252. * Determine the last lcn of the mft bitmap. The allocated size of the
  1253. * mft bitmap cannot be zero so we are ok to do this.
  1254. */
  1255. down_write(&mftbmp_ni->runlist.lock);
  1256. read_lock_irqsave(&mftbmp_ni->size_lock, flags);
  1257. ll = mftbmp_ni->allocated_size;
  1258. read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  1259. rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
  1260. (ll - 1) >> vol->cluster_size_bits, NULL);
  1261. if (IS_ERR(rl) || unlikely(!rl->length || rl->lcn < 0)) {
  1262. up_write(&mftbmp_ni->runlist.lock);
  1263. ntfs_error(vol->sb, "Failed to determine last allocated "
  1264. "cluster of mft bitmap attribute.");
  1265. if (!IS_ERR(rl))
  1266. ret = -EIO;
  1267. else
  1268. ret = PTR_ERR(rl);
  1269. return ret;
  1270. }
  1271. lcn = rl->lcn + rl->length;
  1272. ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
  1273. (long long)lcn);
  1274. /*
  1275. * Attempt to get the cluster following the last allocated cluster by
  1276. * hand as it may be in the MFT zone so the allocator would not give it
  1277. * to us.
  1278. */
  1279. ll = lcn >> 3;
  1280. page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
  1281. ll >> PAGE_SHIFT);
  1282. if (IS_ERR(page)) {
  1283. up_write(&mftbmp_ni->runlist.lock);
  1284. ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
  1285. return PTR_ERR(page);
  1286. }
  1287. b = (u8*)page_address(page) + (ll & ~PAGE_MASK);
  1288. tb = 1 << (lcn & 7ull);
  1289. down_write(&vol->lcnbmp_lock);
  1290. if (*b != 0xff && !(*b & tb)) {
  1291. /* Next cluster is free, allocate it. */
  1292. *b |= tb;
  1293. flush_dcache_page(page);
  1294. set_page_dirty(page);
  1295. up_write(&vol->lcnbmp_lock);
  1296. ntfs_unmap_page(page);
  1297. /* Update the mft bitmap runlist. */
  1298. rl->length++;
  1299. rl[1].vcn++;
  1300. status.added_cluster = 1;
  1301. ntfs_debug("Appending one cluster to mft bitmap.");
  1302. } else {
  1303. up_write(&vol->lcnbmp_lock);
  1304. ntfs_unmap_page(page);
  1305. /* Allocate a cluster from the DATA_ZONE. */
  1306. rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
  1307. true);
  1308. if (IS_ERR(rl2)) {
  1309. up_write(&mftbmp_ni->runlist.lock);
  1310. ntfs_error(vol->sb, "Failed to allocate a cluster for "
  1311. "the mft bitmap.");
  1312. return PTR_ERR(rl2);
  1313. }
  1314. rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
  1315. if (IS_ERR(rl)) {
  1316. up_write(&mftbmp_ni->runlist.lock);
  1317. ntfs_error(vol->sb, "Failed to merge runlists for mft "
  1318. "bitmap.");
  1319. if (ntfs_cluster_free_from_rl(vol, rl2)) {
  1320. ntfs_error(vol->sb, "Failed to deallocate "
  1321. "allocated cluster.%s", es);
  1322. NVolSetErrors(vol);
  1323. }
  1324. ntfs_free(rl2);
  1325. return PTR_ERR(rl);
  1326. }
  1327. mftbmp_ni->runlist.rl = rl;
  1328. status.added_run = 1;
  1329. ntfs_debug("Adding one run to mft bitmap.");
  1330. /* Find the last run in the new runlist. */
  1331. for (; rl[1].length; rl++)
  1332. ;
  1333. }
  1334. /*
  1335. * Update the attribute record as well. Note: @rl is the last
  1336. * (non-terminator) runlist element of mft bitmap.
  1337. */
  1338. mrec = map_mft_record(mft_ni);
  1339. if (IS_ERR(mrec)) {
  1340. ntfs_error(vol->sb, "Failed to map mft record.");
  1341. ret = PTR_ERR(mrec);
  1342. goto undo_alloc;
  1343. }
  1344. ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
  1345. if (unlikely(!ctx)) {
  1346. ntfs_error(vol->sb, "Failed to get search context.");
  1347. ret = -ENOMEM;
  1348. goto undo_alloc;
  1349. }
  1350. ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
  1351. mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
  1352. 0, ctx);
  1353. if (unlikely(ret)) {
  1354. ntfs_error(vol->sb, "Failed to find last attribute extent of "
  1355. "mft bitmap attribute.");
  1356. if (ret == -ENOENT)
  1357. ret = -EIO;
  1358. goto undo_alloc;
  1359. }
  1360. a = ctx->attr;
  1361. ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
  1362. /* Search back for the previous last allocated cluster of mft bitmap. */
  1363. for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
  1364. if (ll >= rl2->vcn)
  1365. break;
  1366. }
  1367. BUG_ON(ll < rl2->vcn);
  1368. BUG_ON(ll >= rl2->vcn + rl2->length);
  1369. /* Get the size for the new mapping pairs array for this extent. */
  1370. mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
  1371. if (unlikely(mp_size <= 0)) {
  1372. ntfs_error(vol->sb, "Get size for mapping pairs failed for "
  1373. "mft bitmap attribute extent.");
  1374. ret = mp_size;
  1375. if (!ret)
  1376. ret = -EIO;
  1377. goto undo_alloc;
  1378. }
  1379. /* Expand the attribute record if necessary. */
  1380. old_alen = le32_to_cpu(a->length);
  1381. ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
  1382. le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
  1383. if (unlikely(ret)) {
  1384. if (ret != -ENOSPC) {
  1385. ntfs_error(vol->sb, "Failed to resize attribute "
  1386. "record for mft bitmap attribute.");
  1387. goto undo_alloc;
  1388. }
  1389. // TODO: Deal with this by moving this extent to a new mft
  1390. // record or by starting a new extent in a new mft record or by
  1391. // moving other attributes out of this mft record.
  1392. // Note: It will need to be a special mft record and if none of
  1393. // those are available it gets rather complicated...
  1394. ntfs_error(vol->sb, "Not enough space in this mft record to "
  1395. "accommodate extended mft bitmap attribute "
  1396. "extent. Cannot handle this yet.");
  1397. ret = -EOPNOTSUPP;
  1398. goto undo_alloc;
  1399. }
  1400. status.mp_rebuilt = 1;
  1401. /* Generate the mapping pairs array directly into the attr record. */
  1402. ret = ntfs_mapping_pairs_build(vol, (u8*)a +
  1403. le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
  1404. mp_size, rl2, ll, -1, NULL);
  1405. if (unlikely(ret)) {
  1406. ntfs_error(vol->sb, "Failed to build mapping pairs array for "
  1407. "mft bitmap attribute.");
  1408. goto undo_alloc;
  1409. }
  1410. /* Update the highest_vcn. */
  1411. a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
  1412. /*
  1413. * We now have extended the mft bitmap allocated_size by one cluster.
  1414. * Reflect this in the ntfs_inode structure and the attribute record.
  1415. */
  1416. if (a->data.non_resident.lowest_vcn) {
  1417. /*
  1418. * We are not in the first attribute extent, switch to it, but
  1419. * first ensure the changes will make it to disk later.
  1420. */
  1421. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1422. mark_mft_record_dirty(ctx->ntfs_ino);
  1423. ntfs_attr_reinit_search_ctx(ctx);
  1424. ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
  1425. mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
  1426. 0, ctx);
  1427. if (unlikely(ret)) {
  1428. ntfs_error(vol->sb, "Failed to find first attribute "
  1429. "extent of mft bitmap attribute.");
  1430. goto restore_undo_alloc;
  1431. }
  1432. a = ctx->attr;
  1433. }
  1434. write_lock_irqsave(&mftbmp_ni->size_lock, flags);
  1435. mftbmp_ni->allocated_size += vol->cluster_size;
  1436. a->data.non_resident.allocated_size =
  1437. cpu_to_sle64(mftbmp_ni->allocated_size);
  1438. write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  1439. /* Ensure the changes make it to disk. */
  1440. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1441. mark_mft_record_dirty(ctx->ntfs_ino);
  1442. ntfs_attr_put_search_ctx(ctx);
  1443. unmap_mft_record(mft_ni);
  1444. up_write(&mftbmp_ni->runlist.lock);
  1445. ntfs_debug("Done.");
  1446. return 0;
  1447. restore_undo_alloc:
  1448. ntfs_attr_reinit_search_ctx(ctx);
  1449. if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
  1450. mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
  1451. 0, ctx)) {
  1452. ntfs_error(vol->sb, "Failed to find last attribute extent of "
  1453. "mft bitmap attribute.%s", es);
  1454. write_lock_irqsave(&mftbmp_ni->size_lock, flags);
  1455. mftbmp_ni->allocated_size += vol->cluster_size;
  1456. write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  1457. ntfs_attr_put_search_ctx(ctx);
  1458. unmap_mft_record(mft_ni);
  1459. up_write(&mftbmp_ni->runlist.lock);
  1460. /*
  1461. * The only thing that is now wrong is ->allocated_size of the
  1462. * base attribute extent which chkdsk should be able to fix.
  1463. */
  1464. NVolSetErrors(vol);
  1465. return ret;
  1466. }
  1467. a = ctx->attr;
  1468. a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
  1469. undo_alloc:
  1470. if (status.added_cluster) {
  1471. /* Truncate the last run in the runlist by one cluster. */
  1472. rl->length--;
  1473. rl[1].vcn--;
  1474. } else if (status.added_run) {
  1475. lcn = rl->lcn;
  1476. /* Remove the last run from the runlist. */
  1477. rl->lcn = rl[1].lcn;
  1478. rl->length = 0;
  1479. }
  1480. /* Deallocate the cluster. */
  1481. down_write(&vol->lcnbmp_lock);
  1482. if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
  1483. ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
  1484. NVolSetErrors(vol);
  1485. }
  1486. up_write(&vol->lcnbmp_lock);
  1487. if (status.mp_rebuilt) {
  1488. if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
  1489. a->data.non_resident.mapping_pairs_offset),
  1490. old_alen - le16_to_cpu(
  1491. a->data.non_resident.mapping_pairs_offset),
  1492. rl2, ll, -1, NULL)) {
  1493. ntfs_error(vol->sb, "Failed to restore mapping pairs "
  1494. "array.%s", es);
  1495. NVolSetErrors(vol);
  1496. }
  1497. if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
  1498. ntfs_error(vol->sb, "Failed to restore attribute "
  1499. "record.%s", es);
  1500. NVolSetErrors(vol);
  1501. }
  1502. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1503. mark_mft_record_dirty(ctx->ntfs_ino);
  1504. }
  1505. if (ctx)
  1506. ntfs_attr_put_search_ctx(ctx);
  1507. if (!IS_ERR(mrec))
  1508. unmap_mft_record(mft_ni);
  1509. up_write(&mftbmp_ni->runlist.lock);
  1510. return ret;
  1511. }
  1512. /**
  1513. * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
  1514. * @vol: volume on which to extend the mft bitmap attribute
  1515. *
  1516. * Extend the initialized portion of the mft bitmap attribute on the ntfs
  1517. * volume @vol by 8 bytes.
  1518. *
  1519. * Note: Only changes initialized_size and data_size, i.e. requires that
  1520. * allocated_size is big enough to fit the new initialized_size.
  1521. *
  1522. * Return 0 on success and -error on error.
  1523. *
  1524. * Locking: Caller must hold vol->mftbmp_lock for writing.
  1525. */
  1526. static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
  1527. {
  1528. s64 old_data_size, old_initialized_size;
  1529. unsigned long flags;
  1530. struct inode *mftbmp_vi;
  1531. ntfs_inode *mft_ni, *mftbmp_ni;
  1532. ntfs_attr_search_ctx *ctx;
  1533. MFT_RECORD *mrec;
  1534. ATTR_RECORD *a;
  1535. int ret;
  1536. ntfs_debug("Extending mft bitmap initiailized (and data) size.");
  1537. mft_ni = NTFS_I(vol->mft_ino);
  1538. mftbmp_vi = vol->mftbmp_ino;
  1539. mftbmp_ni = NTFS_I(mftbmp_vi);
  1540. /* Get the attribute record. */
  1541. mrec = map_mft_record(mft_ni);
  1542. if (IS_ERR(mrec)) {
  1543. ntfs_error(vol->sb, "Failed to map mft record.");
  1544. return PTR_ERR(mrec);
  1545. }
  1546. ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
  1547. if (unlikely(!ctx)) {
  1548. ntfs_error(vol->sb, "Failed to get search context.");
  1549. ret = -ENOMEM;
  1550. goto unm_err_out;
  1551. }
  1552. ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
  1553. mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
  1554. if (unlikely(ret)) {
  1555. ntfs_error(vol->sb, "Failed to find first attribute extent of "
  1556. "mft bitmap attribute.");
  1557. if (ret == -ENOENT)
  1558. ret = -EIO;
  1559. goto put_err_out;
  1560. }
  1561. a = ctx->attr;
  1562. write_lock_irqsave(&mftbmp_ni->size_lock, flags);
  1563. old_data_size = i_size_read(mftbmp_vi);
  1564. old_initialized_size = mftbmp_ni->initialized_size;
  1565. /*
  1566. * We can simply update the initialized_size before filling the space
  1567. * with zeroes because the caller is holding the mft bitmap lock for
  1568. * writing which ensures that no one else is trying to access the data.
  1569. */
  1570. mftbmp_ni->initialized_size += 8;
  1571. a->data.non_resident.initialized_size =
  1572. cpu_to_sle64(mftbmp_ni->initialized_size);
  1573. if (mftbmp_ni->initialized_size > old_data_size) {
  1574. i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
  1575. a->data.non_resident.data_size =
  1576. cpu_to_sle64(mftbmp_ni->initialized_size);
  1577. }
  1578. write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  1579. /* Ensure the changes make it to disk. */
  1580. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1581. mark_mft_record_dirty(ctx->ntfs_ino);
  1582. ntfs_attr_put_search_ctx(ctx);
  1583. unmap_mft_record(mft_ni);
  1584. /* Initialize the mft bitmap attribute value with zeroes. */
  1585. ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
  1586. if (likely(!ret)) {
  1587. ntfs_debug("Done. (Wrote eight initialized bytes to mft "
  1588. "bitmap.");
  1589. return 0;
  1590. }
  1591. ntfs_error(vol->sb, "Failed to write to mft bitmap.");
  1592. /* Try to recover from the error. */
  1593. mrec = map_mft_record(mft_ni);
  1594. if (IS_ERR(mrec)) {
  1595. ntfs_error(vol->sb, "Failed to map mft record.%s", es);
  1596. NVolSetErrors(vol);
  1597. return ret;
  1598. }
  1599. ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
  1600. if (unlikely(!ctx)) {
  1601. ntfs_error(vol->sb, "Failed to get search context.%s", es);
  1602. NVolSetErrors(vol);
  1603. goto unm_err_out;
  1604. }
  1605. if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
  1606. mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
  1607. ntfs_error(vol->sb, "Failed to find first attribute extent of "
  1608. "mft bitmap attribute.%s", es);
  1609. NVolSetErrors(vol);
  1610. put_err_out:
  1611. ntfs_attr_put_search_ctx(ctx);
  1612. unm_err_out:
  1613. unmap_mft_record(mft_ni);
  1614. goto err_out;
  1615. }
  1616. a = ctx->attr;
  1617. write_lock_irqsave(&mftbmp_ni->size_lock, flags);
  1618. mftbmp_ni->initialized_size = old_initialized_size;
  1619. a->data.non_resident.initialized_size =
  1620. cpu_to_sle64(old_initialized_size);
  1621. if (i_size_read(mftbmp_vi) != old_data_size) {
  1622. i_size_write(mftbmp_vi, old_data_size);
  1623. a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
  1624. }
  1625. write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  1626. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1627. mark_mft_record_dirty(ctx->ntfs_ino);
  1628. ntfs_attr_put_search_ctx(ctx);
  1629. unmap_mft_record(mft_ni);
  1630. #ifdef DEBUG
  1631. read_lock_irqsave(&mftbmp_ni->size_lock, flags);
  1632. ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
  1633. "data_size 0x%llx, initialized_size 0x%llx.",
  1634. (long long)mftbmp_ni->allocated_size,
  1635. (long long)i_size_read(mftbmp_vi),
  1636. (long long)mftbmp_ni->initialized_size);
  1637. read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  1638. #endif /* DEBUG */
  1639. err_out:
  1640. return ret;
  1641. }
  1642. /**
  1643. * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
  1644. * @vol: volume on which to extend the mft data attribute
  1645. *
  1646. * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
  1647. * worth of clusters or if not enough space for this by one mft record worth
  1648. * of clusters.
  1649. *
  1650. * Note: Only changes allocated_size, i.e. does not touch initialized_size or
  1651. * data_size.
  1652. *
  1653. * Return 0 on success and -errno on error.
  1654. *
  1655. * Locking: - Caller must hold vol->mftbmp_lock for writing.
  1656. * - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
  1657. * writing and releases it before returning.
  1658. * - This function calls functions which take vol->lcnbmp_lock for
  1659. * writing and release it before returning.
  1660. */
  1661. static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
  1662. {
  1663. LCN lcn;
  1664. VCN old_last_vcn;
  1665. s64 min_nr, nr, ll;
  1666. unsigned long flags;
  1667. ntfs_inode *mft_ni;
  1668. runlist_element *rl, *rl2;
  1669. ntfs_attr_search_ctx *ctx = NULL;
  1670. MFT_RECORD *mrec;
  1671. ATTR_RECORD *a = NULL;
  1672. int ret, mp_size;
  1673. u32 old_alen = 0;
  1674. bool mp_rebuilt = false;
  1675. ntfs_debug("Extending mft data allocation.");
  1676. mft_ni = NTFS_I(vol->mft_ino);
  1677. /*
  1678. * Determine the preferred allocation location, i.e. the last lcn of
  1679. * the mft data attribute. The allocated size of the mft data
  1680. * attribute cannot be zero so we are ok to do this.
  1681. */
  1682. down_write(&mft_ni->runlist.lock);
  1683. read_lock_irqsave(&mft_ni->size_lock, flags);
  1684. ll = mft_ni->allocated_size;
  1685. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  1686. rl = ntfs_attr_find_vcn_nolock(mft_ni,
  1687. (ll - 1) >> vol->cluster_size_bits, NULL);
  1688. if (IS_ERR(rl) || unlikely(!rl->length || rl->lcn < 0)) {
  1689. up_write(&mft_ni->runlist.lock);
  1690. ntfs_error(vol->sb, "Failed to determine last allocated "
  1691. "cluster of mft data attribute.");
  1692. if (!IS_ERR(rl))
  1693. ret = -EIO;
  1694. else
  1695. ret = PTR_ERR(rl);
  1696. return ret;
  1697. }
  1698. lcn = rl->lcn + rl->length;
  1699. ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
  1700. /* Minimum allocation is one mft record worth of clusters. */
  1701. min_nr = vol->mft_record_size >> vol->cluster_size_bits;
  1702. if (!min_nr)
  1703. min_nr = 1;
  1704. /* Want to allocate 16 mft records worth of clusters. */
  1705. nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
  1706. if (!nr)
  1707. nr = min_nr;
  1708. /* Ensure we do not go above 2^32-1 mft records. */
  1709. read_lock_irqsave(&mft_ni->size_lock, flags);
  1710. ll = mft_ni->allocated_size;
  1711. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  1712. if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
  1713. vol->mft_record_size_bits >= (1ll << 32))) {
  1714. nr = min_nr;
  1715. if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
  1716. vol->mft_record_size_bits >= (1ll << 32))) {
  1717. ntfs_warning(vol->sb, "Cannot allocate mft record "
  1718. "because the maximum number of inodes "
  1719. "(2^32) has already been reached.");
  1720. up_write(&mft_ni->runlist.lock);
  1721. return -ENOSPC;
  1722. }
  1723. }
  1724. ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
  1725. nr > min_nr ? "default" : "minimal", (long long)nr);
  1726. old_last_vcn = rl[1].vcn;
  1727. do {
  1728. rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
  1729. true);
  1730. if (!IS_ERR(rl2))
  1731. break;
  1732. if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
  1733. ntfs_error(vol->sb, "Failed to allocate the minimal "
  1734. "number of clusters (%lli) for the "
  1735. "mft data attribute.", (long long)nr);
  1736. up_write(&mft_ni->runlist.lock);
  1737. return PTR_ERR(rl2);
  1738. }
  1739. /*
  1740. * There is not enough space to do the allocation, but there
  1741. * might be enough space to do a minimal allocation so try that
  1742. * before failing.
  1743. */
  1744. nr = min_nr;
  1745. ntfs_debug("Retrying mft data allocation with minimal cluster "
  1746. "count %lli.", (long long)nr);
  1747. } while (1);
  1748. rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
  1749. if (IS_ERR(rl)) {
  1750. up_write(&mft_ni->runlist.lock);
  1751. ntfs_error(vol->sb, "Failed to merge runlists for mft data "
  1752. "attribute.");
  1753. if (ntfs_cluster_free_from_rl(vol, rl2)) {
  1754. ntfs_error(vol->sb, "Failed to deallocate clusters "
  1755. "from the mft data attribute.%s", es);
  1756. NVolSetErrors(vol);
  1757. }
  1758. ntfs_free(rl2);
  1759. return PTR_ERR(rl);
  1760. }
  1761. mft_ni->runlist.rl = rl;
  1762. ntfs_debug("Allocated %lli clusters.", (long long)nr);
  1763. /* Find the last run in the new runlist. */
  1764. for (; rl[1].length; rl++)
  1765. ;
  1766. /* Update the attribute record as well. */
  1767. mrec = map_mft_record(mft_ni);
  1768. if (IS_ERR(mrec)) {
  1769. ntfs_error(vol->sb, "Failed to map mft record.");
  1770. ret = PTR_ERR(mrec);
  1771. goto undo_alloc;
  1772. }
  1773. ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
  1774. if (unlikely(!ctx)) {
  1775. ntfs_error(vol->sb, "Failed to get search context.");
  1776. ret = -ENOMEM;
  1777. goto undo_alloc;
  1778. }
  1779. ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
  1780. CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
  1781. if (unlikely(ret)) {
  1782. ntfs_error(vol->sb, "Failed to find last attribute extent of "
  1783. "mft data attribute.");
  1784. if (ret == -ENOENT)
  1785. ret = -EIO;
  1786. goto undo_alloc;
  1787. }
  1788. a = ctx->attr;
  1789. ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
  1790. /* Search back for the previous last allocated cluster of mft bitmap. */
  1791. for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
  1792. if (ll >= rl2->vcn)
  1793. break;
  1794. }
  1795. BUG_ON(ll < rl2->vcn);
  1796. BUG_ON(ll >= rl2->vcn + rl2->length);
  1797. /* Get the size for the new mapping pairs array for this extent. */
  1798. mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
  1799. if (unlikely(mp_size <= 0)) {
  1800. ntfs_error(vol->sb, "Get size for mapping pairs failed for "
  1801. "mft data attribute extent.");
  1802. ret = mp_size;
  1803. if (!ret)
  1804. ret = -EIO;
  1805. goto undo_alloc;
  1806. }
  1807. /* Expand the attribute record if necessary. */
  1808. old_alen = le32_to_cpu(a->length);
  1809. ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
  1810. le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
  1811. if (unlikely(ret)) {
  1812. if (ret != -ENOSPC) {
  1813. ntfs_error(vol->sb, "Failed to resize attribute "
  1814. "record for mft data attribute.");
  1815. goto undo_alloc;
  1816. }
  1817. // TODO: Deal with this by moving this extent to a new mft
  1818. // record or by starting a new extent in a new mft record or by
  1819. // moving other attributes out of this mft record.
  1820. // Note: Use the special reserved mft records and ensure that
  1821. // this extent is not required to find the mft record in
  1822. // question. If no free special records left we would need to
  1823. // move an existing record away, insert ours in its place, and
  1824. // then place the moved record into the newly allocated space
  1825. // and we would then need to update all references to this mft
  1826. // record appropriately. This is rather complicated...
  1827. ntfs_error(vol->sb, "Not enough space in this mft record to "
  1828. "accommodate extended mft data attribute "
  1829. "extent. Cannot handle this yet.");
  1830. ret = -EOPNOTSUPP;
  1831. goto undo_alloc;
  1832. }
  1833. mp_rebuilt = true;
  1834. /* Generate the mapping pairs array directly into the attr record. */
  1835. ret = ntfs_mapping_pairs_build(vol, (u8*)a +
  1836. le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
  1837. mp_size, rl2, ll, -1, NULL);
  1838. if (unlikely(ret)) {
  1839. ntfs_error(vol->sb, "Failed to build mapping pairs array of "
  1840. "mft data attribute.");
  1841. goto undo_alloc;
  1842. }
  1843. /* Update the highest_vcn. */
  1844. a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
  1845. /*
  1846. * We now have extended the mft data allocated_size by nr clusters.
  1847. * Reflect this in the ntfs_inode structure and the attribute record.
  1848. * @rl is the last (non-terminator) runlist element of mft data
  1849. * attribute.
  1850. */
  1851. if (a->data.non_resident.lowest_vcn) {
  1852. /*
  1853. * We are not in the first attribute extent, switch to it, but
  1854. * first ensure the changes will make it to disk later.
  1855. */
  1856. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1857. mark_mft_record_dirty(ctx->ntfs_ino);
  1858. ntfs_attr_reinit_search_ctx(ctx);
  1859. ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
  1860. mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
  1861. ctx);
  1862. if (unlikely(ret)) {
  1863. ntfs_error(vol->sb, "Failed to find first attribute "
  1864. "extent of mft data attribute.");
  1865. goto restore_undo_alloc;
  1866. }
  1867. a = ctx->attr;
  1868. }
  1869. write_lock_irqsave(&mft_ni->size_lock, flags);
  1870. mft_ni->allocated_size += nr << vol->cluster_size_bits;
  1871. a->data.non_resident.allocated_size =
  1872. cpu_to_sle64(mft_ni->allocated_size);
  1873. write_unlock_irqrestore(&mft_ni->size_lock, flags);
  1874. /* Ensure the changes make it to disk. */
  1875. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1876. mark_mft_record_dirty(ctx->ntfs_ino);
  1877. ntfs_attr_put_search_ctx(ctx);
  1878. unmap_mft_record(mft_ni);
  1879. up_write(&mft_ni->runlist.lock);
  1880. ntfs_debug("Done.");
  1881. return 0;
  1882. restore_undo_alloc:
  1883. ntfs_attr_reinit_search_ctx(ctx);
  1884. if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
  1885. CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
  1886. ntfs_error(vol->sb, "Failed to find last attribute extent of "
  1887. "mft data attribute.%s", es);
  1888. write_lock_irqsave(&mft_ni->size_lock, flags);
  1889. mft_ni->allocated_size += nr << vol->cluster_size_bits;
  1890. write_unlock_irqrestore(&mft_ni->size_lock, flags);
  1891. ntfs_attr_put_search_ctx(ctx);
  1892. unmap_mft_record(mft_ni);
  1893. up_write(&mft_ni->runlist.lock);
  1894. /*
  1895. * The only thing that is now wrong is ->allocated_size of the
  1896. * base attribute extent which chkdsk should be able to fix.
  1897. */
  1898. NVolSetErrors(vol);
  1899. return ret;
  1900. }
  1901. ctx->attr->data.non_resident.highest_vcn =
  1902. cpu_to_sle64(old_last_vcn - 1);
  1903. undo_alloc:
  1904. if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
  1905. ntfs_error(vol->sb, "Failed to free clusters from mft data "
  1906. "attribute.%s", es);
  1907. NVolSetErrors(vol);
  1908. }
  1909. a = ctx->attr;
  1910. if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
  1911. ntfs_error(vol->sb, "Failed to truncate mft data attribute "
  1912. "runlist.%s", es);
  1913. NVolSetErrors(vol);
  1914. }
  1915. if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
  1916. if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
  1917. a->data.non_resident.mapping_pairs_offset),
  1918. old_alen - le16_to_cpu(
  1919. a->data.non_resident.mapping_pairs_offset),
  1920. rl2, ll, -1, NULL)) {
  1921. ntfs_error(vol->sb, "Failed to restore mapping pairs "
  1922. "array.%s", es);
  1923. NVolSetErrors(vol);
  1924. }
  1925. if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
  1926. ntfs_error(vol->sb, "Failed to restore attribute "
  1927. "record.%s", es);
  1928. NVolSetErrors(vol);
  1929. }
  1930. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1931. mark_mft_record_dirty(ctx->ntfs_ino);
  1932. } else if (IS_ERR(ctx->mrec)) {
  1933. ntfs_error(vol->sb, "Failed to restore attribute search "
  1934. "context.%s", es);
  1935. NVolSetErrors(vol);
  1936. }
  1937. if (ctx)
  1938. ntfs_attr_put_search_ctx(ctx);
  1939. if (!IS_ERR(mrec))
  1940. unmap_mft_record(mft_ni);
  1941. up_write(&mft_ni->runlist.lock);
  1942. return ret;
  1943. }
  1944. /**
  1945. * ntfs_mft_record_layout - layout an mft record into a memory buffer
  1946. * @vol: volume to which the mft record will belong
  1947. * @mft_no: mft reference specifying the mft record number
  1948. * @m: destination buffer of size >= @vol->mft_record_size bytes
  1949. *
  1950. * Layout an empty, unused mft record with the mft record number @mft_no into
  1951. * the buffer @m. The volume @vol is needed because the mft record structure
  1952. * was modified in NTFS 3.1 so we need to know which volume version this mft
  1953. * record will be used on.
  1954. *
  1955. * Return 0 on success and -errno on error.
  1956. */
  1957. static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
  1958. MFT_RECORD *m)
  1959. {
  1960. ATTR_RECORD *a;
  1961. ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
  1962. if (mft_no >= (1ll << 32)) {
  1963. ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
  1964. "maximum of 2^32.", (long long)mft_no);
  1965. return -ERANGE;
  1966. }
  1967. /* Start by clearing the whole mft record to gives us a clean slate. */
  1968. memset(m, 0, vol->mft_record_size);
  1969. /* Aligned to 2-byte boundary. */
  1970. if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
  1971. m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
  1972. else {
  1973. m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
  1974. /*
  1975. * Set the NTFS 3.1+ specific fields while we know that the
  1976. * volume version is 3.1+.
  1977. */
  1978. m->reserved = 0;
  1979. m->mft_record_number = cpu_to_le32((u32)mft_no);
  1980. }
  1981. m->magic = magic_FILE;
  1982. if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
  1983. m->usa_count = cpu_to_le16(vol->mft_record_size /
  1984. NTFS_BLOCK_SIZE + 1);
  1985. else {
  1986. m->usa_count = cpu_to_le16(1);
  1987. ntfs_warning(vol->sb, "Sector size is bigger than mft record "
  1988. "size. Setting usa_count to 1. If chkdsk "
  1989. "reports this as corruption, please email "
  1990. "linux-ntfs-dev@lists.sourceforge.net stating "
  1991. "that you saw this message and that the "
  1992. "modified filesystem created was corrupt. "
  1993. "Thank you.");
  1994. }
  1995. /* Set the update sequence number to 1. */
  1996. *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
  1997. m->lsn = 0;
  1998. m->sequence_number = cpu_to_le16(1);
  1999. m->link_count = 0;
  2000. /*
  2001. * Place the attributes straight after the update sequence array,
  2002. * aligned to 8-byte boundary.
  2003. */
  2004. m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
  2005. (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
  2006. m->flags = 0;
  2007. /*
  2008. * Using attrs_offset plus eight bytes (for the termination attribute).
  2009. * attrs_offset is already aligned to 8-byte boundary, so no need to
  2010. * align again.
  2011. */
  2012. m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
  2013. m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
  2014. m->base_mft_record = 0;
  2015. m->next_attr_instance = 0;
  2016. /* Add the termination attribute. */
  2017. a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
  2018. a->type = AT_END;
  2019. a->length = 0;
  2020. ntfs_debug("Done.");
  2021. return 0;
  2022. }
  2023. /**
  2024. * ntfs_mft_record_format - format an mft record on an ntfs volume
  2025. * @vol: volume on which to format the mft record
  2026. * @mft_no: mft record number to format
  2027. *
  2028. * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
  2029. * mft record into the appropriate place of the mft data attribute. This is
  2030. * used when extending the mft data attribute.
  2031. *
  2032. * Return 0 on success and -errno on error.
  2033. */
  2034. static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
  2035. {
  2036. loff_t i_size;
  2037. struct inode *mft_vi = vol->mft_ino;
  2038. struct page *page;
  2039. MFT_RECORD *m;
  2040. pgoff_t index, end_index;
  2041. unsigned int ofs;
  2042. int err;
  2043. ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
  2044. /*
  2045. * The index into the page cache and the offset within the page cache
  2046. * page of the wanted mft record.
  2047. */
  2048. index = mft_no << vol->mft_record_size_bits >> PAGE_SHIFT;
  2049. ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_MASK;
  2050. /* The maximum valid index into the page cache for $MFT's data. */
  2051. i_size = i_size_read(mft_vi);
  2052. end_index = i_size >> PAGE_SHIFT;
  2053. if (unlikely(index >= end_index)) {
  2054. if (unlikely(index > end_index || ofs + vol->mft_record_size >=
  2055. (i_size & ~PAGE_MASK))) {
  2056. ntfs_error(vol->sb, "Tried to format non-existing mft "
  2057. "record 0x%llx.", (long long)mft_no);
  2058. return -ENOENT;
  2059. }
  2060. }
  2061. /* Read, map, and pin the page containing the mft record. */
  2062. page = ntfs_map_page(mft_vi->i_mapping, index);
  2063. if (IS_ERR(page)) {
  2064. ntfs_error(vol->sb, "Failed to map page containing mft record "
  2065. "to format 0x%llx.", (long long)mft_no);
  2066. return PTR_ERR(page);
  2067. }
  2068. lock_page(page);
  2069. BUG_ON(!PageUptodate(page));
  2070. ClearPageUptodate(page);
  2071. m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
  2072. err = ntfs_mft_record_layout(vol, mft_no, m);
  2073. if (unlikely(err)) {
  2074. ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
  2075. (long long)mft_no);
  2076. SetPageUptodate(page);
  2077. unlock_page(page);
  2078. ntfs_unmap_page(page);
  2079. return err;
  2080. }
  2081. flush_dcache_page(page);
  2082. SetPageUptodate(page);
  2083. unlock_page(page);
  2084. /*
  2085. * Make sure the mft record is written out to disk. We could use
  2086. * ilookup5() to check if an inode is in icache and so on but this is
  2087. * unnecessary as ntfs_writepage() will write the dirty record anyway.
  2088. */
  2089. mark_ntfs_record_dirty(page, ofs);
  2090. ntfs_unmap_page(page);
  2091. ntfs_debug("Done.");
  2092. return 0;
  2093. }
  2094. /**
  2095. * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
  2096. * @vol: [IN] volume on which to allocate the mft record
  2097. * @mode: [IN] mode if want a file or directory, i.e. base inode or 0
  2098. * @base_ni: [IN] open base inode if allocating an extent mft record or NULL
  2099. * @mrec: [OUT] on successful return this is the mapped mft record
  2100. *
  2101. * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
  2102. *
  2103. * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
  2104. * direvctory inode, and allocate it at the default allocator position. In
  2105. * this case @mode is the file mode as given to us by the caller. We in
  2106. * particular use @mode to distinguish whether a file or a directory is being
  2107. * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
  2108. *
  2109. * If @base_ni is not NULL make the allocated mft record an extent record,
  2110. * allocate it starting at the mft record after the base mft record and attach
  2111. * the allocated and opened ntfs inode to the base inode @base_ni. In this
  2112. * case @mode must be 0 as it is meaningless for extent inodes.
  2113. *
  2114. * You need to check the return value with IS_ERR(). If false, the function
  2115. * was successful and the return value is the now opened ntfs inode of the
  2116. * allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
  2117. * and locked mft record. If IS_ERR() is true, the function failed and the
  2118. * error code is obtained from PTR_ERR(return value). *@mrec is undefined in
  2119. * this case.
  2120. *
  2121. * Allocation strategy:
  2122. *
  2123. * To find a free mft record, we scan the mft bitmap for a zero bit. To
  2124. * optimize this we start scanning at the place specified by @base_ni or if
  2125. * @base_ni is NULL we start where we last stopped and we perform wrap around
  2126. * when we reach the end. Note, we do not try to allocate mft records below
  2127. * number 24 because numbers 0 to 15 are the defined system files anyway and 16
  2128. * to 24 are special in that they are used for storing extension mft records
  2129. * for the $DATA attribute of $MFT. This is required to avoid the possibility
  2130. * of creating a runlist with a circular dependency which once written to disk
  2131. * can never be read in again. Windows will only use records 16 to 24 for
  2132. * normal files if the volume is completely out of space. We never use them
  2133. * which means that when the volume is really out of space we cannot create any
  2134. * more files while Windows can still create up to 8 small files. We can start
  2135. * doing this at some later time, it does not matter much for now.
  2136. *
  2137. * When scanning the mft bitmap, we only search up to the last allocated mft
  2138. * record. If there are no free records left in the range 24 to number of
  2139. * allocated mft records, then we extend the $MFT/$DATA attribute in order to
  2140. * create free mft records. We extend the allocated size of $MFT/$DATA by 16
  2141. * records at a time or one cluster, if cluster size is above 16kiB. If there
  2142. * is not sufficient space to do this, we try to extend by a single mft record
  2143. * or one cluster, if cluster size is above the mft record size.
  2144. *
  2145. * No matter how many mft records we allocate, we initialize only the first
  2146. * allocated mft record, incrementing mft data size and initialized size
  2147. * accordingly, open an ntfs_inode for it and return it to the caller, unless
  2148. * there are less than 24 mft records, in which case we allocate and initialize
  2149. * mft records until we reach record 24 which we consider as the first free mft
  2150. * record for use by normal files.
  2151. *
  2152. * If during any stage we overflow the initialized data in the mft bitmap, we
  2153. * extend the initialized size (and data size) by 8 bytes, allocating another
  2154. * cluster if required. The bitmap data size has to be at least equal to the
  2155. * number of mft records in the mft, but it can be bigger, in which case the
  2156. * superflous bits are padded with zeroes.
  2157. *
  2158. * Thus, when we return successfully (IS_ERR() is false), we will have:
  2159. * - initialized / extended the mft bitmap if necessary,
  2160. * - initialized / extended the mft data if necessary,
  2161. * - set the bit corresponding to the mft record being allocated in the
  2162. * mft bitmap,
  2163. * - opened an ntfs_inode for the allocated mft record, and we will have
  2164. * - returned the ntfs_inode as well as the allocated mapped, pinned, and
  2165. * locked mft record.
  2166. *
  2167. * On error, the volume will be left in a consistent state and no record will
  2168. * be allocated. If rolling back a partial operation fails, we may leave some
  2169. * inconsistent metadata in which case we set NVolErrors() so the volume is
  2170. * left dirty when unmounted.
  2171. *
  2172. * Note, this function cannot make use of most of the normal functions, like
  2173. * for example for attribute resizing, etc, because when the run list overflows
  2174. * the base mft record and an attribute list is used, it is very important that
  2175. * the extension mft records used to store the $DATA attribute of $MFT can be
  2176. * reached without having to read the information contained inside them, as
  2177. * this would make it impossible to find them in the first place after the
  2178. * volume is unmounted. $MFT/$BITMAP probably does not need to follow this
  2179. * rule because the bitmap is not essential for finding the mft records, but on
  2180. * the other hand, handling the bitmap in this special way would make life
  2181. * easier because otherwise there might be circular invocations of functions
  2182. * when reading the bitmap.
  2183. */
  2184. ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
  2185. ntfs_inode *base_ni, MFT_RECORD **mrec)
  2186. {
  2187. s64 ll, bit, old_data_initialized, old_data_size;
  2188. unsigned long flags;
  2189. struct inode *vi;
  2190. struct page *page;
  2191. ntfs_inode *mft_ni, *mftbmp_ni, *ni;
  2192. ntfs_attr_search_ctx *ctx;
  2193. MFT_RECORD *m;
  2194. ATTR_RECORD *a;
  2195. pgoff_t index;
  2196. unsigned int ofs;
  2197. int err;
  2198. le16 seq_no, usn;
  2199. bool record_formatted = false;
  2200. if (base_ni) {
  2201. ntfs_debug("Entering (allocating an extent mft record for "
  2202. "base mft record 0x%llx).",
  2203. (long long)base_ni->mft_no);
  2204. /* @mode and @base_ni are mutually exclusive. */
  2205. BUG_ON(mode);
  2206. } else
  2207. ntfs_debug("Entering (allocating a base mft record).");
  2208. if (mode) {
  2209. /* @mode and @base_ni are mutually exclusive. */
  2210. BUG_ON(base_ni);
  2211. /* We only support creation of normal files and directories. */
  2212. if (!S_ISREG(mode) && !S_ISDIR(mode))
  2213. return ERR_PTR(-EOPNOTSUPP);
  2214. }
  2215. BUG_ON(!mrec);
  2216. mft_ni = NTFS_I(vol->mft_ino);
  2217. mftbmp_ni = NTFS_I(vol->mftbmp_ino);
  2218. down_write(&vol->mftbmp_lock);
  2219. bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
  2220. if (bit >= 0) {
  2221. ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
  2222. (long long)bit);
  2223. goto have_alloc_rec;
  2224. }
  2225. if (bit != -ENOSPC) {
  2226. up_write(&vol->mftbmp_lock);
  2227. return ERR_PTR(bit);
  2228. }
  2229. /*
  2230. * No free mft records left. If the mft bitmap already covers more
  2231. * than the currently used mft records, the next records are all free,
  2232. * so we can simply allocate the first unused mft record.
  2233. * Note: We also have to make sure that the mft bitmap at least covers
  2234. * the first 24 mft records as they are special and whilst they may not
  2235. * be in use, we do not allocate from them.
  2236. */
  2237. read_lock_irqsave(&mft_ni->size_lock, flags);
  2238. ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
  2239. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  2240. read_lock_irqsave(&mftbmp_ni->size_lock, flags);
  2241. old_data_initialized = mftbmp_ni->initialized_size;
  2242. read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  2243. if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
  2244. bit = ll;
  2245. if (bit < 24)
  2246. bit = 24;
  2247. if (unlikely(bit >= (1ll << 32)))
  2248. goto max_err_out;
  2249. ntfs_debug("Found free record (#2), bit 0x%llx.",
  2250. (long long)bit);
  2251. goto found_free_rec;
  2252. }
  2253. /*
  2254. * The mft bitmap needs to be expanded until it covers the first unused
  2255. * mft record that we can allocate.
  2256. * Note: The smallest mft record we allocate is mft record 24.
  2257. */
  2258. bit = old_data_initialized << 3;
  2259. if (unlikely(bit >= (1ll << 32)))
  2260. goto max_err_out;
  2261. read_lock_irqsave(&mftbmp_ni->size_lock, flags);
  2262. old_data_size = mftbmp_ni->allocated_size;
  2263. ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
  2264. "data_size 0x%llx, initialized_size 0x%llx.",
  2265. (long long)old_data_size,
  2266. (long long)i_size_read(vol->mftbmp_ino),
  2267. (long long)old_data_initialized);
  2268. read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  2269. if (old_data_initialized + 8 > old_data_size) {
  2270. /* Need to extend bitmap by one more cluster. */
  2271. ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
  2272. err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
  2273. if (unlikely(err)) {
  2274. up_write(&vol->mftbmp_lock);
  2275. goto err_out;
  2276. }
  2277. #ifdef DEBUG
  2278. read_lock_irqsave(&mftbmp_ni->size_lock, flags);
  2279. ntfs_debug("Status of mftbmp after allocation extension: "
  2280. "allocated_size 0x%llx, data_size 0x%llx, "
  2281. "initialized_size 0x%llx.",
  2282. (long long)mftbmp_ni->allocated_size,
  2283. (long long)i_size_read(vol->mftbmp_ino),
  2284. (long long)mftbmp_ni->initialized_size);
  2285. read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  2286. #endif /* DEBUG */
  2287. }
  2288. /*
  2289. * We now have sufficient allocated space, extend the initialized_size
  2290. * as well as the data_size if necessary and fill the new space with
  2291. * zeroes.
  2292. */
  2293. err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
  2294. if (unlikely(err)) {
  2295. up_write(&vol->mftbmp_lock);
  2296. goto err_out;
  2297. }
  2298. #ifdef DEBUG
  2299. read_lock_irqsave(&mftbmp_ni->size_lock, flags);
  2300. ntfs_debug("Status of mftbmp after initialized extension: "
  2301. "allocated_size 0x%llx, data_size 0x%llx, "
  2302. "initialized_size 0x%llx.",
  2303. (long long)mftbmp_ni->allocated_size,
  2304. (long long)i_size_read(vol->mftbmp_ino),
  2305. (long long)mftbmp_ni->initialized_size);
  2306. read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
  2307. #endif /* DEBUG */
  2308. ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
  2309. found_free_rec:
  2310. /* @bit is the found free mft record, allocate it in the mft bitmap. */
  2311. ntfs_debug("At found_free_rec.");
  2312. err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
  2313. if (unlikely(err)) {
  2314. ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
  2315. up_write(&vol->mftbmp_lock);
  2316. goto err_out;
  2317. }
  2318. ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
  2319. have_alloc_rec:
  2320. /*
  2321. * The mft bitmap is now uptodate. Deal with mft data attribute now.
  2322. * Note, we keep hold of the mft bitmap lock for writing until all
  2323. * modifications to the mft data attribute are complete, too, as they
  2324. * will impact decisions for mft bitmap and mft record allocation done
  2325. * by a parallel allocation and if the lock is not maintained a
  2326. * parallel allocation could allocate the same mft record as this one.
  2327. */
  2328. ll = (bit + 1) << vol->mft_record_size_bits;
  2329. read_lock_irqsave(&mft_ni->size_lock, flags);
  2330. old_data_initialized = mft_ni->initialized_size;
  2331. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  2332. if (ll <= old_data_initialized) {
  2333. ntfs_debug("Allocated mft record already initialized.");
  2334. goto mft_rec_already_initialized;
  2335. }
  2336. ntfs_debug("Initializing allocated mft record.");
  2337. /*
  2338. * The mft record is outside the initialized data. Extend the mft data
  2339. * attribute until it covers the allocated record. The loop is only
  2340. * actually traversed more than once when a freshly formatted volume is
  2341. * first written to so it optimizes away nicely in the common case.
  2342. */
  2343. read_lock_irqsave(&mft_ni->size_lock, flags);
  2344. ntfs_debug("Status of mft data before extension: "
  2345. "allocated_size 0x%llx, data_size 0x%llx, "
  2346. "initialized_size 0x%llx.",
  2347. (long long)mft_ni->allocated_size,
  2348. (long long)i_size_read(vol->mft_ino),
  2349. (long long)mft_ni->initialized_size);
  2350. while (ll > mft_ni->allocated_size) {
  2351. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  2352. err = ntfs_mft_data_extend_allocation_nolock(vol);
  2353. if (unlikely(err)) {
  2354. ntfs_error(vol->sb, "Failed to extend mft data "
  2355. "allocation.");
  2356. goto undo_mftbmp_alloc_nolock;
  2357. }
  2358. read_lock_irqsave(&mft_ni->size_lock, flags);
  2359. ntfs_debug("Status of mft data after allocation extension: "
  2360. "allocated_size 0x%llx, data_size 0x%llx, "
  2361. "initialized_size 0x%llx.",
  2362. (long long)mft_ni->allocated_size,
  2363. (long long)i_size_read(vol->mft_ino),
  2364. (long long)mft_ni->initialized_size);
  2365. }
  2366. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  2367. /*
  2368. * Extend mft data initialized size (and data size of course) to reach
  2369. * the allocated mft record, formatting the mft records allong the way.
  2370. * Note: We only modify the ntfs_inode structure as that is all that is
  2371. * needed by ntfs_mft_record_format(). We will update the attribute
  2372. * record itself in one fell swoop later on.
  2373. */
  2374. write_lock_irqsave(&mft_ni->size_lock, flags);
  2375. old_data_initialized = mft_ni->initialized_size;
  2376. old_data_size = vol->mft_ino->i_size;
  2377. while (ll > mft_ni->initialized_size) {
  2378. s64 new_initialized_size, mft_no;
  2379. new_initialized_size = mft_ni->initialized_size +
  2380. vol->mft_record_size;
  2381. mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
  2382. if (new_initialized_size > i_size_read(vol->mft_ino))
  2383. i_size_write(vol->mft_ino, new_initialized_size);
  2384. write_unlock_irqrestore(&mft_ni->size_lock, flags);
  2385. ntfs_debug("Initializing mft record 0x%llx.",
  2386. (long long)mft_no);
  2387. err = ntfs_mft_record_format(vol, mft_no);
  2388. if (unlikely(err)) {
  2389. ntfs_error(vol->sb, "Failed to format mft record.");
  2390. goto undo_data_init;
  2391. }
  2392. write_lock_irqsave(&mft_ni->size_lock, flags);
  2393. mft_ni->initialized_size = new_initialized_size;
  2394. }
  2395. write_unlock_irqrestore(&mft_ni->size_lock, flags);
  2396. record_formatted = true;
  2397. /* Update the mft data attribute record to reflect the new sizes. */
  2398. m = map_mft_record(mft_ni);
  2399. if (IS_ERR(m)) {
  2400. ntfs_error(vol->sb, "Failed to map mft record.");
  2401. err = PTR_ERR(m);
  2402. goto undo_data_init;
  2403. }
  2404. ctx = ntfs_attr_get_search_ctx(mft_ni, m);
  2405. if (unlikely(!ctx)) {
  2406. ntfs_error(vol->sb, "Failed to get search context.");
  2407. err = -ENOMEM;
  2408. unmap_mft_record(mft_ni);
  2409. goto undo_data_init;
  2410. }
  2411. err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
  2412. CASE_SENSITIVE, 0, NULL, 0, ctx);
  2413. if (unlikely(err)) {
  2414. ntfs_error(vol->sb, "Failed to find first attribute extent of "
  2415. "mft data attribute.");
  2416. ntfs_attr_put_search_ctx(ctx);
  2417. unmap_mft_record(mft_ni);
  2418. goto undo_data_init;
  2419. }
  2420. a = ctx->attr;
  2421. read_lock_irqsave(&mft_ni->size_lock, flags);
  2422. a->data.non_resident.initialized_size =
  2423. cpu_to_sle64(mft_ni->initialized_size);
  2424. a->data.non_resident.data_size =
  2425. cpu_to_sle64(i_size_read(vol->mft_ino));
  2426. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  2427. /* Ensure the changes make it to disk. */
  2428. flush_dcache_mft_record_page(ctx->ntfs_ino);
  2429. mark_mft_record_dirty(ctx->ntfs_ino);
  2430. ntfs_attr_put_search_ctx(ctx);
  2431. unmap_mft_record(mft_ni);
  2432. read_lock_irqsave(&mft_ni->size_lock, flags);
  2433. ntfs_debug("Status of mft data after mft record initialization: "
  2434. "allocated_size 0x%llx, data_size 0x%llx, "
  2435. "initialized_size 0x%llx.",
  2436. (long long)mft_ni->allocated_size,
  2437. (long long)i_size_read(vol->mft_ino),
  2438. (long long)mft_ni->initialized_size);
  2439. BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
  2440. BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
  2441. read_unlock_irqrestore(&mft_ni->size_lock, flags);
  2442. mft_rec_already_initialized:
  2443. /*
  2444. * We can finally drop the mft bitmap lock as the mft data attribute
  2445. * has been fully updated. The only disparity left is that the
  2446. * allocated mft record still needs to be marked as in use to match the
  2447. * set bit in the mft bitmap but this is actually not a problem since
  2448. * this mft record is not referenced from anywhere yet and the fact
  2449. * that it is allocated in the mft bitmap means that no-one will try to
  2450. * allocate it either.
  2451. */
  2452. up_write(&vol->mftbmp_lock);
  2453. /*
  2454. * We now have allocated and initialized the mft record. Calculate the
  2455. * index of and the offset within the page cache page the record is in.
  2456. */
  2457. index = bit << vol->mft_record_size_bits >> PAGE_SHIFT;
  2458. ofs = (bit << vol->mft_record_size_bits) & ~PAGE_MASK;
  2459. /* Read, map, and pin the page containing the mft record. */
  2460. page = ntfs_map_page(vol->mft_ino->i_mapping, index);
  2461. if (IS_ERR(page)) {
  2462. ntfs_error(vol->sb, "Failed to map page containing allocated "
  2463. "mft record 0x%llx.", (long long)bit);
  2464. err = PTR_ERR(page);
  2465. goto undo_mftbmp_alloc;
  2466. }
  2467. lock_page(page);
  2468. BUG_ON(!PageUptodate(page));
  2469. ClearPageUptodate(page);
  2470. m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
  2471. /* If we just formatted the mft record no need to do it again. */
  2472. if (!record_formatted) {
  2473. /* Sanity check that the mft record is really not in use. */
  2474. if (ntfs_is_file_record(m->magic) &&
  2475. (m->flags & MFT_RECORD_IN_USE)) {
  2476. ntfs_error(vol->sb, "Mft record 0x%llx was marked "
  2477. "free in mft bitmap but is marked "
  2478. "used itself. Corrupt filesystem. "
  2479. "Unmount and run chkdsk.",
  2480. (long long)bit);
  2481. err = -EIO;
  2482. SetPageUptodate(page);
  2483. unlock_page(page);
  2484. ntfs_unmap_page(page);
  2485. NVolSetErrors(vol);
  2486. goto undo_mftbmp_alloc;
  2487. }
  2488. /*
  2489. * We need to (re-)format the mft record, preserving the
  2490. * sequence number if it is not zero as well as the update
  2491. * sequence number if it is not zero or -1 (0xffff). This
  2492. * means we do not need to care whether or not something went
  2493. * wrong with the previous mft record.
  2494. */
  2495. seq_no = m->sequence_number;
  2496. usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
  2497. err = ntfs_mft_record_layout(vol, bit, m);
  2498. if (unlikely(err)) {
  2499. ntfs_error(vol->sb, "Failed to layout allocated mft "
  2500. "record 0x%llx.", (long long)bit);
  2501. SetPageUptodate(page);
  2502. unlock_page(page);
  2503. ntfs_unmap_page(page);
  2504. goto undo_mftbmp_alloc;
  2505. }
  2506. if (seq_no)
  2507. m->sequence_number = seq_no;
  2508. if (usn && le16_to_cpu(usn) != 0xffff)
  2509. *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
  2510. }
  2511. /* Set the mft record itself in use. */
  2512. m->flags |= MFT_RECORD_IN_USE;
  2513. if (S_ISDIR(mode))
  2514. m->flags |= MFT_RECORD_IS_DIRECTORY;
  2515. flush_dcache_page(page);
  2516. SetPageUptodate(page);
  2517. if (base_ni) {
  2518. MFT_RECORD *m_tmp;
  2519. /*
  2520. * Setup the base mft record in the extent mft record. This
  2521. * completes initialization of the allocated extent mft record
  2522. * and we can simply use it with map_extent_mft_record().
  2523. */
  2524. m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
  2525. base_ni->seq_no);
  2526. /*
  2527. * Allocate an extent inode structure for the new mft record,
  2528. * attach it to the base inode @base_ni and map, pin, and lock
  2529. * its, i.e. the allocated, mft record.
  2530. */
  2531. m_tmp = map_extent_mft_record(base_ni, bit, &ni);
  2532. if (IS_ERR(m_tmp)) {
  2533. ntfs_error(vol->sb, "Failed to map allocated extent "
  2534. "mft record 0x%llx.", (long long)bit);
  2535. err = PTR_ERR(m_tmp);
  2536. /* Set the mft record itself not in use. */
  2537. m->flags &= cpu_to_le16(
  2538. ~le16_to_cpu(MFT_RECORD_IN_USE));
  2539. flush_dcache_page(page);
  2540. /* Make sure the mft record is written out to disk. */
  2541. mark_ntfs_record_dirty(page, ofs);
  2542. unlock_page(page);
  2543. ntfs_unmap_page(page);
  2544. goto undo_mftbmp_alloc;
  2545. }
  2546. BUG_ON(m != m_tmp);
  2547. /*
  2548. * Make sure the allocated mft record is written out to disk.
  2549. * No need to set the inode dirty because the caller is going
  2550. * to do that anyway after finishing with the new extent mft
  2551. * record (e.g. at a minimum a new attribute will be added to
  2552. * the mft record.
  2553. */
  2554. mark_ntfs_record_dirty(page, ofs);
  2555. unlock_page(page);
  2556. /*
  2557. * Need to unmap the page since map_extent_mft_record() mapped
  2558. * it as well so we have it mapped twice at the moment.
  2559. */
  2560. ntfs_unmap_page(page);
  2561. } else {
  2562. /*
  2563. * Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
  2564. * is set to 1 but the mft record->link_count is 0. The caller
  2565. * needs to bear this in mind.
  2566. */
  2567. vi = new_inode(vol->sb);
  2568. if (unlikely(!vi)) {
  2569. err = -ENOMEM;
  2570. /* Set the mft record itself not in use. */
  2571. m->flags &= cpu_to_le16(
  2572. ~le16_to_cpu(MFT_RECORD_IN_USE));
  2573. flush_dcache_page(page);
  2574. /* Make sure the mft record is written out to disk. */
  2575. mark_ntfs_record_dirty(page, ofs);
  2576. unlock_page(page);
  2577. ntfs_unmap_page(page);
  2578. goto undo_mftbmp_alloc;
  2579. }
  2580. vi->i_ino = bit;
  2581. /* The owner and group come from the ntfs volume. */
  2582. vi->i_uid = vol->uid;
  2583. vi->i_gid = vol->gid;
  2584. /* Initialize the ntfs specific part of @vi. */
  2585. ntfs_init_big_inode(vi);
  2586. ni = NTFS_I(vi);
  2587. /*
  2588. * Set the appropriate mode, attribute type, and name. For
  2589. * directories, also setup the index values to the defaults.
  2590. */
  2591. if (S_ISDIR(mode)) {
  2592. vi->i_mode = S_IFDIR | S_IRWXUGO;
  2593. vi->i_mode &= ~vol->dmask;
  2594. NInoSetMstProtected(ni);
  2595. ni->type = AT_INDEX_ALLOCATION;
  2596. ni->name = I30;
  2597. ni->name_len = 4;
  2598. ni->itype.index.block_size = 4096;
  2599. ni->itype.index.block_size_bits = ntfs_ffs(4096) - 1;
  2600. ni->itype.index.collation_rule = COLLATION_FILE_NAME;
  2601. if (vol->cluster_size <= ni->itype.index.block_size) {
  2602. ni->itype.index.vcn_size = vol->cluster_size;
  2603. ni->itype.index.vcn_size_bits =
  2604. vol->cluster_size_bits;
  2605. } else {
  2606. ni->itype.index.vcn_size = vol->sector_size;
  2607. ni->itype.index.vcn_size_bits =
  2608. vol->sector_size_bits;
  2609. }
  2610. } else {
  2611. vi->i_mode = S_IFREG | S_IRWXUGO;
  2612. vi->i_mode &= ~vol->fmask;
  2613. ni->type = AT_DATA;
  2614. ni->name = NULL;
  2615. ni->name_len = 0;
  2616. }
  2617. if (IS_RDONLY(vi))
  2618. vi->i_mode &= ~S_IWUGO;
  2619. /* Set the inode times to the current time. */
  2620. vi->i_atime = vi->i_mtime = vi->i_ctime =
  2621. current_time(vi);
  2622. /*
  2623. * Set the file size to 0, the ntfs inode sizes are set to 0 by
  2624. * the call to ntfs_init_big_inode() below.
  2625. */
  2626. vi->i_size = 0;
  2627. vi->i_blocks = 0;
  2628. /* Set the sequence number. */
  2629. vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
  2630. /*
  2631. * Manually map, pin, and lock the mft record as we already
  2632. * have its page mapped and it is very easy to do.
  2633. */
  2634. atomic_inc(&ni->count);
  2635. mutex_lock(&ni->mrec_lock);
  2636. ni->page = page;
  2637. ni->page_ofs = ofs;
  2638. /*
  2639. * Make sure the allocated mft record is written out to disk.
  2640. * NOTE: We do not set the ntfs inode dirty because this would
  2641. * fail in ntfs_write_inode() because the inode does not have a
  2642. * standard information attribute yet. Also, there is no need
  2643. * to set the inode dirty because the caller is going to do
  2644. * that anyway after finishing with the new mft record (e.g. at
  2645. * a minimum some new attributes will be added to the mft
  2646. * record.
  2647. */
  2648. mark_ntfs_record_dirty(page, ofs);
  2649. unlock_page(page);
  2650. /* Add the inode to the inode hash for the superblock. */
  2651. insert_inode_hash(vi);
  2652. /* Update the default mft allocation position. */
  2653. vol->mft_data_pos = bit + 1;
  2654. }
  2655. /*
  2656. * Return the opened, allocated inode of the allocated mft record as
  2657. * well as the mapped, pinned, and locked mft record.
  2658. */
  2659. ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
  2660. base_ni ? "extent " : "", (long long)bit);
  2661. *mrec = m;
  2662. return ni;
  2663. undo_data_init:
  2664. write_lock_irqsave(&mft_ni->size_lock, flags);
  2665. mft_ni->initialized_size = old_data_initialized;
  2666. i_size_write(vol->mft_ino, old_data_size);
  2667. write_unlock_irqrestore(&mft_ni->size_lock, flags);
  2668. goto undo_mftbmp_alloc_nolock;
  2669. undo_mftbmp_alloc:
  2670. down_write(&vol->mftbmp_lock);
  2671. undo_mftbmp_alloc_nolock:
  2672. if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
  2673. ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
  2674. NVolSetErrors(vol);
  2675. }
  2676. up_write(&vol->mftbmp_lock);
  2677. err_out:
  2678. return ERR_PTR(err);
  2679. max_err_out:
  2680. ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
  2681. "number of inodes (2^32) has already been reached.");
  2682. up_write(&vol->mftbmp_lock);
  2683. return ERR_PTR(-ENOSPC);
  2684. }
  2685. /**
  2686. * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
  2687. * @ni: ntfs inode of the mapped extent mft record to free
  2688. * @m: mapped extent mft record of the ntfs inode @ni
  2689. *
  2690. * Free the mapped extent mft record @m of the extent ntfs inode @ni.
  2691. *
  2692. * Note that this function unmaps the mft record and closes and destroys @ni
  2693. * internally and hence you cannot use either @ni nor @m any more after this
  2694. * function returns success.
  2695. *
  2696. * On success return 0 and on error return -errno. @ni and @m are still valid
  2697. * in this case and have not been freed.
  2698. *
  2699. * For some errors an error message is displayed and the success code 0 is
  2700. * returned and the volume is then left dirty on umount. This makes sense in
  2701. * case we could not rollback the changes that were already done since the
  2702. * caller no longer wants to reference this mft record so it does not matter to
  2703. * the caller if something is wrong with it as long as it is properly detached
  2704. * from the base inode.
  2705. */
  2706. int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
  2707. {
  2708. unsigned long mft_no = ni->mft_no;
  2709. ntfs_volume *vol = ni->vol;
  2710. ntfs_inode *base_ni;
  2711. ntfs_inode **extent_nis;
  2712. int i, err;
  2713. le16 old_seq_no;
  2714. u16 seq_no;
  2715. BUG_ON(NInoAttr(ni));
  2716. BUG_ON(ni->nr_extents != -1);
  2717. mutex_lock(&ni->extent_lock);
  2718. base_ni = ni->ext.base_ntfs_ino;
  2719. mutex_unlock(&ni->extent_lock);
  2720. BUG_ON(base_ni->nr_extents <= 0);
  2721. ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
  2722. mft_no, base_ni->mft_no);
  2723. mutex_lock(&base_ni->extent_lock);
  2724. /* Make sure we are holding the only reference to the extent inode. */
  2725. if (atomic_read(&ni->count) > 2) {
  2726. ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
  2727. "not freeing.", base_ni->mft_no);
  2728. mutex_unlock(&base_ni->extent_lock);
  2729. return -EBUSY;
  2730. }
  2731. /* Dissociate the ntfs inode from the base inode. */
  2732. extent_nis = base_ni->ext.extent_ntfs_inos;
  2733. err = -ENOENT;
  2734. for (i = 0; i < base_ni->nr_extents; i++) {
  2735. if (ni != extent_nis[i])
  2736. continue;
  2737. extent_nis += i;
  2738. base_ni->nr_extents--;
  2739. memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
  2740. sizeof(ntfs_inode*));
  2741. err = 0;
  2742. break;
  2743. }
  2744. mutex_unlock(&base_ni->extent_lock);
  2745. if (unlikely(err)) {
  2746. ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
  2747. "its base inode 0x%lx.", mft_no,
  2748. base_ni->mft_no);
  2749. BUG();
  2750. }
  2751. /*
  2752. * The extent inode is no longer attached to the base inode so no one
  2753. * can get a reference to it any more.
  2754. */
  2755. /* Mark the mft record as not in use. */
  2756. m->flags &= ~MFT_RECORD_IN_USE;
  2757. /* Increment the sequence number, skipping zero, if it is not zero. */
  2758. old_seq_no = m->sequence_number;
  2759. seq_no = le16_to_cpu(old_seq_no);
  2760. if (seq_no == 0xffff)
  2761. seq_no = 1;
  2762. else if (seq_no)
  2763. seq_no++;
  2764. m->sequence_number = cpu_to_le16(seq_no);
  2765. /*
  2766. * Set the ntfs inode dirty and write it out. We do not need to worry
  2767. * about the base inode here since whatever caused the extent mft
  2768. * record to be freed is guaranteed to do it already.
  2769. */
  2770. NInoSetDirty(ni);
  2771. err = write_mft_record(ni, m, 0);
  2772. if (unlikely(err)) {
  2773. ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
  2774. "freeing.", mft_no);
  2775. goto rollback;
  2776. }
  2777. rollback_error:
  2778. /* Unmap and throw away the now freed extent inode. */
  2779. unmap_extent_mft_record(ni);
  2780. ntfs_clear_extent_inode(ni);
  2781. /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
  2782. down_write(&vol->mftbmp_lock);
  2783. err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
  2784. up_write(&vol->mftbmp_lock);
  2785. if (unlikely(err)) {
  2786. /*
  2787. * The extent inode is gone but we failed to deallocate it in
  2788. * the mft bitmap. Just emit a warning and leave the volume
  2789. * dirty on umount.
  2790. */
  2791. ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
  2792. NVolSetErrors(vol);
  2793. }
  2794. return 0;
  2795. rollback:
  2796. /* Rollback what we did... */
  2797. mutex_lock(&base_ni->extent_lock);
  2798. extent_nis = base_ni->ext.extent_ntfs_inos;
  2799. if (!(base_ni->nr_extents & 3)) {
  2800. int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
  2801. extent_nis = kmalloc(new_size, GFP_NOFS);
  2802. if (unlikely(!extent_nis)) {
  2803. ntfs_error(vol->sb, "Failed to allocate internal "
  2804. "buffer during rollback.%s", es);
  2805. mutex_unlock(&base_ni->extent_lock);
  2806. NVolSetErrors(vol);
  2807. goto rollback_error;
  2808. }
  2809. if (base_ni->nr_extents) {
  2810. BUG_ON(!base_ni->ext.extent_ntfs_inos);
  2811. memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
  2812. new_size - 4 * sizeof(ntfs_inode*));
  2813. kfree(base_ni->ext.extent_ntfs_inos);
  2814. }
  2815. base_ni->ext.extent_ntfs_inos = extent_nis;
  2816. }
  2817. m->flags |= MFT_RECORD_IN_USE;
  2818. m->sequence_number = old_seq_no;
  2819. extent_nis[base_ni->nr_extents++] = ni;
  2820. mutex_unlock(&base_ni->extent_lock);
  2821. mark_mft_record_dirty(ni);
  2822. return err;
  2823. }
  2824. #endif /* NTFS_RW */