1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2017 NXP Semiconductors
4  * Copyright (C) 2017 Bin Meng <bmeng.cn@gmail.com>
5  */
6 
7 #include <common.h>
8 #include <blk.h>
9 #include <cpu_func.h>
10 #include <dm.h>
11 #include <errno.h>
12 #include <log.h>
13 #include <malloc.h>
14 #include <memalign.h>
15 #include <pci.h>
16 #include <time.h>
17 #include <dm/device-internal.h>
18 #include <linux/compat.h>
19 #include "nvme.h"
20 
21 #define NVME_Q_DEPTH		2
22 #define NVME_AQ_DEPTH		2
23 #define NVME_SQ_SIZE(depth)	(depth * sizeof(struct nvme_command))
24 #define NVME_CQ_SIZE(depth)	(depth * sizeof(struct nvme_completion))
25 #define NVME_CQ_ALLOCATION	ALIGN(NVME_CQ_SIZE(NVME_Q_DEPTH), \
26 				      ARCH_DMA_MINALIGN)
27 #define ADMIN_TIMEOUT		60
28 #define IO_TIMEOUT		30
29 #define MAX_PRP_POOL		512
30 
31 enum nvme_queue_id {
32 	NVME_ADMIN_Q,
33 	NVME_IO_Q,
34 	NVME_Q_NUM,
35 };
36 
37 /*
38  * An NVM Express queue. Each device has at least two (one for admin
39  * commands and one for I/O commands).
40  */
41 struct nvme_queue {
42 	struct nvme_dev *dev;
43 	struct nvme_command *sq_cmds;
44 	struct nvme_completion *cqes;
45 	wait_queue_head_t sq_full;
46 	u32 __iomem *q_db;
47 	u16 q_depth;
48 	s16 cq_vector;
49 	u16 sq_head;
50 	u16 sq_tail;
51 	u16 cq_head;
52 	u16 qid;
53 	u8 cq_phase;
54 	u8 cqe_seen;
55 	unsigned long cmdid_data[];
56 };
57 
nvme_wait_ready(struct nvme_dev * dev,bool enabled)58 static int nvme_wait_ready(struct nvme_dev *dev, bool enabled)
59 {
60 	u32 bit = enabled ? NVME_CSTS_RDY : 0;
61 	int timeout;
62 	ulong start;
63 
64 	/* Timeout field in the CAP register is in 500 millisecond units */
65 	timeout = NVME_CAP_TIMEOUT(dev->cap) * 500;
66 
67 	start = get_timer(0);
68 	while (get_timer(start) < timeout) {
69 		if ((readl(&dev->bar->csts) & NVME_CSTS_RDY) == bit)
70 			return 0;
71 	}
72 
73 	return -ETIME;
74 }
75 
nvme_setup_prps(struct nvme_dev * dev,u64 * prp2,int total_len,u64 dma_addr)76 static int nvme_setup_prps(struct nvme_dev *dev, u64 *prp2,
77 			   int total_len, u64 dma_addr)
78 {
79 	u32 page_size = dev->page_size;
80 	int offset = dma_addr & (page_size - 1);
81 	u64 *prp_pool;
82 	int length = total_len;
83 	int i, nprps;
84 	u32 prps_per_page = (page_size >> 3) - 1;
85 	u32 num_pages;
86 
87 	length -= (page_size - offset);
88 
89 	if (length <= 0) {
90 		*prp2 = 0;
91 		return 0;
92 	}
93 
94 	if (length)
95 		dma_addr += (page_size - offset);
96 
97 	if (length <= page_size) {
98 		*prp2 = dma_addr;
99 		return 0;
100 	}
101 
102 	nprps = DIV_ROUND_UP(length, page_size);
103 	num_pages = DIV_ROUND_UP(nprps, prps_per_page);
104 
105 	if (nprps > dev->prp_entry_num) {
106 		free(dev->prp_pool);
107 		/*
108 		 * Always increase in increments of pages.  It doesn't waste
109 		 * much memory and reduces the number of allocations.
110 		 */
111 		dev->prp_pool = memalign(page_size, num_pages * page_size);
112 		if (!dev->prp_pool) {
113 			printf("Error: malloc prp_pool fail\n");
114 			return -ENOMEM;
115 		}
116 		dev->prp_entry_num = prps_per_page * num_pages;
117 	}
118 
119 	prp_pool = dev->prp_pool;
120 	i = 0;
121 	while (nprps) {
122 		if (i == ((page_size >> 3) - 1)) {
123 			*(prp_pool + i) = cpu_to_le64((ulong)prp_pool +
124 					page_size);
125 			i = 0;
126 			prp_pool += page_size;
127 		}
128 		*(prp_pool + i++) = cpu_to_le64(dma_addr);
129 		dma_addr += page_size;
130 		nprps--;
131 	}
132 	*prp2 = (ulong)dev->prp_pool;
133 
134 	flush_dcache_range((ulong)dev->prp_pool, (ulong)dev->prp_pool +
135 			   dev->prp_entry_num * sizeof(u64));
136 
137 	return 0;
138 }
139 
nvme_get_cmd_id(void)140 static __le16 nvme_get_cmd_id(void)
141 {
142 	static unsigned short cmdid;
143 
144 	return cpu_to_le16((cmdid < USHRT_MAX) ? cmdid++ : 0);
145 }
146 
nvme_read_completion_status(struct nvme_queue * nvmeq,u16 index)147 static u16 nvme_read_completion_status(struct nvme_queue *nvmeq, u16 index)
148 {
149 	/*
150 	 * Single CQ entries are always smaller than a cache line, so we
151 	 * can't invalidate them individually. However CQ entries are
152 	 * read only by the CPU, so it's safe to always invalidate all of them,
153 	 * as the cache line should never become dirty.
154 	 */
155 	ulong start = (ulong)&nvmeq->cqes[0];
156 	ulong stop = start + NVME_CQ_ALLOCATION;
157 
158 	invalidate_dcache_range(start, stop);
159 
160 	return le16_to_cpu(readw(&(nvmeq->cqes[index].status)));
161 }
162 
163 /**
164  * nvme_submit_cmd() - copy a command into a queue and ring the doorbell
165  *
166  * @nvmeq:	The queue to use
167  * @cmd:	The command to send
168  */
nvme_submit_cmd(struct nvme_queue * nvmeq,struct nvme_command * cmd)169 static void nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
170 {
171 	u16 tail = nvmeq->sq_tail;
172 
173 	memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
174 	flush_dcache_range((ulong)&nvmeq->sq_cmds[tail],
175 			   (ulong)&nvmeq->sq_cmds[tail] + sizeof(*cmd));
176 
177 	if (++tail == nvmeq->q_depth)
178 		tail = 0;
179 	writel(tail, nvmeq->q_db);
180 	nvmeq->sq_tail = tail;
181 }
182 
nvme_submit_sync_cmd(struct nvme_queue * nvmeq,struct nvme_command * cmd,u32 * result,unsigned timeout)183 static int nvme_submit_sync_cmd(struct nvme_queue *nvmeq,
184 				struct nvme_command *cmd,
185 				u32 *result, unsigned timeout)
186 {
187 	u16 head = nvmeq->cq_head;
188 	u16 phase = nvmeq->cq_phase;
189 	u16 status;
190 	ulong start_time;
191 	ulong timeout_us = timeout * 100000;
192 
193 	cmd->common.command_id = nvme_get_cmd_id();
194 	nvme_submit_cmd(nvmeq, cmd);
195 
196 	start_time = timer_get_us();
197 
198 	for (;;) {
199 		status = nvme_read_completion_status(nvmeq, head);
200 		if ((status & 0x01) == phase)
201 			break;
202 		if (timeout_us > 0 && (timer_get_us() - start_time)
203 		    >= timeout_us)
204 			return -ETIMEDOUT;
205 	}
206 
207 	status >>= 1;
208 	if (status) {
209 		printf("ERROR: status = %x, phase = %d, head = %d\n",
210 		       status, phase, head);
211 		status = 0;
212 		if (++head == nvmeq->q_depth) {
213 			head = 0;
214 			phase = !phase;
215 		}
216 		writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
217 		nvmeq->cq_head = head;
218 		nvmeq->cq_phase = phase;
219 
220 		return -EIO;
221 	}
222 
223 	if (result)
224 		*result = le32_to_cpu(readl(&(nvmeq->cqes[head].result)));
225 
226 	if (++head == nvmeq->q_depth) {
227 		head = 0;
228 		phase = !phase;
229 	}
230 	writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
231 	nvmeq->cq_head = head;
232 	nvmeq->cq_phase = phase;
233 
234 	return status;
235 }
236 
nvme_submit_admin_cmd(struct nvme_dev * dev,struct nvme_command * cmd,u32 * result)237 static int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
238 				 u32 *result)
239 {
240 	return nvme_submit_sync_cmd(dev->queues[NVME_ADMIN_Q], cmd,
241 				    result, ADMIN_TIMEOUT);
242 }
243 
nvme_alloc_queue(struct nvme_dev * dev,int qid,int depth)244 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev,
245 					   int qid, int depth)
246 {
247 	struct nvme_queue *nvmeq = malloc(sizeof(*nvmeq));
248 	if (!nvmeq)
249 		return NULL;
250 	memset(nvmeq, 0, sizeof(*nvmeq));
251 
252 	nvmeq->cqes = (void *)memalign(4096, NVME_CQ_ALLOCATION);
253 	if (!nvmeq->cqes)
254 		goto free_nvmeq;
255 	memset((void *)nvmeq->cqes, 0, NVME_CQ_SIZE(depth));
256 
257 	nvmeq->sq_cmds = (void *)memalign(4096, NVME_SQ_SIZE(depth));
258 	if (!nvmeq->sq_cmds)
259 		goto free_queue;
260 	memset((void *)nvmeq->sq_cmds, 0, NVME_SQ_SIZE(depth));
261 
262 	nvmeq->dev = dev;
263 
264 	nvmeq->cq_head = 0;
265 	nvmeq->cq_phase = 1;
266 	nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
267 	nvmeq->q_depth = depth;
268 	nvmeq->qid = qid;
269 	dev->queue_count++;
270 	dev->queues[qid] = nvmeq;
271 
272 	return nvmeq;
273 
274  free_queue:
275 	free((void *)nvmeq->cqes);
276  free_nvmeq:
277 	free(nvmeq);
278 
279 	return NULL;
280 }
281 
nvme_delete_queue(struct nvme_dev * dev,u8 opcode,u16 id)282 static int nvme_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
283 {
284 	struct nvme_command c;
285 
286 	memset(&c, 0, sizeof(c));
287 	c.delete_queue.opcode = opcode;
288 	c.delete_queue.qid = cpu_to_le16(id);
289 
290 	return nvme_submit_admin_cmd(dev, &c, NULL);
291 }
292 
nvme_delete_sq(struct nvme_dev * dev,u16 sqid)293 static int nvme_delete_sq(struct nvme_dev *dev, u16 sqid)
294 {
295 	return nvme_delete_queue(dev, nvme_admin_delete_sq, sqid);
296 }
297 
nvme_delete_cq(struct nvme_dev * dev,u16 cqid)298 static int nvme_delete_cq(struct nvme_dev *dev, u16 cqid)
299 {
300 	return nvme_delete_queue(dev, nvme_admin_delete_cq, cqid);
301 }
302 
nvme_enable_ctrl(struct nvme_dev * dev)303 static int nvme_enable_ctrl(struct nvme_dev *dev)
304 {
305 	dev->ctrl_config &= ~NVME_CC_SHN_MASK;
306 	dev->ctrl_config |= NVME_CC_ENABLE;
307 	writel(cpu_to_le32(dev->ctrl_config), &dev->bar->cc);
308 
309 	return nvme_wait_ready(dev, true);
310 }
311 
nvme_disable_ctrl(struct nvme_dev * dev)312 static int nvme_disable_ctrl(struct nvme_dev *dev)
313 {
314 	dev->ctrl_config &= ~NVME_CC_SHN_MASK;
315 	dev->ctrl_config &= ~NVME_CC_ENABLE;
316 	writel(cpu_to_le32(dev->ctrl_config), &dev->bar->cc);
317 
318 	return nvme_wait_ready(dev, false);
319 }
320 
nvme_free_queue(struct nvme_queue * nvmeq)321 static void nvme_free_queue(struct nvme_queue *nvmeq)
322 {
323 	free((void *)nvmeq->cqes);
324 	free(nvmeq->sq_cmds);
325 	free(nvmeq);
326 }
327 
nvme_free_queues(struct nvme_dev * dev,int lowest)328 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
329 {
330 	int i;
331 
332 	for (i = dev->queue_count - 1; i >= lowest; i--) {
333 		struct nvme_queue *nvmeq = dev->queues[i];
334 		dev->queue_count--;
335 		dev->queues[i] = NULL;
336 		nvme_free_queue(nvmeq);
337 	}
338 }
339 
nvme_init_queue(struct nvme_queue * nvmeq,u16 qid)340 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
341 {
342 	struct nvme_dev *dev = nvmeq->dev;
343 
344 	nvmeq->sq_tail = 0;
345 	nvmeq->cq_head = 0;
346 	nvmeq->cq_phase = 1;
347 	nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
348 	memset((void *)nvmeq->cqes, 0, NVME_CQ_SIZE(nvmeq->q_depth));
349 	flush_dcache_range((ulong)nvmeq->cqes,
350 			   (ulong)nvmeq->cqes + NVME_CQ_ALLOCATION);
351 	dev->online_queues++;
352 }
353 
nvme_configure_admin_queue(struct nvme_dev * dev)354 static int nvme_configure_admin_queue(struct nvme_dev *dev)
355 {
356 	int result;
357 	u32 aqa;
358 	u64 cap = dev->cap;
359 	struct nvme_queue *nvmeq;
360 	/* most architectures use 4KB as the page size */
361 	unsigned page_shift = 12;
362 	unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12;
363 	unsigned dev_page_max = NVME_CAP_MPSMAX(cap) + 12;
364 
365 	if (page_shift < dev_page_min) {
366 		debug("Device minimum page size (%u) too large for host (%u)\n",
367 		      1 << dev_page_min, 1 << page_shift);
368 		return -ENODEV;
369 	}
370 
371 	if (page_shift > dev_page_max) {
372 		debug("Device maximum page size (%u) smaller than host (%u)\n",
373 		      1 << dev_page_max, 1 << page_shift);
374 		page_shift = dev_page_max;
375 	}
376 
377 	result = nvme_disable_ctrl(dev);
378 	if (result < 0)
379 		return result;
380 
381 	nvmeq = dev->queues[NVME_ADMIN_Q];
382 	if (!nvmeq) {
383 		nvmeq = nvme_alloc_queue(dev, 0, NVME_AQ_DEPTH);
384 		if (!nvmeq)
385 			return -ENOMEM;
386 	}
387 
388 	aqa = nvmeq->q_depth - 1;
389 	aqa |= aqa << 16;
390 	aqa |= aqa << 16;
391 
392 	dev->page_size = 1 << page_shift;
393 
394 	dev->ctrl_config = NVME_CC_CSS_NVM;
395 	dev->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
396 	dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
397 	dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
398 
399 	writel(aqa, &dev->bar->aqa);
400 	nvme_writeq((ulong)nvmeq->sq_cmds, &dev->bar->asq);
401 	nvme_writeq((ulong)nvmeq->cqes, &dev->bar->acq);
402 
403 	result = nvme_enable_ctrl(dev);
404 	if (result)
405 		goto free_nvmeq;
406 
407 	nvmeq->cq_vector = 0;
408 
409 	nvme_init_queue(dev->queues[NVME_ADMIN_Q], 0);
410 
411 	return result;
412 
413  free_nvmeq:
414 	nvme_free_queues(dev, 0);
415 
416 	return result;
417 }
418 
nvme_alloc_cq(struct nvme_dev * dev,u16 qid,struct nvme_queue * nvmeq)419 static int nvme_alloc_cq(struct nvme_dev *dev, u16 qid,
420 			    struct nvme_queue *nvmeq)
421 {
422 	struct nvme_command c;
423 	int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
424 
425 	memset(&c, 0, sizeof(c));
426 	c.create_cq.opcode = nvme_admin_create_cq;
427 	c.create_cq.prp1 = cpu_to_le64((ulong)nvmeq->cqes);
428 	c.create_cq.cqid = cpu_to_le16(qid);
429 	c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
430 	c.create_cq.cq_flags = cpu_to_le16(flags);
431 	c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
432 
433 	return nvme_submit_admin_cmd(dev, &c, NULL);
434 }
435 
nvme_alloc_sq(struct nvme_dev * dev,u16 qid,struct nvme_queue * nvmeq)436 static int nvme_alloc_sq(struct nvme_dev *dev, u16 qid,
437 			    struct nvme_queue *nvmeq)
438 {
439 	struct nvme_command c;
440 	int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
441 
442 	memset(&c, 0, sizeof(c));
443 	c.create_sq.opcode = nvme_admin_create_sq;
444 	c.create_sq.prp1 = cpu_to_le64((ulong)nvmeq->sq_cmds);
445 	c.create_sq.sqid = cpu_to_le16(qid);
446 	c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
447 	c.create_sq.sq_flags = cpu_to_le16(flags);
448 	c.create_sq.cqid = cpu_to_le16(qid);
449 
450 	return nvme_submit_admin_cmd(dev, &c, NULL);
451 }
452 
nvme_identify(struct nvme_dev * dev,unsigned nsid,unsigned cns,dma_addr_t dma_addr)453 int nvme_identify(struct nvme_dev *dev, unsigned nsid,
454 		  unsigned cns, dma_addr_t dma_addr)
455 {
456 	struct nvme_command c;
457 	u32 page_size = dev->page_size;
458 	int offset = dma_addr & (page_size - 1);
459 	int length = sizeof(struct nvme_id_ctrl);
460 	int ret;
461 
462 	memset(&c, 0, sizeof(c));
463 	c.identify.opcode = nvme_admin_identify;
464 	c.identify.nsid = cpu_to_le32(nsid);
465 	c.identify.prp1 = cpu_to_le64(dma_addr);
466 
467 	length -= (page_size - offset);
468 	if (length <= 0) {
469 		c.identify.prp2 = 0;
470 	} else {
471 		dma_addr += (page_size - offset);
472 		c.identify.prp2 = cpu_to_le64(dma_addr);
473 	}
474 
475 	c.identify.cns = cpu_to_le32(cns);
476 
477 	invalidate_dcache_range(dma_addr,
478 				dma_addr + sizeof(struct nvme_id_ctrl));
479 
480 	ret = nvme_submit_admin_cmd(dev, &c, NULL);
481 	if (!ret)
482 		invalidate_dcache_range(dma_addr,
483 					dma_addr + sizeof(struct nvme_id_ctrl));
484 
485 	return ret;
486 }
487 
nvme_get_features(struct nvme_dev * dev,unsigned fid,unsigned nsid,dma_addr_t dma_addr,u32 * result)488 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
489 		      dma_addr_t dma_addr, u32 *result)
490 {
491 	struct nvme_command c;
492 	int ret;
493 
494 	memset(&c, 0, sizeof(c));
495 	c.features.opcode = nvme_admin_get_features;
496 	c.features.nsid = cpu_to_le32(nsid);
497 	c.features.prp1 = cpu_to_le64(dma_addr);
498 	c.features.fid = cpu_to_le32(fid);
499 
500 	ret = nvme_submit_admin_cmd(dev, &c, result);
501 
502 	/*
503 	 * TODO: Add some cache invalidation when a DMA buffer is involved
504 	 * in the request, here and before the command gets submitted. The
505 	 * buffer size varies by feature, also some features use a different
506 	 * field in the command packet to hold the buffer address.
507 	 * Section 5.21.1 (Set Features command) in the NVMe specification
508 	 * details the buffer requirements for each feature.
509 	 *
510 	 * At the moment there is no user of this function.
511 	 */
512 
513 	return ret;
514 }
515 
nvme_set_features(struct nvme_dev * dev,unsigned fid,unsigned dword11,dma_addr_t dma_addr,u32 * result)516 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
517 		      dma_addr_t dma_addr, u32 *result)
518 {
519 	struct nvme_command c;
520 
521 	memset(&c, 0, sizeof(c));
522 	c.features.opcode = nvme_admin_set_features;
523 	c.features.prp1 = cpu_to_le64(dma_addr);
524 	c.features.fid = cpu_to_le32(fid);
525 	c.features.dword11 = cpu_to_le32(dword11);
526 
527 	/*
528 	 * TODO: Add a cache clean (aka flush) operation when a DMA buffer is
529 	 * involved in the request. The buffer size varies by feature, also
530 	 * some features use a different field in the command packet to hold
531 	 * the buffer address. Section 5.21.1 (Set Features command) in the
532 	 * NVMe specification details the buffer requirements for each
533 	 * feature.
534 	 * At the moment the only user of this function is not using
535 	 * any DMA buffer at all.
536 	 */
537 
538 	return nvme_submit_admin_cmd(dev, &c, result);
539 }
540 
nvme_create_queue(struct nvme_queue * nvmeq,int qid)541 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
542 {
543 	struct nvme_dev *dev = nvmeq->dev;
544 	int result;
545 
546 	nvmeq->cq_vector = qid - 1;
547 	result = nvme_alloc_cq(dev, qid, nvmeq);
548 	if (result < 0)
549 		goto release_cq;
550 
551 	result = nvme_alloc_sq(dev, qid, nvmeq);
552 	if (result < 0)
553 		goto release_sq;
554 
555 	nvme_init_queue(nvmeq, qid);
556 
557 	return result;
558 
559  release_sq:
560 	nvme_delete_sq(dev, qid);
561  release_cq:
562 	nvme_delete_cq(dev, qid);
563 
564 	return result;
565 }
566 
nvme_set_queue_count(struct nvme_dev * dev,int count)567 static int nvme_set_queue_count(struct nvme_dev *dev, int count)
568 {
569 	int status;
570 	u32 result;
571 	u32 q_count = (count - 1) | ((count - 1) << 16);
572 
573 	status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES,
574 			q_count, 0, &result);
575 
576 	if (status < 0)
577 		return status;
578 	if (status > 1)
579 		return 0;
580 
581 	return min(result & 0xffff, result >> 16) + 1;
582 }
583 
nvme_create_io_queues(struct nvme_dev * dev)584 static void nvme_create_io_queues(struct nvme_dev *dev)
585 {
586 	unsigned int i;
587 
588 	for (i = dev->queue_count; i <= dev->max_qid; i++)
589 		if (!nvme_alloc_queue(dev, i, dev->q_depth))
590 			break;
591 
592 	for (i = dev->online_queues; i <= dev->queue_count - 1; i++)
593 		if (nvme_create_queue(dev->queues[i], i))
594 			break;
595 }
596 
nvme_setup_io_queues(struct nvme_dev * dev)597 static int nvme_setup_io_queues(struct nvme_dev *dev)
598 {
599 	int nr_io_queues;
600 	int result;
601 
602 	nr_io_queues = 1;
603 	result = nvme_set_queue_count(dev, nr_io_queues);
604 	if (result <= 0)
605 		return result;
606 
607 	dev->max_qid = nr_io_queues;
608 
609 	/* Free previously allocated queues */
610 	nvme_free_queues(dev, nr_io_queues + 1);
611 	nvme_create_io_queues(dev);
612 
613 	return 0;
614 }
615 
nvme_get_info_from_identify(struct nvme_dev * dev)616 static int nvme_get_info_from_identify(struct nvme_dev *dev)
617 {
618 	struct nvme_id_ctrl *ctrl;
619 	int ret;
620 	int shift = NVME_CAP_MPSMIN(dev->cap) + 12;
621 
622 	ctrl = memalign(dev->page_size, sizeof(struct nvme_id_ctrl));
623 	if (!ctrl)
624 		return -ENOMEM;
625 
626 	ret = nvme_identify(dev, 0, 1, (dma_addr_t)(long)ctrl);
627 	if (ret) {
628 		free(ctrl);
629 		return -EIO;
630 	}
631 
632 	dev->nn = le32_to_cpu(ctrl->nn);
633 	dev->vwc = ctrl->vwc;
634 	memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
635 	memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
636 	memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
637 	if (ctrl->mdts)
638 		dev->max_transfer_shift = (ctrl->mdts + shift);
639 	else {
640 		/*
641 		 * Maximum Data Transfer Size (MDTS) field indicates the maximum
642 		 * data transfer size between the host and the controller. The
643 		 * host should not submit a command that exceeds this transfer
644 		 * size. The value is in units of the minimum memory page size
645 		 * and is reported as a power of two (2^n).
646 		 *
647 		 * The spec also says: a value of 0h indicates no restrictions
648 		 * on transfer size. But in nvme_blk_read/write() below we have
649 		 * the following algorithm for maximum number of logic blocks
650 		 * per transfer:
651 		 *
652 		 * u16 lbas = 1 << (dev->max_transfer_shift - ns->lba_shift);
653 		 *
654 		 * In order for lbas not to overflow, the maximum number is 15
655 		 * which means dev->max_transfer_shift = 15 + 9 (ns->lba_shift).
656 		 * Let's use 20 which provides 1MB size.
657 		 */
658 		dev->max_transfer_shift = 20;
659 	}
660 
661 	free(ctrl);
662 	return 0;
663 }
664 
nvme_get_namespace_id(struct udevice * udev,u32 * ns_id,u8 * eui64)665 int nvme_get_namespace_id(struct udevice *udev, u32 *ns_id, u8 *eui64)
666 {
667 	struct nvme_ns *ns = dev_get_priv(udev);
668 
669 	if (ns_id)
670 		*ns_id = ns->ns_id;
671 	if (eui64)
672 		memcpy(eui64, ns->eui64, sizeof(ns->eui64));
673 
674 	return 0;
675 }
676 
nvme_scan_namespace(void)677 int nvme_scan_namespace(void)
678 {
679 	struct uclass *uc;
680 	struct udevice *dev;
681 	int ret;
682 
683 	ret = uclass_get(UCLASS_NVME, &uc);
684 	if (ret)
685 		return ret;
686 
687 	uclass_foreach_dev(dev, uc) {
688 		ret = device_probe(dev);
689 		if (ret)
690 			return ret;
691 	}
692 
693 	return 0;
694 }
695 
nvme_blk_probe(struct udevice * udev)696 static int nvme_blk_probe(struct udevice *udev)
697 {
698 	struct nvme_dev *ndev = dev_get_priv(udev->parent);
699 	struct blk_desc *desc = dev_get_uclass_plat(udev);
700 	struct nvme_ns *ns = dev_get_priv(udev);
701 	u8 flbas;
702 	struct pci_child_plat *pplat;
703 	struct nvme_id_ns *id;
704 
705 	id = memalign(ndev->page_size, sizeof(struct nvme_id_ns));
706 	if (!id)
707 		return -ENOMEM;
708 
709 	memset(ns, 0, sizeof(*ns));
710 	ns->dev = ndev;
711 	/* extract the namespace id from the block device name */
712 	ns->ns_id = trailing_strtol(udev->name) + 1;
713 	if (nvme_identify(ndev, ns->ns_id, 0, (dma_addr_t)(long)id)) {
714 		free(id);
715 		return -EIO;
716 	}
717 
718 	memcpy(&ns->eui64, &id->eui64, sizeof(id->eui64));
719 	flbas = id->flbas & NVME_NS_FLBAS_LBA_MASK;
720 	ns->flbas = flbas;
721 	ns->lba_shift = id->lbaf[flbas].ds;
722 	ns->mode_select_num_blocks = le64_to_cpu(id->nsze);
723 	ns->mode_select_block_len = 1 << ns->lba_shift;
724 	list_add(&ns->list, &ndev->namespaces);
725 
726 	desc->lba = ns->mode_select_num_blocks;
727 	desc->log2blksz = ns->lba_shift;
728 	desc->blksz = 1 << ns->lba_shift;
729 	desc->bdev = udev;
730 	pplat = dev_get_parent_plat(udev->parent);
731 	sprintf(desc->vendor, "0x%.4x", pplat->vendor);
732 	memcpy(desc->product, ndev->serial, sizeof(ndev->serial));
733 	memcpy(desc->revision, ndev->firmware_rev, sizeof(ndev->firmware_rev));
734 
735 	free(id);
736 	return 0;
737 }
738 
nvme_blk_rw(struct udevice * udev,lbaint_t blknr,lbaint_t blkcnt,void * buffer,bool read)739 static ulong nvme_blk_rw(struct udevice *udev, lbaint_t blknr,
740 			 lbaint_t blkcnt, void *buffer, bool read)
741 {
742 	struct nvme_ns *ns = dev_get_priv(udev);
743 	struct nvme_dev *dev = ns->dev;
744 	struct nvme_command c;
745 	struct blk_desc *desc = dev_get_uclass_plat(udev);
746 	int status;
747 	u64 prp2;
748 	u64 total_len = blkcnt << desc->log2blksz;
749 	u64 temp_len = total_len;
750 
751 	u64 slba = blknr;
752 	u16 lbas = 1 << (dev->max_transfer_shift - ns->lba_shift);
753 	u64 total_lbas = blkcnt;
754 
755 	flush_dcache_range((unsigned long)buffer,
756 			   (unsigned long)buffer + total_len);
757 
758 	c.rw.opcode = read ? nvme_cmd_read : nvme_cmd_write;
759 	c.rw.flags = 0;
760 	c.rw.nsid = cpu_to_le32(ns->ns_id);
761 	c.rw.control = 0;
762 	c.rw.dsmgmt = 0;
763 	c.rw.reftag = 0;
764 	c.rw.apptag = 0;
765 	c.rw.appmask = 0;
766 	c.rw.metadata = 0;
767 
768 	while (total_lbas) {
769 		if (total_lbas < lbas) {
770 			lbas = (u16)total_lbas;
771 			total_lbas = 0;
772 		} else {
773 			total_lbas -= lbas;
774 		}
775 
776 		if (nvme_setup_prps(dev, &prp2,
777 				    lbas << ns->lba_shift, (ulong)buffer))
778 			return -EIO;
779 		c.rw.slba = cpu_to_le64(slba);
780 		slba += lbas;
781 		c.rw.length = cpu_to_le16(lbas - 1);
782 		c.rw.prp1 = cpu_to_le64((ulong)buffer);
783 		c.rw.prp2 = cpu_to_le64(prp2);
784 		status = nvme_submit_sync_cmd(dev->queues[NVME_IO_Q],
785 				&c, NULL, IO_TIMEOUT);
786 		if (status)
787 			break;
788 		temp_len -= (u32)lbas << ns->lba_shift;
789 		buffer += lbas << ns->lba_shift;
790 	}
791 
792 	if (read)
793 		invalidate_dcache_range((unsigned long)buffer,
794 					(unsigned long)buffer + total_len);
795 
796 	return (total_len - temp_len) >> desc->log2blksz;
797 }
798 
nvme_blk_read(struct udevice * udev,lbaint_t blknr,lbaint_t blkcnt,void * buffer)799 static ulong nvme_blk_read(struct udevice *udev, lbaint_t blknr,
800 			   lbaint_t blkcnt, void *buffer)
801 {
802 	return nvme_blk_rw(udev, blknr, blkcnt, buffer, true);
803 }
804 
nvme_blk_write(struct udevice * udev,lbaint_t blknr,lbaint_t blkcnt,const void * buffer)805 static ulong nvme_blk_write(struct udevice *udev, lbaint_t blknr,
806 			    lbaint_t blkcnt, const void *buffer)
807 {
808 	return nvme_blk_rw(udev, blknr, blkcnt, (void *)buffer, false);
809 }
810 
811 static const struct blk_ops nvme_blk_ops = {
812 	.read	= nvme_blk_read,
813 	.write	= nvme_blk_write,
814 };
815 
816 U_BOOT_DRIVER(nvme_blk) = {
817 	.name	= "nvme-blk",
818 	.id	= UCLASS_BLK,
819 	.probe	= nvme_blk_probe,
820 	.ops	= &nvme_blk_ops,
821 	.priv_auto	= sizeof(struct nvme_ns),
822 };
823 
nvme_bind(struct udevice * udev)824 static int nvme_bind(struct udevice *udev)
825 {
826 	static int ndev_num;
827 	char name[20];
828 
829 	sprintf(name, "nvme#%d", ndev_num++);
830 
831 	return device_set_name(udev, name);
832 }
833 
nvme_probe(struct udevice * udev)834 static int nvme_probe(struct udevice *udev)
835 {
836 	int ret;
837 	struct nvme_dev *ndev = dev_get_priv(udev);
838 
839 	ndev->instance = trailing_strtol(udev->name);
840 
841 	INIT_LIST_HEAD(&ndev->namespaces);
842 	ndev->bar = dm_pci_map_bar(udev, PCI_BASE_ADDRESS_0,
843 			PCI_REGION_MEM);
844 	if (readl(&ndev->bar->csts) == -1) {
845 		ret = -ENODEV;
846 		printf("Error: %s: Out of memory!\n", udev->name);
847 		goto free_nvme;
848 	}
849 
850 	ndev->queues = malloc(NVME_Q_NUM * sizeof(struct nvme_queue *));
851 	if (!ndev->queues) {
852 		ret = -ENOMEM;
853 		printf("Error: %s: Out of memory!\n", udev->name);
854 		goto free_nvme;
855 	}
856 	memset(ndev->queues, 0, NVME_Q_NUM * sizeof(struct nvme_queue *));
857 
858 	ndev->cap = nvme_readq(&ndev->bar->cap);
859 	ndev->q_depth = min_t(int, NVME_CAP_MQES(ndev->cap) + 1, NVME_Q_DEPTH);
860 	ndev->db_stride = 1 << NVME_CAP_STRIDE(ndev->cap);
861 	ndev->dbs = ((void __iomem *)ndev->bar) + 4096;
862 
863 	ret = nvme_configure_admin_queue(ndev);
864 	if (ret)
865 		goto free_queue;
866 
867 	/* Allocate after the page size is known */
868 	ndev->prp_pool = memalign(ndev->page_size, MAX_PRP_POOL);
869 	if (!ndev->prp_pool) {
870 		ret = -ENOMEM;
871 		printf("Error: %s: Out of memory!\n", udev->name);
872 		goto free_nvme;
873 	}
874 	ndev->prp_entry_num = MAX_PRP_POOL >> 3;
875 
876 	ret = nvme_setup_io_queues(ndev);
877 	if (ret)
878 		goto free_queue;
879 
880 	nvme_get_info_from_identify(ndev);
881 
882 	return 0;
883 
884 free_queue:
885 	free((void *)ndev->queues);
886 free_nvme:
887 	return ret;
888 }
889 
890 U_BOOT_DRIVER(nvme) = {
891 	.name	= "nvme",
892 	.id	= UCLASS_NVME,
893 	.bind	= nvme_bind,
894 	.probe	= nvme_probe,
895 	.priv_auto	= sizeof(struct nvme_dev),
896 };
897 
898 struct pci_device_id nvme_supported[] = {
899 	{ PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, ~0) },
900 	{}
901 };
902 
903 U_BOOT_PCI_DEVICE(nvme, nvme_supported);
904