nbd.c 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354
  1. /*
  2. * Network block device - make block devices work over TCP
  3. *
  4. * Note that you can not swap over this thing, yet. Seems to work but
  5. * deadlocks sometimes - you can not swap over TCP in general.
  6. *
  7. * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
  8. * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
  9. *
  10. * This file is released under GPLv2 or later.
  11. *
  12. * (part of code stolen from loop.c)
  13. */
  14. #include <linux/major.h>
  15. #include <linux/blkdev.h>
  16. #include <linux/module.h>
  17. #include <linux/init.h>
  18. #include <linux/sched.h>
  19. #include <linux/sched/mm.h>
  20. #include <linux/fs.h>
  21. #include <linux/bio.h>
  22. #include <linux/stat.h>
  23. #include <linux/errno.h>
  24. #include <linux/file.h>
  25. #include <linux/ioctl.h>
  26. #include <linux/mutex.h>
  27. #include <linux/compiler.h>
  28. #include <linux/err.h>
  29. #include <linux/kernel.h>
  30. #include <linux/slab.h>
  31. #include <net/sock.h>
  32. #include <linux/net.h>
  33. #include <linux/kthread.h>
  34. #include <linux/types.h>
  35. #include <linux/debugfs.h>
  36. #include <linux/blk-mq.h>
  37. #include <linux/uaccess.h>
  38. #include <asm/types.h>
  39. #include <linux/nbd.h>
  40. #include <linux/nbd-netlink.h>
  41. #include <net/genetlink.h>
  42. static DEFINE_IDR(nbd_index_idr);
  43. static DEFINE_MUTEX(nbd_index_mutex);
  44. static int nbd_total_devices = 0;
  45. struct nbd_sock {
  46. struct socket *sock;
  47. struct mutex tx_lock;
  48. struct request *pending;
  49. int sent;
  50. bool dead;
  51. int fallback_index;
  52. int cookie;
  53. };
  54. struct recv_thread_args {
  55. struct work_struct work;
  56. struct nbd_device *nbd;
  57. int index;
  58. };
  59. struct link_dead_args {
  60. struct work_struct work;
  61. int index;
  62. };
  63. #define NBD_TIMEDOUT 0
  64. #define NBD_DISCONNECT_REQUESTED 1
  65. #define NBD_DISCONNECTED 2
  66. #define NBD_HAS_PID_FILE 3
  67. #define NBD_HAS_CONFIG_REF 4
  68. #define NBD_BOUND 5
  69. #define NBD_DESTROY_ON_DISCONNECT 6
  70. #define NBD_DISCONNECT_ON_CLOSE 7
  71. struct nbd_config {
  72. u32 flags;
  73. unsigned long runtime_flags;
  74. u64 dead_conn_timeout;
  75. struct nbd_sock **socks;
  76. int num_connections;
  77. atomic_t live_connections;
  78. wait_queue_head_t conn_wait;
  79. atomic_t recv_threads;
  80. wait_queue_head_t recv_wq;
  81. loff_t blksize;
  82. loff_t bytesize;
  83. #if IS_ENABLED(CONFIG_DEBUG_FS)
  84. struct dentry *dbg_dir;
  85. #endif
  86. };
  87. struct nbd_device {
  88. struct blk_mq_tag_set tag_set;
  89. int index;
  90. refcount_t config_refs;
  91. refcount_t refs;
  92. struct nbd_config *config;
  93. struct mutex config_lock;
  94. struct gendisk *disk;
  95. struct workqueue_struct *recv_workq;
  96. struct list_head list;
  97. struct task_struct *task_recv;
  98. struct task_struct *task_setup;
  99. };
  100. #define NBD_CMD_REQUEUED 1
  101. struct nbd_cmd {
  102. struct nbd_device *nbd;
  103. struct mutex lock;
  104. int index;
  105. int cookie;
  106. blk_status_t status;
  107. unsigned long flags;
  108. u32 cmd_cookie;
  109. };
  110. #if IS_ENABLED(CONFIG_DEBUG_FS)
  111. static struct dentry *nbd_dbg_dir;
  112. #endif
  113. #define nbd_name(nbd) ((nbd)->disk->disk_name)
  114. #define NBD_MAGIC 0x68797548
  115. #define NBD_DEF_BLKSIZE 1024
  116. static unsigned int nbds_max = 16;
  117. static int max_part = 16;
  118. static int part_shift;
  119. static int nbd_dev_dbg_init(struct nbd_device *nbd);
  120. static void nbd_dev_dbg_close(struct nbd_device *nbd);
  121. static void nbd_config_put(struct nbd_device *nbd);
  122. static void nbd_connect_reply(struct genl_info *info, int index);
  123. static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
  124. static void nbd_dead_link_work(struct work_struct *work);
  125. static void nbd_disconnect_and_put(struct nbd_device *nbd);
  126. static inline struct device *nbd_to_dev(struct nbd_device *nbd)
  127. {
  128. return disk_to_dev(nbd->disk);
  129. }
  130. static void nbd_requeue_cmd(struct nbd_cmd *cmd)
  131. {
  132. struct request *req = blk_mq_rq_from_pdu(cmd);
  133. if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
  134. blk_mq_requeue_request(req, true);
  135. }
  136. #define NBD_COOKIE_BITS 32
  137. static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
  138. {
  139. struct request *req = blk_mq_rq_from_pdu(cmd);
  140. u32 tag = blk_mq_unique_tag(req);
  141. u64 cookie = cmd->cmd_cookie;
  142. return (cookie << NBD_COOKIE_BITS) | tag;
  143. }
  144. static u32 nbd_handle_to_tag(u64 handle)
  145. {
  146. return (u32)handle;
  147. }
  148. static u32 nbd_handle_to_cookie(u64 handle)
  149. {
  150. return (u32)(handle >> NBD_COOKIE_BITS);
  151. }
  152. static const char *nbdcmd_to_ascii(int cmd)
  153. {
  154. switch (cmd) {
  155. case NBD_CMD_READ: return "read";
  156. case NBD_CMD_WRITE: return "write";
  157. case NBD_CMD_DISC: return "disconnect";
  158. case NBD_CMD_FLUSH: return "flush";
  159. case NBD_CMD_TRIM: return "trim/discard";
  160. }
  161. return "invalid";
  162. }
  163. static ssize_t pid_show(struct device *dev,
  164. struct device_attribute *attr, char *buf)
  165. {
  166. struct gendisk *disk = dev_to_disk(dev);
  167. struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
  168. return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
  169. }
  170. static const struct device_attribute pid_attr = {
  171. .attr = { .name = "pid", .mode = 0444},
  172. .show = pid_show,
  173. };
  174. static void nbd_dev_remove(struct nbd_device *nbd)
  175. {
  176. struct gendisk *disk = nbd->disk;
  177. struct request_queue *q;
  178. if (disk) {
  179. q = disk->queue;
  180. del_gendisk(disk);
  181. blk_cleanup_queue(q);
  182. blk_mq_free_tag_set(&nbd->tag_set);
  183. disk->private_data = NULL;
  184. put_disk(disk);
  185. }
  186. kfree(nbd);
  187. }
  188. static void nbd_put(struct nbd_device *nbd)
  189. {
  190. if (refcount_dec_and_mutex_lock(&nbd->refs,
  191. &nbd_index_mutex)) {
  192. idr_remove(&nbd_index_idr, nbd->index);
  193. nbd_dev_remove(nbd);
  194. mutex_unlock(&nbd_index_mutex);
  195. }
  196. }
  197. static int nbd_disconnected(struct nbd_config *config)
  198. {
  199. return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
  200. test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
  201. }
  202. static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
  203. int notify)
  204. {
  205. if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
  206. struct link_dead_args *args;
  207. args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
  208. if (args) {
  209. INIT_WORK(&args->work, nbd_dead_link_work);
  210. args->index = nbd->index;
  211. queue_work(system_wq, &args->work);
  212. }
  213. }
  214. if (!nsock->dead) {
  215. kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
  216. if (atomic_dec_return(&nbd->config->live_connections) == 0) {
  217. if (test_and_clear_bit(NBD_DISCONNECT_REQUESTED,
  218. &nbd->config->runtime_flags)) {
  219. set_bit(NBD_DISCONNECTED,
  220. &nbd->config->runtime_flags);
  221. dev_info(nbd_to_dev(nbd),
  222. "Disconnected due to user request.\n");
  223. }
  224. }
  225. }
  226. nsock->dead = true;
  227. nsock->pending = NULL;
  228. nsock->sent = 0;
  229. }
  230. static void nbd_size_clear(struct nbd_device *nbd)
  231. {
  232. if (nbd->config->bytesize) {
  233. set_capacity(nbd->disk, 0);
  234. kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
  235. }
  236. }
  237. static void nbd_size_update(struct nbd_device *nbd)
  238. {
  239. struct nbd_config *config = nbd->config;
  240. struct block_device *bdev = bdget_disk(nbd->disk, 0);
  241. if (config->flags & NBD_FLAG_SEND_TRIM) {
  242. nbd->disk->queue->limits.discard_granularity = config->blksize;
  243. nbd->disk->queue->limits.discard_alignment = config->blksize;
  244. blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
  245. }
  246. blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
  247. blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
  248. set_capacity(nbd->disk, config->bytesize >> 9);
  249. if (bdev) {
  250. if (bdev->bd_disk) {
  251. bd_set_size(bdev, config->bytesize);
  252. set_blocksize(bdev, config->blksize);
  253. } else
  254. bdev->bd_invalidated = 1;
  255. bdput(bdev);
  256. }
  257. kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
  258. }
  259. static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
  260. loff_t nr_blocks)
  261. {
  262. struct nbd_config *config = nbd->config;
  263. config->blksize = blocksize;
  264. config->bytesize = blocksize * nr_blocks;
  265. if (nbd->task_recv != NULL)
  266. nbd_size_update(nbd);
  267. }
  268. static void nbd_complete_rq(struct request *req)
  269. {
  270. struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
  271. dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
  272. cmd->status ? "failed" : "done");
  273. blk_mq_end_request(req, cmd->status);
  274. }
  275. /*
  276. * Forcibly shutdown the socket causing all listeners to error
  277. */
  278. static void sock_shutdown(struct nbd_device *nbd)
  279. {
  280. struct nbd_config *config = nbd->config;
  281. int i;
  282. if (config->num_connections == 0)
  283. return;
  284. if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
  285. return;
  286. for (i = 0; i < config->num_connections; i++) {
  287. struct nbd_sock *nsock = config->socks[i];
  288. mutex_lock(&nsock->tx_lock);
  289. nbd_mark_nsock_dead(nbd, nsock, 0);
  290. mutex_unlock(&nsock->tx_lock);
  291. }
  292. dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
  293. }
  294. static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
  295. bool reserved)
  296. {
  297. struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
  298. struct nbd_device *nbd = cmd->nbd;
  299. struct nbd_config *config;
  300. if (!mutex_trylock(&cmd->lock))
  301. return BLK_EH_RESET_TIMER;
  302. if (!refcount_inc_not_zero(&nbd->config_refs)) {
  303. cmd->status = BLK_STS_TIMEOUT;
  304. mutex_unlock(&cmd->lock);
  305. goto done;
  306. }
  307. config = nbd->config;
  308. if (config->num_connections > 1) {
  309. dev_err_ratelimited(nbd_to_dev(nbd),
  310. "Connection timed out, retrying (%d/%d alive)\n",
  311. atomic_read(&config->live_connections),
  312. config->num_connections);
  313. /*
  314. * Hooray we have more connections, requeue this IO, the submit
  315. * path will put it on a real connection.
  316. */
  317. if (config->socks && config->num_connections > 1) {
  318. if (cmd->index < config->num_connections) {
  319. struct nbd_sock *nsock =
  320. config->socks[cmd->index];
  321. mutex_lock(&nsock->tx_lock);
  322. /* We can have multiple outstanding requests, so
  323. * we don't want to mark the nsock dead if we've
  324. * already reconnected with a new socket, so
  325. * only mark it dead if its the same socket we
  326. * were sent out on.
  327. */
  328. if (cmd->cookie == nsock->cookie)
  329. nbd_mark_nsock_dead(nbd, nsock, 1);
  330. mutex_unlock(&nsock->tx_lock);
  331. }
  332. mutex_unlock(&cmd->lock);
  333. nbd_requeue_cmd(cmd);
  334. nbd_config_put(nbd);
  335. return BLK_EH_DONE;
  336. }
  337. } else {
  338. dev_err_ratelimited(nbd_to_dev(nbd),
  339. "Connection timed out\n");
  340. }
  341. set_bit(NBD_TIMEDOUT, &config->runtime_flags);
  342. cmd->status = BLK_STS_IOERR;
  343. mutex_unlock(&cmd->lock);
  344. sock_shutdown(nbd);
  345. nbd_config_put(nbd);
  346. done:
  347. blk_mq_complete_request(req);
  348. return BLK_EH_DONE;
  349. }
  350. /*
  351. * Send or receive packet.
  352. */
  353. static int sock_xmit(struct nbd_device *nbd, int index, int send,
  354. struct iov_iter *iter, int msg_flags, int *sent)
  355. {
  356. struct nbd_config *config = nbd->config;
  357. struct socket *sock = config->socks[index]->sock;
  358. int result;
  359. struct msghdr msg;
  360. unsigned int noreclaim_flag;
  361. if (unlikely(!sock)) {
  362. dev_err_ratelimited(disk_to_dev(nbd->disk),
  363. "Attempted %s on closed socket in sock_xmit\n",
  364. (send ? "send" : "recv"));
  365. return -EINVAL;
  366. }
  367. msg.msg_iter = *iter;
  368. noreclaim_flag = memalloc_noreclaim_save();
  369. do {
  370. sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
  371. msg.msg_name = NULL;
  372. msg.msg_namelen = 0;
  373. msg.msg_control = NULL;
  374. msg.msg_controllen = 0;
  375. msg.msg_flags = msg_flags | MSG_NOSIGNAL;
  376. if (send)
  377. result = sock_sendmsg(sock, &msg);
  378. else
  379. result = sock_recvmsg(sock, &msg, msg.msg_flags);
  380. if (result <= 0) {
  381. if (result == 0)
  382. result = -EPIPE; /* short read */
  383. break;
  384. }
  385. if (sent)
  386. *sent += result;
  387. } while (msg_data_left(&msg));
  388. memalloc_noreclaim_restore(noreclaim_flag);
  389. return result;
  390. }
  391. /*
  392. * Different settings for sk->sk_sndtimeo can result in different return values
  393. * if there is a signal pending when we enter sendmsg, because reasons?
  394. */
  395. static inline int was_interrupted(int result)
  396. {
  397. return result == -ERESTARTSYS || result == -EINTR;
  398. }
  399. /* always call with the tx_lock held */
  400. static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
  401. {
  402. struct request *req = blk_mq_rq_from_pdu(cmd);
  403. struct nbd_config *config = nbd->config;
  404. struct nbd_sock *nsock = config->socks[index];
  405. int result;
  406. struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
  407. struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
  408. struct iov_iter from;
  409. unsigned long size = blk_rq_bytes(req);
  410. struct bio *bio;
  411. u64 handle;
  412. u32 type;
  413. u32 nbd_cmd_flags = 0;
  414. int sent = nsock->sent, skip = 0;
  415. iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
  416. switch (req_op(req)) {
  417. case REQ_OP_DISCARD:
  418. type = NBD_CMD_TRIM;
  419. break;
  420. case REQ_OP_FLUSH:
  421. type = NBD_CMD_FLUSH;
  422. break;
  423. case REQ_OP_WRITE:
  424. type = NBD_CMD_WRITE;
  425. break;
  426. case REQ_OP_READ:
  427. type = NBD_CMD_READ;
  428. break;
  429. default:
  430. return -EIO;
  431. }
  432. if (rq_data_dir(req) == WRITE &&
  433. (config->flags & NBD_FLAG_READ_ONLY)) {
  434. dev_err_ratelimited(disk_to_dev(nbd->disk),
  435. "Write on read-only\n");
  436. return -EIO;
  437. }
  438. if (req->cmd_flags & REQ_FUA)
  439. nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
  440. /* We did a partial send previously, and we at least sent the whole
  441. * request struct, so just go and send the rest of the pages in the
  442. * request.
  443. */
  444. if (sent) {
  445. if (sent >= sizeof(request)) {
  446. skip = sent - sizeof(request);
  447. goto send_pages;
  448. }
  449. iov_iter_advance(&from, sent);
  450. } else {
  451. cmd->cmd_cookie++;
  452. }
  453. cmd->index = index;
  454. cmd->cookie = nsock->cookie;
  455. request.type = htonl(type | nbd_cmd_flags);
  456. if (type != NBD_CMD_FLUSH) {
  457. request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
  458. request.len = htonl(size);
  459. }
  460. handle = nbd_cmd_handle(cmd);
  461. memcpy(request.handle, &handle, sizeof(handle));
  462. dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
  463. req, nbdcmd_to_ascii(type),
  464. (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
  465. result = sock_xmit(nbd, index, 1, &from,
  466. (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
  467. if (result <= 0) {
  468. if (was_interrupted(result)) {
  469. /* If we havne't sent anything we can just return BUSY,
  470. * however if we have sent something we need to make
  471. * sure we only allow this req to be sent until we are
  472. * completely done.
  473. */
  474. if (sent) {
  475. nsock->pending = req;
  476. nsock->sent = sent;
  477. }
  478. set_bit(NBD_CMD_REQUEUED, &cmd->flags);
  479. return BLK_STS_RESOURCE;
  480. }
  481. dev_err_ratelimited(disk_to_dev(nbd->disk),
  482. "Send control failed (result %d)\n", result);
  483. return -EAGAIN;
  484. }
  485. send_pages:
  486. if (type != NBD_CMD_WRITE)
  487. goto out;
  488. bio = req->bio;
  489. while (bio) {
  490. struct bio *next = bio->bi_next;
  491. struct bvec_iter iter;
  492. struct bio_vec bvec;
  493. bio_for_each_segment(bvec, bio, iter) {
  494. bool is_last = !next && bio_iter_last(bvec, iter);
  495. int flags = is_last ? 0 : MSG_MORE;
  496. dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
  497. req, bvec.bv_len);
  498. iov_iter_bvec(&from, ITER_BVEC | WRITE,
  499. &bvec, 1, bvec.bv_len);
  500. if (skip) {
  501. if (skip >= iov_iter_count(&from)) {
  502. skip -= iov_iter_count(&from);
  503. continue;
  504. }
  505. iov_iter_advance(&from, skip);
  506. skip = 0;
  507. }
  508. result = sock_xmit(nbd, index, 1, &from, flags, &sent);
  509. if (result <= 0) {
  510. if (was_interrupted(result)) {
  511. /* We've already sent the header, we
  512. * have no choice but to set pending and
  513. * return BUSY.
  514. */
  515. nsock->pending = req;
  516. nsock->sent = sent;
  517. set_bit(NBD_CMD_REQUEUED, &cmd->flags);
  518. return BLK_STS_RESOURCE;
  519. }
  520. dev_err(disk_to_dev(nbd->disk),
  521. "Send data failed (result %d)\n",
  522. result);
  523. return -EAGAIN;
  524. }
  525. /*
  526. * The completion might already have come in,
  527. * so break for the last one instead of letting
  528. * the iterator do it. This prevents use-after-free
  529. * of the bio.
  530. */
  531. if (is_last)
  532. break;
  533. }
  534. bio = next;
  535. }
  536. out:
  537. nsock->pending = NULL;
  538. nsock->sent = 0;
  539. return 0;
  540. }
  541. /* NULL returned = something went wrong, inform userspace */
  542. static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
  543. {
  544. struct nbd_config *config = nbd->config;
  545. int result;
  546. struct nbd_reply reply;
  547. struct nbd_cmd *cmd;
  548. struct request *req = NULL;
  549. u64 handle;
  550. u16 hwq;
  551. u32 tag;
  552. struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
  553. struct iov_iter to;
  554. int ret = 0;
  555. reply.magic = 0;
  556. iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
  557. result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
  558. if (result <= 0) {
  559. if (!nbd_disconnected(config))
  560. dev_err(disk_to_dev(nbd->disk),
  561. "Receive control failed (result %d)\n", result);
  562. return ERR_PTR(result);
  563. }
  564. if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
  565. dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
  566. (unsigned long)ntohl(reply.magic));
  567. return ERR_PTR(-EPROTO);
  568. }
  569. memcpy(&handle, reply.handle, sizeof(handle));
  570. tag = nbd_handle_to_tag(handle);
  571. hwq = blk_mq_unique_tag_to_hwq(tag);
  572. if (hwq < nbd->tag_set.nr_hw_queues)
  573. req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
  574. blk_mq_unique_tag_to_tag(tag));
  575. if (!req || !blk_mq_request_started(req)) {
  576. dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
  577. tag, req);
  578. return ERR_PTR(-ENOENT);
  579. }
  580. cmd = blk_mq_rq_to_pdu(req);
  581. mutex_lock(&cmd->lock);
  582. if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
  583. dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
  584. req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
  585. ret = -ENOENT;
  586. goto out;
  587. }
  588. if (cmd->status != BLK_STS_OK) {
  589. dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
  590. req);
  591. ret = -ENOENT;
  592. goto out;
  593. }
  594. if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
  595. dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
  596. req);
  597. ret = -ENOENT;
  598. goto out;
  599. }
  600. if (ntohl(reply.error)) {
  601. dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
  602. ntohl(reply.error));
  603. cmd->status = BLK_STS_IOERR;
  604. goto out;
  605. }
  606. dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
  607. if (rq_data_dir(req) != WRITE) {
  608. struct req_iterator iter;
  609. struct bio_vec bvec;
  610. rq_for_each_segment(bvec, req, iter) {
  611. iov_iter_bvec(&to, ITER_BVEC | READ,
  612. &bvec, 1, bvec.bv_len);
  613. result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
  614. if (result <= 0) {
  615. dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
  616. result);
  617. /*
  618. * If we've disconnected or we only have 1
  619. * connection then we need to make sure we
  620. * complete this request, otherwise error out
  621. * and let the timeout stuff handle resubmitting
  622. * this request onto another connection.
  623. */
  624. if (nbd_disconnected(config) ||
  625. config->num_connections <= 1) {
  626. cmd->status = BLK_STS_IOERR;
  627. goto out;
  628. }
  629. ret = -EIO;
  630. goto out;
  631. }
  632. dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
  633. req, bvec.bv_len);
  634. }
  635. }
  636. out:
  637. mutex_unlock(&cmd->lock);
  638. return ret ? ERR_PTR(ret) : cmd;
  639. }
  640. static void recv_work(struct work_struct *work)
  641. {
  642. struct recv_thread_args *args = container_of(work,
  643. struct recv_thread_args,
  644. work);
  645. struct nbd_device *nbd = args->nbd;
  646. struct nbd_config *config = nbd->config;
  647. struct nbd_cmd *cmd;
  648. while (1) {
  649. cmd = nbd_read_stat(nbd, args->index);
  650. if (IS_ERR(cmd)) {
  651. struct nbd_sock *nsock = config->socks[args->index];
  652. mutex_lock(&nsock->tx_lock);
  653. nbd_mark_nsock_dead(nbd, nsock, 1);
  654. mutex_unlock(&nsock->tx_lock);
  655. break;
  656. }
  657. blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
  658. }
  659. atomic_dec(&config->recv_threads);
  660. wake_up(&config->recv_wq);
  661. nbd_config_put(nbd);
  662. kfree(args);
  663. }
  664. static void nbd_clear_req(struct request *req, void *data, bool reserved)
  665. {
  666. struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
  667. mutex_lock(&cmd->lock);
  668. cmd->status = BLK_STS_IOERR;
  669. mutex_unlock(&cmd->lock);
  670. blk_mq_complete_request(req);
  671. }
  672. static void nbd_clear_que(struct nbd_device *nbd)
  673. {
  674. blk_mq_quiesce_queue(nbd->disk->queue);
  675. blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
  676. blk_mq_unquiesce_queue(nbd->disk->queue);
  677. dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
  678. }
  679. static int find_fallback(struct nbd_device *nbd, int index)
  680. {
  681. struct nbd_config *config = nbd->config;
  682. int new_index = -1;
  683. struct nbd_sock *nsock = config->socks[index];
  684. int fallback = nsock->fallback_index;
  685. if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
  686. return new_index;
  687. if (config->num_connections <= 1) {
  688. dev_err_ratelimited(disk_to_dev(nbd->disk),
  689. "Attempted send on invalid socket\n");
  690. return new_index;
  691. }
  692. if (fallback >= 0 && fallback < config->num_connections &&
  693. !config->socks[fallback]->dead)
  694. return fallback;
  695. if (nsock->fallback_index < 0 ||
  696. nsock->fallback_index >= config->num_connections ||
  697. config->socks[nsock->fallback_index]->dead) {
  698. int i;
  699. for (i = 0; i < config->num_connections; i++) {
  700. if (i == index)
  701. continue;
  702. if (!config->socks[i]->dead) {
  703. new_index = i;
  704. break;
  705. }
  706. }
  707. nsock->fallback_index = new_index;
  708. if (new_index < 0) {
  709. dev_err_ratelimited(disk_to_dev(nbd->disk),
  710. "Dead connection, failed to find a fallback\n");
  711. return new_index;
  712. }
  713. }
  714. new_index = nsock->fallback_index;
  715. return new_index;
  716. }
  717. static int wait_for_reconnect(struct nbd_device *nbd)
  718. {
  719. struct nbd_config *config = nbd->config;
  720. if (!config->dead_conn_timeout)
  721. return 0;
  722. if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
  723. return 0;
  724. return wait_event_timeout(config->conn_wait,
  725. atomic_read(&config->live_connections) > 0,
  726. config->dead_conn_timeout) > 0;
  727. }
  728. static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
  729. {
  730. struct request *req = blk_mq_rq_from_pdu(cmd);
  731. struct nbd_device *nbd = cmd->nbd;
  732. struct nbd_config *config;
  733. struct nbd_sock *nsock;
  734. int ret;
  735. if (!refcount_inc_not_zero(&nbd->config_refs)) {
  736. dev_err_ratelimited(disk_to_dev(nbd->disk),
  737. "Socks array is empty\n");
  738. blk_mq_start_request(req);
  739. return -EINVAL;
  740. }
  741. config = nbd->config;
  742. if (index >= config->num_connections) {
  743. dev_err_ratelimited(disk_to_dev(nbd->disk),
  744. "Attempted send on invalid socket\n");
  745. nbd_config_put(nbd);
  746. blk_mq_start_request(req);
  747. return -EINVAL;
  748. }
  749. cmd->status = BLK_STS_OK;
  750. again:
  751. nsock = config->socks[index];
  752. mutex_lock(&nsock->tx_lock);
  753. if (nsock->dead) {
  754. int old_index = index;
  755. index = find_fallback(nbd, index);
  756. mutex_unlock(&nsock->tx_lock);
  757. if (index < 0) {
  758. if (wait_for_reconnect(nbd)) {
  759. index = old_index;
  760. goto again;
  761. }
  762. /* All the sockets should already be down at this point,
  763. * we just want to make sure that DISCONNECTED is set so
  764. * any requests that come in that were queue'ed waiting
  765. * for the reconnect timer don't trigger the timer again
  766. * and instead just error out.
  767. */
  768. sock_shutdown(nbd);
  769. nbd_config_put(nbd);
  770. blk_mq_start_request(req);
  771. return -EIO;
  772. }
  773. goto again;
  774. }
  775. /* Handle the case that we have a pending request that was partially
  776. * transmitted that _has_ to be serviced first. We need to call requeue
  777. * here so that it gets put _after_ the request that is already on the
  778. * dispatch list.
  779. */
  780. blk_mq_start_request(req);
  781. if (unlikely(nsock->pending && nsock->pending != req)) {
  782. nbd_requeue_cmd(cmd);
  783. ret = 0;
  784. goto out;
  785. }
  786. /*
  787. * Some failures are related to the link going down, so anything that
  788. * returns EAGAIN can be retried on a different socket.
  789. */
  790. ret = nbd_send_cmd(nbd, cmd, index);
  791. if (ret == -EAGAIN) {
  792. dev_err_ratelimited(disk_to_dev(nbd->disk),
  793. "Request send failed, requeueing\n");
  794. nbd_mark_nsock_dead(nbd, nsock, 1);
  795. nbd_requeue_cmd(cmd);
  796. ret = 0;
  797. }
  798. out:
  799. mutex_unlock(&nsock->tx_lock);
  800. nbd_config_put(nbd);
  801. return ret;
  802. }
  803. static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
  804. const struct blk_mq_queue_data *bd)
  805. {
  806. struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
  807. int ret;
  808. /*
  809. * Since we look at the bio's to send the request over the network we
  810. * need to make sure the completion work doesn't mark this request done
  811. * before we are done doing our send. This keeps us from dereferencing
  812. * freed data if we have particularly fast completions (ie we get the
  813. * completion before we exit sock_xmit on the last bvec) or in the case
  814. * that the server is misbehaving (or there was an error) before we're
  815. * done sending everything over the wire.
  816. */
  817. mutex_lock(&cmd->lock);
  818. clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
  819. /* We can be called directly from the user space process, which means we
  820. * could possibly have signals pending so our sendmsg will fail. In
  821. * this case we need to return that we are busy, otherwise error out as
  822. * appropriate.
  823. */
  824. ret = nbd_handle_cmd(cmd, hctx->queue_num);
  825. if (ret < 0)
  826. ret = BLK_STS_IOERR;
  827. else if (!ret)
  828. ret = BLK_STS_OK;
  829. mutex_unlock(&cmd->lock);
  830. return ret;
  831. }
  832. static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
  833. int *err)
  834. {
  835. struct socket *sock;
  836. *err = 0;
  837. sock = sockfd_lookup(fd, err);
  838. if (!sock)
  839. return NULL;
  840. if (sock->ops->shutdown == sock_no_shutdown) {
  841. dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
  842. *err = -EINVAL;
  843. sockfd_put(sock);
  844. return NULL;
  845. }
  846. return sock;
  847. }
  848. static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
  849. bool netlink)
  850. {
  851. struct nbd_config *config = nbd->config;
  852. struct socket *sock;
  853. struct nbd_sock **socks;
  854. struct nbd_sock *nsock;
  855. int err;
  856. sock = nbd_get_socket(nbd, arg, &err);
  857. if (!sock)
  858. return err;
  859. if (!netlink && !nbd->task_setup &&
  860. !test_bit(NBD_BOUND, &config->runtime_flags))
  861. nbd->task_setup = current;
  862. if (!netlink &&
  863. (nbd->task_setup != current ||
  864. test_bit(NBD_BOUND, &config->runtime_flags))) {
  865. dev_err(disk_to_dev(nbd->disk),
  866. "Device being setup by another task");
  867. sockfd_put(sock);
  868. return -EBUSY;
  869. }
  870. socks = krealloc(config->socks, (config->num_connections + 1) *
  871. sizeof(struct nbd_sock *), GFP_KERNEL);
  872. if (!socks) {
  873. sockfd_put(sock);
  874. return -ENOMEM;
  875. }
  876. config->socks = socks;
  877. nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
  878. if (!nsock) {
  879. sockfd_put(sock);
  880. return -ENOMEM;
  881. }
  882. nsock->fallback_index = -1;
  883. nsock->dead = false;
  884. mutex_init(&nsock->tx_lock);
  885. nsock->sock = sock;
  886. nsock->pending = NULL;
  887. nsock->sent = 0;
  888. nsock->cookie = 0;
  889. socks[config->num_connections++] = nsock;
  890. atomic_inc(&config->live_connections);
  891. return 0;
  892. }
  893. static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
  894. {
  895. struct nbd_config *config = nbd->config;
  896. struct socket *sock, *old;
  897. struct recv_thread_args *args;
  898. int i;
  899. int err;
  900. sock = nbd_get_socket(nbd, arg, &err);
  901. if (!sock)
  902. return err;
  903. args = kzalloc(sizeof(*args), GFP_KERNEL);
  904. if (!args) {
  905. sockfd_put(sock);
  906. return -ENOMEM;
  907. }
  908. for (i = 0; i < config->num_connections; i++) {
  909. struct nbd_sock *nsock = config->socks[i];
  910. if (!nsock->dead)
  911. continue;
  912. mutex_lock(&nsock->tx_lock);
  913. if (!nsock->dead) {
  914. mutex_unlock(&nsock->tx_lock);
  915. continue;
  916. }
  917. sk_set_memalloc(sock->sk);
  918. if (nbd->tag_set.timeout)
  919. sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
  920. atomic_inc(&config->recv_threads);
  921. refcount_inc(&nbd->config_refs);
  922. old = nsock->sock;
  923. nsock->fallback_index = -1;
  924. nsock->sock = sock;
  925. nsock->dead = false;
  926. INIT_WORK(&args->work, recv_work);
  927. args->index = i;
  928. args->nbd = nbd;
  929. nsock->cookie++;
  930. mutex_unlock(&nsock->tx_lock);
  931. sockfd_put(old);
  932. clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
  933. /* We take the tx_mutex in an error path in the recv_work, so we
  934. * need to queue_work outside of the tx_mutex.
  935. */
  936. queue_work(nbd->recv_workq, &args->work);
  937. atomic_inc(&config->live_connections);
  938. wake_up(&config->conn_wait);
  939. return 0;
  940. }
  941. sockfd_put(sock);
  942. kfree(args);
  943. return -ENOSPC;
  944. }
  945. static void nbd_bdev_reset(struct block_device *bdev)
  946. {
  947. if (bdev->bd_openers > 1)
  948. return;
  949. bd_set_size(bdev, 0);
  950. }
  951. static void nbd_parse_flags(struct nbd_device *nbd)
  952. {
  953. struct nbd_config *config = nbd->config;
  954. if (config->flags & NBD_FLAG_READ_ONLY)
  955. set_disk_ro(nbd->disk, true);
  956. else
  957. set_disk_ro(nbd->disk, false);
  958. if (config->flags & NBD_FLAG_SEND_TRIM)
  959. blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
  960. if (config->flags & NBD_FLAG_SEND_FLUSH) {
  961. if (config->flags & NBD_FLAG_SEND_FUA)
  962. blk_queue_write_cache(nbd->disk->queue, true, true);
  963. else
  964. blk_queue_write_cache(nbd->disk->queue, true, false);
  965. }
  966. else
  967. blk_queue_write_cache(nbd->disk->queue, false, false);
  968. }
  969. static void send_disconnects(struct nbd_device *nbd)
  970. {
  971. struct nbd_config *config = nbd->config;
  972. struct nbd_request request = {
  973. .magic = htonl(NBD_REQUEST_MAGIC),
  974. .type = htonl(NBD_CMD_DISC),
  975. };
  976. struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
  977. struct iov_iter from;
  978. int i, ret;
  979. for (i = 0; i < config->num_connections; i++) {
  980. struct nbd_sock *nsock = config->socks[i];
  981. iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
  982. mutex_lock(&nsock->tx_lock);
  983. ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
  984. if (ret <= 0)
  985. dev_err(disk_to_dev(nbd->disk),
  986. "Send disconnect failed %d\n", ret);
  987. mutex_unlock(&nsock->tx_lock);
  988. }
  989. }
  990. static int nbd_disconnect(struct nbd_device *nbd)
  991. {
  992. struct nbd_config *config = nbd->config;
  993. dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
  994. set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
  995. send_disconnects(nbd);
  996. return 0;
  997. }
  998. static void nbd_clear_sock(struct nbd_device *nbd)
  999. {
  1000. sock_shutdown(nbd);
  1001. nbd_clear_que(nbd);
  1002. nbd->task_setup = NULL;
  1003. }
  1004. static void nbd_config_put(struct nbd_device *nbd)
  1005. {
  1006. if (refcount_dec_and_mutex_lock(&nbd->config_refs,
  1007. &nbd->config_lock)) {
  1008. struct nbd_config *config = nbd->config;
  1009. nbd_dev_dbg_close(nbd);
  1010. nbd_size_clear(nbd);
  1011. if (test_and_clear_bit(NBD_HAS_PID_FILE,
  1012. &config->runtime_flags))
  1013. device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
  1014. nbd->task_recv = NULL;
  1015. nbd_clear_sock(nbd);
  1016. if (config->num_connections) {
  1017. int i;
  1018. for (i = 0; i < config->num_connections; i++) {
  1019. sockfd_put(config->socks[i]->sock);
  1020. kfree(config->socks[i]);
  1021. }
  1022. kfree(config->socks);
  1023. }
  1024. kfree(nbd->config);
  1025. nbd->config = NULL;
  1026. if (nbd->recv_workq)
  1027. destroy_workqueue(nbd->recv_workq);
  1028. nbd->recv_workq = NULL;
  1029. nbd->tag_set.timeout = 0;
  1030. nbd->disk->queue->limits.discard_granularity = 0;
  1031. nbd->disk->queue->limits.discard_alignment = 0;
  1032. blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
  1033. blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
  1034. mutex_unlock(&nbd->config_lock);
  1035. nbd_put(nbd);
  1036. module_put(THIS_MODULE);
  1037. }
  1038. }
  1039. static int nbd_start_device(struct nbd_device *nbd)
  1040. {
  1041. struct nbd_config *config = nbd->config;
  1042. int num_connections = config->num_connections;
  1043. int error = 0, i;
  1044. if (nbd->task_recv)
  1045. return -EBUSY;
  1046. if (!config->socks)
  1047. return -EINVAL;
  1048. if (num_connections > 1 &&
  1049. !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
  1050. dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
  1051. return -EINVAL;
  1052. }
  1053. nbd->recv_workq = alloc_workqueue("knbd%d-recv",
  1054. WQ_MEM_RECLAIM | WQ_HIGHPRI |
  1055. WQ_UNBOUND, 0, nbd->index);
  1056. if (!nbd->recv_workq) {
  1057. dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
  1058. return -ENOMEM;
  1059. }
  1060. blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
  1061. nbd->task_recv = current;
  1062. nbd_parse_flags(nbd);
  1063. error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
  1064. if (error) {
  1065. dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
  1066. return error;
  1067. }
  1068. set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
  1069. nbd_dev_dbg_init(nbd);
  1070. for (i = 0; i < num_connections; i++) {
  1071. struct recv_thread_args *args;
  1072. args = kzalloc(sizeof(*args), GFP_KERNEL);
  1073. if (!args) {
  1074. sock_shutdown(nbd);
  1075. /*
  1076. * If num_connections is m (2 < m),
  1077. * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
  1078. * But NO.(n + 1) failed. We still have n recv threads.
  1079. * So, add flush_workqueue here to prevent recv threads
  1080. * dropping the last config_refs and trying to destroy
  1081. * the workqueue from inside the workqueue.
  1082. */
  1083. if (i)
  1084. flush_workqueue(nbd->recv_workq);
  1085. return -ENOMEM;
  1086. }
  1087. sk_set_memalloc(config->socks[i]->sock->sk);
  1088. if (nbd->tag_set.timeout)
  1089. config->socks[i]->sock->sk->sk_sndtimeo =
  1090. nbd->tag_set.timeout;
  1091. atomic_inc(&config->recv_threads);
  1092. refcount_inc(&nbd->config_refs);
  1093. INIT_WORK(&args->work, recv_work);
  1094. args->nbd = nbd;
  1095. args->index = i;
  1096. queue_work(nbd->recv_workq, &args->work);
  1097. }
  1098. nbd_size_update(nbd);
  1099. return error;
  1100. }
  1101. static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
  1102. {
  1103. struct nbd_config *config = nbd->config;
  1104. int ret;
  1105. ret = nbd_start_device(nbd);
  1106. if (ret)
  1107. return ret;
  1108. if (max_part)
  1109. bdev->bd_invalidated = 1;
  1110. mutex_unlock(&nbd->config_lock);
  1111. ret = wait_event_interruptible(config->recv_wq,
  1112. atomic_read(&config->recv_threads) == 0);
  1113. if (ret)
  1114. sock_shutdown(nbd);
  1115. flush_workqueue(nbd->recv_workq);
  1116. mutex_lock(&nbd->config_lock);
  1117. nbd_bdev_reset(bdev);
  1118. /* user requested, ignore socket errors */
  1119. if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
  1120. ret = 0;
  1121. if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
  1122. ret = -ETIMEDOUT;
  1123. return ret;
  1124. }
  1125. static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
  1126. struct block_device *bdev)
  1127. {
  1128. sock_shutdown(nbd);
  1129. __invalidate_device(bdev, true);
  1130. nbd_bdev_reset(bdev);
  1131. if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
  1132. &nbd->config->runtime_flags))
  1133. nbd_config_put(nbd);
  1134. }
  1135. static bool nbd_is_valid_blksize(unsigned long blksize)
  1136. {
  1137. if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
  1138. blksize > PAGE_SIZE)
  1139. return false;
  1140. return true;
  1141. }
  1142. /* Must be called with config_lock held */
  1143. static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
  1144. unsigned int cmd, unsigned long arg)
  1145. {
  1146. struct nbd_config *config = nbd->config;
  1147. switch (cmd) {
  1148. case NBD_DISCONNECT:
  1149. return nbd_disconnect(nbd);
  1150. case NBD_CLEAR_SOCK:
  1151. nbd_clear_sock_ioctl(nbd, bdev);
  1152. return 0;
  1153. case NBD_SET_SOCK:
  1154. return nbd_add_socket(nbd, arg, false);
  1155. case NBD_SET_BLKSIZE:
  1156. if (!arg)
  1157. arg = NBD_DEF_BLKSIZE;
  1158. if (!nbd_is_valid_blksize(arg))
  1159. return -EINVAL;
  1160. nbd_size_set(nbd, arg,
  1161. div_s64(config->bytesize, arg));
  1162. return 0;
  1163. case NBD_SET_SIZE:
  1164. nbd_size_set(nbd, config->blksize,
  1165. div_s64(arg, config->blksize));
  1166. return 0;
  1167. case NBD_SET_SIZE_BLOCKS:
  1168. nbd_size_set(nbd, config->blksize, arg);
  1169. return 0;
  1170. case NBD_SET_TIMEOUT:
  1171. if (arg) {
  1172. nbd->tag_set.timeout = arg * HZ;
  1173. blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
  1174. }
  1175. return 0;
  1176. case NBD_SET_FLAGS:
  1177. config->flags = arg;
  1178. return 0;
  1179. case NBD_DO_IT:
  1180. return nbd_start_device_ioctl(nbd, bdev);
  1181. case NBD_CLEAR_QUE:
  1182. /*
  1183. * This is for compatibility only. The queue is always cleared
  1184. * by NBD_DO_IT or NBD_CLEAR_SOCK.
  1185. */
  1186. return 0;
  1187. case NBD_PRINT_DEBUG:
  1188. /*
  1189. * For compatibility only, we no longer keep a list of
  1190. * outstanding requests.
  1191. */
  1192. return 0;
  1193. }
  1194. return -ENOTTY;
  1195. }
  1196. static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
  1197. unsigned int cmd, unsigned long arg)
  1198. {
  1199. struct nbd_device *nbd = bdev->bd_disk->private_data;
  1200. struct nbd_config *config = nbd->config;
  1201. int error = -EINVAL;
  1202. if (!capable(CAP_SYS_ADMIN))
  1203. return -EPERM;
  1204. /* The block layer will pass back some non-nbd ioctls in case we have
  1205. * special handling for them, but we don't so just return an error.
  1206. */
  1207. if (_IOC_TYPE(cmd) != 0xab)
  1208. return -EINVAL;
  1209. mutex_lock(&nbd->config_lock);
  1210. /* Don't allow ioctl operations on a nbd device that was created with
  1211. * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
  1212. */
  1213. if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
  1214. (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
  1215. error = __nbd_ioctl(bdev, nbd, cmd, arg);
  1216. else
  1217. dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
  1218. mutex_unlock(&nbd->config_lock);
  1219. return error;
  1220. }
  1221. static struct nbd_config *nbd_alloc_config(void)
  1222. {
  1223. struct nbd_config *config;
  1224. config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
  1225. if (!config)
  1226. return NULL;
  1227. atomic_set(&config->recv_threads, 0);
  1228. init_waitqueue_head(&config->recv_wq);
  1229. init_waitqueue_head(&config->conn_wait);
  1230. config->blksize = NBD_DEF_BLKSIZE;
  1231. atomic_set(&config->live_connections, 0);
  1232. try_module_get(THIS_MODULE);
  1233. return config;
  1234. }
  1235. static int nbd_open(struct block_device *bdev, fmode_t mode)
  1236. {
  1237. struct nbd_device *nbd;
  1238. int ret = 0;
  1239. mutex_lock(&nbd_index_mutex);
  1240. nbd = bdev->bd_disk->private_data;
  1241. if (!nbd) {
  1242. ret = -ENXIO;
  1243. goto out;
  1244. }
  1245. if (!refcount_inc_not_zero(&nbd->refs)) {
  1246. ret = -ENXIO;
  1247. goto out;
  1248. }
  1249. if (!refcount_inc_not_zero(&nbd->config_refs)) {
  1250. struct nbd_config *config;
  1251. mutex_lock(&nbd->config_lock);
  1252. if (refcount_inc_not_zero(&nbd->config_refs)) {
  1253. mutex_unlock(&nbd->config_lock);
  1254. goto out;
  1255. }
  1256. config = nbd->config = nbd_alloc_config();
  1257. if (!config) {
  1258. ret = -ENOMEM;
  1259. mutex_unlock(&nbd->config_lock);
  1260. goto out;
  1261. }
  1262. refcount_set(&nbd->config_refs, 1);
  1263. refcount_inc(&nbd->refs);
  1264. mutex_unlock(&nbd->config_lock);
  1265. bdev->bd_invalidated = 1;
  1266. } else if (nbd_disconnected(nbd->config)) {
  1267. bdev->bd_invalidated = 1;
  1268. }
  1269. out:
  1270. mutex_unlock(&nbd_index_mutex);
  1271. return ret;
  1272. }
  1273. static void nbd_release(struct gendisk *disk, fmode_t mode)
  1274. {
  1275. struct nbd_device *nbd = disk->private_data;
  1276. struct block_device *bdev = bdget_disk(disk, 0);
  1277. if (test_bit(NBD_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
  1278. bdev->bd_openers == 0)
  1279. nbd_disconnect_and_put(nbd);
  1280. nbd_config_put(nbd);
  1281. nbd_put(nbd);
  1282. }
  1283. static const struct block_device_operations nbd_fops =
  1284. {
  1285. .owner = THIS_MODULE,
  1286. .open = nbd_open,
  1287. .release = nbd_release,
  1288. .ioctl = nbd_ioctl,
  1289. .compat_ioctl = nbd_ioctl,
  1290. };
  1291. #if IS_ENABLED(CONFIG_DEBUG_FS)
  1292. static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
  1293. {
  1294. struct nbd_device *nbd = s->private;
  1295. if (nbd->task_recv)
  1296. seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
  1297. return 0;
  1298. }
  1299. static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
  1300. {
  1301. return single_open(file, nbd_dbg_tasks_show, inode->i_private);
  1302. }
  1303. static const struct file_operations nbd_dbg_tasks_ops = {
  1304. .open = nbd_dbg_tasks_open,
  1305. .read = seq_read,
  1306. .llseek = seq_lseek,
  1307. .release = single_release,
  1308. };
  1309. static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
  1310. {
  1311. struct nbd_device *nbd = s->private;
  1312. u32 flags = nbd->config->flags;
  1313. seq_printf(s, "Hex: 0x%08x\n\n", flags);
  1314. seq_puts(s, "Known flags:\n");
  1315. if (flags & NBD_FLAG_HAS_FLAGS)
  1316. seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
  1317. if (flags & NBD_FLAG_READ_ONLY)
  1318. seq_puts(s, "NBD_FLAG_READ_ONLY\n");
  1319. if (flags & NBD_FLAG_SEND_FLUSH)
  1320. seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
  1321. if (flags & NBD_FLAG_SEND_FUA)
  1322. seq_puts(s, "NBD_FLAG_SEND_FUA\n");
  1323. if (flags & NBD_FLAG_SEND_TRIM)
  1324. seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
  1325. return 0;
  1326. }
  1327. static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
  1328. {
  1329. return single_open(file, nbd_dbg_flags_show, inode->i_private);
  1330. }
  1331. static const struct file_operations nbd_dbg_flags_ops = {
  1332. .open = nbd_dbg_flags_open,
  1333. .read = seq_read,
  1334. .llseek = seq_lseek,
  1335. .release = single_release,
  1336. };
  1337. static int nbd_dev_dbg_init(struct nbd_device *nbd)
  1338. {
  1339. struct dentry *dir;
  1340. struct nbd_config *config = nbd->config;
  1341. if (!nbd_dbg_dir)
  1342. return -EIO;
  1343. dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
  1344. if (!dir) {
  1345. dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
  1346. nbd_name(nbd));
  1347. return -EIO;
  1348. }
  1349. config->dbg_dir = dir;
  1350. debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
  1351. debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
  1352. debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
  1353. debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
  1354. debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
  1355. return 0;
  1356. }
  1357. static void nbd_dev_dbg_close(struct nbd_device *nbd)
  1358. {
  1359. debugfs_remove_recursive(nbd->config->dbg_dir);
  1360. }
  1361. static int nbd_dbg_init(void)
  1362. {
  1363. struct dentry *dbg_dir;
  1364. dbg_dir = debugfs_create_dir("nbd", NULL);
  1365. if (!dbg_dir)
  1366. return -EIO;
  1367. nbd_dbg_dir = dbg_dir;
  1368. return 0;
  1369. }
  1370. static void nbd_dbg_close(void)
  1371. {
  1372. debugfs_remove_recursive(nbd_dbg_dir);
  1373. }
  1374. #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
  1375. static int nbd_dev_dbg_init(struct nbd_device *nbd)
  1376. {
  1377. return 0;
  1378. }
  1379. static void nbd_dev_dbg_close(struct nbd_device *nbd)
  1380. {
  1381. }
  1382. static int nbd_dbg_init(void)
  1383. {
  1384. return 0;
  1385. }
  1386. static void nbd_dbg_close(void)
  1387. {
  1388. }
  1389. #endif
  1390. static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
  1391. unsigned int hctx_idx, unsigned int numa_node)
  1392. {
  1393. struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
  1394. cmd->nbd = set->driver_data;
  1395. cmd->flags = 0;
  1396. mutex_init(&cmd->lock);
  1397. return 0;
  1398. }
  1399. static const struct blk_mq_ops nbd_mq_ops = {
  1400. .queue_rq = nbd_queue_rq,
  1401. .complete = nbd_complete_rq,
  1402. .init_request = nbd_init_request,
  1403. .timeout = nbd_xmit_timeout,
  1404. };
  1405. static int nbd_dev_add(int index)
  1406. {
  1407. struct nbd_device *nbd;
  1408. struct gendisk *disk;
  1409. struct request_queue *q;
  1410. int err = -ENOMEM;
  1411. nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
  1412. if (!nbd)
  1413. goto out;
  1414. disk = alloc_disk(1 << part_shift);
  1415. if (!disk)
  1416. goto out_free_nbd;
  1417. if (index >= 0) {
  1418. err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
  1419. GFP_KERNEL);
  1420. if (err == -ENOSPC)
  1421. err = -EEXIST;
  1422. } else {
  1423. err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
  1424. if (err >= 0)
  1425. index = err;
  1426. }
  1427. if (err < 0)
  1428. goto out_free_disk;
  1429. nbd->index = index;
  1430. nbd->disk = disk;
  1431. nbd->tag_set.ops = &nbd_mq_ops;
  1432. nbd->tag_set.nr_hw_queues = 1;
  1433. nbd->tag_set.queue_depth = 128;
  1434. nbd->tag_set.numa_node = NUMA_NO_NODE;
  1435. nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
  1436. nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
  1437. BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
  1438. nbd->tag_set.driver_data = nbd;
  1439. err = blk_mq_alloc_tag_set(&nbd->tag_set);
  1440. if (err)
  1441. goto out_free_idr;
  1442. q = blk_mq_init_queue(&nbd->tag_set);
  1443. if (IS_ERR(q)) {
  1444. err = PTR_ERR(q);
  1445. goto out_free_tags;
  1446. }
  1447. disk->queue = q;
  1448. /*
  1449. * Tell the block layer that we are not a rotational device
  1450. */
  1451. blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
  1452. blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
  1453. disk->queue->limits.discard_granularity = 0;
  1454. disk->queue->limits.discard_alignment = 0;
  1455. blk_queue_max_discard_sectors(disk->queue, 0);
  1456. blk_queue_max_segment_size(disk->queue, UINT_MAX);
  1457. blk_queue_max_segments(disk->queue, USHRT_MAX);
  1458. blk_queue_max_hw_sectors(disk->queue, 65536);
  1459. disk->queue->limits.max_sectors = 256;
  1460. mutex_init(&nbd->config_lock);
  1461. refcount_set(&nbd->config_refs, 0);
  1462. refcount_set(&nbd->refs, 1);
  1463. INIT_LIST_HEAD(&nbd->list);
  1464. disk->major = NBD_MAJOR;
  1465. disk->first_minor = index << part_shift;
  1466. disk->fops = &nbd_fops;
  1467. disk->private_data = nbd;
  1468. sprintf(disk->disk_name, "nbd%d", index);
  1469. add_disk(disk);
  1470. nbd_total_devices++;
  1471. return index;
  1472. out_free_tags:
  1473. blk_mq_free_tag_set(&nbd->tag_set);
  1474. out_free_idr:
  1475. idr_remove(&nbd_index_idr, index);
  1476. out_free_disk:
  1477. put_disk(disk);
  1478. out_free_nbd:
  1479. kfree(nbd);
  1480. out:
  1481. return err;
  1482. }
  1483. static int find_free_cb(int id, void *ptr, void *data)
  1484. {
  1485. struct nbd_device *nbd = ptr;
  1486. struct nbd_device **found = data;
  1487. if (!refcount_read(&nbd->config_refs)) {
  1488. *found = nbd;
  1489. return 1;
  1490. }
  1491. return 0;
  1492. }
  1493. /* Netlink interface. */
  1494. static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
  1495. [NBD_ATTR_INDEX] = { .type = NLA_U32 },
  1496. [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
  1497. [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
  1498. [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
  1499. [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
  1500. [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
  1501. [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
  1502. [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
  1503. [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
  1504. };
  1505. static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
  1506. [NBD_SOCK_FD] = { .type = NLA_U32 },
  1507. };
  1508. /* We don't use this right now since we don't parse the incoming list, but we
  1509. * still want it here so userspace knows what to expect.
  1510. */
  1511. static const struct nla_policy __attribute__((unused))
  1512. nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
  1513. [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
  1514. [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
  1515. };
  1516. static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
  1517. {
  1518. struct nbd_device *nbd = NULL;
  1519. struct nbd_config *config;
  1520. int index = -1;
  1521. int ret;
  1522. bool put_dev = false;
  1523. if (!netlink_capable(skb, CAP_SYS_ADMIN))
  1524. return -EPERM;
  1525. if (info->attrs[NBD_ATTR_INDEX])
  1526. index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
  1527. if (!info->attrs[NBD_ATTR_SOCKETS]) {
  1528. printk(KERN_ERR "nbd: must specify at least one socket\n");
  1529. return -EINVAL;
  1530. }
  1531. if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
  1532. printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
  1533. return -EINVAL;
  1534. }
  1535. again:
  1536. mutex_lock(&nbd_index_mutex);
  1537. if (index == -1) {
  1538. ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
  1539. if (ret == 0) {
  1540. int new_index;
  1541. new_index = nbd_dev_add(-1);
  1542. if (new_index < 0) {
  1543. mutex_unlock(&nbd_index_mutex);
  1544. printk(KERN_ERR "nbd: failed to add new device\n");
  1545. return new_index;
  1546. }
  1547. nbd = idr_find(&nbd_index_idr, new_index);
  1548. }
  1549. } else {
  1550. nbd = idr_find(&nbd_index_idr, index);
  1551. if (!nbd) {
  1552. ret = nbd_dev_add(index);
  1553. if (ret < 0) {
  1554. mutex_unlock(&nbd_index_mutex);
  1555. printk(KERN_ERR "nbd: failed to add new device\n");
  1556. return ret;
  1557. }
  1558. nbd = idr_find(&nbd_index_idr, index);
  1559. }
  1560. }
  1561. if (!nbd) {
  1562. printk(KERN_ERR "nbd: couldn't find device at index %d\n",
  1563. index);
  1564. mutex_unlock(&nbd_index_mutex);
  1565. return -EINVAL;
  1566. }
  1567. if (!refcount_inc_not_zero(&nbd->refs)) {
  1568. mutex_unlock(&nbd_index_mutex);
  1569. if (index == -1)
  1570. goto again;
  1571. printk(KERN_ERR "nbd: device at index %d is going down\n",
  1572. index);
  1573. return -EINVAL;
  1574. }
  1575. mutex_unlock(&nbd_index_mutex);
  1576. mutex_lock(&nbd->config_lock);
  1577. if (refcount_read(&nbd->config_refs)) {
  1578. mutex_unlock(&nbd->config_lock);
  1579. nbd_put(nbd);
  1580. if (index == -1)
  1581. goto again;
  1582. printk(KERN_ERR "nbd: nbd%d already in use\n", index);
  1583. return -EBUSY;
  1584. }
  1585. if (WARN_ON(nbd->config)) {
  1586. mutex_unlock(&nbd->config_lock);
  1587. nbd_put(nbd);
  1588. return -EINVAL;
  1589. }
  1590. config = nbd->config = nbd_alloc_config();
  1591. if (!nbd->config) {
  1592. mutex_unlock(&nbd->config_lock);
  1593. nbd_put(nbd);
  1594. printk(KERN_ERR "nbd: couldn't allocate config\n");
  1595. return -ENOMEM;
  1596. }
  1597. refcount_set(&nbd->config_refs, 1);
  1598. set_bit(NBD_BOUND, &config->runtime_flags);
  1599. if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
  1600. u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
  1601. nbd_size_set(nbd, config->blksize,
  1602. div64_u64(bytes, config->blksize));
  1603. }
  1604. if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
  1605. u64 bsize =
  1606. nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
  1607. if (!bsize)
  1608. bsize = NBD_DEF_BLKSIZE;
  1609. if (!nbd_is_valid_blksize(bsize)) {
  1610. ret = -EINVAL;
  1611. goto out;
  1612. }
  1613. nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
  1614. }
  1615. if (info->attrs[NBD_ATTR_TIMEOUT]) {
  1616. u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
  1617. nbd->tag_set.timeout = timeout * HZ;
  1618. blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
  1619. }
  1620. if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
  1621. config->dead_conn_timeout =
  1622. nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
  1623. config->dead_conn_timeout *= HZ;
  1624. }
  1625. if (info->attrs[NBD_ATTR_SERVER_FLAGS])
  1626. config->flags =
  1627. nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
  1628. if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
  1629. u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
  1630. if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
  1631. set_bit(NBD_DESTROY_ON_DISCONNECT,
  1632. &config->runtime_flags);
  1633. put_dev = true;
  1634. }
  1635. if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
  1636. set_bit(NBD_DISCONNECT_ON_CLOSE,
  1637. &config->runtime_flags);
  1638. }
  1639. }
  1640. if (info->attrs[NBD_ATTR_SOCKETS]) {
  1641. struct nlattr *attr;
  1642. int rem, fd;
  1643. nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
  1644. rem) {
  1645. struct nlattr *socks[NBD_SOCK_MAX+1];
  1646. if (nla_type(attr) != NBD_SOCK_ITEM) {
  1647. printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
  1648. ret = -EINVAL;
  1649. goto out;
  1650. }
  1651. ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
  1652. nbd_sock_policy, info->extack);
  1653. if (ret != 0) {
  1654. printk(KERN_ERR "nbd: error processing sock list\n");
  1655. ret = -EINVAL;
  1656. goto out;
  1657. }
  1658. if (!socks[NBD_SOCK_FD])
  1659. continue;
  1660. fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
  1661. ret = nbd_add_socket(nbd, fd, true);
  1662. if (ret)
  1663. goto out;
  1664. }
  1665. }
  1666. ret = nbd_start_device(nbd);
  1667. out:
  1668. mutex_unlock(&nbd->config_lock);
  1669. if (!ret) {
  1670. set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
  1671. refcount_inc(&nbd->config_refs);
  1672. nbd_connect_reply(info, nbd->index);
  1673. }
  1674. nbd_config_put(nbd);
  1675. if (put_dev)
  1676. nbd_put(nbd);
  1677. return ret;
  1678. }
  1679. static void nbd_disconnect_and_put(struct nbd_device *nbd)
  1680. {
  1681. mutex_lock(&nbd->config_lock);
  1682. nbd_disconnect(nbd);
  1683. nbd_clear_sock(nbd);
  1684. mutex_unlock(&nbd->config_lock);
  1685. /*
  1686. * Make sure recv thread has finished, so it does not drop the last
  1687. * config ref and try to destroy the workqueue from inside the work
  1688. * queue.
  1689. */
  1690. flush_workqueue(nbd->recv_workq);
  1691. if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
  1692. &nbd->config->runtime_flags))
  1693. nbd_config_put(nbd);
  1694. }
  1695. static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
  1696. {
  1697. struct nbd_device *nbd;
  1698. int index;
  1699. if (!netlink_capable(skb, CAP_SYS_ADMIN))
  1700. return -EPERM;
  1701. if (!info->attrs[NBD_ATTR_INDEX]) {
  1702. printk(KERN_ERR "nbd: must specify an index to disconnect\n");
  1703. return -EINVAL;
  1704. }
  1705. index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
  1706. mutex_lock(&nbd_index_mutex);
  1707. nbd = idr_find(&nbd_index_idr, index);
  1708. if (!nbd) {
  1709. mutex_unlock(&nbd_index_mutex);
  1710. printk(KERN_ERR "nbd: couldn't find device at index %d\n",
  1711. index);
  1712. return -EINVAL;
  1713. }
  1714. if (!refcount_inc_not_zero(&nbd->refs)) {
  1715. mutex_unlock(&nbd_index_mutex);
  1716. printk(KERN_ERR "nbd: device at index %d is going down\n",
  1717. index);
  1718. return -EINVAL;
  1719. }
  1720. mutex_unlock(&nbd_index_mutex);
  1721. if (!refcount_inc_not_zero(&nbd->config_refs)) {
  1722. nbd_put(nbd);
  1723. return 0;
  1724. }
  1725. nbd_disconnect_and_put(nbd);
  1726. nbd_config_put(nbd);
  1727. nbd_put(nbd);
  1728. return 0;
  1729. }
  1730. static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
  1731. {
  1732. struct nbd_device *nbd = NULL;
  1733. struct nbd_config *config;
  1734. int index;
  1735. int ret = 0;
  1736. bool put_dev = false;
  1737. if (!netlink_capable(skb, CAP_SYS_ADMIN))
  1738. return -EPERM;
  1739. if (!info->attrs[NBD_ATTR_INDEX]) {
  1740. printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
  1741. return -EINVAL;
  1742. }
  1743. index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
  1744. mutex_lock(&nbd_index_mutex);
  1745. nbd = idr_find(&nbd_index_idr, index);
  1746. if (!nbd) {
  1747. mutex_unlock(&nbd_index_mutex);
  1748. printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
  1749. index);
  1750. return -EINVAL;
  1751. }
  1752. if (!refcount_inc_not_zero(&nbd->refs)) {
  1753. mutex_unlock(&nbd_index_mutex);
  1754. printk(KERN_ERR "nbd: device at index %d is going down\n",
  1755. index);
  1756. return -EINVAL;
  1757. }
  1758. mutex_unlock(&nbd_index_mutex);
  1759. if (!refcount_inc_not_zero(&nbd->config_refs)) {
  1760. dev_err(nbd_to_dev(nbd),
  1761. "not configured, cannot reconfigure\n");
  1762. nbd_put(nbd);
  1763. return -EINVAL;
  1764. }
  1765. mutex_lock(&nbd->config_lock);
  1766. config = nbd->config;
  1767. if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
  1768. !nbd->task_recv) {
  1769. dev_err(nbd_to_dev(nbd),
  1770. "not configured, cannot reconfigure\n");
  1771. ret = -EINVAL;
  1772. goto out;
  1773. }
  1774. if (info->attrs[NBD_ATTR_TIMEOUT]) {
  1775. u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
  1776. nbd->tag_set.timeout = timeout * HZ;
  1777. blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
  1778. }
  1779. if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
  1780. config->dead_conn_timeout =
  1781. nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
  1782. config->dead_conn_timeout *= HZ;
  1783. }
  1784. if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
  1785. u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
  1786. if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
  1787. if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
  1788. &config->runtime_flags))
  1789. put_dev = true;
  1790. } else {
  1791. if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
  1792. &config->runtime_flags))
  1793. refcount_inc(&nbd->refs);
  1794. }
  1795. if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
  1796. set_bit(NBD_DISCONNECT_ON_CLOSE,
  1797. &config->runtime_flags);
  1798. } else {
  1799. clear_bit(NBD_DISCONNECT_ON_CLOSE,
  1800. &config->runtime_flags);
  1801. }
  1802. }
  1803. if (info->attrs[NBD_ATTR_SOCKETS]) {
  1804. struct nlattr *attr;
  1805. int rem, fd;
  1806. nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
  1807. rem) {
  1808. struct nlattr *socks[NBD_SOCK_MAX+1];
  1809. if (nla_type(attr) != NBD_SOCK_ITEM) {
  1810. printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
  1811. ret = -EINVAL;
  1812. goto out;
  1813. }
  1814. ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
  1815. nbd_sock_policy, info->extack);
  1816. if (ret != 0) {
  1817. printk(KERN_ERR "nbd: error processing sock list\n");
  1818. ret = -EINVAL;
  1819. goto out;
  1820. }
  1821. if (!socks[NBD_SOCK_FD])
  1822. continue;
  1823. fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
  1824. ret = nbd_reconnect_socket(nbd, fd);
  1825. if (ret) {
  1826. if (ret == -ENOSPC)
  1827. ret = 0;
  1828. goto out;
  1829. }
  1830. dev_info(nbd_to_dev(nbd), "reconnected socket\n");
  1831. }
  1832. }
  1833. out:
  1834. mutex_unlock(&nbd->config_lock);
  1835. nbd_config_put(nbd);
  1836. nbd_put(nbd);
  1837. if (put_dev)
  1838. nbd_put(nbd);
  1839. return ret;
  1840. }
  1841. static const struct genl_ops nbd_connect_genl_ops[] = {
  1842. {
  1843. .cmd = NBD_CMD_CONNECT,
  1844. .policy = nbd_attr_policy,
  1845. .doit = nbd_genl_connect,
  1846. },
  1847. {
  1848. .cmd = NBD_CMD_DISCONNECT,
  1849. .policy = nbd_attr_policy,
  1850. .doit = nbd_genl_disconnect,
  1851. },
  1852. {
  1853. .cmd = NBD_CMD_RECONFIGURE,
  1854. .policy = nbd_attr_policy,
  1855. .doit = nbd_genl_reconfigure,
  1856. },
  1857. {
  1858. .cmd = NBD_CMD_STATUS,
  1859. .policy = nbd_attr_policy,
  1860. .doit = nbd_genl_status,
  1861. },
  1862. };
  1863. static const struct genl_multicast_group nbd_mcast_grps[] = {
  1864. { .name = NBD_GENL_MCAST_GROUP_NAME, },
  1865. };
  1866. static struct genl_family nbd_genl_family __ro_after_init = {
  1867. .hdrsize = 0,
  1868. .name = NBD_GENL_FAMILY_NAME,
  1869. .version = NBD_GENL_VERSION,
  1870. .module = THIS_MODULE,
  1871. .ops = nbd_connect_genl_ops,
  1872. .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
  1873. .maxattr = NBD_ATTR_MAX,
  1874. .mcgrps = nbd_mcast_grps,
  1875. .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
  1876. };
  1877. static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
  1878. {
  1879. struct nlattr *dev_opt;
  1880. u8 connected = 0;
  1881. int ret;
  1882. /* This is a little racey, but for status it's ok. The
  1883. * reason we don't take a ref here is because we can't
  1884. * take a ref in the index == -1 case as we would need
  1885. * to put under the nbd_index_mutex, which could
  1886. * deadlock if we are configured to remove ourselves
  1887. * once we're disconnected.
  1888. */
  1889. if (refcount_read(&nbd->config_refs))
  1890. connected = 1;
  1891. dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
  1892. if (!dev_opt)
  1893. return -EMSGSIZE;
  1894. ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
  1895. if (ret)
  1896. return -EMSGSIZE;
  1897. ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
  1898. connected);
  1899. if (ret)
  1900. return -EMSGSIZE;
  1901. nla_nest_end(reply, dev_opt);
  1902. return 0;
  1903. }
  1904. static int status_cb(int id, void *ptr, void *data)
  1905. {
  1906. struct nbd_device *nbd = ptr;
  1907. return populate_nbd_status(nbd, (struct sk_buff *)data);
  1908. }
  1909. static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
  1910. {
  1911. struct nlattr *dev_list;
  1912. struct sk_buff *reply;
  1913. void *reply_head;
  1914. size_t msg_size;
  1915. int index = -1;
  1916. int ret = -ENOMEM;
  1917. if (info->attrs[NBD_ATTR_INDEX])
  1918. index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
  1919. mutex_lock(&nbd_index_mutex);
  1920. msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
  1921. nla_attr_size(sizeof(u8)));
  1922. msg_size *= (index == -1) ? nbd_total_devices : 1;
  1923. reply = genlmsg_new(msg_size, GFP_KERNEL);
  1924. if (!reply)
  1925. goto out;
  1926. reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
  1927. NBD_CMD_STATUS);
  1928. if (!reply_head) {
  1929. nlmsg_free(reply);
  1930. goto out;
  1931. }
  1932. dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
  1933. if (index == -1) {
  1934. ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
  1935. if (ret) {
  1936. nlmsg_free(reply);
  1937. goto out;
  1938. }
  1939. } else {
  1940. struct nbd_device *nbd;
  1941. nbd = idr_find(&nbd_index_idr, index);
  1942. if (nbd) {
  1943. ret = populate_nbd_status(nbd, reply);
  1944. if (ret) {
  1945. nlmsg_free(reply);
  1946. goto out;
  1947. }
  1948. }
  1949. }
  1950. nla_nest_end(reply, dev_list);
  1951. genlmsg_end(reply, reply_head);
  1952. genlmsg_reply(reply, info);
  1953. ret = 0;
  1954. out:
  1955. mutex_unlock(&nbd_index_mutex);
  1956. return ret;
  1957. }
  1958. static void nbd_connect_reply(struct genl_info *info, int index)
  1959. {
  1960. struct sk_buff *skb;
  1961. void *msg_head;
  1962. int ret;
  1963. skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
  1964. if (!skb)
  1965. return;
  1966. msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
  1967. NBD_CMD_CONNECT);
  1968. if (!msg_head) {
  1969. nlmsg_free(skb);
  1970. return;
  1971. }
  1972. ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
  1973. if (ret) {
  1974. nlmsg_free(skb);
  1975. return;
  1976. }
  1977. genlmsg_end(skb, msg_head);
  1978. genlmsg_reply(skb, info);
  1979. }
  1980. static void nbd_mcast_index(int index)
  1981. {
  1982. struct sk_buff *skb;
  1983. void *msg_head;
  1984. int ret;
  1985. skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
  1986. if (!skb)
  1987. return;
  1988. msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
  1989. NBD_CMD_LINK_DEAD);
  1990. if (!msg_head) {
  1991. nlmsg_free(skb);
  1992. return;
  1993. }
  1994. ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
  1995. if (ret) {
  1996. nlmsg_free(skb);
  1997. return;
  1998. }
  1999. genlmsg_end(skb, msg_head);
  2000. genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
  2001. }
  2002. static void nbd_dead_link_work(struct work_struct *work)
  2003. {
  2004. struct link_dead_args *args = container_of(work, struct link_dead_args,
  2005. work);
  2006. nbd_mcast_index(args->index);
  2007. kfree(args);
  2008. }
  2009. static int __init nbd_init(void)
  2010. {
  2011. int i;
  2012. BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
  2013. if (max_part < 0) {
  2014. printk(KERN_ERR "nbd: max_part must be >= 0\n");
  2015. return -EINVAL;
  2016. }
  2017. part_shift = 0;
  2018. if (max_part > 0) {
  2019. part_shift = fls(max_part);
  2020. /*
  2021. * Adjust max_part according to part_shift as it is exported
  2022. * to user space so that user can know the max number of
  2023. * partition kernel should be able to manage.
  2024. *
  2025. * Note that -1 is required because partition 0 is reserved
  2026. * for the whole disk.
  2027. */
  2028. max_part = (1UL << part_shift) - 1;
  2029. }
  2030. if ((1UL << part_shift) > DISK_MAX_PARTS)
  2031. return -EINVAL;
  2032. if (nbds_max > 1UL << (MINORBITS - part_shift))
  2033. return -EINVAL;
  2034. if (register_blkdev(NBD_MAJOR, "nbd"))
  2035. return -EIO;
  2036. if (genl_register_family(&nbd_genl_family)) {
  2037. unregister_blkdev(NBD_MAJOR, "nbd");
  2038. return -EINVAL;
  2039. }
  2040. nbd_dbg_init();
  2041. mutex_lock(&nbd_index_mutex);
  2042. for (i = 0; i < nbds_max; i++)
  2043. nbd_dev_add(i);
  2044. mutex_unlock(&nbd_index_mutex);
  2045. return 0;
  2046. }
  2047. static int nbd_exit_cb(int id, void *ptr, void *data)
  2048. {
  2049. struct list_head *list = (struct list_head *)data;
  2050. struct nbd_device *nbd = ptr;
  2051. list_add_tail(&nbd->list, list);
  2052. return 0;
  2053. }
  2054. static void __exit nbd_cleanup(void)
  2055. {
  2056. struct nbd_device *nbd;
  2057. LIST_HEAD(del_list);
  2058. nbd_dbg_close();
  2059. mutex_lock(&nbd_index_mutex);
  2060. idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
  2061. mutex_unlock(&nbd_index_mutex);
  2062. while (!list_empty(&del_list)) {
  2063. nbd = list_first_entry(&del_list, struct nbd_device, list);
  2064. list_del_init(&nbd->list);
  2065. if (refcount_read(&nbd->refs) != 1)
  2066. printk(KERN_ERR "nbd: possibly leaking a device\n");
  2067. nbd_put(nbd);
  2068. }
  2069. idr_destroy(&nbd_index_idr);
  2070. genl_unregister_family(&nbd_genl_family);
  2071. unregister_blkdev(NBD_MAJOR, "nbd");
  2072. }
  2073. module_init(nbd_init);
  2074. module_exit(nbd_cleanup);
  2075. MODULE_DESCRIPTION("Network Block Device");
  2076. MODULE_LICENSE("GPL");
  2077. module_param(nbds_max, int, 0444);
  2078. MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
  2079. module_param(max_part, int, 0444);
  2080. MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");