server.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. /*
  2. * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
  3. *
  4. * Network Block Device Server Side
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; under version 2 of the License.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "qemu/osdep.h"
  19. #include "nbd-internal.h"
  20. static int system_errno_to_nbd_errno(int err)
  21. {
  22. switch (err) {
  23. case 0:
  24. return NBD_SUCCESS;
  25. case EPERM:
  26. return NBD_EPERM;
  27. case EIO:
  28. return NBD_EIO;
  29. case ENOMEM:
  30. return NBD_ENOMEM;
  31. #ifdef EDQUOT
  32. case EDQUOT:
  33. #endif
  34. case EFBIG:
  35. case ENOSPC:
  36. return NBD_ENOSPC;
  37. case EINVAL:
  38. default:
  39. return NBD_EINVAL;
  40. }
  41. }
  42. /* Definitions for opaque data types */
  43. typedef struct NBDRequest NBDRequest;
  44. struct NBDRequest {
  45. QSIMPLEQ_ENTRY(NBDRequest) entry;
  46. NBDClient *client;
  47. uint8_t *data;
  48. };
  49. struct NBDExport {
  50. int refcount;
  51. void (*close)(NBDExport *exp);
  52. BlockBackend *blk;
  53. char *name;
  54. off_t dev_offset;
  55. off_t size;
  56. uint32_t nbdflags;
  57. QTAILQ_HEAD(, NBDClient) clients;
  58. QTAILQ_ENTRY(NBDExport) next;
  59. AioContext *ctx;
  60. Notifier eject_notifier;
  61. };
  62. static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
  63. struct NBDClient {
  64. int refcount;
  65. void (*close)(NBDClient *client);
  66. NBDExport *exp;
  67. int sock;
  68. Coroutine *recv_coroutine;
  69. CoMutex send_lock;
  70. Coroutine *send_coroutine;
  71. bool can_read;
  72. QTAILQ_ENTRY(NBDClient) next;
  73. int nb_requests;
  74. bool closing;
  75. };
  76. /* That's all folks */
  77. static void nbd_set_handlers(NBDClient *client);
  78. static void nbd_unset_handlers(NBDClient *client);
  79. static void nbd_update_can_read(NBDClient *client);
  80. static void nbd_negotiate_continue(void *opaque)
  81. {
  82. qemu_coroutine_enter(opaque, NULL);
  83. }
  84. static ssize_t nbd_negotiate_read(int fd, void *buffer, size_t size)
  85. {
  86. ssize_t ret;
  87. assert(qemu_in_coroutine());
  88. /* Negotiation are always in main loop. */
  89. qemu_set_fd_handler(fd, nbd_negotiate_continue, NULL,
  90. qemu_coroutine_self());
  91. ret = read_sync(fd, buffer, size);
  92. qemu_set_fd_handler(fd, NULL, NULL, NULL);
  93. return ret;
  94. }
  95. static ssize_t nbd_negotiate_write(int fd, void *buffer, size_t size)
  96. {
  97. ssize_t ret;
  98. assert(qemu_in_coroutine());
  99. /* Negotiation are always in main loop. */
  100. qemu_set_fd_handler(fd, NULL, nbd_negotiate_continue,
  101. qemu_coroutine_self());
  102. ret = write_sync(fd, buffer, size);
  103. qemu_set_fd_handler(fd, NULL, NULL, NULL);
  104. return ret;
  105. }
  106. static ssize_t nbd_negotiate_drop_sync(int fd, size_t size)
  107. {
  108. ssize_t ret, dropped = size;
  109. uint8_t *buffer = g_malloc(MIN(65536, size));
  110. while (size > 0) {
  111. ret = nbd_negotiate_read(fd, buffer, MIN(65536, size));
  112. if (ret < 0) {
  113. g_free(buffer);
  114. return ret;
  115. }
  116. assert(ret <= size);
  117. size -= ret;
  118. }
  119. g_free(buffer);
  120. return dropped;
  121. }
  122. /* Basic flow for negotiation
  123. Server Client
  124. Negotiate
  125. or
  126. Server Client
  127. Negotiate #1
  128. Option
  129. Negotiate #2
  130. ----
  131. followed by
  132. Server Client
  133. Request
  134. Response
  135. Request
  136. Response
  137. ...
  138. ...
  139. Request (type == 2)
  140. */
  141. static int nbd_negotiate_send_rep(int csock, uint32_t type, uint32_t opt)
  142. {
  143. uint64_t magic;
  144. uint32_t len;
  145. magic = cpu_to_be64(NBD_REP_MAGIC);
  146. if (nbd_negotiate_write(csock, &magic, sizeof(magic)) != sizeof(magic)) {
  147. LOG("write failed (rep magic)");
  148. return -EINVAL;
  149. }
  150. opt = cpu_to_be32(opt);
  151. if (nbd_negotiate_write(csock, &opt, sizeof(opt)) != sizeof(opt)) {
  152. LOG("write failed (rep opt)");
  153. return -EINVAL;
  154. }
  155. type = cpu_to_be32(type);
  156. if (nbd_negotiate_write(csock, &type, sizeof(type)) != sizeof(type)) {
  157. LOG("write failed (rep type)");
  158. return -EINVAL;
  159. }
  160. len = cpu_to_be32(0);
  161. if (nbd_negotiate_write(csock, &len, sizeof(len)) != sizeof(len)) {
  162. LOG("write failed (rep data length)");
  163. return -EINVAL;
  164. }
  165. return 0;
  166. }
  167. static int nbd_negotiate_send_rep_list(int csock, NBDExport *exp)
  168. {
  169. uint64_t magic, name_len;
  170. uint32_t opt, type, len;
  171. name_len = strlen(exp->name);
  172. magic = cpu_to_be64(NBD_REP_MAGIC);
  173. if (nbd_negotiate_write(csock, &magic, sizeof(magic)) != sizeof(magic)) {
  174. LOG("write failed (magic)");
  175. return -EINVAL;
  176. }
  177. opt = cpu_to_be32(NBD_OPT_LIST);
  178. if (nbd_negotiate_write(csock, &opt, sizeof(opt)) != sizeof(opt)) {
  179. LOG("write failed (opt)");
  180. return -EINVAL;
  181. }
  182. type = cpu_to_be32(NBD_REP_SERVER);
  183. if (nbd_negotiate_write(csock, &type, sizeof(type)) != sizeof(type)) {
  184. LOG("write failed (reply type)");
  185. return -EINVAL;
  186. }
  187. len = cpu_to_be32(name_len + sizeof(len));
  188. if (nbd_negotiate_write(csock, &len, sizeof(len)) != sizeof(len)) {
  189. LOG("write failed (length)");
  190. return -EINVAL;
  191. }
  192. len = cpu_to_be32(name_len);
  193. if (nbd_negotiate_write(csock, &len, sizeof(len)) != sizeof(len)) {
  194. LOG("write failed (length)");
  195. return -EINVAL;
  196. }
  197. if (nbd_negotiate_write(csock, exp->name, name_len) != name_len) {
  198. LOG("write failed (buffer)");
  199. return -EINVAL;
  200. }
  201. return 0;
  202. }
  203. static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length)
  204. {
  205. int csock;
  206. NBDExport *exp;
  207. csock = client->sock;
  208. if (length) {
  209. if (nbd_negotiate_drop_sync(csock, length) != length) {
  210. return -EIO;
  211. }
  212. return nbd_negotiate_send_rep(csock, NBD_REP_ERR_INVALID, NBD_OPT_LIST);
  213. }
  214. /* For each export, send a NBD_REP_SERVER reply. */
  215. QTAILQ_FOREACH(exp, &exports, next) {
  216. if (nbd_negotiate_send_rep_list(csock, exp)) {
  217. return -EINVAL;
  218. }
  219. }
  220. /* Finish with a NBD_REP_ACK. */
  221. return nbd_negotiate_send_rep(csock, NBD_REP_ACK, NBD_OPT_LIST);
  222. }
  223. static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length)
  224. {
  225. int rc = -EINVAL, csock = client->sock;
  226. char name[256];
  227. /* Client sends:
  228. [20 .. xx] export name (length bytes)
  229. */
  230. TRACE("Checking length");
  231. if (length > 255) {
  232. LOG("Bad length received");
  233. goto fail;
  234. }
  235. if (nbd_negotiate_read(csock, name, length) != length) {
  236. LOG("read failed");
  237. goto fail;
  238. }
  239. name[length] = '\0';
  240. client->exp = nbd_export_find(name);
  241. if (!client->exp) {
  242. LOG("export not found");
  243. goto fail;
  244. }
  245. QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
  246. nbd_export_get(client->exp);
  247. rc = 0;
  248. fail:
  249. return rc;
  250. }
  251. static int nbd_negotiate_options(NBDClient *client)
  252. {
  253. int csock = client->sock;
  254. uint32_t flags;
  255. /* Client sends:
  256. [ 0 .. 3] client flags
  257. [ 0 .. 7] NBD_OPTS_MAGIC
  258. [ 8 .. 11] NBD option
  259. [12 .. 15] Data length
  260. ... Rest of request
  261. [ 0 .. 7] NBD_OPTS_MAGIC
  262. [ 8 .. 11] Second NBD option
  263. [12 .. 15] Data length
  264. ... Rest of request
  265. */
  266. if (nbd_negotiate_read(csock, &flags, sizeof(flags)) != sizeof(flags)) {
  267. LOG("read failed");
  268. return -EIO;
  269. }
  270. TRACE("Checking client flags");
  271. be32_to_cpus(&flags);
  272. if (flags != 0 && flags != NBD_FLAG_C_FIXED_NEWSTYLE) {
  273. LOG("Bad client flags received");
  274. return -EIO;
  275. }
  276. while (1) {
  277. int ret;
  278. uint32_t tmp, length;
  279. uint64_t magic;
  280. if (nbd_negotiate_read(csock, &magic, sizeof(magic)) != sizeof(magic)) {
  281. LOG("read failed");
  282. return -EINVAL;
  283. }
  284. TRACE("Checking opts magic");
  285. if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
  286. LOG("Bad magic received");
  287. return -EINVAL;
  288. }
  289. if (nbd_negotiate_read(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
  290. LOG("read failed");
  291. return -EINVAL;
  292. }
  293. if (nbd_negotiate_read(csock, &length,
  294. sizeof(length)) != sizeof(length)) {
  295. LOG("read failed");
  296. return -EINVAL;
  297. }
  298. length = be32_to_cpu(length);
  299. TRACE("Checking option");
  300. switch (be32_to_cpu(tmp)) {
  301. case NBD_OPT_LIST:
  302. ret = nbd_negotiate_handle_list(client, length);
  303. if (ret < 0) {
  304. return ret;
  305. }
  306. break;
  307. case NBD_OPT_ABORT:
  308. return -EINVAL;
  309. case NBD_OPT_EXPORT_NAME:
  310. return nbd_negotiate_handle_export_name(client, length);
  311. default:
  312. tmp = be32_to_cpu(tmp);
  313. LOG("Unsupported option 0x%x", tmp);
  314. nbd_negotiate_send_rep(client->sock, NBD_REP_ERR_UNSUP, tmp);
  315. return -EINVAL;
  316. }
  317. }
  318. }
  319. typedef struct {
  320. NBDClient *client;
  321. Coroutine *co;
  322. } NBDClientNewData;
  323. static coroutine_fn int nbd_negotiate(NBDClientNewData *data)
  324. {
  325. NBDClient *client = data->client;
  326. int csock = client->sock;
  327. char buf[8 + 8 + 8 + 128];
  328. int rc;
  329. const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
  330. NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
  331. /* Negotiation header without options:
  332. [ 0 .. 7] passwd ("NBDMAGIC")
  333. [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
  334. [16 .. 23] size
  335. [24 .. 25] server flags (0)
  336. [26 .. 27] export flags
  337. [28 .. 151] reserved (0)
  338. Negotiation header with options, part 1:
  339. [ 0 .. 7] passwd ("NBDMAGIC")
  340. [ 8 .. 15] magic (NBD_OPTS_MAGIC)
  341. [16 .. 17] server flags (0)
  342. part 2 (after options are sent):
  343. [18 .. 25] size
  344. [26 .. 27] export flags
  345. [28 .. 151] reserved (0)
  346. */
  347. rc = -EINVAL;
  348. TRACE("Beginning negotiation.");
  349. memset(buf, 0, sizeof(buf));
  350. memcpy(buf, "NBDMAGIC", 8);
  351. if (client->exp) {
  352. assert ((client->exp->nbdflags & ~65535) == 0);
  353. cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
  354. cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);
  355. cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
  356. } else {
  357. cpu_to_be64w((uint64_t*)(buf + 8), NBD_OPTS_MAGIC);
  358. cpu_to_be16w((uint16_t *)(buf + 16), NBD_FLAG_FIXED_NEWSTYLE);
  359. }
  360. if (client->exp) {
  361. if (nbd_negotiate_write(csock, buf, sizeof(buf)) != sizeof(buf)) {
  362. LOG("write failed");
  363. goto fail;
  364. }
  365. } else {
  366. if (nbd_negotiate_write(csock, buf, 18) != 18) {
  367. LOG("write failed");
  368. goto fail;
  369. }
  370. rc = nbd_negotiate_options(client);
  371. if (rc != 0) {
  372. LOG("option negotiation failed");
  373. goto fail;
  374. }
  375. assert ((client->exp->nbdflags & ~65535) == 0);
  376. cpu_to_be64w((uint64_t*)(buf + 18), client->exp->size);
  377. cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
  378. if (nbd_negotiate_write(csock, buf + 18,
  379. sizeof(buf) - 18) != sizeof(buf) - 18) {
  380. LOG("write failed");
  381. goto fail;
  382. }
  383. }
  384. TRACE("Negotiation succeeded.");
  385. rc = 0;
  386. fail:
  387. return rc;
  388. }
  389. #ifdef __linux__
  390. int nbd_disconnect(int fd)
  391. {
  392. ioctl(fd, NBD_CLEAR_QUE);
  393. ioctl(fd, NBD_DISCONNECT);
  394. ioctl(fd, NBD_CLEAR_SOCK);
  395. return 0;
  396. }
  397. #else
  398. int nbd_disconnect(int fd)
  399. {
  400. return -ENOTSUP;
  401. }
  402. #endif
  403. static ssize_t nbd_receive_request(int csock, struct nbd_request *request)
  404. {
  405. uint8_t buf[NBD_REQUEST_SIZE];
  406. uint32_t magic;
  407. ssize_t ret;
  408. ret = read_sync(csock, buf, sizeof(buf));
  409. if (ret < 0) {
  410. return ret;
  411. }
  412. if (ret != sizeof(buf)) {
  413. LOG("read failed");
  414. return -EINVAL;
  415. }
  416. /* Request
  417. [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
  418. [ 4 .. 7] type (0 == READ, 1 == WRITE)
  419. [ 8 .. 15] handle
  420. [16 .. 23] from
  421. [24 .. 27] len
  422. */
  423. magic = be32_to_cpup((uint32_t*)buf);
  424. request->type = be32_to_cpup((uint32_t*)(buf + 4));
  425. request->handle = be64_to_cpup((uint64_t*)(buf + 8));
  426. request->from = be64_to_cpup((uint64_t*)(buf + 16));
  427. request->len = be32_to_cpup((uint32_t*)(buf + 24));
  428. TRACE("Got request: "
  429. "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
  430. magic, request->type, request->from, request->len);
  431. if (magic != NBD_REQUEST_MAGIC) {
  432. LOG("invalid magic (got 0x%x)", magic);
  433. return -EINVAL;
  434. }
  435. return 0;
  436. }
  437. static ssize_t nbd_send_reply(int csock, struct nbd_reply *reply)
  438. {
  439. uint8_t buf[NBD_REPLY_SIZE];
  440. ssize_t ret;
  441. reply->error = system_errno_to_nbd_errno(reply->error);
  442. /* Reply
  443. [ 0 .. 3] magic (NBD_REPLY_MAGIC)
  444. [ 4 .. 7] error (0 == no error)
  445. [ 7 .. 15] handle
  446. */
  447. cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
  448. cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
  449. cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
  450. TRACE("Sending response to client");
  451. ret = write_sync(csock, buf, sizeof(buf));
  452. if (ret < 0) {
  453. return ret;
  454. }
  455. if (ret != sizeof(buf)) {
  456. LOG("writing to socket failed");
  457. return -EINVAL;
  458. }
  459. return 0;
  460. }
  461. #define MAX_NBD_REQUESTS 16
  462. void nbd_client_get(NBDClient *client)
  463. {
  464. client->refcount++;
  465. }
  466. void nbd_client_put(NBDClient *client)
  467. {
  468. if (--client->refcount == 0) {
  469. /* The last reference should be dropped by client->close,
  470. * which is called by client_close.
  471. */
  472. assert(client->closing);
  473. nbd_unset_handlers(client);
  474. close(client->sock);
  475. client->sock = -1;
  476. if (client->exp) {
  477. QTAILQ_REMOVE(&client->exp->clients, client, next);
  478. nbd_export_put(client->exp);
  479. }
  480. g_free(client);
  481. }
  482. }
  483. static void client_close(NBDClient *client)
  484. {
  485. if (client->closing) {
  486. return;
  487. }
  488. client->closing = true;
  489. /* Force requests to finish. They will drop their own references,
  490. * then we'll close the socket and free the NBDClient.
  491. */
  492. shutdown(client->sock, 2);
  493. /* Also tell the client, so that they release their reference. */
  494. if (client->close) {
  495. client->close(client);
  496. }
  497. }
  498. static NBDRequest *nbd_request_get(NBDClient *client)
  499. {
  500. NBDRequest *req;
  501. assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
  502. client->nb_requests++;
  503. nbd_update_can_read(client);
  504. req = g_new0(NBDRequest, 1);
  505. nbd_client_get(client);
  506. req->client = client;
  507. return req;
  508. }
  509. static void nbd_request_put(NBDRequest *req)
  510. {
  511. NBDClient *client = req->client;
  512. if (req->data) {
  513. qemu_vfree(req->data);
  514. }
  515. g_free(req);
  516. client->nb_requests--;
  517. nbd_update_can_read(client);
  518. nbd_client_put(client);
  519. }
  520. static void blk_aio_attached(AioContext *ctx, void *opaque)
  521. {
  522. NBDExport *exp = opaque;
  523. NBDClient *client;
  524. TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
  525. exp->ctx = ctx;
  526. QTAILQ_FOREACH(client, &exp->clients, next) {
  527. nbd_set_handlers(client);
  528. }
  529. }
  530. static void blk_aio_detach(void *opaque)
  531. {
  532. NBDExport *exp = opaque;
  533. NBDClient *client;
  534. TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
  535. QTAILQ_FOREACH(client, &exp->clients, next) {
  536. nbd_unset_handlers(client);
  537. }
  538. exp->ctx = NULL;
  539. }
  540. static void nbd_eject_notifier(Notifier *n, void *data)
  541. {
  542. NBDExport *exp = container_of(n, NBDExport, eject_notifier);
  543. nbd_export_close(exp);
  544. }
  545. NBDExport *nbd_export_new(BlockBackend *blk, off_t dev_offset, off_t size,
  546. uint32_t nbdflags, void (*close)(NBDExport *),
  547. Error **errp)
  548. {
  549. NBDExport *exp = g_malloc0(sizeof(NBDExport));
  550. exp->refcount = 1;
  551. QTAILQ_INIT(&exp->clients);
  552. exp->blk = blk;
  553. exp->dev_offset = dev_offset;
  554. exp->nbdflags = nbdflags;
  555. exp->size = size < 0 ? blk_getlength(blk) : size;
  556. if (exp->size < 0) {
  557. error_setg_errno(errp, -exp->size,
  558. "Failed to determine the NBD export's length");
  559. goto fail;
  560. }
  561. exp->size -= exp->size % BDRV_SECTOR_SIZE;
  562. exp->close = close;
  563. exp->ctx = blk_get_aio_context(blk);
  564. blk_ref(blk);
  565. blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
  566. exp->eject_notifier.notify = nbd_eject_notifier;
  567. blk_add_remove_bs_notifier(blk, &exp->eject_notifier);
  568. /*
  569. * NBD exports are used for non-shared storage migration. Make sure
  570. * that BDRV_O_INACTIVE is cleared and the image is ready for write
  571. * access since the export could be available before migration handover.
  572. */
  573. aio_context_acquire(exp->ctx);
  574. blk_invalidate_cache(blk, NULL);
  575. aio_context_release(exp->ctx);
  576. return exp;
  577. fail:
  578. g_free(exp);
  579. return NULL;
  580. }
  581. NBDExport *nbd_export_find(const char *name)
  582. {
  583. NBDExport *exp;
  584. QTAILQ_FOREACH(exp, &exports, next) {
  585. if (strcmp(name, exp->name) == 0) {
  586. return exp;
  587. }
  588. }
  589. return NULL;
  590. }
  591. void nbd_export_set_name(NBDExport *exp, const char *name)
  592. {
  593. if (exp->name == name) {
  594. return;
  595. }
  596. nbd_export_get(exp);
  597. if (exp->name != NULL) {
  598. g_free(exp->name);
  599. exp->name = NULL;
  600. QTAILQ_REMOVE(&exports, exp, next);
  601. nbd_export_put(exp);
  602. }
  603. if (name != NULL) {
  604. nbd_export_get(exp);
  605. exp->name = g_strdup(name);
  606. QTAILQ_INSERT_TAIL(&exports, exp, next);
  607. }
  608. nbd_export_put(exp);
  609. }
  610. void nbd_export_close(NBDExport *exp)
  611. {
  612. NBDClient *client, *next;
  613. nbd_export_get(exp);
  614. QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
  615. client_close(client);
  616. }
  617. nbd_export_set_name(exp, NULL);
  618. nbd_export_put(exp);
  619. }
  620. void nbd_export_get(NBDExport *exp)
  621. {
  622. assert(exp->refcount > 0);
  623. exp->refcount++;
  624. }
  625. void nbd_export_put(NBDExport *exp)
  626. {
  627. assert(exp->refcount > 0);
  628. if (exp->refcount == 1) {
  629. nbd_export_close(exp);
  630. }
  631. if (--exp->refcount == 0) {
  632. assert(exp->name == NULL);
  633. if (exp->close) {
  634. exp->close(exp);
  635. }
  636. if (exp->blk) {
  637. notifier_remove(&exp->eject_notifier);
  638. blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
  639. blk_aio_detach, exp);
  640. blk_unref(exp->blk);
  641. exp->blk = NULL;
  642. }
  643. g_free(exp);
  644. }
  645. }
  646. BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
  647. {
  648. return exp->blk;
  649. }
  650. void nbd_export_close_all(void)
  651. {
  652. NBDExport *exp, *next;
  653. QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
  654. nbd_export_close(exp);
  655. }
  656. }
  657. static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
  658. int len)
  659. {
  660. NBDClient *client = req->client;
  661. int csock = client->sock;
  662. ssize_t rc, ret;
  663. qemu_co_mutex_lock(&client->send_lock);
  664. client->send_coroutine = qemu_coroutine_self();
  665. nbd_set_handlers(client);
  666. if (!len) {
  667. rc = nbd_send_reply(csock, reply);
  668. } else {
  669. socket_set_cork(csock, 1);
  670. rc = nbd_send_reply(csock, reply);
  671. if (rc >= 0) {
  672. ret = qemu_co_send(csock, req->data, len);
  673. if (ret != len) {
  674. rc = -EIO;
  675. }
  676. }
  677. socket_set_cork(csock, 0);
  678. }
  679. client->send_coroutine = NULL;
  680. nbd_set_handlers(client);
  681. qemu_co_mutex_unlock(&client->send_lock);
  682. return rc;
  683. }
  684. static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
  685. {
  686. NBDClient *client = req->client;
  687. int csock = client->sock;
  688. uint32_t command;
  689. ssize_t rc;
  690. client->recv_coroutine = qemu_coroutine_self();
  691. nbd_update_can_read(client);
  692. rc = nbd_receive_request(csock, request);
  693. if (rc < 0) {
  694. if (rc != -EAGAIN) {
  695. rc = -EIO;
  696. }
  697. goto out;
  698. }
  699. if ((request->from + request->len) < request->from) {
  700. LOG("integer overflow detected! "
  701. "you're probably being attacked");
  702. rc = -EINVAL;
  703. goto out;
  704. }
  705. TRACE("Decoding type");
  706. command = request->type & NBD_CMD_MASK_COMMAND;
  707. if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
  708. if (request->len > NBD_MAX_BUFFER_SIZE) {
  709. LOG("len (%u) is larger than max len (%u)",
  710. request->len, NBD_MAX_BUFFER_SIZE);
  711. rc = -EINVAL;
  712. goto out;
  713. }
  714. req->data = blk_try_blockalign(client->exp->blk, request->len);
  715. if (req->data == NULL) {
  716. rc = -ENOMEM;
  717. goto out;
  718. }
  719. }
  720. if (command == NBD_CMD_WRITE) {
  721. TRACE("Reading %u byte(s)", request->len);
  722. if (qemu_co_recv(csock, req->data, request->len) != request->len) {
  723. LOG("reading from socket failed");
  724. rc = -EIO;
  725. goto out;
  726. }
  727. }
  728. rc = 0;
  729. out:
  730. client->recv_coroutine = NULL;
  731. nbd_update_can_read(client);
  732. return rc;
  733. }
  734. static void nbd_trip(void *opaque)
  735. {
  736. NBDClient *client = opaque;
  737. NBDExport *exp = client->exp;
  738. NBDRequest *req;
  739. struct nbd_request request;
  740. struct nbd_reply reply;
  741. ssize_t ret;
  742. uint32_t command;
  743. TRACE("Reading request.");
  744. if (client->closing) {
  745. return;
  746. }
  747. req = nbd_request_get(client);
  748. ret = nbd_co_receive_request(req, &request);
  749. if (ret == -EAGAIN) {
  750. goto done;
  751. }
  752. if (ret == -EIO) {
  753. goto out;
  754. }
  755. reply.handle = request.handle;
  756. reply.error = 0;
  757. if (ret < 0) {
  758. reply.error = -ret;
  759. goto error_reply;
  760. }
  761. command = request.type & NBD_CMD_MASK_COMMAND;
  762. if (command != NBD_CMD_DISC && (request.from + request.len) > exp->size) {
  763. LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
  764. ", Offset: %" PRIu64 "\n",
  765. request.from, request.len,
  766. (uint64_t)exp->size, (uint64_t)exp->dev_offset);
  767. LOG("requested operation past EOF--bad client?");
  768. goto invalid_request;
  769. }
  770. if (client->closing) {
  771. /*
  772. * The client may be closed when we are blocked in
  773. * nbd_co_receive_request()
  774. */
  775. goto done;
  776. }
  777. switch (command) {
  778. case NBD_CMD_READ:
  779. TRACE("Request type is READ");
  780. if (request.type & NBD_CMD_FLAG_FUA) {
  781. ret = blk_co_flush(exp->blk);
  782. if (ret < 0) {
  783. LOG("flush failed");
  784. reply.error = -ret;
  785. goto error_reply;
  786. }
  787. }
  788. ret = blk_read(exp->blk,
  789. (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
  790. req->data, request.len / BDRV_SECTOR_SIZE);
  791. if (ret < 0) {
  792. LOG("reading from file failed");
  793. reply.error = -ret;
  794. goto error_reply;
  795. }
  796. TRACE("Read %u byte(s)", request.len);
  797. if (nbd_co_send_reply(req, &reply, request.len) < 0)
  798. goto out;
  799. break;
  800. case NBD_CMD_WRITE:
  801. TRACE("Request type is WRITE");
  802. if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
  803. TRACE("Server is read-only, return error");
  804. reply.error = EROFS;
  805. goto error_reply;
  806. }
  807. TRACE("Writing to device");
  808. ret = blk_write(exp->blk,
  809. (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
  810. req->data, request.len / BDRV_SECTOR_SIZE);
  811. if (ret < 0) {
  812. LOG("writing to file failed");
  813. reply.error = -ret;
  814. goto error_reply;
  815. }
  816. if (request.type & NBD_CMD_FLAG_FUA) {
  817. ret = blk_co_flush(exp->blk);
  818. if (ret < 0) {
  819. LOG("flush failed");
  820. reply.error = -ret;
  821. goto error_reply;
  822. }
  823. }
  824. if (nbd_co_send_reply(req, &reply, 0) < 0) {
  825. goto out;
  826. }
  827. break;
  828. case NBD_CMD_DISC:
  829. TRACE("Request type is DISCONNECT");
  830. errno = 0;
  831. goto out;
  832. case NBD_CMD_FLUSH:
  833. TRACE("Request type is FLUSH");
  834. ret = blk_co_flush(exp->blk);
  835. if (ret < 0) {
  836. LOG("flush failed");
  837. reply.error = -ret;
  838. }
  839. if (nbd_co_send_reply(req, &reply, 0) < 0) {
  840. goto out;
  841. }
  842. break;
  843. case NBD_CMD_TRIM:
  844. TRACE("Request type is TRIM");
  845. ret = blk_co_discard(exp->blk, (request.from + exp->dev_offset)
  846. / BDRV_SECTOR_SIZE,
  847. request.len / BDRV_SECTOR_SIZE);
  848. if (ret < 0) {
  849. LOG("discard failed");
  850. reply.error = -ret;
  851. }
  852. if (nbd_co_send_reply(req, &reply, 0) < 0) {
  853. goto out;
  854. }
  855. break;
  856. default:
  857. LOG("invalid request type (%u) received", request.type);
  858. invalid_request:
  859. reply.error = EINVAL;
  860. error_reply:
  861. if (nbd_co_send_reply(req, &reply, 0) < 0) {
  862. goto out;
  863. }
  864. break;
  865. }
  866. TRACE("Request/Reply complete");
  867. done:
  868. nbd_request_put(req);
  869. return;
  870. out:
  871. nbd_request_put(req);
  872. client_close(client);
  873. }
  874. static void nbd_read(void *opaque)
  875. {
  876. NBDClient *client = opaque;
  877. if (client->recv_coroutine) {
  878. qemu_coroutine_enter(client->recv_coroutine, NULL);
  879. } else {
  880. qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
  881. }
  882. }
  883. static void nbd_restart_write(void *opaque)
  884. {
  885. NBDClient *client = opaque;
  886. qemu_coroutine_enter(client->send_coroutine, NULL);
  887. }
  888. static void nbd_set_handlers(NBDClient *client)
  889. {
  890. if (client->exp && client->exp->ctx) {
  891. aio_set_fd_handler(client->exp->ctx, client->sock,
  892. true,
  893. client->can_read ? nbd_read : NULL,
  894. client->send_coroutine ? nbd_restart_write : NULL,
  895. client);
  896. }
  897. }
  898. static void nbd_unset_handlers(NBDClient *client)
  899. {
  900. if (client->exp && client->exp->ctx) {
  901. aio_set_fd_handler(client->exp->ctx, client->sock,
  902. true, NULL, NULL, NULL);
  903. }
  904. }
  905. static void nbd_update_can_read(NBDClient *client)
  906. {
  907. bool can_read = client->recv_coroutine ||
  908. client->nb_requests < MAX_NBD_REQUESTS;
  909. if (can_read != client->can_read) {
  910. client->can_read = can_read;
  911. nbd_set_handlers(client);
  912. /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
  913. * in nbd_set_handlers() will have taken care of that */
  914. }
  915. }
  916. static coroutine_fn void nbd_co_client_start(void *opaque)
  917. {
  918. NBDClientNewData *data = opaque;
  919. NBDClient *client = data->client;
  920. NBDExport *exp = client->exp;
  921. if (exp) {
  922. nbd_export_get(exp);
  923. }
  924. if (nbd_negotiate(data)) {
  925. client_close(client);
  926. goto out;
  927. }
  928. qemu_co_mutex_init(&client->send_lock);
  929. nbd_set_handlers(client);
  930. if (exp) {
  931. QTAILQ_INSERT_TAIL(&exp->clients, client, next);
  932. }
  933. out:
  934. g_free(data);
  935. }
  936. void nbd_client_new(NBDExport *exp, int csock, void (*close_fn)(NBDClient *))
  937. {
  938. NBDClient *client;
  939. NBDClientNewData *data = g_new(NBDClientNewData, 1);
  940. client = g_malloc0(sizeof(NBDClient));
  941. client->refcount = 1;
  942. client->exp = exp;
  943. client->sock = csock;
  944. client->can_read = true;
  945. client->close = close_fn;
  946. data->client = client;
  947. data->co = qemu_coroutine_create(nbd_co_client_start);
  948. qemu_coroutine_enter(data->co, data);
  949. }