nbd.c 53 KB

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