xref: /openbmc/qemu/hw/nvme/ns.c (revision df1f50c3)
1 /*
2  * QEMU NVM Express Virtual Namespace
3  *
4  * Copyright (c) 2019 CNEX Labs
5  * Copyright (c) 2020 Samsung Electronics
6  *
7  * Authors:
8  *  Klaus Jensen      <k.jensen@samsung.com>
9  *
10  * This work is licensed under the terms of the GNU GPL, version 2. See the
11  * COPYING file in the top-level directory.
12  *
13  */
14 
15 #include "qemu/osdep.h"
16 #include "qemu/units.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "qapi/error.h"
20 #include "qemu/bitops.h"
21 #include "sysemu/sysemu.h"
22 #include "sysemu/block-backend.h"
23 
24 #include "nvme.h"
25 #include "trace.h"
26 
27 #define MIN_DISCARD_GRANULARITY (4 * KiB)
28 #define NVME_DEFAULT_ZONE_SIZE   (128 * MiB)
29 
30 void nvme_ns_init_format(NvmeNamespace *ns)
31 {
32     NvmeIdNs *id_ns = &ns->id_ns;
33     BlockDriverInfo bdi;
34     int npdg, ret;
35     int64_t nlbas;
36 
37     ns->lbaf = id_ns->lbaf[NVME_ID_NS_FLBAS_INDEX(id_ns->flbas)];
38     ns->lbasz = 1 << ns->lbaf.ds;
39 
40     nlbas = ns->size / (ns->lbasz + ns->lbaf.ms);
41 
42     id_ns->nsze = cpu_to_le64(nlbas);
43 
44     /* no thin provisioning */
45     id_ns->ncap = id_ns->nsze;
46     id_ns->nuse = id_ns->ncap;
47 
48     ns->moff = nlbas << ns->lbaf.ds;
49 
50     npdg = ns->blkconf.discard_granularity / ns->lbasz;
51 
52     ret = bdrv_get_info(blk_bs(ns->blkconf.blk), &bdi);
53     if (ret >= 0 && bdi.cluster_size > ns->blkconf.discard_granularity) {
54         npdg = bdi.cluster_size / ns->lbasz;
55     }
56 
57     id_ns->npda = id_ns->npdg = npdg - 1;
58 }
59 
60 static int nvme_ns_init(NvmeNamespace *ns, Error **errp)
61 {
62     static uint64_t ns_count;
63     NvmeIdNs *id_ns = &ns->id_ns;
64     NvmeIdNsNvm *id_ns_nvm = &ns->id_ns_nvm;
65     uint8_t ds;
66     uint16_t ms;
67     int i;
68 
69     ns->csi = NVME_CSI_NVM;
70     ns->status = 0x0;
71 
72     ns->id_ns.dlfeat = 0x1;
73 
74     /* support DULBE and I/O optimization fields */
75     id_ns->nsfeat |= (0x4 | 0x10);
76 
77     if (ns->params.shared) {
78         id_ns->nmic |= NVME_NMIC_NS_SHARED;
79     }
80 
81     /* Substitute a missing EUI-64 by an autogenerated one */
82     ++ns_count;
83     if (!ns->params.eui64 && ns->params.eui64_default) {
84         ns->params.eui64 = ns_count + NVME_EUI64_DEFAULT;
85     }
86 
87     /* simple copy */
88     id_ns->mssrl = cpu_to_le16(ns->params.mssrl);
89     id_ns->mcl = cpu_to_le32(ns->params.mcl);
90     id_ns->msrc = ns->params.msrc;
91     id_ns->eui64 = cpu_to_be64(ns->params.eui64);
92 
93     ds = 31 - clz32(ns->blkconf.logical_block_size);
94     ms = ns->params.ms;
95 
96     id_ns->mc = NVME_ID_NS_MC_EXTENDED | NVME_ID_NS_MC_SEPARATE;
97 
98     if (ms && ns->params.mset) {
99         id_ns->flbas |= NVME_ID_NS_FLBAS_EXTENDED;
100     }
101 
102     id_ns->dpc = 0x1f;
103     id_ns->dps = ns->params.pi;
104     if (ns->params.pi && ns->params.pil) {
105         id_ns->dps |= NVME_ID_NS_DPS_FIRST_EIGHT;
106     }
107 
108     ns->pif = ns->params.pif;
109 
110     static const NvmeLBAF lbaf[16] = {
111         [0] = { .ds =  9           },
112         [1] = { .ds =  9, .ms =  8 },
113         [2] = { .ds =  9, .ms = 16 },
114         [3] = { .ds =  9, .ms = 64 },
115         [4] = { .ds = 12           },
116         [5] = { .ds = 12, .ms =  8 },
117         [6] = { .ds = 12, .ms = 16 },
118         [7] = { .ds = 12, .ms = 64 },
119     };
120 
121     ns->nlbaf = 8;
122 
123     memcpy(&id_ns->lbaf, &lbaf, sizeof(lbaf));
124 
125     for (i = 0; i < ns->nlbaf; i++) {
126         NvmeLBAF *lbaf = &id_ns->lbaf[i];
127         if (lbaf->ds == ds) {
128             if (lbaf->ms == ms) {
129                 id_ns->flbas |= i;
130                 goto lbaf_found;
131             }
132         }
133     }
134 
135     /* add non-standard lba format */
136     id_ns->lbaf[ns->nlbaf].ds = ds;
137     id_ns->lbaf[ns->nlbaf].ms = ms;
138     ns->nlbaf++;
139 
140     id_ns->flbas |= i;
141 
142 
143 lbaf_found:
144     id_ns_nvm->elbaf[i] = (ns->pif & 0x3) << 7;
145     id_ns->nlbaf = ns->nlbaf - 1;
146     nvme_ns_init_format(ns);
147 
148     return 0;
149 }
150 
151 static int nvme_ns_init_blk(NvmeNamespace *ns, Error **errp)
152 {
153     bool read_only;
154 
155     if (!blkconf_blocksizes(&ns->blkconf, errp)) {
156         return -1;
157     }
158 
159     read_only = !blk_supports_write_perm(ns->blkconf.blk);
160     if (!blkconf_apply_backend_options(&ns->blkconf, read_only, false, errp)) {
161         return -1;
162     }
163 
164     if (ns->blkconf.discard_granularity == -1) {
165         ns->blkconf.discard_granularity =
166             MAX(ns->blkconf.logical_block_size, MIN_DISCARD_GRANULARITY);
167     }
168 
169     ns->size = blk_getlength(ns->blkconf.blk);
170     if (ns->size < 0) {
171         error_setg_errno(errp, -ns->size, "could not get blockdev size");
172         return -1;
173     }
174 
175     return 0;
176 }
177 
178 static int nvme_ns_zoned_check_calc_geometry(NvmeNamespace *ns, Error **errp)
179 {
180     uint64_t zone_size, zone_cap;
181 
182     /* Make sure that the values of ZNS properties are sane */
183     if (ns->params.zone_size_bs) {
184         zone_size = ns->params.zone_size_bs;
185     } else {
186         zone_size = NVME_DEFAULT_ZONE_SIZE;
187     }
188     if (ns->params.zone_cap_bs) {
189         zone_cap = ns->params.zone_cap_bs;
190     } else {
191         zone_cap = zone_size;
192     }
193     if (zone_cap > zone_size) {
194         error_setg(errp, "zone capacity %"PRIu64"B exceeds "
195                    "zone size %"PRIu64"B", zone_cap, zone_size);
196         return -1;
197     }
198     if (zone_size < ns->lbasz) {
199         error_setg(errp, "zone size %"PRIu64"B too small, "
200                    "must be at least %zuB", zone_size, ns->lbasz);
201         return -1;
202     }
203     if (zone_cap < ns->lbasz) {
204         error_setg(errp, "zone capacity %"PRIu64"B too small, "
205                    "must be at least %zuB", zone_cap, ns->lbasz);
206         return -1;
207     }
208 
209     /*
210      * Save the main zone geometry values to avoid
211      * calculating them later again.
212      */
213     ns->zone_size = zone_size / ns->lbasz;
214     ns->zone_capacity = zone_cap / ns->lbasz;
215     ns->num_zones = le64_to_cpu(ns->id_ns.nsze) / ns->zone_size;
216 
217     /* Do a few more sanity checks of ZNS properties */
218     if (!ns->num_zones) {
219         error_setg(errp,
220                    "insufficient drive capacity, must be at least the size "
221                    "of one zone (%"PRIu64"B)", zone_size);
222         return -1;
223     }
224 
225     return 0;
226 }
227 
228 static void nvme_ns_zoned_init_state(NvmeNamespace *ns)
229 {
230     uint64_t start = 0, zone_size = ns->zone_size;
231     uint64_t capacity = ns->num_zones * zone_size;
232     NvmeZone *zone;
233     int i;
234 
235     ns->zone_array = g_new0(NvmeZone, ns->num_zones);
236     if (ns->params.zd_extension_size) {
237         ns->zd_extensions = g_malloc0(ns->params.zd_extension_size *
238                                       ns->num_zones);
239     }
240 
241     QTAILQ_INIT(&ns->exp_open_zones);
242     QTAILQ_INIT(&ns->imp_open_zones);
243     QTAILQ_INIT(&ns->closed_zones);
244     QTAILQ_INIT(&ns->full_zones);
245 
246     zone = ns->zone_array;
247     for (i = 0; i < ns->num_zones; i++, zone++) {
248         if (start + zone_size > capacity) {
249             zone_size = capacity - start;
250         }
251         zone->d.zt = NVME_ZONE_TYPE_SEQ_WRITE;
252         nvme_set_zone_state(zone, NVME_ZONE_STATE_EMPTY);
253         zone->d.za = 0;
254         zone->d.zcap = ns->zone_capacity;
255         zone->d.zslba = start;
256         zone->d.wp = start;
257         zone->w_ptr = start;
258         start += zone_size;
259     }
260 
261     ns->zone_size_log2 = 0;
262     if (is_power_of_2(ns->zone_size)) {
263         ns->zone_size_log2 = 63 - clz64(ns->zone_size);
264     }
265 }
266 
267 static void nvme_ns_init_zoned(NvmeNamespace *ns)
268 {
269     NvmeIdNsZoned *id_ns_z;
270     int i;
271 
272     nvme_ns_zoned_init_state(ns);
273 
274     id_ns_z = g_new0(NvmeIdNsZoned, 1);
275 
276     /* MAR/MOR are zeroes-based, FFFFFFFFFh means no limit */
277     id_ns_z->mar = cpu_to_le32(ns->params.max_active_zones - 1);
278     id_ns_z->mor = cpu_to_le32(ns->params.max_open_zones - 1);
279     id_ns_z->zoc = 0;
280     id_ns_z->ozcs = ns->params.cross_zone_read ?
281         NVME_ID_NS_ZONED_OZCS_RAZB : 0x00;
282 
283     for (i = 0; i <= ns->id_ns.nlbaf; i++) {
284         id_ns_z->lbafe[i].zsze = cpu_to_le64(ns->zone_size);
285         id_ns_z->lbafe[i].zdes =
286             ns->params.zd_extension_size >> 6; /* Units of 64B */
287     }
288 
289     if (ns->params.zrwas) {
290         ns->zns.numzrwa = ns->params.numzrwa ?
291             ns->params.numzrwa : ns->num_zones;
292 
293         ns->zns.zrwas = ns->params.zrwas >> ns->lbaf.ds;
294         ns->zns.zrwafg = ns->params.zrwafg >> ns->lbaf.ds;
295 
296         id_ns_z->ozcs |= NVME_ID_NS_ZONED_OZCS_ZRWASUP;
297         id_ns_z->zrwacap = NVME_ID_NS_ZONED_ZRWACAP_EXPFLUSHSUP;
298 
299         id_ns_z->numzrwa = cpu_to_le32(ns->params.numzrwa);
300         id_ns_z->zrwas = cpu_to_le16(ns->zns.zrwas);
301         id_ns_z->zrwafg = cpu_to_le16(ns->zns.zrwafg);
302     }
303 
304     id_ns_z->ozcs = cpu_to_le16(id_ns_z->ozcs);
305 
306     ns->csi = NVME_CSI_ZONED;
307     ns->id_ns.nsze = cpu_to_le64(ns->num_zones * ns->zone_size);
308     ns->id_ns.ncap = ns->id_ns.nsze;
309     ns->id_ns.nuse = ns->id_ns.ncap;
310 
311     /*
312      * The device uses the BDRV_BLOCK_ZERO flag to determine the "deallocated"
313      * status of logical blocks. Since the spec defines that logical blocks
314      * SHALL be deallocated when then zone is in the Empty or Offline states,
315      * we can only support DULBE if the zone size is a multiple of the
316      * calculated NPDG.
317      */
318     if (ns->zone_size % (ns->id_ns.npdg + 1)) {
319         warn_report("the zone size (%"PRIu64" blocks) is not a multiple of "
320                     "the calculated deallocation granularity (%d blocks); "
321                     "DULBE support disabled",
322                     ns->zone_size, ns->id_ns.npdg + 1);
323 
324         ns->id_ns.nsfeat &= ~0x4;
325     }
326 
327     ns->id_ns_zoned = id_ns_z;
328 }
329 
330 static void nvme_clear_zone(NvmeNamespace *ns, NvmeZone *zone)
331 {
332     uint8_t state;
333 
334     zone->w_ptr = zone->d.wp;
335     state = nvme_get_zone_state(zone);
336     if (zone->d.wp != zone->d.zslba ||
337         (zone->d.za & NVME_ZA_ZD_EXT_VALID)) {
338         if (state != NVME_ZONE_STATE_CLOSED) {
339             trace_pci_nvme_clear_ns_close(state, zone->d.zslba);
340             nvme_set_zone_state(zone, NVME_ZONE_STATE_CLOSED);
341         }
342         nvme_aor_inc_active(ns);
343         QTAILQ_INSERT_HEAD(&ns->closed_zones, zone, entry);
344     } else {
345         trace_pci_nvme_clear_ns_reset(state, zone->d.zslba);
346         if (zone->d.za & NVME_ZA_ZRWA_VALID) {
347             zone->d.za &= ~NVME_ZA_ZRWA_VALID;
348             ns->zns.numzrwa++;
349         }
350         nvme_set_zone_state(zone, NVME_ZONE_STATE_EMPTY);
351     }
352 }
353 
354 /*
355  * Close all the zones that are currently open.
356  */
357 static void nvme_zoned_ns_shutdown(NvmeNamespace *ns)
358 {
359     NvmeZone *zone, *next;
360 
361     QTAILQ_FOREACH_SAFE(zone, &ns->closed_zones, entry, next) {
362         QTAILQ_REMOVE(&ns->closed_zones, zone, entry);
363         nvme_aor_dec_active(ns);
364         nvme_clear_zone(ns, zone);
365     }
366     QTAILQ_FOREACH_SAFE(zone, &ns->imp_open_zones, entry, next) {
367         QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
368         nvme_aor_dec_open(ns);
369         nvme_aor_dec_active(ns);
370         nvme_clear_zone(ns, zone);
371     }
372     QTAILQ_FOREACH_SAFE(zone, &ns->exp_open_zones, entry, next) {
373         QTAILQ_REMOVE(&ns->exp_open_zones, zone, entry);
374         nvme_aor_dec_open(ns);
375         nvme_aor_dec_active(ns);
376         nvme_clear_zone(ns, zone);
377     }
378 
379     assert(ns->nr_open_zones == 0);
380 }
381 
382 static NvmeRuHandle *nvme_find_ruh_by_attr(NvmeEnduranceGroup *endgrp,
383                                            uint8_t ruha, uint16_t *ruhid)
384 {
385     for (uint16_t i = 0; i < endgrp->fdp.nruh; i++) {
386         NvmeRuHandle *ruh = &endgrp->fdp.ruhs[i];
387 
388         if (ruh->ruha == ruha) {
389             *ruhid = i;
390             return ruh;
391         }
392     }
393 
394     return NULL;
395 }
396 
397 static bool nvme_ns_init_fdp(NvmeNamespace *ns, Error **errp)
398 {
399     NvmeEnduranceGroup *endgrp = ns->endgrp;
400     NvmeRuHandle *ruh;
401     uint8_t lbafi = NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas);
402     g_autofree unsigned int *ruhids = NULL;
403     unsigned int *ruhid;
404     char *r, *p, *token;
405     uint16_t *ph;
406 
407     if (!ns->params.fdp.ruhs) {
408         ns->fdp.nphs = 1;
409         ph = ns->fdp.phs = g_new(uint16_t, 1);
410 
411         ruh = nvme_find_ruh_by_attr(endgrp, NVME_RUHA_CTRL, ph);
412         if (!ruh) {
413             ruh = nvme_find_ruh_by_attr(endgrp, NVME_RUHA_UNUSED, ph);
414             if (!ruh) {
415                 error_setg(errp, "no unused reclaim unit handles left");
416                 return false;
417             }
418 
419             ruh->ruha = NVME_RUHA_CTRL;
420             ruh->lbafi = lbafi;
421             ruh->ruamw = endgrp->fdp.runs >> ns->lbaf.ds;
422 
423             for (uint16_t rg = 0; rg < endgrp->fdp.nrg; rg++) {
424                 ruh->rus[rg].ruamw = ruh->ruamw;
425             }
426         } else if (ruh->lbafi != lbafi) {
427             error_setg(errp, "lba format index of controller assigned "
428                        "reclaim unit handle does not match namespace lba "
429                        "format index");
430             return false;
431         }
432 
433         return true;
434     }
435 
436     ruhid = ruhids = g_new0(unsigned int, endgrp->fdp.nruh);
437     r = p = strdup(ns->params.fdp.ruhs);
438 
439     /* parse the placement handle identifiers */
440     while ((token = qemu_strsep(&p, ";")) != NULL) {
441         ns->fdp.nphs += 1;
442         if (ns->fdp.nphs > NVME_FDP_MAXPIDS ||
443             ns->fdp.nphs == endgrp->fdp.nruh) {
444             error_setg(errp, "too many placement handles");
445             free(r);
446             return false;
447         }
448 
449         if (qemu_strtoui(token, NULL, 0, ruhid++) < 0) {
450             error_setg(errp, "cannot parse reclaim unit handle identifier");
451             free(r);
452             return false;
453         }
454     }
455 
456     free(r);
457 
458     ph = ns->fdp.phs = g_new(uint16_t, ns->fdp.nphs);
459 
460     ruhid = ruhids;
461 
462     /* verify the identifiers */
463     for (unsigned int i = 0; i < ns->fdp.nphs; i++, ruhid++, ph++) {
464         if (*ruhid >= endgrp->fdp.nruh) {
465             error_setg(errp, "invalid reclaim unit handle identifier");
466             return false;
467         }
468 
469         ruh = &endgrp->fdp.ruhs[*ruhid];
470 
471         switch (ruh->ruha) {
472         case NVME_RUHA_UNUSED:
473             ruh->ruha = NVME_RUHA_HOST;
474             ruh->lbafi = lbafi;
475             ruh->ruamw = endgrp->fdp.runs >> ns->lbaf.ds;
476 
477             for (uint16_t rg = 0; rg < endgrp->fdp.nrg; rg++) {
478                 ruh->rus[rg].ruamw = ruh->ruamw;
479             }
480 
481             break;
482 
483         case NVME_RUHA_HOST:
484             if (ruh->lbafi != lbafi) {
485                 error_setg(errp, "lba format index of host assigned"
486                            "reclaim unit handle does not match namespace "
487                            "lba format index");
488                 return false;
489             }
490 
491             break;
492 
493         case NVME_RUHA_CTRL:
494             error_setg(errp, "reclaim unit handle is controller assigned");
495             return false;
496 
497         default:
498             abort();
499         }
500 
501         *ph = *ruhid;
502     }
503 
504     return true;
505 }
506 
507 static int nvme_ns_check_constraints(NvmeNamespace *ns, Error **errp)
508 {
509     unsigned int pi_size;
510 
511     if (!ns->blkconf.blk) {
512         error_setg(errp, "block backend not configured");
513         return -1;
514     }
515 
516     if (ns->params.pi) {
517         if (ns->params.pi > NVME_ID_NS_DPS_TYPE_3) {
518             error_setg(errp, "invalid 'pi' value");
519             return -1;
520         }
521 
522         switch (ns->params.pif) {
523         case NVME_PI_GUARD_16:
524             pi_size = 8;
525             break;
526         case NVME_PI_GUARD_64:
527             pi_size = 16;
528             break;
529         default:
530             error_setg(errp, "invalid 'pif'");
531             return -1;
532         }
533 
534         if (ns->params.ms < pi_size) {
535             error_setg(errp, "at least %u bytes of metadata required to "
536                        "enable protection information", pi_size);
537             return -1;
538         }
539     }
540 
541     if (ns->params.nsid > NVME_MAX_NAMESPACES) {
542         error_setg(errp, "invalid namespace id (must be between 0 and %d)",
543                    NVME_MAX_NAMESPACES);
544         return -1;
545     }
546 
547     if (ns->params.zoned && ns->endgrp && ns->endgrp->fdp.enabled) {
548         error_setg(errp, "cannot be a zoned- in an FDP configuration");
549         return -1;
550     }
551 
552     if (ns->params.zoned) {
553         if (ns->params.max_active_zones) {
554             if (ns->params.max_open_zones > ns->params.max_active_zones) {
555                 error_setg(errp, "max_open_zones (%u) exceeds "
556                            "max_active_zones (%u)", ns->params.max_open_zones,
557                            ns->params.max_active_zones);
558                 return -1;
559             }
560 
561             if (!ns->params.max_open_zones) {
562                 ns->params.max_open_zones = ns->params.max_active_zones;
563             }
564         }
565 
566         if (ns->params.zd_extension_size) {
567             if (ns->params.zd_extension_size & 0x3f) {
568                 error_setg(errp, "zone descriptor extension size must be a "
569                            "multiple of 64B");
570                 return -1;
571             }
572             if ((ns->params.zd_extension_size >> 6) > 0xff) {
573                 error_setg(errp,
574                            "zone descriptor extension size is too large");
575                 return -1;
576             }
577         }
578 
579         if (ns->params.zrwas) {
580             if (ns->params.zrwas % ns->blkconf.logical_block_size) {
581                 error_setg(errp, "zone random write area size (zoned.zrwas "
582                            "%"PRIu64") must be a multiple of the logical "
583                            "block size (logical_block_size %"PRIu32")",
584                            ns->params.zrwas, ns->blkconf.logical_block_size);
585                 return -1;
586             }
587 
588             if (ns->params.zrwafg == -1) {
589                 ns->params.zrwafg = ns->blkconf.logical_block_size;
590             }
591 
592             if (ns->params.zrwas % ns->params.zrwafg) {
593                 error_setg(errp, "zone random write area size (zoned.zrwas "
594                            "%"PRIu64") must be a multiple of the zone random "
595                            "write area flush granularity (zoned.zrwafg, "
596                            "%"PRIu64")", ns->params.zrwas, ns->params.zrwafg);
597                 return -1;
598             }
599 
600             if (ns->params.max_active_zones) {
601                 if (ns->params.numzrwa > ns->params.max_active_zones) {
602                     error_setg(errp, "number of zone random write area "
603                                "resources (zoned.numzrwa, %d) must be less "
604                                "than or equal to maximum active resources "
605                                "(zoned.max_active_zones, %d)",
606                                ns->params.numzrwa,
607                                ns->params.max_active_zones);
608                     return -1;
609                 }
610             }
611         }
612     }
613 
614     return 0;
615 }
616 
617 int nvme_ns_setup(NvmeNamespace *ns, Error **errp)
618 {
619     if (nvme_ns_check_constraints(ns, errp)) {
620         return -1;
621     }
622 
623     if (nvme_ns_init_blk(ns, errp)) {
624         return -1;
625     }
626 
627     if (nvme_ns_init(ns, errp)) {
628         return -1;
629     }
630     if (ns->params.zoned) {
631         if (nvme_ns_zoned_check_calc_geometry(ns, errp) != 0) {
632             return -1;
633         }
634         nvme_ns_init_zoned(ns);
635     }
636 
637     if (ns->endgrp && ns->endgrp->fdp.enabled) {
638         if (!nvme_ns_init_fdp(ns, errp)) {
639             return -1;
640         }
641     }
642 
643     return 0;
644 }
645 
646 void nvme_ns_drain(NvmeNamespace *ns)
647 {
648     blk_drain(ns->blkconf.blk);
649 }
650 
651 void nvme_ns_shutdown(NvmeNamespace *ns)
652 {
653     blk_flush(ns->blkconf.blk);
654     if (ns->params.zoned) {
655         nvme_zoned_ns_shutdown(ns);
656     }
657 }
658 
659 void nvme_ns_cleanup(NvmeNamespace *ns)
660 {
661     if (ns->params.zoned) {
662         g_free(ns->id_ns_zoned);
663         g_free(ns->zone_array);
664         g_free(ns->zd_extensions);
665     }
666 
667     if (ns->endgrp && ns->endgrp->fdp.enabled) {
668         g_free(ns->fdp.phs);
669     }
670 }
671 
672 static void nvme_ns_unrealize(DeviceState *dev)
673 {
674     NvmeNamespace *ns = NVME_NS(dev);
675 
676     nvme_ns_drain(ns);
677     nvme_ns_shutdown(ns);
678     nvme_ns_cleanup(ns);
679 }
680 
681 static void nvme_ns_realize(DeviceState *dev, Error **errp)
682 {
683     NvmeNamespace *ns = NVME_NS(dev);
684     BusState *s = qdev_get_parent_bus(dev);
685     NvmeCtrl *n = NVME(s->parent);
686     NvmeSubsystem *subsys = n->subsys;
687     uint32_t nsid = ns->params.nsid;
688     int i;
689 
690     if (!n->subsys) {
691         /* If no subsys, the ns cannot be attached to more than one ctrl. */
692         ns->params.shared = false;
693         if (ns->params.detached) {
694             error_setg(errp, "detached requires that the nvme device is "
695                        "linked to an nvme-subsys device");
696             return;
697         }
698     } else {
699         /*
700          * If this namespace belongs to a subsystem (through a link on the
701          * controller device), reparent the device.
702          */
703         if (!qdev_set_parent_bus(dev, &subsys->bus.parent_bus, errp)) {
704             return;
705         }
706         ns->subsys = subsys;
707         ns->endgrp = &subsys->endgrp;
708     }
709 
710     if (nvme_ns_setup(ns, errp)) {
711         return;
712     }
713 
714     if (!nsid) {
715         for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
716             if (nvme_ns(n, i) || nvme_subsys_ns(subsys, i)) {
717                 continue;
718             }
719 
720             nsid = ns->params.nsid = i;
721             break;
722         }
723 
724         if (!nsid) {
725             error_setg(errp, "no free namespace id");
726             return;
727         }
728     } else {
729         if (nvme_ns(n, nsid) || nvme_subsys_ns(subsys, nsid)) {
730             error_setg(errp, "namespace id '%d' already allocated", nsid);
731             return;
732         }
733     }
734 
735     if (subsys) {
736         subsys->namespaces[nsid] = ns;
737 
738         ns->id_ns.endgid = cpu_to_le16(0x1);
739 
740         if (ns->params.detached) {
741             return;
742         }
743 
744         if (ns->params.shared) {
745             for (i = 0; i < ARRAY_SIZE(subsys->ctrls); i++) {
746                 NvmeCtrl *ctrl = subsys->ctrls[i];
747 
748                 if (ctrl && ctrl != SUBSYS_SLOT_RSVD) {
749                     nvme_attach_ns(ctrl, ns);
750                 }
751             }
752 
753             return;
754         }
755 
756     }
757 
758     nvme_attach_ns(n, ns);
759 }
760 
761 static Property nvme_ns_props[] = {
762     DEFINE_BLOCK_PROPERTIES(NvmeNamespace, blkconf),
763     DEFINE_PROP_BOOL("detached", NvmeNamespace, params.detached, false),
764     DEFINE_PROP_BOOL("shared", NvmeNamespace, params.shared, true),
765     DEFINE_PROP_UINT32("nsid", NvmeNamespace, params.nsid, 0),
766     DEFINE_PROP_UUID_NODEFAULT("uuid", NvmeNamespace, params.uuid),
767     DEFINE_PROP_UINT64("eui64", NvmeNamespace, params.eui64, 0),
768     DEFINE_PROP_UINT16("ms", NvmeNamespace, params.ms, 0),
769     DEFINE_PROP_UINT8("mset", NvmeNamespace, params.mset, 0),
770     DEFINE_PROP_UINT8("pi", NvmeNamespace, params.pi, 0),
771     DEFINE_PROP_UINT8("pil", NvmeNamespace, params.pil, 0),
772     DEFINE_PROP_UINT8("pif", NvmeNamespace, params.pif, 0),
773     DEFINE_PROP_UINT16("mssrl", NvmeNamespace, params.mssrl, 128),
774     DEFINE_PROP_UINT32("mcl", NvmeNamespace, params.mcl, 128),
775     DEFINE_PROP_UINT8("msrc", NvmeNamespace, params.msrc, 127),
776     DEFINE_PROP_BOOL("zoned", NvmeNamespace, params.zoned, false),
777     DEFINE_PROP_SIZE("zoned.zone_size", NvmeNamespace, params.zone_size_bs,
778                      NVME_DEFAULT_ZONE_SIZE),
779     DEFINE_PROP_SIZE("zoned.zone_capacity", NvmeNamespace, params.zone_cap_bs,
780                      0),
781     DEFINE_PROP_BOOL("zoned.cross_read", NvmeNamespace,
782                      params.cross_zone_read, false),
783     DEFINE_PROP_UINT32("zoned.max_active", NvmeNamespace,
784                        params.max_active_zones, 0),
785     DEFINE_PROP_UINT32("zoned.max_open", NvmeNamespace,
786                        params.max_open_zones, 0),
787     DEFINE_PROP_UINT32("zoned.descr_ext_size", NvmeNamespace,
788                        params.zd_extension_size, 0),
789     DEFINE_PROP_UINT32("zoned.numzrwa", NvmeNamespace, params.numzrwa, 0),
790     DEFINE_PROP_SIZE("zoned.zrwas", NvmeNamespace, params.zrwas, 0),
791     DEFINE_PROP_SIZE("zoned.zrwafg", NvmeNamespace, params.zrwafg, -1),
792     DEFINE_PROP_BOOL("eui64-default", NvmeNamespace, params.eui64_default,
793                      false),
794     DEFINE_PROP_STRING("fdp.ruhs", NvmeNamespace, params.fdp.ruhs),
795     DEFINE_PROP_END_OF_LIST(),
796 };
797 
798 static void nvme_ns_class_init(ObjectClass *oc, void *data)
799 {
800     DeviceClass *dc = DEVICE_CLASS(oc);
801 
802     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
803 
804     dc->bus_type = TYPE_NVME_BUS;
805     dc->realize = nvme_ns_realize;
806     dc->unrealize = nvme_ns_unrealize;
807     device_class_set_props(dc, nvme_ns_props);
808     dc->desc = "Virtual NVMe namespace";
809 }
810 
811 static void nvme_ns_instance_init(Object *obj)
812 {
813     NvmeNamespace *ns = NVME_NS(obj);
814     char *bootindex = g_strdup_printf("/namespace@%d,0", ns->params.nsid);
815 
816     device_add_bootindex_property(obj, &ns->bootindex, "bootindex",
817                                   bootindex, DEVICE(obj));
818 
819     g_free(bootindex);
820 }
821 
822 static const TypeInfo nvme_ns_info = {
823     .name = TYPE_NVME_NS,
824     .parent = TYPE_DEVICE,
825     .class_init = nvme_ns_class_init,
826     .instance_size = sizeof(NvmeNamespace),
827     .instance_init = nvme_ns_instance_init,
828 };
829 
830 static void nvme_ns_register_types(void)
831 {
832     type_register_static(&nvme_ns_info);
833 }
834 
835 type_init(nvme_ns_register_types)
836