xref: /openbmc/qemu/util/iov.c (revision ca5aa28e)
1 /*
2  * Helpers for getting linearized buffers from iov / filling buffers into iovs
3  *
4  * Copyright IBM, Corp. 2007, 2008
5  * Copyright (C) 2010 Red Hat, Inc.
6  * Copyright (c) 2024 Seagate Technology LLC and/or its Affiliates
7  *
8  * Author(s):
9  *  Anthony Liguori <aliguori@us.ibm.com>
10  *  Amit Shah <amit.shah@redhat.com>
11  *  Michael Tokarev <mjt@tls.msk.ru>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  * Contributions after 2012-01-13 are licensed under the terms of the
17  * GNU GPL, version 2 or (at your option) any later version.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/iov.h"
22 #include "qemu/sockets.h"
23 #include "qemu/cutils.h"
24 
25 size_t iov_from_buf_full(const struct iovec *iov, unsigned int iov_cnt,
26                          size_t offset, const void *buf, size_t bytes)
27 {
28     size_t done;
29     unsigned int i;
30     for (i = 0, done = 0; (offset || done < bytes) && i < iov_cnt; i++) {
31         if (offset < iov[i].iov_len) {
32             size_t len = MIN(iov[i].iov_len - offset, bytes - done);
33             memcpy(iov[i].iov_base + offset, buf + done, len);
34             done += len;
35             offset = 0;
36         } else {
37             offset -= iov[i].iov_len;
38         }
39     }
40     assert(offset == 0);
41     return done;
42 }
43 
44 size_t iov_to_buf_full(const struct iovec *iov, const unsigned int iov_cnt,
45                        size_t offset, void *buf, size_t bytes)
46 {
47     size_t done;
48     unsigned int i;
49     for (i = 0, done = 0; (offset || done < bytes) && i < iov_cnt; i++) {
50         if (offset < iov[i].iov_len) {
51             size_t len = MIN(iov[i].iov_len - offset, bytes - done);
52             memcpy(buf + done, iov[i].iov_base + offset, len);
53             done += len;
54             offset = 0;
55         } else {
56             offset -= iov[i].iov_len;
57         }
58     }
59     assert(offset == 0);
60     return done;
61 }
62 
63 size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
64                   size_t offset, int fillc, size_t bytes)
65 {
66     size_t done;
67     unsigned int i;
68     for (i = 0, done = 0; (offset || done < bytes) && i < iov_cnt; i++) {
69         if (offset < iov[i].iov_len) {
70             size_t len = MIN(iov[i].iov_len - offset, bytes - done);
71             memset(iov[i].iov_base + offset, fillc, len);
72             done += len;
73             offset = 0;
74         } else {
75             offset -= iov[i].iov_len;
76         }
77     }
78     assert(offset == 0);
79     return done;
80 }
81 
82 size_t iov_size(const struct iovec *iov, const unsigned int iov_cnt)
83 {
84     size_t len;
85     unsigned int i;
86 
87     len = 0;
88     for (i = 0; i < iov_cnt; i++) {
89         len += iov[i].iov_len;
90     }
91     return len;
92 }
93 
94 /* helper function for iov_send_recv() */
95 static ssize_t
96 do_send_recv(int sockfd, int flags, struct iovec *iov, unsigned iov_cnt,
97              bool do_send)
98 {
99 #ifdef CONFIG_POSIX
100     ssize_t ret;
101     struct msghdr msg;
102     memset(&msg, 0, sizeof(msg));
103     msg.msg_iov = iov;
104     msg.msg_iovlen = iov_cnt;
105     do {
106         ret = do_send
107             ? sendmsg(sockfd, &msg, flags)
108             : recvmsg(sockfd, &msg, flags);
109     } while (ret < 0 && errno == EINTR);
110     return ret;
111 #else
112     /* else send piece-by-piece */
113     /*XXX Note: windows has WSASend() and WSARecv() */
114     unsigned i = 0;
115     ssize_t ret = 0;
116     ssize_t off = 0;
117     while (i < iov_cnt) {
118         ssize_t r = do_send
119             ? send(sockfd, iov[i].iov_base + off, iov[i].iov_len - off, flags)
120             : recv(sockfd, iov[i].iov_base + off, iov[i].iov_len - off, flags);
121         if (r > 0) {
122             ret += r;
123             off += r;
124             if (off < iov[i].iov_len) {
125                 continue;
126             }
127         } else if (!r) {
128             break;
129         } else if (errno == EINTR) {
130             continue;
131         } else {
132             /* else it is some "other" error,
133              * only return if there was no data processed. */
134             if (ret == 0) {
135                 ret = -1;
136             }
137             break;
138         }
139         off = 0;
140         i++;
141     }
142     return ret;
143 #endif
144 }
145 
146 ssize_t iov_send_recv(int sockfd, const struct iovec *_iov, unsigned iov_cnt,
147                       size_t offset, size_t bytes,
148                       bool do_send)
149 {
150     return iov_send_recv_with_flags(sockfd, 0, _iov, iov_cnt, offset, bytes,
151                                     do_send);
152 }
153 
154 ssize_t iov_send_recv_with_flags(int sockfd, int sockflags,
155                                  const struct iovec *_iov,
156                                  unsigned iov_cnt, size_t offset,
157                                  size_t bytes, bool do_send)
158 {
159     ssize_t total = 0;
160     ssize_t ret;
161     size_t orig_len, tail;
162     unsigned niov;
163     struct iovec *local_iov, *iov;
164 
165     if (bytes <= 0) {
166         return 0;
167     }
168 
169     local_iov = g_new0(struct iovec, iov_cnt);
170     iov_copy(local_iov, iov_cnt, _iov, iov_cnt, offset, bytes);
171     offset = 0;
172     iov = local_iov;
173 
174     while (bytes > 0) {
175         /* Find the start position, skipping `offset' bytes:
176          * first, skip all full-sized vector elements, */
177         for (niov = 0; niov < iov_cnt && offset >= iov[niov].iov_len; ++niov) {
178             offset -= iov[niov].iov_len;
179         }
180 
181         /* niov == iov_cnt would only be valid if bytes == 0, which
182          * we already ruled out in the loop condition.  */
183         assert(niov < iov_cnt);
184         iov += niov;
185         iov_cnt -= niov;
186 
187         if (offset) {
188             /* second, skip `offset' bytes from the (now) first element,
189              * undo it on exit */
190             iov[0].iov_base += offset;
191             iov[0].iov_len -= offset;
192         }
193         /* Find the end position skipping `bytes' bytes: */
194         /* first, skip all full-sized elements */
195         tail = bytes;
196         for (niov = 0; niov < iov_cnt && iov[niov].iov_len <= tail; ++niov) {
197             tail -= iov[niov].iov_len;
198         }
199         if (tail) {
200             /* second, fixup the last element, and remember the original
201              * length */
202             assert(niov < iov_cnt);
203             assert(iov[niov].iov_len > tail);
204             orig_len = iov[niov].iov_len;
205             iov[niov++].iov_len = tail;
206             ret = do_send_recv(sockfd, sockflags, iov, niov, do_send);
207             /* Undo the changes above before checking for errors */
208             iov[niov-1].iov_len = orig_len;
209         } else {
210             ret = do_send_recv(sockfd, sockflags, iov, niov, do_send);
211         }
212         if (offset) {
213             iov[0].iov_base -= offset;
214             iov[0].iov_len += offset;
215         }
216 
217         if (ret < 0) {
218             assert(errno != EINTR);
219             g_free(local_iov);
220             if (errno == EAGAIN && total > 0) {
221                 return total;
222             }
223             return -1;
224         }
225 
226         if (ret == 0 && !do_send) {
227             /* recv returns 0 when the peer has performed an orderly
228              * shutdown. */
229             break;
230         }
231 
232         /* Prepare for the next iteration */
233         offset += ret;
234         total += ret;
235         bytes -= ret;
236     }
237 
238     g_free(local_iov);
239     return total;
240 }
241 
242 
243 void iov_hexdump(const struct iovec *iov, const unsigned int iov_cnt,
244                  FILE *fp, const char *prefix, size_t limit)
245 {
246     int v;
247     size_t size = 0;
248     char *buf;
249 
250     for (v = 0; v < iov_cnt; v++) {
251         size += iov[v].iov_len;
252     }
253     size = size > limit ? limit : size;
254     buf = g_malloc(size);
255     iov_to_buf(iov, iov_cnt, 0, buf, size);
256     qemu_hexdump(fp, prefix, buf, size);
257     g_free(buf);
258 }
259 
260 unsigned iov_copy(struct iovec *dst_iov, unsigned int dst_iov_cnt,
261                  const struct iovec *iov, unsigned int iov_cnt,
262                  size_t offset, size_t bytes)
263 {
264     size_t len;
265     unsigned int i, j;
266     for (i = 0, j = 0;
267          i < iov_cnt && j < dst_iov_cnt && (offset || bytes); i++) {
268         if (offset >= iov[i].iov_len) {
269             offset -= iov[i].iov_len;
270             continue;
271         }
272         len = MIN(bytes, iov[i].iov_len - offset);
273 
274         dst_iov[j].iov_base = iov[i].iov_base + offset;
275         dst_iov[j].iov_len = len;
276         j++;
277         bytes -= len;
278         offset = 0;
279     }
280     assert(offset == 0);
281     return j;
282 }
283 
284 /* io vectors */
285 
286 void qemu_iovec_init(QEMUIOVector *qiov, int alloc_hint)
287 {
288     qiov->iov = g_new(struct iovec, alloc_hint);
289     qiov->niov = 0;
290     qiov->nalloc = alloc_hint;
291     qiov->size = 0;
292 }
293 
294 void qemu_iovec_init_external(QEMUIOVector *qiov, struct iovec *iov, int niov)
295 {
296     int i;
297 
298     qiov->iov = iov;
299     qiov->niov = niov;
300     qiov->nalloc = -1;
301     qiov->size = 0;
302     for (i = 0; i < niov; i++)
303         qiov->size += iov[i].iov_len;
304 }
305 
306 void qemu_iovec_add(QEMUIOVector *qiov, void *base, size_t len)
307 {
308     assert(qiov->nalloc != -1);
309 
310     if (qiov->niov == qiov->nalloc) {
311         qiov->nalloc = 2 * qiov->nalloc + 1;
312         qiov->iov = g_renew(struct iovec, qiov->iov, qiov->nalloc);
313     }
314     qiov->iov[qiov->niov].iov_base = base;
315     qiov->iov[qiov->niov].iov_len = len;
316     qiov->size += len;
317     ++qiov->niov;
318 }
319 
320 /*
321  * Concatenates (partial) iovecs from src_iov to the end of dst.
322  * It starts copying after skipping `soffset' bytes at the
323  * beginning of src and adds individual vectors from src to
324  * dst copies up to `sbytes' bytes total, or up to the end
325  * of src_iov if it comes first.  This way, it is okay to specify
326  * very large value for `sbytes' to indicate "up to the end
327  * of src".
328  * Only vector pointers are processed, not the actual data buffers.
329  */
330 size_t qemu_iovec_concat_iov(QEMUIOVector *dst,
331                              struct iovec *src_iov, unsigned int src_cnt,
332                              size_t soffset, size_t sbytes)
333 {
334     int i;
335     size_t done;
336 
337     if (!sbytes) {
338         return 0;
339     }
340     assert(dst->nalloc != -1);
341     for (i = 0, done = 0; done < sbytes && i < src_cnt; i++) {
342         if (soffset < src_iov[i].iov_len) {
343             size_t len = MIN(src_iov[i].iov_len - soffset, sbytes - done);
344             qemu_iovec_add(dst, src_iov[i].iov_base + soffset, len);
345             done += len;
346             soffset = 0;
347         } else {
348             soffset -= src_iov[i].iov_len;
349         }
350     }
351     assert(soffset == 0); /* offset beyond end of src */
352 
353     return done;
354 }
355 
356 /*
357  * Concatenates (partial) iovecs from src to the end of dst.
358  * It starts copying after skipping `soffset' bytes at the
359  * beginning of src and adds individual vectors from src to
360  * dst copies up to `sbytes' bytes total, or up to the end
361  * of src if it comes first.  This way, it is okay to specify
362  * very large value for `sbytes' to indicate "up to the end
363  * of src".
364  * Only vector pointers are processed, not the actual data buffers.
365  */
366 void qemu_iovec_concat(QEMUIOVector *dst,
367                        QEMUIOVector *src, size_t soffset, size_t sbytes)
368 {
369     qemu_iovec_concat_iov(dst, src->iov, src->niov, soffset, sbytes);
370 }
371 
372 /*
373  * qiov_find_iov
374  *
375  * Return pointer to iovec structure, where byte at @offset in original vector
376  * @iov exactly is.
377  * Set @remaining_offset to be offset inside that iovec to the same byte.
378  */
379 static struct iovec *iov_skip_offset(struct iovec *iov, size_t offset,
380                                      size_t *remaining_offset)
381 {
382     while (offset > 0 && offset >= iov->iov_len) {
383         offset -= iov->iov_len;
384         iov++;
385     }
386     *remaining_offset = offset;
387 
388     return iov;
389 }
390 
391 /*
392  * qemu_iovec_slice
393  *
394  * Find subarray of iovec's, containing requested range. @head would
395  * be offset in first iov (returned by the function), @tail would be
396  * count of extra bytes in last iovec (returned iov + @niov - 1).
397  */
398 struct iovec *qemu_iovec_slice(QEMUIOVector *qiov,
399                                size_t offset, size_t len,
400                                size_t *head, size_t *tail, int *niov)
401 {
402     struct iovec *iov, *end_iov;
403 
404     assert(offset + len <= qiov->size);
405 
406     iov = iov_skip_offset(qiov->iov, offset, head);
407     end_iov = iov_skip_offset(iov, *head + len, tail);
408 
409     if (*tail > 0) {
410         assert(*tail < end_iov->iov_len);
411         *tail = end_iov->iov_len - *tail;
412         end_iov++;
413     }
414 
415     *niov = end_iov - iov;
416 
417     return iov;
418 }
419 
420 int qemu_iovec_subvec_niov(QEMUIOVector *qiov, size_t offset, size_t len)
421 {
422     size_t head, tail;
423     int niov;
424 
425     qemu_iovec_slice(qiov, offset, len, &head, &tail, &niov);
426 
427     return niov;
428 }
429 
430 /*
431  * Check if the contents of subrange of qiov data is all zeroes.
432  */
433 bool qemu_iovec_is_zero(QEMUIOVector *qiov, size_t offset, size_t bytes)
434 {
435     struct iovec *iov;
436     size_t current_offset;
437 
438     assert(offset + bytes <= qiov->size);
439 
440     iov = iov_skip_offset(qiov->iov, offset, &current_offset);
441 
442     while (bytes) {
443         uint8_t *base = (uint8_t *)iov->iov_base + current_offset;
444         size_t len = MIN(iov->iov_len - current_offset, bytes);
445 
446         if (!buffer_is_zero(base, len)) {
447             return false;
448         }
449 
450         current_offset = 0;
451         bytes -= len;
452         iov++;
453     }
454 
455     return true;
456 }
457 
458 void qemu_iovec_init_slice(QEMUIOVector *qiov, QEMUIOVector *source,
459                            size_t offset, size_t len)
460 {
461     struct iovec *slice_iov;
462     int slice_niov;
463     size_t slice_head, slice_tail;
464 
465     assert(source->size >= len);
466     assert(source->size - len >= offset);
467 
468     slice_iov = qemu_iovec_slice(source, offset, len,
469                                  &slice_head, &slice_tail, &slice_niov);
470     if (slice_niov == 1) {
471         qemu_iovec_init_buf(qiov, slice_iov[0].iov_base + slice_head, len);
472     } else {
473         qemu_iovec_init(qiov, slice_niov);
474         qemu_iovec_concat_iov(qiov, slice_iov, slice_niov, slice_head, len);
475     }
476 }
477 
478 void qemu_iovec_destroy(QEMUIOVector *qiov)
479 {
480     if (qiov->nalloc != -1) {
481         g_free(qiov->iov);
482     }
483 
484     memset(qiov, 0, sizeof(*qiov));
485 }
486 
487 void qemu_iovec_reset(QEMUIOVector *qiov)
488 {
489     assert(qiov->nalloc != -1);
490 
491     qiov->niov = 0;
492     qiov->size = 0;
493 }
494 
495 size_t qemu_iovec_to_buf(QEMUIOVector *qiov, size_t offset,
496                          void *buf, size_t bytes)
497 {
498     return iov_to_buf(qiov->iov, qiov->niov, offset, buf, bytes);
499 }
500 
501 size_t qemu_iovec_from_buf(QEMUIOVector *qiov, size_t offset,
502                            const void *buf, size_t bytes)
503 {
504     return iov_from_buf(qiov->iov, qiov->niov, offset, buf, bytes);
505 }
506 
507 size_t qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
508                          int fillc, size_t bytes)
509 {
510     return iov_memset(qiov->iov, qiov->niov, offset, fillc, bytes);
511 }
512 
513 /**
514  * Check that I/O vector contents are identical
515  *
516  * The IO vectors must have the same structure (same length of all parts).
517  * A typical usage is to compare vectors created with qemu_iovec_clone().
518  *
519  * @a:          I/O vector
520  * @b:          I/O vector
521  * @ret:        Offset to first mismatching byte or -1 if match
522  */
523 ssize_t qemu_iovec_compare(QEMUIOVector *a, QEMUIOVector *b)
524 {
525     int i;
526     ssize_t offset = 0;
527 
528     assert(a->niov == b->niov);
529     for (i = 0; i < a->niov; i++) {
530         size_t len = 0;
531         uint8_t *p = (uint8_t *)a->iov[i].iov_base;
532         uint8_t *q = (uint8_t *)b->iov[i].iov_base;
533 
534         assert(a->iov[i].iov_len == b->iov[i].iov_len);
535         while (len < a->iov[i].iov_len && *p++ == *q++) {
536             len++;
537         }
538 
539         offset += len;
540 
541         if (len != a->iov[i].iov_len) {
542             return offset;
543         }
544     }
545     return -1;
546 }
547 
548 typedef struct {
549     int src_index;
550     struct iovec *src_iov;
551     void *dest_base;
552 } IOVectorSortElem;
553 
554 static int sortelem_cmp_src_base(const void *a, const void *b)
555 {
556     const IOVectorSortElem *elem_a = a;
557     const IOVectorSortElem *elem_b = b;
558 
559     /* Don't overflow */
560     if (elem_a->src_iov->iov_base < elem_b->src_iov->iov_base) {
561         return -1;
562     } else if (elem_a->src_iov->iov_base > elem_b->src_iov->iov_base) {
563         return 1;
564     } else {
565         return 0;
566     }
567 }
568 
569 static int sortelem_cmp_src_index(const void *a, const void *b)
570 {
571     const IOVectorSortElem *elem_a = a;
572     const IOVectorSortElem *elem_b = b;
573 
574     return elem_a->src_index - elem_b->src_index;
575 }
576 
577 /**
578  * Copy contents of I/O vector
579  *
580  * The relative relationships of overlapping iovecs are preserved.  This is
581  * necessary to ensure identical semantics in the cloned I/O vector.
582  */
583 void qemu_iovec_clone(QEMUIOVector *dest, const QEMUIOVector *src, void *buf)
584 {
585     g_autofree IOVectorSortElem *sortelems = g_new(IOVectorSortElem, src->niov);
586     void *last_end;
587     int i;
588 
589     /* Sort by source iovecs by base address */
590     for (i = 0; i < src->niov; i++) {
591         sortelems[i].src_index = i;
592         sortelems[i].src_iov = &src->iov[i];
593     }
594     qsort(sortelems, src->niov, sizeof(sortelems[0]), sortelem_cmp_src_base);
595 
596     /* Allocate buffer space taking into account overlapping iovecs */
597     last_end = NULL;
598     for (i = 0; i < src->niov; i++) {
599         struct iovec *cur = sortelems[i].src_iov;
600         ptrdiff_t rewind = 0;
601 
602         /* Detect overlap */
603         if (last_end && last_end > cur->iov_base) {
604             rewind = last_end - cur->iov_base;
605         }
606 
607         sortelems[i].dest_base = buf - rewind;
608         buf += cur->iov_len - MIN(rewind, cur->iov_len);
609         last_end = MAX(cur->iov_base + cur->iov_len, last_end);
610     }
611 
612     /* Sort by source iovec index and build destination iovec */
613     qsort(sortelems, src->niov, sizeof(sortelems[0]), sortelem_cmp_src_index);
614     for (i = 0; i < src->niov; i++) {
615         qemu_iovec_add(dest, sortelems[i].dest_base, src->iov[i].iov_len);
616     }
617 }
618 
619 void iov_discard_undo(IOVDiscardUndo *undo)
620 {
621     /* Restore original iovec if it was modified */
622     if (undo->modified_iov) {
623         *undo->modified_iov = undo->orig;
624     }
625 }
626 
627 size_t iov_discard_front_undoable(struct iovec **iov,
628                                   unsigned int *iov_cnt,
629                                   size_t bytes,
630                                   IOVDiscardUndo *undo)
631 {
632     size_t total = 0;
633     struct iovec *cur;
634 
635     if (undo) {
636         undo->modified_iov = NULL;
637     }
638 
639     for (cur = *iov; *iov_cnt > 0; cur++) {
640         if (cur->iov_len > bytes) {
641             if (undo) {
642                 undo->modified_iov = cur;
643                 undo->orig = *cur;
644             }
645 
646             cur->iov_base += bytes;
647             cur->iov_len -= bytes;
648             total += bytes;
649             break;
650         }
651 
652         bytes -= cur->iov_len;
653         total += cur->iov_len;
654         *iov_cnt -= 1;
655     }
656 
657     *iov = cur;
658     return total;
659 }
660 
661 size_t iov_discard_front(struct iovec **iov, unsigned int *iov_cnt,
662                          size_t bytes)
663 {
664     return iov_discard_front_undoable(iov, iov_cnt, bytes, NULL);
665 }
666 
667 size_t iov_discard_back_undoable(struct iovec *iov,
668                                  unsigned int *iov_cnt,
669                                  size_t bytes,
670                                  IOVDiscardUndo *undo)
671 {
672     size_t total = 0;
673     struct iovec *cur;
674 
675     if (undo) {
676         undo->modified_iov = NULL;
677     }
678 
679     if (*iov_cnt == 0) {
680         return 0;
681     }
682 
683     cur = iov + (*iov_cnt - 1);
684 
685     while (*iov_cnt > 0) {
686         if (cur->iov_len > bytes) {
687             if (undo) {
688                 undo->modified_iov = cur;
689                 undo->orig = *cur;
690             }
691 
692             cur->iov_len -= bytes;
693             total += bytes;
694             break;
695         }
696 
697         bytes -= cur->iov_len;
698         total += cur->iov_len;
699         cur--;
700         *iov_cnt -= 1;
701     }
702 
703     return total;
704 }
705 
706 size_t iov_discard_back(struct iovec *iov, unsigned int *iov_cnt,
707                         size_t bytes)
708 {
709     return iov_discard_back_undoable(iov, iov_cnt, bytes, NULL);
710 }
711 
712 void qemu_iovec_discard_back(QEMUIOVector *qiov, size_t bytes)
713 {
714     size_t total;
715     unsigned int niov = qiov->niov;
716 
717     assert(qiov->size >= bytes);
718     total = iov_discard_back(qiov->iov, &niov, bytes);
719     assert(total == bytes);
720 
721     qiov->niov = niov;
722     qiov->size -= bytes;
723 }
724