build.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Copyright (c) International Business Machines Corp., 2006
  4. * Copyright (c) Nokia Corporation, 2007
  5. *
  6. * Author: Artem Bityutskiy (Битюцкий Артём),
  7. * Frank Haverkamp
  8. */
  9. /*
  10. * This file includes UBI initialization and building of UBI devices.
  11. *
  12. * When UBI is initialized, it attaches all the MTD devices specified as the
  13. * module load parameters or the kernel boot parameters. If MTD devices were
  14. * specified, UBI does not attach any MTD device, but it is possible to do
  15. * later using the "UBI control device".
  16. */
  17. #include <linux/err.h>
  18. #include <linux/module.h>
  19. #include <linux/moduleparam.h>
  20. #include <linux/stringify.h>
  21. #include <linux/namei.h>
  22. #include <linux/stat.h>
  23. #include <linux/miscdevice.h>
  24. #include <linux/mtd/partitions.h>
  25. #include <linux/log2.h>
  26. #include <linux/kthread.h>
  27. #include <linux/kernel.h>
  28. #include <linux/of.h>
  29. #include <linux/slab.h>
  30. #include <linux/major.h>
  31. #include "ubi.h"
  32. /* Maximum length of the 'mtd=' parameter */
  33. #define MTD_PARAM_LEN_MAX 64
  34. /* Maximum number of comma-separated items in the 'mtd=' parameter */
  35. #define MTD_PARAM_MAX_COUNT 6
  36. /* Maximum value for the number of bad PEBs per 1024 PEBs */
  37. #define MAX_MTD_UBI_BEB_LIMIT 768
  38. #ifdef CONFIG_MTD_UBI_MODULE
  39. #define ubi_is_module() 1
  40. #else
  41. #define ubi_is_module() 0
  42. #endif
  43. /**
  44. * struct mtd_dev_param - MTD device parameter description data structure.
  45. * @name: MTD character device node path, MTD device name, or MTD device number
  46. * string
  47. * @ubi_num: UBI number
  48. * @vid_hdr_offs: VID header offset
  49. * @max_beb_per1024: maximum expected number of bad PEBs per 1024 PEBs
  50. * @enable_fm: enable fastmap when value is non-zero
  51. * @need_resv_pool: reserve pool->max_size pebs when value is none-zero
  52. */
  53. struct mtd_dev_param {
  54. char name[MTD_PARAM_LEN_MAX];
  55. int ubi_num;
  56. int vid_hdr_offs;
  57. int max_beb_per1024;
  58. int enable_fm;
  59. int need_resv_pool;
  60. };
  61. /* Numbers of elements set in the @mtd_dev_param array */
  62. static int mtd_devs;
  63. /* MTD devices specification parameters */
  64. static struct mtd_dev_param mtd_dev_param[UBI_MAX_DEVICES];
  65. #ifdef CONFIG_MTD_UBI_FASTMAP
  66. /* UBI module parameter to enable fastmap automatically on non-fastmap images */
  67. static bool fm_autoconvert;
  68. static bool fm_debug;
  69. #endif
  70. /* Slab cache for wear-leveling entries */
  71. struct kmem_cache *ubi_wl_entry_slab;
  72. /* UBI control character device */
  73. static struct miscdevice ubi_ctrl_cdev = {
  74. .minor = MISC_DYNAMIC_MINOR,
  75. .name = "ubi_ctrl",
  76. .fops = &ubi_ctrl_cdev_operations,
  77. };
  78. /* All UBI devices in system */
  79. static struct ubi_device *ubi_devices[UBI_MAX_DEVICES];
  80. /* Serializes UBI devices creations and removals */
  81. DEFINE_MUTEX(ubi_devices_mutex);
  82. /* Protects @ubi_devices, @ubi->ref_count and @ubi->is_dead */
  83. static DEFINE_SPINLOCK(ubi_devices_lock);
  84. /* "Show" method for files in '/<sysfs>/class/ubi/' */
  85. /* UBI version attribute ('/<sysfs>/class/ubi/version') */
  86. static ssize_t version_show(const struct class *class, const struct class_attribute *attr,
  87. char *buf)
  88. {
  89. return sprintf(buf, "%d\n", UBI_VERSION);
  90. }
  91. static CLASS_ATTR_RO(version);
  92. static struct attribute *ubi_class_attrs[] = {
  93. &class_attr_version.attr,
  94. NULL,
  95. };
  96. ATTRIBUTE_GROUPS(ubi_class);
  97. /* Root UBI "class" object (corresponds to '/<sysfs>/class/ubi/') */
  98. const struct class ubi_class = {
  99. .name = UBI_NAME_STR,
  100. .class_groups = ubi_class_groups,
  101. };
  102. static ssize_t dev_attribute_show(struct device *dev,
  103. struct device_attribute *attr, char *buf);
  104. /* UBI device attributes (correspond to files in '/<sysfs>/class/ubi/ubiX') */
  105. static struct device_attribute dev_eraseblock_size =
  106. __ATTR(eraseblock_size, S_IRUGO, dev_attribute_show, NULL);
  107. static struct device_attribute dev_avail_eraseblocks =
  108. __ATTR(avail_eraseblocks, S_IRUGO, dev_attribute_show, NULL);
  109. static struct device_attribute dev_total_eraseblocks =
  110. __ATTR(total_eraseblocks, S_IRUGO, dev_attribute_show, NULL);
  111. static struct device_attribute dev_volumes_count =
  112. __ATTR(volumes_count, S_IRUGO, dev_attribute_show, NULL);
  113. static struct device_attribute dev_max_ec =
  114. __ATTR(max_ec, S_IRUGO, dev_attribute_show, NULL);
  115. static struct device_attribute dev_reserved_for_bad =
  116. __ATTR(reserved_for_bad, S_IRUGO, dev_attribute_show, NULL);
  117. static struct device_attribute dev_bad_peb_count =
  118. __ATTR(bad_peb_count, S_IRUGO, dev_attribute_show, NULL);
  119. static struct device_attribute dev_max_vol_count =
  120. __ATTR(max_vol_count, S_IRUGO, dev_attribute_show, NULL);
  121. static struct device_attribute dev_min_io_size =
  122. __ATTR(min_io_size, S_IRUGO, dev_attribute_show, NULL);
  123. static struct device_attribute dev_bgt_enabled =
  124. __ATTR(bgt_enabled, S_IRUGO, dev_attribute_show, NULL);
  125. static struct device_attribute dev_mtd_num =
  126. __ATTR(mtd_num, S_IRUGO, dev_attribute_show, NULL);
  127. static struct device_attribute dev_ro_mode =
  128. __ATTR(ro_mode, S_IRUGO, dev_attribute_show, NULL);
  129. /**
  130. * ubi_volume_notify - send a volume change notification.
  131. * @ubi: UBI device description object
  132. * @vol: volume description object of the changed volume
  133. * @ntype: notification type to send (%UBI_VOLUME_ADDED, etc)
  134. *
  135. * This is a helper function which notifies all subscribers about a volume
  136. * change event (creation, removal, re-sizing, re-naming, updating). Returns
  137. * zero in case of success and a negative error code in case of failure.
  138. */
  139. int ubi_volume_notify(struct ubi_device *ubi, struct ubi_volume *vol, int ntype)
  140. {
  141. int ret;
  142. struct ubi_notification nt;
  143. ubi_do_get_device_info(ubi, &nt.di);
  144. ubi_do_get_volume_info(ubi, vol, &nt.vi);
  145. switch (ntype) {
  146. case UBI_VOLUME_ADDED:
  147. case UBI_VOLUME_REMOVED:
  148. case UBI_VOLUME_RESIZED:
  149. case UBI_VOLUME_RENAMED:
  150. ret = ubi_update_fastmap(ubi);
  151. if (ret)
  152. ubi_msg(ubi, "Unable to write a new fastmap: %i", ret);
  153. }
  154. return blocking_notifier_call_chain(&ubi_notifiers, ntype, &nt);
  155. }
  156. /**
  157. * ubi_notify_all - send a notification to all volumes.
  158. * @ubi: UBI device description object
  159. * @ntype: notification type to send (%UBI_VOLUME_ADDED, etc)
  160. * @nb: the notifier to call
  161. *
  162. * This function walks all volumes of UBI device @ubi and sends the @ntype
  163. * notification for each volume. If @nb is %NULL, then all registered notifiers
  164. * are called, otherwise only the @nb notifier is called. Returns the number of
  165. * sent notifications.
  166. */
  167. int ubi_notify_all(struct ubi_device *ubi, int ntype, struct notifier_block *nb)
  168. {
  169. struct ubi_notification nt;
  170. int i, count = 0;
  171. ubi_do_get_device_info(ubi, &nt.di);
  172. mutex_lock(&ubi->device_mutex);
  173. for (i = 0; i < ubi->vtbl_slots; i++) {
  174. /*
  175. * Since the @ubi->device is locked, and we are not going to
  176. * change @ubi->volumes, we do not have to lock
  177. * @ubi->volumes_lock.
  178. */
  179. if (!ubi->volumes[i])
  180. continue;
  181. ubi_do_get_volume_info(ubi, ubi->volumes[i], &nt.vi);
  182. if (nb)
  183. nb->notifier_call(nb, ntype, &nt);
  184. else
  185. blocking_notifier_call_chain(&ubi_notifiers, ntype,
  186. &nt);
  187. count += 1;
  188. }
  189. mutex_unlock(&ubi->device_mutex);
  190. return count;
  191. }
  192. /**
  193. * ubi_enumerate_volumes - send "add" notification for all existing volumes.
  194. * @nb: the notifier to call
  195. *
  196. * This function walks all UBI devices and volumes and sends the
  197. * %UBI_VOLUME_ADDED notification for each volume. If @nb is %NULL, then all
  198. * registered notifiers are called, otherwise only the @nb notifier is called.
  199. * Returns the number of sent notifications.
  200. */
  201. int ubi_enumerate_volumes(struct notifier_block *nb)
  202. {
  203. int i, count = 0;
  204. /*
  205. * Since the @ubi_devices_mutex is locked, and we are not going to
  206. * change @ubi_devices, we do not have to lock @ubi_devices_lock.
  207. */
  208. for (i = 0; i < UBI_MAX_DEVICES; i++) {
  209. struct ubi_device *ubi = ubi_devices[i];
  210. if (!ubi)
  211. continue;
  212. count += ubi_notify_all(ubi, UBI_VOLUME_ADDED, nb);
  213. }
  214. return count;
  215. }
  216. /**
  217. * ubi_get_device - get UBI device.
  218. * @ubi_num: UBI device number
  219. *
  220. * This function returns UBI device description object for UBI device number
  221. * @ubi_num, or %NULL if the device does not exist. This function increases the
  222. * device reference count to prevent removal of the device. In other words, the
  223. * device cannot be removed if its reference count is not zero.
  224. */
  225. struct ubi_device *ubi_get_device(int ubi_num)
  226. {
  227. struct ubi_device *ubi;
  228. spin_lock(&ubi_devices_lock);
  229. ubi = ubi_devices[ubi_num];
  230. if (ubi && ubi->is_dead)
  231. ubi = NULL;
  232. if (ubi) {
  233. ubi_assert(ubi->ref_count >= 0);
  234. ubi->ref_count += 1;
  235. get_device(&ubi->dev);
  236. }
  237. spin_unlock(&ubi_devices_lock);
  238. return ubi;
  239. }
  240. /**
  241. * ubi_put_device - drop an UBI device reference.
  242. * @ubi: UBI device description object
  243. */
  244. void ubi_put_device(struct ubi_device *ubi)
  245. {
  246. spin_lock(&ubi_devices_lock);
  247. ubi->ref_count -= 1;
  248. put_device(&ubi->dev);
  249. spin_unlock(&ubi_devices_lock);
  250. }
  251. /**
  252. * ubi_get_by_major - get UBI device by character device major number.
  253. * @major: major number
  254. *
  255. * This function is similar to 'ubi_get_device()', but it searches the device
  256. * by its major number.
  257. */
  258. struct ubi_device *ubi_get_by_major(int major)
  259. {
  260. int i;
  261. struct ubi_device *ubi;
  262. spin_lock(&ubi_devices_lock);
  263. for (i = 0; i < UBI_MAX_DEVICES; i++) {
  264. ubi = ubi_devices[i];
  265. if (ubi && !ubi->is_dead && MAJOR(ubi->cdev.dev) == major) {
  266. ubi_assert(ubi->ref_count >= 0);
  267. ubi->ref_count += 1;
  268. get_device(&ubi->dev);
  269. spin_unlock(&ubi_devices_lock);
  270. return ubi;
  271. }
  272. }
  273. spin_unlock(&ubi_devices_lock);
  274. return NULL;
  275. }
  276. /**
  277. * ubi_major2num - get UBI device number by character device major number.
  278. * @major: major number
  279. *
  280. * This function searches UBI device number object by its major number. If UBI
  281. * device was not found, this function returns -ENODEV, otherwise the UBI device
  282. * number is returned.
  283. */
  284. int ubi_major2num(int major)
  285. {
  286. int i, ubi_num = -ENODEV;
  287. spin_lock(&ubi_devices_lock);
  288. for (i = 0; i < UBI_MAX_DEVICES; i++) {
  289. struct ubi_device *ubi = ubi_devices[i];
  290. if (ubi && !ubi->is_dead && MAJOR(ubi->cdev.dev) == major) {
  291. ubi_num = ubi->ubi_num;
  292. break;
  293. }
  294. }
  295. spin_unlock(&ubi_devices_lock);
  296. return ubi_num;
  297. }
  298. /* "Show" method for files in '/<sysfs>/class/ubi/ubiX/' */
  299. static ssize_t dev_attribute_show(struct device *dev,
  300. struct device_attribute *attr, char *buf)
  301. {
  302. ssize_t ret;
  303. struct ubi_device *ubi;
  304. /*
  305. * The below code looks weird, but it actually makes sense. We get the
  306. * UBI device reference from the contained 'struct ubi_device'. But it
  307. * is unclear if the device was removed or not yet. Indeed, if the
  308. * device was removed before we increased its reference count,
  309. * 'ubi_get_device()' will return -ENODEV and we fail.
  310. *
  311. * Remember, 'struct ubi_device' is freed in the release function, so
  312. * we still can use 'ubi->ubi_num'.
  313. */
  314. ubi = container_of(dev, struct ubi_device, dev);
  315. if (attr == &dev_eraseblock_size)
  316. ret = sprintf(buf, "%d\n", ubi->leb_size);
  317. else if (attr == &dev_avail_eraseblocks)
  318. ret = sprintf(buf, "%d\n", ubi->avail_pebs);
  319. else if (attr == &dev_total_eraseblocks)
  320. ret = sprintf(buf, "%d\n", ubi->good_peb_count);
  321. else if (attr == &dev_volumes_count)
  322. ret = sprintf(buf, "%d\n", ubi->vol_count - UBI_INT_VOL_COUNT);
  323. else if (attr == &dev_max_ec)
  324. ret = sprintf(buf, "%d\n", ubi->max_ec);
  325. else if (attr == &dev_reserved_for_bad)
  326. ret = sprintf(buf, "%d\n", ubi->beb_rsvd_pebs);
  327. else if (attr == &dev_bad_peb_count)
  328. ret = sprintf(buf, "%d\n", ubi->bad_peb_count);
  329. else if (attr == &dev_max_vol_count)
  330. ret = sprintf(buf, "%d\n", ubi->vtbl_slots);
  331. else if (attr == &dev_min_io_size)
  332. ret = sprintf(buf, "%d\n", ubi->min_io_size);
  333. else if (attr == &dev_bgt_enabled)
  334. ret = sprintf(buf, "%d\n", ubi->thread_enabled);
  335. else if (attr == &dev_mtd_num)
  336. ret = sprintf(buf, "%d\n", ubi->mtd->index);
  337. else if (attr == &dev_ro_mode)
  338. ret = sprintf(buf, "%d\n", ubi->ro_mode);
  339. else
  340. ret = -EINVAL;
  341. return ret;
  342. }
  343. static struct attribute *ubi_dev_attrs[] = {
  344. &dev_eraseblock_size.attr,
  345. &dev_avail_eraseblocks.attr,
  346. &dev_total_eraseblocks.attr,
  347. &dev_volumes_count.attr,
  348. &dev_max_ec.attr,
  349. &dev_reserved_for_bad.attr,
  350. &dev_bad_peb_count.attr,
  351. &dev_max_vol_count.attr,
  352. &dev_min_io_size.attr,
  353. &dev_bgt_enabled.attr,
  354. &dev_mtd_num.attr,
  355. &dev_ro_mode.attr,
  356. NULL
  357. };
  358. ATTRIBUTE_GROUPS(ubi_dev);
  359. static void dev_release(struct device *dev)
  360. {
  361. struct ubi_device *ubi = container_of(dev, struct ubi_device, dev);
  362. kfree(ubi);
  363. }
  364. /**
  365. * kill_volumes - destroy all user volumes.
  366. * @ubi: UBI device description object
  367. */
  368. static void kill_volumes(struct ubi_device *ubi)
  369. {
  370. int i;
  371. for (i = 0; i < ubi->vtbl_slots; i++)
  372. if (ubi->volumes[i])
  373. ubi_free_volume(ubi, ubi->volumes[i]);
  374. }
  375. /**
  376. * uif_init - initialize user interfaces for an UBI device.
  377. * @ubi: UBI device description object
  378. *
  379. * This function initializes various user interfaces for an UBI device. If the
  380. * initialization fails at an early stage, this function frees all the
  381. * resources it allocated, returns an error.
  382. *
  383. * This function returns zero in case of success and a negative error code in
  384. * case of failure.
  385. */
  386. static int uif_init(struct ubi_device *ubi)
  387. {
  388. int i, err;
  389. dev_t dev;
  390. sprintf(ubi->ubi_name, UBI_NAME_STR "%d", ubi->ubi_num);
  391. /*
  392. * Major numbers for the UBI character devices are allocated
  393. * dynamically. Major numbers of volume character devices are
  394. * equivalent to ones of the corresponding UBI character device. Minor
  395. * numbers of UBI character devices are 0, while minor numbers of
  396. * volume character devices start from 1. Thus, we allocate one major
  397. * number and ubi->vtbl_slots + 1 minor numbers.
  398. */
  399. err = alloc_chrdev_region(&dev, 0, ubi->vtbl_slots + 1, ubi->ubi_name);
  400. if (err) {
  401. ubi_err(ubi, "cannot register UBI character devices");
  402. return err;
  403. }
  404. ubi->dev.devt = dev;
  405. ubi_assert(MINOR(dev) == 0);
  406. cdev_init(&ubi->cdev, &ubi_cdev_operations);
  407. dbg_gen("%s major is %u", ubi->ubi_name, MAJOR(dev));
  408. ubi->cdev.owner = THIS_MODULE;
  409. dev_set_name(&ubi->dev, UBI_NAME_STR "%d", ubi->ubi_num);
  410. err = cdev_device_add(&ubi->cdev, &ubi->dev);
  411. if (err)
  412. goto out_unreg;
  413. for (i = 0; i < ubi->vtbl_slots; i++)
  414. if (ubi->volumes[i]) {
  415. err = ubi_add_volume(ubi, ubi->volumes[i]);
  416. if (err) {
  417. ubi_err(ubi, "cannot add volume %d", i);
  418. ubi->volumes[i] = NULL;
  419. goto out_volumes;
  420. }
  421. }
  422. return 0;
  423. out_volumes:
  424. kill_volumes(ubi);
  425. cdev_device_del(&ubi->cdev, &ubi->dev);
  426. out_unreg:
  427. unregister_chrdev_region(ubi->cdev.dev, ubi->vtbl_slots + 1);
  428. ubi_err(ubi, "cannot initialize UBI %s, error %d",
  429. ubi->ubi_name, err);
  430. return err;
  431. }
  432. /**
  433. * uif_close - close user interfaces for an UBI device.
  434. * @ubi: UBI device description object
  435. *
  436. * Note, since this function un-registers UBI volume device objects (@vol->dev),
  437. * the memory allocated voe the volumes is freed as well (in the release
  438. * function).
  439. */
  440. static void uif_close(struct ubi_device *ubi)
  441. {
  442. kill_volumes(ubi);
  443. cdev_device_del(&ubi->cdev, &ubi->dev);
  444. unregister_chrdev_region(ubi->cdev.dev, ubi->vtbl_slots + 1);
  445. }
  446. /**
  447. * ubi_free_volumes_from - free volumes from specific index.
  448. * @ubi: UBI device description object
  449. * @from: the start index used for volume free.
  450. */
  451. static void ubi_free_volumes_from(struct ubi_device *ubi, int from)
  452. {
  453. int i;
  454. for (i = from; i < ubi->vtbl_slots + UBI_INT_VOL_COUNT; i++) {
  455. if (!ubi->volumes[i] || ubi->volumes[i]->is_dead)
  456. continue;
  457. ubi_eba_replace_table(ubi->volumes[i], NULL);
  458. ubi_fastmap_destroy_checkmap(ubi->volumes[i]);
  459. kfree(ubi->volumes[i]);
  460. ubi->volumes[i] = NULL;
  461. }
  462. }
  463. /**
  464. * ubi_free_all_volumes - free all volumes.
  465. * @ubi: UBI device description object
  466. */
  467. void ubi_free_all_volumes(struct ubi_device *ubi)
  468. {
  469. ubi_free_volumes_from(ubi, 0);
  470. }
  471. /**
  472. * ubi_free_internal_volumes - free internal volumes.
  473. * @ubi: UBI device description object
  474. */
  475. void ubi_free_internal_volumes(struct ubi_device *ubi)
  476. {
  477. ubi_free_volumes_from(ubi, ubi->vtbl_slots);
  478. }
  479. static int get_bad_peb_limit(const struct ubi_device *ubi, int max_beb_per1024)
  480. {
  481. int limit, device_pebs;
  482. uint64_t device_size;
  483. if (!max_beb_per1024) {
  484. /*
  485. * Since max_beb_per1024 has not been set by the user in either
  486. * the cmdline or Kconfig, use mtd_max_bad_blocks to set the
  487. * limit if it is supported by the device.
  488. */
  489. limit = mtd_max_bad_blocks(ubi->mtd, 0, ubi->mtd->size);
  490. if (limit < 0)
  491. return 0;
  492. return limit;
  493. }
  494. /*
  495. * Here we are using size of the entire flash chip and
  496. * not just the MTD partition size because the maximum
  497. * number of bad eraseblocks is a percentage of the
  498. * whole device and bad eraseblocks are not fairly
  499. * distributed over the flash chip. So the worst case
  500. * is that all the bad eraseblocks of the chip are in
  501. * the MTD partition we are attaching (ubi->mtd).
  502. */
  503. device_size = mtd_get_device_size(ubi->mtd);
  504. device_pebs = mtd_div_by_eb(device_size, ubi->mtd);
  505. limit = mult_frac(device_pebs, max_beb_per1024, 1024);
  506. /* Round it up */
  507. if (mult_frac(limit, 1024, max_beb_per1024) < device_pebs)
  508. limit += 1;
  509. return limit;
  510. }
  511. /**
  512. * io_init - initialize I/O sub-system for a given UBI device.
  513. * @ubi: UBI device description object
  514. * @max_beb_per1024: maximum expected number of bad PEB per 1024 PEBs
  515. *
  516. * If @ubi->vid_hdr_offset or @ubi->leb_start is zero, default offsets are
  517. * assumed:
  518. * o EC header is always at offset zero - this cannot be changed;
  519. * o VID header starts just after the EC header at the closest address
  520. * aligned to @io->hdrs_min_io_size;
  521. * o data starts just after the VID header at the closest address aligned to
  522. * @io->min_io_size
  523. *
  524. * This function returns zero in case of success and a negative error code in
  525. * case of failure.
  526. */
  527. static int io_init(struct ubi_device *ubi, int max_beb_per1024)
  528. {
  529. dbg_gen("sizeof(struct ubi_ainf_peb) %zu", sizeof(struct ubi_ainf_peb));
  530. dbg_gen("sizeof(struct ubi_wl_entry) %zu", sizeof(struct ubi_wl_entry));
  531. if (ubi->mtd->numeraseregions != 0) {
  532. /*
  533. * Some flashes have several erase regions. Different regions
  534. * may have different eraseblock size and other
  535. * characteristics. It looks like mostly multi-region flashes
  536. * have one "main" region and one or more small regions to
  537. * store boot loader code or boot parameters or whatever. I
  538. * guess we should just pick the largest region. But this is
  539. * not implemented.
  540. */
  541. ubi_err(ubi, "multiple regions, not implemented");
  542. return -EINVAL;
  543. }
  544. if (ubi->vid_hdr_offset < 0)
  545. return -EINVAL;
  546. /*
  547. * Note, in this implementation we support MTD devices with 0x7FFFFFFF
  548. * physical eraseblocks maximum.
  549. */
  550. ubi->peb_size = ubi->mtd->erasesize;
  551. ubi->peb_count = mtd_div_by_eb(ubi->mtd->size, ubi->mtd);
  552. ubi->flash_size = ubi->mtd->size;
  553. if (mtd_can_have_bb(ubi->mtd)) {
  554. ubi->bad_allowed = 1;
  555. ubi->bad_peb_limit = get_bad_peb_limit(ubi, max_beb_per1024);
  556. }
  557. if (ubi->mtd->type == MTD_NORFLASH)
  558. ubi->nor_flash = 1;
  559. ubi->min_io_size = ubi->mtd->writesize;
  560. ubi->hdrs_min_io_size = ubi->mtd->writesize >> ubi->mtd->subpage_sft;
  561. /*
  562. * Make sure minimal I/O unit is power of 2. Note, there is no
  563. * fundamental reason for this assumption. It is just an optimization
  564. * which allows us to avoid costly division operations.
  565. */
  566. if (!is_power_of_2(ubi->min_io_size)) {
  567. ubi_err(ubi, "min. I/O unit (%d) is not power of 2",
  568. ubi->min_io_size);
  569. return -EINVAL;
  570. }
  571. ubi_assert(ubi->hdrs_min_io_size > 0);
  572. ubi_assert(ubi->hdrs_min_io_size <= ubi->min_io_size);
  573. ubi_assert(ubi->min_io_size % ubi->hdrs_min_io_size == 0);
  574. ubi->max_write_size = ubi->mtd->writebufsize;
  575. /*
  576. * Maximum write size has to be greater or equivalent to min. I/O
  577. * size, and be multiple of min. I/O size.
  578. */
  579. if (ubi->max_write_size < ubi->min_io_size ||
  580. ubi->max_write_size % ubi->min_io_size ||
  581. !is_power_of_2(ubi->max_write_size)) {
  582. ubi_err(ubi, "bad write buffer size %d for %d min. I/O unit",
  583. ubi->max_write_size, ubi->min_io_size);
  584. return -EINVAL;
  585. }
  586. /* Calculate default aligned sizes of EC and VID headers */
  587. ubi->ec_hdr_alsize = ALIGN(UBI_EC_HDR_SIZE, ubi->hdrs_min_io_size);
  588. ubi->vid_hdr_alsize = ALIGN(UBI_VID_HDR_SIZE, ubi->hdrs_min_io_size);
  589. dbg_gen("min_io_size %d", ubi->min_io_size);
  590. dbg_gen("max_write_size %d", ubi->max_write_size);
  591. dbg_gen("hdrs_min_io_size %d", ubi->hdrs_min_io_size);
  592. dbg_gen("ec_hdr_alsize %d", ubi->ec_hdr_alsize);
  593. dbg_gen("vid_hdr_alsize %d", ubi->vid_hdr_alsize);
  594. if (ubi->vid_hdr_offset == 0)
  595. /* Default offset */
  596. ubi->vid_hdr_offset = ubi->vid_hdr_aloffset =
  597. ubi->ec_hdr_alsize;
  598. else {
  599. ubi->vid_hdr_aloffset = ubi->vid_hdr_offset &
  600. ~(ubi->hdrs_min_io_size - 1);
  601. ubi->vid_hdr_shift = ubi->vid_hdr_offset -
  602. ubi->vid_hdr_aloffset;
  603. }
  604. /*
  605. * Memory allocation for VID header is ubi->vid_hdr_alsize
  606. * which is described in comments in io.c.
  607. * Make sure VID header shift + UBI_VID_HDR_SIZE not exceeds
  608. * ubi->vid_hdr_alsize, so that all vid header operations
  609. * won't access memory out of bounds.
  610. */
  611. if ((ubi->vid_hdr_shift + UBI_VID_HDR_SIZE) > ubi->vid_hdr_alsize) {
  612. ubi_err(ubi, "Invalid VID header offset %d, VID header shift(%d)"
  613. " + VID header size(%zu) > VID header aligned size(%d).",
  614. ubi->vid_hdr_offset, ubi->vid_hdr_shift,
  615. UBI_VID_HDR_SIZE, ubi->vid_hdr_alsize);
  616. return -EINVAL;
  617. }
  618. /* Similar for the data offset */
  619. ubi->leb_start = ubi->vid_hdr_offset + UBI_VID_HDR_SIZE;
  620. ubi->leb_start = ALIGN(ubi->leb_start, ubi->min_io_size);
  621. dbg_gen("vid_hdr_offset %d", ubi->vid_hdr_offset);
  622. dbg_gen("vid_hdr_aloffset %d", ubi->vid_hdr_aloffset);
  623. dbg_gen("vid_hdr_shift %d", ubi->vid_hdr_shift);
  624. dbg_gen("leb_start %d", ubi->leb_start);
  625. /* The shift must be aligned to 32-bit boundary */
  626. if (ubi->vid_hdr_shift % 4) {
  627. ubi_err(ubi, "unaligned VID header shift %d",
  628. ubi->vid_hdr_shift);
  629. return -EINVAL;
  630. }
  631. /* Check sanity */
  632. if (ubi->vid_hdr_offset < UBI_EC_HDR_SIZE ||
  633. ubi->leb_start < ubi->vid_hdr_offset + UBI_VID_HDR_SIZE ||
  634. ubi->leb_start > ubi->peb_size - UBI_VID_HDR_SIZE ||
  635. ubi->leb_start & (ubi->min_io_size - 1)) {
  636. ubi_err(ubi, "bad VID header (%d) or data offsets (%d)",
  637. ubi->vid_hdr_offset, ubi->leb_start);
  638. return -EINVAL;
  639. }
  640. /*
  641. * Set maximum amount of physical erroneous eraseblocks to be 10%.
  642. * Erroneous PEB are those which have read errors.
  643. */
  644. ubi->max_erroneous = ubi->peb_count / 10;
  645. if (ubi->max_erroneous < 16)
  646. ubi->max_erroneous = 16;
  647. dbg_gen("max_erroneous %d", ubi->max_erroneous);
  648. /*
  649. * It may happen that EC and VID headers are situated in one minimal
  650. * I/O unit. In this case we can only accept this UBI image in
  651. * read-only mode.
  652. */
  653. if (ubi->vid_hdr_offset + UBI_VID_HDR_SIZE <= ubi->hdrs_min_io_size) {
  654. ubi_warn(ubi, "EC and VID headers are in the same minimal I/O unit, switch to read-only mode");
  655. ubi->ro_mode = 1;
  656. }
  657. ubi->leb_size = ubi->peb_size - ubi->leb_start;
  658. if (!(ubi->mtd->flags & MTD_WRITEABLE)) {
  659. ubi_msg(ubi, "MTD device %d is write-protected, attach in read-only mode",
  660. ubi->mtd->index);
  661. ubi->ro_mode = 1;
  662. }
  663. /*
  664. * Note, ideally, we have to initialize @ubi->bad_peb_count here. But
  665. * unfortunately, MTD does not provide this information. We should loop
  666. * over all physical eraseblocks and invoke mtd->block_is_bad() for
  667. * each physical eraseblock. So, we leave @ubi->bad_peb_count
  668. * uninitialized so far.
  669. */
  670. return 0;
  671. }
  672. /**
  673. * autoresize - re-size the volume which has the "auto-resize" flag set.
  674. * @ubi: UBI device description object
  675. * @vol_id: ID of the volume to re-size
  676. *
  677. * This function re-sizes the volume marked by the %UBI_VTBL_AUTORESIZE_FLG in
  678. * the volume table to the largest possible size. See comments in ubi-header.h
  679. * for more description of the flag. Returns zero in case of success and a
  680. * negative error code in case of failure.
  681. */
  682. static int autoresize(struct ubi_device *ubi, int vol_id)
  683. {
  684. struct ubi_volume_desc desc;
  685. struct ubi_volume *vol = ubi->volumes[vol_id];
  686. int err, old_reserved_pebs = vol->reserved_pebs;
  687. if (ubi->ro_mode) {
  688. ubi_warn(ubi, "skip auto-resize because of R/O mode");
  689. return 0;
  690. }
  691. /*
  692. * Clear the auto-resize flag in the volume in-memory copy of the
  693. * volume table, and 'ubi_resize_volume()' will propagate this change
  694. * to the flash.
  695. */
  696. ubi->vtbl[vol_id].flags &= ~UBI_VTBL_AUTORESIZE_FLG;
  697. if (ubi->avail_pebs == 0) {
  698. struct ubi_vtbl_record vtbl_rec;
  699. /*
  700. * No available PEBs to re-size the volume, clear the flag on
  701. * flash and exit.
  702. */
  703. vtbl_rec = ubi->vtbl[vol_id];
  704. err = ubi_change_vtbl_record(ubi, vol_id, &vtbl_rec);
  705. if (err)
  706. ubi_err(ubi, "cannot clean auto-resize flag for volume %d",
  707. vol_id);
  708. } else {
  709. desc.vol = vol;
  710. err = ubi_resize_volume(&desc,
  711. old_reserved_pebs + ubi->avail_pebs);
  712. if (err)
  713. ubi_err(ubi, "cannot auto-resize volume %d",
  714. vol_id);
  715. }
  716. if (err)
  717. return err;
  718. ubi_msg(ubi, "volume %d (\"%s\") re-sized from %d to %d LEBs",
  719. vol_id, vol->name, old_reserved_pebs, vol->reserved_pebs);
  720. return 0;
  721. }
  722. /**
  723. * ubi_attach_mtd_dev - attach an MTD device.
  724. * @mtd: MTD device description object
  725. * @ubi_num: number to assign to the new UBI device
  726. * @vid_hdr_offset: VID header offset
  727. * @max_beb_per1024: maximum expected number of bad PEB per 1024 PEBs
  728. * @disable_fm: whether disable fastmap
  729. * @need_resv_pool: whether reserve pebs to fill fm_pool
  730. *
  731. * This function attaches MTD device @mtd_dev to UBI and assign @ubi_num number
  732. * to the newly created UBI device, unless @ubi_num is %UBI_DEV_NUM_AUTO, in
  733. * which case this function finds a vacant device number and assigns it
  734. * automatically. Returns the new UBI device number in case of success and a
  735. * negative error code in case of failure.
  736. *
  737. * If @disable_fm is true, ubi doesn't create new fastmap even the module param
  738. * 'fm_autoconvert' is set, and existed old fastmap will be destroyed after
  739. * doing full scanning.
  740. *
  741. * Note, the invocations of this function has to be serialized by the
  742. * @ubi_devices_mutex.
  743. */
  744. int ubi_attach_mtd_dev(struct mtd_info *mtd, int ubi_num,
  745. int vid_hdr_offset, int max_beb_per1024, bool disable_fm,
  746. bool need_resv_pool)
  747. {
  748. struct ubi_device *ubi;
  749. int i, err;
  750. if (max_beb_per1024 < 0 || max_beb_per1024 > MAX_MTD_UBI_BEB_LIMIT)
  751. return -EINVAL;
  752. if (!max_beb_per1024)
  753. max_beb_per1024 = CONFIG_MTD_UBI_BEB_LIMIT;
  754. /*
  755. * Check if we already have the same MTD device attached.
  756. *
  757. * Note, this function assumes that UBI devices creations and deletions
  758. * are serialized, so it does not take the &ubi_devices_lock.
  759. */
  760. for (i = 0; i < UBI_MAX_DEVICES; i++) {
  761. ubi = ubi_devices[i];
  762. if (ubi && mtd->index == ubi->mtd->index) {
  763. pr_err("ubi: mtd%d is already attached to ubi%d\n",
  764. mtd->index, i);
  765. return -EEXIST;
  766. }
  767. }
  768. /*
  769. * Make sure this MTD device is not emulated on top of an UBI volume
  770. * already. Well, generally this recursion works fine, but there are
  771. * different problems like the UBI module takes a reference to itself
  772. * by attaching (and thus, opening) the emulated MTD device. This
  773. * results in inability to unload the module. And in general it makes
  774. * no sense to attach emulated MTD devices, so we prohibit this.
  775. */
  776. if (mtd->type == MTD_UBIVOLUME) {
  777. pr_err("ubi: refuse attaching mtd%d - it is already emulated on top of UBI\n",
  778. mtd->index);
  779. return -EINVAL;
  780. }
  781. /*
  782. * Both UBI and UBIFS have been designed for SLC NAND and NOR flashes.
  783. * MLC NAND is different and needs special care, otherwise UBI or UBIFS
  784. * will die soon and you will lose all your data.
  785. * Relax this rule if the partition we're attaching to operates in SLC
  786. * mode.
  787. */
  788. if (mtd->type == MTD_MLCNANDFLASH &&
  789. !(mtd->flags & MTD_SLC_ON_MLC_EMULATION)) {
  790. pr_err("ubi: refuse attaching mtd%d - MLC NAND is not supported\n",
  791. mtd->index);
  792. return -EINVAL;
  793. }
  794. /* UBI cannot work on flashes with zero erasesize. */
  795. if (!mtd->erasesize) {
  796. pr_err("ubi: refuse attaching mtd%d - zero erasesize flash is not supported\n",
  797. mtd->index);
  798. return -EINVAL;
  799. }
  800. if (ubi_num == UBI_DEV_NUM_AUTO) {
  801. /* Search for an empty slot in the @ubi_devices array */
  802. for (ubi_num = 0; ubi_num < UBI_MAX_DEVICES; ubi_num++)
  803. if (!ubi_devices[ubi_num])
  804. break;
  805. if (ubi_num == UBI_MAX_DEVICES) {
  806. pr_err("ubi: only %d UBI devices may be created\n",
  807. UBI_MAX_DEVICES);
  808. return -ENFILE;
  809. }
  810. } else {
  811. if (ubi_num >= UBI_MAX_DEVICES)
  812. return -EINVAL;
  813. /* Make sure ubi_num is not busy */
  814. if (ubi_devices[ubi_num]) {
  815. pr_err("ubi: ubi%i already exists\n", ubi_num);
  816. return -EEXIST;
  817. }
  818. }
  819. ubi = kzalloc(sizeof(struct ubi_device), GFP_KERNEL);
  820. if (!ubi)
  821. return -ENOMEM;
  822. device_initialize(&ubi->dev);
  823. ubi->dev.release = dev_release;
  824. ubi->dev.class = &ubi_class;
  825. ubi->dev.groups = ubi_dev_groups;
  826. ubi->dev.parent = &mtd->dev;
  827. ubi->mtd = mtd;
  828. ubi->ubi_num = ubi_num;
  829. ubi->vid_hdr_offset = vid_hdr_offset;
  830. ubi->autoresize_vol_id = -1;
  831. #ifdef CONFIG_MTD_UBI_FASTMAP
  832. ubi->fm_pool.used = ubi->fm_pool.size = 0;
  833. ubi->fm_wl_pool.used = ubi->fm_wl_pool.size = 0;
  834. /*
  835. * fm_pool.max_size is 5% of the total number of PEBs but it's also
  836. * between UBI_FM_MAX_POOL_SIZE and UBI_FM_MIN_POOL_SIZE.
  837. */
  838. ubi->fm_pool.max_size = min(((int)mtd_div_by_eb(ubi->mtd->size,
  839. ubi->mtd) / 100) * 5, UBI_FM_MAX_POOL_SIZE);
  840. ubi->fm_pool.max_size = max(ubi->fm_pool.max_size,
  841. UBI_FM_MIN_POOL_SIZE);
  842. ubi->fm_wl_pool.max_size = ubi->fm_pool.max_size / 2;
  843. ubi->fm_pool_rsv_cnt = need_resv_pool ? ubi->fm_pool.max_size : 0;
  844. ubi->fm_disabled = (!fm_autoconvert || disable_fm) ? 1 : 0;
  845. if (fm_debug)
  846. ubi_enable_dbg_chk_fastmap(ubi);
  847. if (!ubi->fm_disabled && (int)mtd_div_by_eb(ubi->mtd->size, ubi->mtd)
  848. <= UBI_FM_MAX_START) {
  849. ubi_err(ubi, "More than %i PEBs are needed for fastmap, sorry.",
  850. UBI_FM_MAX_START);
  851. ubi->fm_disabled = 1;
  852. }
  853. ubi_msg(ubi, "default fastmap pool size: %d", ubi->fm_pool.max_size);
  854. ubi_msg(ubi, "default fastmap WL pool size: %d",
  855. ubi->fm_wl_pool.max_size);
  856. #else
  857. ubi->fm_disabled = 1;
  858. #endif
  859. mutex_init(&ubi->buf_mutex);
  860. mutex_init(&ubi->ckvol_mutex);
  861. mutex_init(&ubi->device_mutex);
  862. spin_lock_init(&ubi->volumes_lock);
  863. init_rwsem(&ubi->fm_protect);
  864. init_rwsem(&ubi->fm_eba_sem);
  865. ubi_msg(ubi, "attaching mtd%d", mtd->index);
  866. err = io_init(ubi, max_beb_per1024);
  867. if (err)
  868. goto out_free;
  869. err = -ENOMEM;
  870. ubi->peb_buf = vmalloc(ubi->peb_size);
  871. if (!ubi->peb_buf)
  872. goto out_free;
  873. #ifdef CONFIG_MTD_UBI_FASTMAP
  874. ubi->fm_size = ubi_calc_fm_size(ubi);
  875. ubi->fm_buf = vzalloc(ubi->fm_size);
  876. if (!ubi->fm_buf)
  877. goto out_free;
  878. #endif
  879. err = ubi_attach(ubi, disable_fm ? 1 : 0);
  880. if (err) {
  881. ubi_err(ubi, "failed to attach mtd%d, error %d",
  882. mtd->index, err);
  883. goto out_free;
  884. }
  885. if (ubi->autoresize_vol_id != -1) {
  886. err = autoresize(ubi, ubi->autoresize_vol_id);
  887. if (err)
  888. goto out_detach;
  889. }
  890. err = uif_init(ubi);
  891. if (err)
  892. goto out_detach;
  893. err = ubi_debugfs_init_dev(ubi);
  894. if (err)
  895. goto out_uif;
  896. ubi->bgt_thread = kthread_create(ubi_thread, ubi, "%s", ubi->bgt_name);
  897. if (IS_ERR(ubi->bgt_thread)) {
  898. err = PTR_ERR(ubi->bgt_thread);
  899. ubi_err(ubi, "cannot spawn \"%s\", error %d",
  900. ubi->bgt_name, err);
  901. goto out_debugfs;
  902. }
  903. ubi_msg(ubi, "attached mtd%d (name \"%s\", size %llu MiB)",
  904. mtd->index, mtd->name, ubi->flash_size >> 20);
  905. ubi_msg(ubi, "PEB size: %d bytes (%d KiB), LEB size: %d bytes",
  906. ubi->peb_size, ubi->peb_size >> 10, ubi->leb_size);
  907. ubi_msg(ubi, "min./max. I/O unit sizes: %d/%d, sub-page size %d",
  908. ubi->min_io_size, ubi->max_write_size, ubi->hdrs_min_io_size);
  909. ubi_msg(ubi, "VID header offset: %d (aligned %d), data offset: %d",
  910. ubi->vid_hdr_offset, ubi->vid_hdr_aloffset, ubi->leb_start);
  911. ubi_msg(ubi, "good PEBs: %d, bad PEBs: %d, corrupted PEBs: %d",
  912. ubi->good_peb_count, ubi->bad_peb_count, ubi->corr_peb_count);
  913. ubi_msg(ubi, "user volume: %d, internal volumes: %d, max. volumes count: %d",
  914. ubi->vol_count - UBI_INT_VOL_COUNT, UBI_INT_VOL_COUNT,
  915. ubi->vtbl_slots);
  916. ubi_msg(ubi, "max/mean erase counter: %d/%d, WL threshold: %d, image sequence number: %u",
  917. ubi->max_ec, ubi->mean_ec, CONFIG_MTD_UBI_WL_THRESHOLD,
  918. ubi->image_seq);
  919. ubi_msg(ubi, "available PEBs: %d, total reserved PEBs: %d, PEBs reserved for bad PEB handling: %d",
  920. ubi->avail_pebs, ubi->rsvd_pebs, ubi->beb_rsvd_pebs);
  921. /*
  922. * The below lock makes sure we do not race with 'ubi_thread()' which
  923. * checks @ubi->thread_enabled. Otherwise we may fail to wake it up.
  924. */
  925. spin_lock(&ubi->wl_lock);
  926. ubi->thread_enabled = 1;
  927. wake_up_process(ubi->bgt_thread);
  928. spin_unlock(&ubi->wl_lock);
  929. ubi_devices[ubi_num] = ubi;
  930. ubi_notify_all(ubi, UBI_VOLUME_ADDED, NULL);
  931. return ubi_num;
  932. out_debugfs:
  933. ubi_debugfs_exit_dev(ubi);
  934. out_uif:
  935. uif_close(ubi);
  936. out_detach:
  937. ubi_wl_close(ubi);
  938. ubi_free_all_volumes(ubi);
  939. vfree(ubi->vtbl);
  940. out_free:
  941. vfree(ubi->peb_buf);
  942. vfree(ubi->fm_buf);
  943. put_device(&ubi->dev);
  944. return err;
  945. }
  946. /**
  947. * ubi_detach_mtd_dev - detach an MTD device.
  948. * @ubi_num: UBI device number to detach from
  949. * @anyway: detach MTD even if device reference count is not zero
  950. *
  951. * This function destroys an UBI device number @ubi_num and detaches the
  952. * underlying MTD device. Returns zero in case of success and %-EBUSY if the
  953. * UBI device is busy and cannot be destroyed, and %-EINVAL if it does not
  954. * exist.
  955. *
  956. * Note, the invocations of this function has to be serialized by the
  957. * @ubi_devices_mutex.
  958. */
  959. int ubi_detach_mtd_dev(int ubi_num, int anyway)
  960. {
  961. struct ubi_device *ubi;
  962. if (ubi_num < 0 || ubi_num >= UBI_MAX_DEVICES)
  963. return -EINVAL;
  964. ubi = ubi_get_device(ubi_num);
  965. if (!ubi)
  966. return -EINVAL;
  967. spin_lock(&ubi_devices_lock);
  968. ubi->ref_count -= 1;
  969. if (ubi->ref_count) {
  970. if (!anyway) {
  971. spin_unlock(&ubi_devices_lock);
  972. return -EBUSY;
  973. }
  974. /* This may only happen if there is a bug */
  975. ubi_err(ubi, "%s reference count %d, destroy anyway",
  976. ubi->ubi_name, ubi->ref_count);
  977. }
  978. ubi->is_dead = true;
  979. spin_unlock(&ubi_devices_lock);
  980. ubi_notify_all(ubi, UBI_VOLUME_SHUTDOWN, NULL);
  981. spin_lock(&ubi_devices_lock);
  982. put_device(&ubi->dev);
  983. ubi_devices[ubi_num] = NULL;
  984. spin_unlock(&ubi_devices_lock);
  985. ubi_assert(ubi_num == ubi->ubi_num);
  986. ubi_notify_all(ubi, UBI_VOLUME_REMOVED, NULL);
  987. ubi_msg(ubi, "detaching mtd%d", ubi->mtd->index);
  988. #ifdef CONFIG_MTD_UBI_FASTMAP
  989. /* If we don't write a new fastmap at detach time we lose all
  990. * EC updates that have been made since the last written fastmap.
  991. * In case of fastmap debugging we omit the update to simulate an
  992. * unclean shutdown. */
  993. if (!ubi_dbg_chk_fastmap(ubi))
  994. ubi_update_fastmap(ubi);
  995. #endif
  996. /*
  997. * Before freeing anything, we have to stop the background thread to
  998. * prevent it from doing anything on this device while we are freeing.
  999. */
  1000. if (ubi->bgt_thread)
  1001. kthread_stop(ubi->bgt_thread);
  1002. #ifdef CONFIG_MTD_UBI_FASTMAP
  1003. cancel_work_sync(&ubi->fm_work);
  1004. #endif
  1005. ubi_debugfs_exit_dev(ubi);
  1006. uif_close(ubi);
  1007. ubi_wl_close(ubi);
  1008. ubi_free_internal_volumes(ubi);
  1009. vfree(ubi->vtbl);
  1010. vfree(ubi->peb_buf);
  1011. vfree(ubi->fm_buf);
  1012. ubi_msg(ubi, "mtd%d is detached", ubi->mtd->index);
  1013. put_mtd_device(ubi->mtd);
  1014. put_device(&ubi->dev);
  1015. return 0;
  1016. }
  1017. /**
  1018. * open_mtd_by_chdev - open an MTD device by its character device node path.
  1019. * @mtd_dev: MTD character device node path
  1020. *
  1021. * This helper function opens an MTD device by its character node device path.
  1022. * Returns MTD device description object in case of success and a negative
  1023. * error code in case of failure.
  1024. */
  1025. static struct mtd_info * __init open_mtd_by_chdev(const char *mtd_dev)
  1026. {
  1027. int err, minor;
  1028. struct path path;
  1029. struct kstat stat;
  1030. /* Probably this is an MTD character device node path */
  1031. err = kern_path(mtd_dev, LOOKUP_FOLLOW, &path);
  1032. if (err)
  1033. return ERR_PTR(err);
  1034. err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
  1035. path_put(&path);
  1036. if (err)
  1037. return ERR_PTR(err);
  1038. /* MTD device number is defined by the major / minor numbers */
  1039. if (MAJOR(stat.rdev) != MTD_CHAR_MAJOR || !S_ISCHR(stat.mode))
  1040. return ERR_PTR(-EINVAL);
  1041. minor = MINOR(stat.rdev);
  1042. if (minor & 1)
  1043. /*
  1044. * Just do not think the "/dev/mtdrX" devices support is need,
  1045. * so do not support them to avoid doing extra work.
  1046. */
  1047. return ERR_PTR(-EINVAL);
  1048. return get_mtd_device(NULL, minor / 2);
  1049. }
  1050. /**
  1051. * open_mtd_device - open MTD device by name, character device path, or number.
  1052. * @mtd_dev: name, character device node path, or MTD device device number
  1053. *
  1054. * This function tries to open and MTD device described by @mtd_dev string,
  1055. * which is first treated as ASCII MTD device number, and if it is not true, it
  1056. * is treated as MTD device name, and if that is also not true, it is treated
  1057. * as MTD character device node path. Returns MTD device description object in
  1058. * case of success and a negative error code in case of failure.
  1059. */
  1060. static struct mtd_info * __init open_mtd_device(const char *mtd_dev)
  1061. {
  1062. struct mtd_info *mtd;
  1063. int mtd_num;
  1064. char *endp;
  1065. mtd_num = simple_strtoul(mtd_dev, &endp, 0);
  1066. if (*endp != '\0' || mtd_dev == endp) {
  1067. /*
  1068. * This does not look like an ASCII integer, probably this is
  1069. * MTD device name.
  1070. */
  1071. mtd = get_mtd_device_nm(mtd_dev);
  1072. if (PTR_ERR(mtd) == -ENODEV)
  1073. /* Probably this is an MTD character device node path */
  1074. mtd = open_mtd_by_chdev(mtd_dev);
  1075. } else
  1076. mtd = get_mtd_device(NULL, mtd_num);
  1077. return mtd;
  1078. }
  1079. static void ubi_notify_add(struct mtd_info *mtd)
  1080. {
  1081. struct device_node *np = mtd_get_of_node(mtd);
  1082. int err;
  1083. if (!of_device_is_compatible(np, "linux,ubi"))
  1084. return;
  1085. /*
  1086. * we are already holding &mtd_table_mutex, but still need
  1087. * to bump refcount
  1088. */
  1089. err = __get_mtd_device(mtd);
  1090. if (err)
  1091. return;
  1092. /* called while holding mtd_table_mutex */
  1093. mutex_lock_nested(&ubi_devices_mutex, SINGLE_DEPTH_NESTING);
  1094. err = ubi_attach_mtd_dev(mtd, UBI_DEV_NUM_AUTO, 0, 0, false, false);
  1095. mutex_unlock(&ubi_devices_mutex);
  1096. if (err < 0)
  1097. __put_mtd_device(mtd);
  1098. }
  1099. static void ubi_notify_remove(struct mtd_info *mtd)
  1100. {
  1101. /* do nothing for now */
  1102. }
  1103. static struct mtd_notifier ubi_mtd_notifier = {
  1104. .add = ubi_notify_add,
  1105. .remove = ubi_notify_remove,
  1106. };
  1107. static int __init ubi_init_attach(void)
  1108. {
  1109. int err, i, k;
  1110. /* Attach MTD devices */
  1111. for (i = 0; i < mtd_devs; i++) {
  1112. struct mtd_dev_param *p = &mtd_dev_param[i];
  1113. struct mtd_info *mtd;
  1114. cond_resched();
  1115. mtd = open_mtd_device(p->name);
  1116. if (IS_ERR(mtd)) {
  1117. err = PTR_ERR(mtd);
  1118. pr_err("UBI error: cannot open mtd %s, error %d\n",
  1119. p->name, err);
  1120. /* See comment below re-ubi_is_module(). */
  1121. if (ubi_is_module())
  1122. goto out_detach;
  1123. continue;
  1124. }
  1125. mutex_lock(&ubi_devices_mutex);
  1126. err = ubi_attach_mtd_dev(mtd, p->ubi_num,
  1127. p->vid_hdr_offs, p->max_beb_per1024,
  1128. p->enable_fm == 0,
  1129. p->need_resv_pool != 0);
  1130. mutex_unlock(&ubi_devices_mutex);
  1131. if (err < 0) {
  1132. pr_err("UBI error: cannot attach mtd%d\n",
  1133. mtd->index);
  1134. put_mtd_device(mtd);
  1135. /*
  1136. * Originally UBI stopped initializing on any error.
  1137. * However, later on it was found out that this
  1138. * behavior is not very good when UBI is compiled into
  1139. * the kernel and the MTD devices to attach are passed
  1140. * through the command line. Indeed, UBI failure
  1141. * stopped whole boot sequence.
  1142. *
  1143. * To fix this, we changed the behavior for the
  1144. * non-module case, but preserved the old behavior for
  1145. * the module case, just for compatibility. This is a
  1146. * little inconsistent, though.
  1147. */
  1148. if (ubi_is_module())
  1149. goto out_detach;
  1150. }
  1151. }
  1152. return 0;
  1153. out_detach:
  1154. for (k = 0; k < i; k++)
  1155. if (ubi_devices[k]) {
  1156. mutex_lock(&ubi_devices_mutex);
  1157. ubi_detach_mtd_dev(ubi_devices[k]->ubi_num, 1);
  1158. mutex_unlock(&ubi_devices_mutex);
  1159. }
  1160. return err;
  1161. }
  1162. #ifndef CONFIG_MTD_UBI_MODULE
  1163. late_initcall(ubi_init_attach);
  1164. #endif
  1165. static int __init ubi_init(void)
  1166. {
  1167. int err;
  1168. /* Ensure that EC and VID headers have correct size */
  1169. BUILD_BUG_ON(sizeof(struct ubi_ec_hdr) != 64);
  1170. BUILD_BUG_ON(sizeof(struct ubi_vid_hdr) != 64);
  1171. if (mtd_devs > UBI_MAX_DEVICES) {
  1172. pr_err("UBI error: too many MTD devices, maximum is %d\n",
  1173. UBI_MAX_DEVICES);
  1174. return -EINVAL;
  1175. }
  1176. /* Create base sysfs directory and sysfs files */
  1177. err = class_register(&ubi_class);
  1178. if (err < 0)
  1179. return err;
  1180. err = misc_register(&ubi_ctrl_cdev);
  1181. if (err) {
  1182. pr_err("UBI error: cannot register device\n");
  1183. goto out;
  1184. }
  1185. ubi_wl_entry_slab = kmem_cache_create("ubi_wl_entry_slab",
  1186. sizeof(struct ubi_wl_entry),
  1187. 0, 0, NULL);
  1188. if (!ubi_wl_entry_slab) {
  1189. err = -ENOMEM;
  1190. goto out_dev_unreg;
  1191. }
  1192. err = ubi_debugfs_init();
  1193. if (err)
  1194. goto out_slab;
  1195. err = ubiblock_init();
  1196. if (err) {
  1197. pr_err("UBI error: block: cannot initialize, error %d\n", err);
  1198. /* See comment above re-ubi_is_module(). */
  1199. if (ubi_is_module())
  1200. goto out_debugfs;
  1201. }
  1202. register_mtd_user(&ubi_mtd_notifier);
  1203. if (ubi_is_module()) {
  1204. err = ubi_init_attach();
  1205. if (err)
  1206. goto out_mtd_notifier;
  1207. }
  1208. return 0;
  1209. out_mtd_notifier:
  1210. unregister_mtd_user(&ubi_mtd_notifier);
  1211. ubiblock_exit();
  1212. out_debugfs:
  1213. ubi_debugfs_exit();
  1214. out_slab:
  1215. kmem_cache_destroy(ubi_wl_entry_slab);
  1216. out_dev_unreg:
  1217. misc_deregister(&ubi_ctrl_cdev);
  1218. out:
  1219. class_unregister(&ubi_class);
  1220. pr_err("UBI error: cannot initialize UBI, error %d\n", err);
  1221. return err;
  1222. }
  1223. device_initcall(ubi_init);
  1224. static void __exit ubi_exit(void)
  1225. {
  1226. int i;
  1227. ubiblock_exit();
  1228. unregister_mtd_user(&ubi_mtd_notifier);
  1229. for (i = 0; i < UBI_MAX_DEVICES; i++)
  1230. if (ubi_devices[i]) {
  1231. mutex_lock(&ubi_devices_mutex);
  1232. ubi_detach_mtd_dev(ubi_devices[i]->ubi_num, 1);
  1233. mutex_unlock(&ubi_devices_mutex);
  1234. }
  1235. ubi_debugfs_exit();
  1236. kmem_cache_destroy(ubi_wl_entry_slab);
  1237. misc_deregister(&ubi_ctrl_cdev);
  1238. class_unregister(&ubi_class);
  1239. }
  1240. module_exit(ubi_exit);
  1241. /**
  1242. * bytes_str_to_int - convert a number of bytes string into an integer.
  1243. * @str: the string to convert
  1244. *
  1245. * This function returns positive resulting integer in case of success and a
  1246. * negative error code in case of failure.
  1247. */
  1248. static int bytes_str_to_int(const char *str)
  1249. {
  1250. char *endp;
  1251. unsigned long result;
  1252. result = simple_strtoul(str, &endp, 0);
  1253. if (str == endp || result >= INT_MAX) {
  1254. pr_err("UBI error: incorrect bytes count: \"%s\"\n", str);
  1255. return -EINVAL;
  1256. }
  1257. switch (*endp) {
  1258. case 'G':
  1259. result *= 1024;
  1260. fallthrough;
  1261. case 'M':
  1262. result *= 1024;
  1263. fallthrough;
  1264. case 'K':
  1265. result *= 1024;
  1266. break;
  1267. case '\0':
  1268. break;
  1269. default:
  1270. pr_err("UBI error: incorrect bytes count: \"%s\"\n", str);
  1271. return -EINVAL;
  1272. }
  1273. return result;
  1274. }
  1275. /**
  1276. * ubi_mtd_param_parse - parse the 'mtd=' UBI parameter.
  1277. * @val: the parameter value to parse
  1278. * @kp: not used
  1279. *
  1280. * This function returns zero in case of success and a negative error code in
  1281. * case of error.
  1282. */
  1283. static int ubi_mtd_param_parse(const char *val, const struct kernel_param *kp)
  1284. {
  1285. int i, len;
  1286. struct mtd_dev_param *p;
  1287. char buf[MTD_PARAM_LEN_MAX];
  1288. char *pbuf = &buf[0];
  1289. char *tokens[MTD_PARAM_MAX_COUNT], *token;
  1290. if (!val)
  1291. return -EINVAL;
  1292. if (mtd_devs == UBI_MAX_DEVICES) {
  1293. pr_err("UBI error: too many parameters, max. is %d\n",
  1294. UBI_MAX_DEVICES);
  1295. return -EINVAL;
  1296. }
  1297. len = strnlen(val, MTD_PARAM_LEN_MAX);
  1298. if (len == MTD_PARAM_LEN_MAX) {
  1299. pr_err("UBI error: parameter \"%s\" is too long, max. is %d\n",
  1300. val, MTD_PARAM_LEN_MAX);
  1301. return -EINVAL;
  1302. }
  1303. if (len == 0) {
  1304. pr_warn("UBI warning: empty 'mtd=' parameter - ignored\n");
  1305. return 0;
  1306. }
  1307. strcpy(buf, val);
  1308. /* Get rid of the final newline */
  1309. if (buf[len - 1] == '\n')
  1310. buf[len - 1] = '\0';
  1311. for (i = 0; i < MTD_PARAM_MAX_COUNT; i++)
  1312. tokens[i] = strsep(&pbuf, ",");
  1313. if (pbuf) {
  1314. pr_err("UBI error: too many arguments at \"%s\"\n", val);
  1315. return -EINVAL;
  1316. }
  1317. p = &mtd_dev_param[mtd_devs];
  1318. strcpy(&p->name[0], tokens[0]);
  1319. token = tokens[1];
  1320. if (token) {
  1321. p->vid_hdr_offs = bytes_str_to_int(token);
  1322. if (p->vid_hdr_offs < 0)
  1323. return p->vid_hdr_offs;
  1324. }
  1325. token = tokens[2];
  1326. if (token) {
  1327. int err = kstrtoint(token, 10, &p->max_beb_per1024);
  1328. if (err) {
  1329. pr_err("UBI error: bad value for max_beb_per1024 parameter: %s\n",
  1330. token);
  1331. return -EINVAL;
  1332. }
  1333. }
  1334. token = tokens[3];
  1335. if (token) {
  1336. int err = kstrtoint(token, 10, &p->ubi_num);
  1337. if (err || p->ubi_num < UBI_DEV_NUM_AUTO) {
  1338. pr_err("UBI error: bad value for ubi_num parameter: %s\n",
  1339. token);
  1340. return -EINVAL;
  1341. }
  1342. } else
  1343. p->ubi_num = UBI_DEV_NUM_AUTO;
  1344. token = tokens[4];
  1345. if (token) {
  1346. int err = kstrtoint(token, 10, &p->enable_fm);
  1347. if (err) {
  1348. pr_err("UBI error: bad value for enable_fm parameter: %s\n",
  1349. token);
  1350. return -EINVAL;
  1351. }
  1352. } else
  1353. p->enable_fm = 0;
  1354. token = tokens[5];
  1355. if (token) {
  1356. int err = kstrtoint(token, 10, &p->need_resv_pool);
  1357. if (err) {
  1358. pr_err("UBI error: bad value for need_resv_pool parameter: %s\n",
  1359. token);
  1360. return -EINVAL;
  1361. }
  1362. } else
  1363. p->need_resv_pool = 0;
  1364. mtd_devs += 1;
  1365. return 0;
  1366. }
  1367. module_param_call(mtd, ubi_mtd_param_parse, NULL, NULL, 0400);
  1368. MODULE_PARM_DESC(mtd, "MTD devices to attach. Parameter format: mtd=<name|num|path>[,<vid_hdr_offs>[,max_beb_per1024[,ubi_num]]].\n"
  1369. "Multiple \"mtd\" parameters may be specified.\n"
  1370. "MTD devices may be specified by their number, name, or path to the MTD character device node.\n"
  1371. "Optional \"vid_hdr_offs\" parameter specifies UBI VID header position to be used by UBI. (default value if 0)\n"
  1372. "Optional \"max_beb_per1024\" parameter specifies the maximum expected bad eraseblock per 1024 eraseblocks. (default value ("
  1373. __stringify(CONFIG_MTD_UBI_BEB_LIMIT) ") if 0)\n"
  1374. "Optional \"ubi_num\" parameter specifies UBI device number which have to be assigned to the newly created UBI device (assigned automatically by default)\n"
  1375. "Optional \"enable_fm\" parameter determines whether to enable fastmap during attach. If the value is non-zero, fastmap is enabled. Default value is 0.\n"
  1376. "Optional \"need_resv_pool\" parameter determines whether to reserve pool->max_size pebs during attach. If the value is non-zero, peb reservation is enabled. Default value is 0.\n"
  1377. "\n"
  1378. "Example 1: mtd=/dev/mtd0 - attach MTD device /dev/mtd0.\n"
  1379. "Example 2: mtd=content,1984 mtd=4 - attach MTD device with name \"content\" using VID header offset 1984, and MTD device number 4 with default VID header offset.\n"
  1380. "Example 3: mtd=/dev/mtd1,0,25 - attach MTD device /dev/mtd1 using default VID header offset and reserve 25*nand_size_in_blocks/1024 erase blocks for bad block handling.\n"
  1381. "Example 4: mtd=/dev/mtd1,0,0,5 - attach MTD device /dev/mtd1 to UBI 5 and using default values for the other fields.\n"
  1382. "example 5: mtd=1,0,0,5 mtd=2,0,0,6,1 - attach MTD device /dev/mtd1 to UBI 5 and disable fastmap; attach MTD device /dev/mtd2 to UBI 6 and enable fastmap.(only works when fastmap is enabled and fm_autoconvert=Y).\n"
  1383. "\t(e.g. if the NAND *chipset* has 4096 PEB, 100 will be reserved for this UBI device).");
  1384. #ifdef CONFIG_MTD_UBI_FASTMAP
  1385. module_param(fm_autoconvert, bool, 0644);
  1386. MODULE_PARM_DESC(fm_autoconvert, "Set this parameter to enable fastmap automatically on images without a fastmap.");
  1387. module_param(fm_debug, bool, 0);
  1388. MODULE_PARM_DESC(fm_debug, "Set this parameter to enable fastmap debugging by default. Warning, this will make fastmap slow!");
  1389. #endif
  1390. MODULE_VERSION(__stringify(UBI_VERSION));
  1391. MODULE_DESCRIPTION("UBI - Unsorted Block Images");
  1392. MODULE_AUTHOR("Artem Bityutskiy");
  1393. MODULE_LICENSE("GPL");