drivers: use req op accessor
[cascardo/linux.git] / drivers / nvme / host / scsi.c
1 /*
2  * NVM Express device driver
3  * Copyright (c) 2011-2014, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14
15 /*
16  * Refer to the SCSI-NVMe Translation spec for details on how
17  * each command is translated.
18  */
19
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/compat.h>
24 #include <linux/delay.h>
25 #include <linux/errno.h>
26 #include <linux/fs.h>
27 #include <linux/genhd.h>
28 #include <linux/idr.h>
29 #include <linux/init.h>
30 #include <linux/interrupt.h>
31 #include <linux/io.h>
32 #include <linux/kdev_t.h>
33 #include <linux/kthread.h>
34 #include <linux/kernel.h>
35 #include <linux/mm.h>
36 #include <linux/module.h>
37 #include <linux/moduleparam.h>
38 #include <linux/pci.h>
39 #include <linux/poison.h>
40 #include <linux/sched.h>
41 #include <linux/slab.h>
42 #include <linux/types.h>
43 #include <asm/unaligned.h>
44 #include <scsi/sg.h>
45 #include <scsi/scsi.h>
46
47 #include "nvme.h"
48
49 static int sg_version_num = 30534;      /* 2 digits for each component */
50
51 /* VPD Page Codes */
52 #define VPD_SUPPORTED_PAGES                             0x00
53 #define VPD_SERIAL_NUMBER                               0x80
54 #define VPD_DEVICE_IDENTIFIERS                          0x83
55 #define VPD_EXTENDED_INQUIRY                            0x86
56 #define VPD_BLOCK_LIMITS                                0xB0
57 #define VPD_BLOCK_DEV_CHARACTERISTICS                   0xB1
58
59 /* format unit paramter list offsets */
60 #define FORMAT_UNIT_SHORT_PARM_LIST_LEN                 4
61 #define FORMAT_UNIT_LONG_PARM_LIST_LEN                  8
62 #define FORMAT_UNIT_PROT_INT_OFFSET                     3
63 #define FORMAT_UNIT_PROT_FIELD_USAGE_OFFSET             0
64 #define FORMAT_UNIT_PROT_FIELD_USAGE_MASK               0x07
65
66 /* Misc. defines */
67 #define FIXED_SENSE_DATA                                0x70
68 #define DESC_FORMAT_SENSE_DATA                          0x72
69 #define FIXED_SENSE_DATA_ADD_LENGTH                     10
70 #define LUN_ENTRY_SIZE                                  8
71 #define LUN_DATA_HEADER_SIZE                            8
72 #define ALL_LUNS_RETURNED                               0x02
73 #define ALL_WELL_KNOWN_LUNS_RETURNED                    0x01
74 #define RESTRICTED_LUNS_RETURNED                        0x00
75 #define NVME_POWER_STATE_START_VALID                    0x00
76 #define NVME_POWER_STATE_ACTIVE                         0x01
77 #define NVME_POWER_STATE_IDLE                           0x02
78 #define NVME_POWER_STATE_STANDBY                        0x03
79 #define NVME_POWER_STATE_LU_CONTROL                     0x07
80 #define POWER_STATE_0                                   0
81 #define POWER_STATE_1                                   1
82 #define POWER_STATE_2                                   2
83 #define POWER_STATE_3                                   3
84 #define DOWNLOAD_SAVE_ACTIVATE                          0x05
85 #define DOWNLOAD_SAVE_DEFER_ACTIVATE                    0x0E
86 #define ACTIVATE_DEFERRED_MICROCODE                     0x0F
87 #define FORMAT_UNIT_IMMED_MASK                          0x2
88 #define FORMAT_UNIT_IMMED_OFFSET                        1
89 #define KELVIN_TEMP_FACTOR                              273
90 #define FIXED_FMT_SENSE_DATA_SIZE                       18
91 #define DESC_FMT_SENSE_DATA_SIZE                        8
92
93 /* SCSI/NVMe defines and bit masks */
94 #define INQ_STANDARD_INQUIRY_PAGE                       0x00
95 #define INQ_SUPPORTED_VPD_PAGES_PAGE                    0x00
96 #define INQ_UNIT_SERIAL_NUMBER_PAGE                     0x80
97 #define INQ_DEVICE_IDENTIFICATION_PAGE                  0x83
98 #define INQ_EXTENDED_INQUIRY_DATA_PAGE                  0x86
99 #define INQ_BDEV_LIMITS_PAGE                            0xB0
100 #define INQ_BDEV_CHARACTERISTICS_PAGE                   0xB1
101 #define INQ_SERIAL_NUMBER_LENGTH                        0x14
102 #define INQ_NUM_SUPPORTED_VPD_PAGES                     6
103 #define VERSION_SPC_4                                   0x06
104 #define ACA_UNSUPPORTED                                 0
105 #define STANDARD_INQUIRY_LENGTH                         36
106 #define ADDITIONAL_STD_INQ_LENGTH                       31
107 #define EXTENDED_INQUIRY_DATA_PAGE_LENGTH               0x3C
108 #define RESERVED_FIELD                                  0
109
110 /* Mode Sense/Select defines */
111 #define MODE_PAGE_INFO_EXCEP                            0x1C
112 #define MODE_PAGE_CACHING                               0x08
113 #define MODE_PAGE_CONTROL                               0x0A
114 #define MODE_PAGE_POWER_CONDITION                       0x1A
115 #define MODE_PAGE_RETURN_ALL                            0x3F
116 #define MODE_PAGE_BLK_DES_LEN                           0x08
117 #define MODE_PAGE_LLBAA_BLK_DES_LEN                     0x10
118 #define MODE_PAGE_CACHING_LEN                           0x14
119 #define MODE_PAGE_CONTROL_LEN                           0x0C
120 #define MODE_PAGE_POW_CND_LEN                           0x28
121 #define MODE_PAGE_INF_EXC_LEN                           0x0C
122 #define MODE_PAGE_ALL_LEN                               0x54
123 #define MODE_SENSE6_MPH_SIZE                            4
124 #define MODE_SENSE_PAGE_CONTROL_MASK                    0xC0
125 #define MODE_SENSE_PAGE_CODE_OFFSET                     2
126 #define MODE_SENSE_PAGE_CODE_MASK                       0x3F
127 #define MODE_SENSE_LLBAA_MASK                           0x10
128 #define MODE_SENSE_LLBAA_SHIFT                          4
129 #define MODE_SENSE_DBD_MASK                             8
130 #define MODE_SENSE_DBD_SHIFT                            3
131 #define MODE_SENSE10_MPH_SIZE                           8
132 #define MODE_SELECT_CDB_PAGE_FORMAT_MASK                0x10
133 #define MODE_SELECT_CDB_SAVE_PAGES_MASK                 0x1
134 #define MODE_SELECT_6_BD_OFFSET                         3
135 #define MODE_SELECT_10_BD_OFFSET                        6
136 #define MODE_SELECT_10_LLBAA_OFFSET                     4
137 #define MODE_SELECT_10_LLBAA_MASK                       1
138 #define MODE_SELECT_6_MPH_SIZE                          4
139 #define MODE_SELECT_10_MPH_SIZE                         8
140 #define CACHING_MODE_PAGE_WCE_MASK                      0x04
141 #define MODE_SENSE_BLK_DESC_ENABLED                     0
142 #define MODE_SENSE_BLK_DESC_COUNT                       1
143 #define MODE_SELECT_PAGE_CODE_MASK                      0x3F
144 #define SHORT_DESC_BLOCK                                8
145 #define LONG_DESC_BLOCK                                 16
146 #define MODE_PAGE_POW_CND_LEN_FIELD                     0x26
147 #define MODE_PAGE_INF_EXC_LEN_FIELD                     0x0A
148 #define MODE_PAGE_CACHING_LEN_FIELD                     0x12
149 #define MODE_PAGE_CONTROL_LEN_FIELD                     0x0A
150 #define MODE_SENSE_PC_CURRENT_VALUES                    0
151
152 /* Log Sense defines */
153 #define LOG_PAGE_SUPPORTED_LOG_PAGES_PAGE               0x00
154 #define LOG_PAGE_SUPPORTED_LOG_PAGES_LENGTH             0x07
155 #define LOG_PAGE_INFORMATIONAL_EXCEPTIONS_PAGE          0x2F
156 #define LOG_PAGE_TEMPERATURE_PAGE                       0x0D
157 #define LOG_SENSE_CDB_SP_NOT_ENABLED                    0
158 #define LOG_SENSE_CDB_PC_MASK                           0xC0
159 #define LOG_SENSE_CDB_PC_SHIFT                          6
160 #define LOG_SENSE_CDB_PC_CUMULATIVE_VALUES              1
161 #define LOG_SENSE_CDB_PAGE_CODE_MASK                    0x3F
162 #define REMAINING_INFO_EXCP_PAGE_LENGTH                 0x8
163 #define LOG_INFO_EXCP_PAGE_LENGTH                       0xC
164 #define REMAINING_TEMP_PAGE_LENGTH                      0xC
165 #define LOG_TEMP_PAGE_LENGTH                            0x10
166 #define LOG_TEMP_UNKNOWN                                0xFF
167 #define SUPPORTED_LOG_PAGES_PAGE_LENGTH                 0x3
168
169 /* Read Capacity defines */
170 #define READ_CAP_10_RESP_SIZE                           8
171 #define READ_CAP_16_RESP_SIZE                           32
172
173 /* NVMe Namespace and Command Defines */
174 #define BYTES_TO_DWORDS                                 4
175 #define NVME_MAX_FIRMWARE_SLOT                          7
176
177 /* Report LUNs defines */
178 #define REPORT_LUNS_FIRST_LUN_OFFSET                    8
179
180 /* SCSI ADDITIONAL SENSE Codes */
181
182 #define SCSI_ASC_NO_SENSE                               0x00
183 #define SCSI_ASC_PERIPHERAL_DEV_WRITE_FAULT             0x03
184 #define SCSI_ASC_LUN_NOT_READY                          0x04
185 #define SCSI_ASC_WARNING                                0x0B
186 #define SCSI_ASC_LOG_BLOCK_GUARD_CHECK_FAILED           0x10
187 #define SCSI_ASC_LOG_BLOCK_APPTAG_CHECK_FAILED          0x10
188 #define SCSI_ASC_LOG_BLOCK_REFTAG_CHECK_FAILED          0x10
189 #define SCSI_ASC_UNRECOVERED_READ_ERROR                 0x11
190 #define SCSI_ASC_MISCOMPARE_DURING_VERIFY               0x1D
191 #define SCSI_ASC_ACCESS_DENIED_INVALID_LUN_ID           0x20
192 #define SCSI_ASC_ILLEGAL_COMMAND                        0x20
193 #define SCSI_ASC_ILLEGAL_BLOCK                          0x21
194 #define SCSI_ASC_INVALID_CDB                            0x24
195 #define SCSI_ASC_INVALID_LUN                            0x25
196 #define SCSI_ASC_INVALID_PARAMETER                      0x26
197 #define SCSI_ASC_FORMAT_COMMAND_FAILED                  0x31
198 #define SCSI_ASC_INTERNAL_TARGET_FAILURE                0x44
199
200 /* SCSI ADDITIONAL SENSE Code Qualifiers */
201
202 #define SCSI_ASCQ_CAUSE_NOT_REPORTABLE                  0x00
203 #define SCSI_ASCQ_FORMAT_COMMAND_FAILED                 0x01
204 #define SCSI_ASCQ_LOG_BLOCK_GUARD_CHECK_FAILED          0x01
205 #define SCSI_ASCQ_LOG_BLOCK_APPTAG_CHECK_FAILED         0x02
206 #define SCSI_ASCQ_LOG_BLOCK_REFTAG_CHECK_FAILED         0x03
207 #define SCSI_ASCQ_FORMAT_IN_PROGRESS                    0x04
208 #define SCSI_ASCQ_POWER_LOSS_EXPECTED                   0x08
209 #define SCSI_ASCQ_INVALID_LUN_ID                        0x09
210
211 /* copied from drivers/usb/gadget/function/storage_common.h */
212 static inline u32 get_unaligned_be24(u8 *buf)
213 {
214         return 0xffffff & (u32) get_unaligned_be32(buf - 1);
215 }
216
217 /* Struct to gather data that needs to be extracted from a SCSI CDB.
218    Not conforming to any particular CDB variant, but compatible with all. */
219
220 struct nvme_trans_io_cdb {
221         u8 fua;
222         u8 prot_info;
223         u64 lba;
224         u32 xfer_len;
225 };
226
227
228 /* Internal Helper Functions */
229
230
231 /* Copy data to userspace memory */
232
233 static int nvme_trans_copy_to_user(struct sg_io_hdr *hdr, void *from,
234                                                                 unsigned long n)
235 {
236         int i;
237         void *index = from;
238         size_t remaining = n;
239         size_t xfer_len;
240
241         if (hdr->iovec_count > 0) {
242                 struct sg_iovec sgl;
243
244                 for (i = 0; i < hdr->iovec_count; i++) {
245                         if (copy_from_user(&sgl, hdr->dxferp +
246                                                 i * sizeof(struct sg_iovec),
247                                                 sizeof(struct sg_iovec)))
248                                 return -EFAULT;
249                         xfer_len = min(remaining, sgl.iov_len);
250                         if (copy_to_user(sgl.iov_base, index, xfer_len))
251                                 return -EFAULT;
252
253                         index += xfer_len;
254                         remaining -= xfer_len;
255                         if (remaining == 0)
256                                 break;
257                 }
258                 return 0;
259         }
260
261         if (copy_to_user(hdr->dxferp, from, n))
262                 return -EFAULT;
263         return 0;
264 }
265
266 /* Copy data from userspace memory */
267
268 static int nvme_trans_copy_from_user(struct sg_io_hdr *hdr, void *to,
269                                                                 unsigned long n)
270 {
271         int i;
272         void *index = to;
273         size_t remaining = n;
274         size_t xfer_len;
275
276         if (hdr->iovec_count > 0) {
277                 struct sg_iovec sgl;
278
279                 for (i = 0; i < hdr->iovec_count; i++) {
280                         if (copy_from_user(&sgl, hdr->dxferp +
281                                                 i * sizeof(struct sg_iovec),
282                                                 sizeof(struct sg_iovec)))
283                                 return -EFAULT;
284                         xfer_len = min(remaining, sgl.iov_len);
285                         if (copy_from_user(index, sgl.iov_base, xfer_len))
286                                 return -EFAULT;
287                         index += xfer_len;
288                         remaining -= xfer_len;
289                         if (remaining == 0)
290                                 break;
291                 }
292                 return 0;
293         }
294
295         if (copy_from_user(to, hdr->dxferp, n))
296                 return -EFAULT;
297         return 0;
298 }
299
300 /* Status/Sense Buffer Writeback */
301
302 static int nvme_trans_completion(struct sg_io_hdr *hdr, u8 status, u8 sense_key,
303                                  u8 asc, u8 ascq)
304 {
305         u8 xfer_len;
306         u8 resp[DESC_FMT_SENSE_DATA_SIZE];
307
308         if (scsi_status_is_good(status)) {
309                 hdr->status = SAM_STAT_GOOD;
310                 hdr->masked_status = GOOD;
311                 hdr->host_status = DID_OK;
312                 hdr->driver_status = DRIVER_OK;
313                 hdr->sb_len_wr = 0;
314         } else {
315                 hdr->status = status;
316                 hdr->masked_status = status >> 1;
317                 hdr->host_status = DID_OK;
318                 hdr->driver_status = DRIVER_OK;
319
320                 memset(resp, 0, DESC_FMT_SENSE_DATA_SIZE);
321                 resp[0] = DESC_FORMAT_SENSE_DATA;
322                 resp[1] = sense_key;
323                 resp[2] = asc;
324                 resp[3] = ascq;
325
326                 xfer_len = min_t(u8, hdr->mx_sb_len, DESC_FMT_SENSE_DATA_SIZE);
327                 hdr->sb_len_wr = xfer_len;
328                 if (copy_to_user(hdr->sbp, resp, xfer_len) > 0)
329                         return -EFAULT;
330         }
331
332         return 0;
333 }
334
335 /*
336  * Take a status code from a lowlevel routine, and if it was a positive NVMe
337  * error code update the sense data based on it.  In either case the passed
338  * in value is returned again, unless an -EFAULT from copy_to_user overrides
339  * it.
340  */
341 static int nvme_trans_status_code(struct sg_io_hdr *hdr, int nvme_sc)
342 {
343         u8 status, sense_key, asc, ascq;
344         int res;
345
346         /* For non-nvme (Linux) errors, simply return the error code */
347         if (nvme_sc < 0)
348                 return nvme_sc;
349
350         /* Mask DNR, More, and reserved fields */
351         switch (nvme_sc & 0x7FF) {
352         /* Generic Command Status */
353         case NVME_SC_SUCCESS:
354                 status = SAM_STAT_GOOD;
355                 sense_key = NO_SENSE;
356                 asc = SCSI_ASC_NO_SENSE;
357                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
358                 break;
359         case NVME_SC_INVALID_OPCODE:
360                 status = SAM_STAT_CHECK_CONDITION;
361                 sense_key = ILLEGAL_REQUEST;
362                 asc = SCSI_ASC_ILLEGAL_COMMAND;
363                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
364                 break;
365         case NVME_SC_INVALID_FIELD:
366                 status = SAM_STAT_CHECK_CONDITION;
367                 sense_key = ILLEGAL_REQUEST;
368                 asc = SCSI_ASC_INVALID_CDB;
369                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
370                 break;
371         case NVME_SC_DATA_XFER_ERROR:
372                 status = SAM_STAT_CHECK_CONDITION;
373                 sense_key = MEDIUM_ERROR;
374                 asc = SCSI_ASC_NO_SENSE;
375                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
376                 break;
377         case NVME_SC_POWER_LOSS:
378                 status = SAM_STAT_TASK_ABORTED;
379                 sense_key = ABORTED_COMMAND;
380                 asc = SCSI_ASC_WARNING;
381                 ascq = SCSI_ASCQ_POWER_LOSS_EXPECTED;
382                 break;
383         case NVME_SC_INTERNAL:
384                 status = SAM_STAT_CHECK_CONDITION;
385                 sense_key = HARDWARE_ERROR;
386                 asc = SCSI_ASC_INTERNAL_TARGET_FAILURE;
387                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
388                 break;
389         case NVME_SC_ABORT_REQ:
390                 status = SAM_STAT_TASK_ABORTED;
391                 sense_key = ABORTED_COMMAND;
392                 asc = SCSI_ASC_NO_SENSE;
393                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
394                 break;
395         case NVME_SC_ABORT_QUEUE:
396                 status = SAM_STAT_TASK_ABORTED;
397                 sense_key = ABORTED_COMMAND;
398                 asc = SCSI_ASC_NO_SENSE;
399                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
400                 break;
401         case NVME_SC_FUSED_FAIL:
402                 status = SAM_STAT_TASK_ABORTED;
403                 sense_key = ABORTED_COMMAND;
404                 asc = SCSI_ASC_NO_SENSE;
405                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
406                 break;
407         case NVME_SC_FUSED_MISSING:
408                 status = SAM_STAT_TASK_ABORTED;
409                 sense_key = ABORTED_COMMAND;
410                 asc = SCSI_ASC_NO_SENSE;
411                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
412                 break;
413         case NVME_SC_INVALID_NS:
414                 status = SAM_STAT_CHECK_CONDITION;
415                 sense_key = ILLEGAL_REQUEST;
416                 asc = SCSI_ASC_ACCESS_DENIED_INVALID_LUN_ID;
417                 ascq = SCSI_ASCQ_INVALID_LUN_ID;
418                 break;
419         case NVME_SC_LBA_RANGE:
420                 status = SAM_STAT_CHECK_CONDITION;
421                 sense_key = ILLEGAL_REQUEST;
422                 asc = SCSI_ASC_ILLEGAL_BLOCK;
423                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
424                 break;
425         case NVME_SC_CAP_EXCEEDED:
426                 status = SAM_STAT_CHECK_CONDITION;
427                 sense_key = MEDIUM_ERROR;
428                 asc = SCSI_ASC_NO_SENSE;
429                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
430                 break;
431         case NVME_SC_NS_NOT_READY:
432                 status = SAM_STAT_CHECK_CONDITION;
433                 sense_key = NOT_READY;
434                 asc = SCSI_ASC_LUN_NOT_READY;
435                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
436                 break;
437
438         /* Command Specific Status */
439         case NVME_SC_INVALID_FORMAT:
440                 status = SAM_STAT_CHECK_CONDITION;
441                 sense_key = ILLEGAL_REQUEST;
442                 asc = SCSI_ASC_FORMAT_COMMAND_FAILED;
443                 ascq = SCSI_ASCQ_FORMAT_COMMAND_FAILED;
444                 break;
445         case NVME_SC_BAD_ATTRIBUTES:
446                 status = SAM_STAT_CHECK_CONDITION;
447                 sense_key = ILLEGAL_REQUEST;
448                 asc = SCSI_ASC_INVALID_CDB;
449                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
450                 break;
451
452         /* Media Errors */
453         case NVME_SC_WRITE_FAULT:
454                 status = SAM_STAT_CHECK_CONDITION;
455                 sense_key = MEDIUM_ERROR;
456                 asc = SCSI_ASC_PERIPHERAL_DEV_WRITE_FAULT;
457                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
458                 break;
459         case NVME_SC_READ_ERROR:
460                 status = SAM_STAT_CHECK_CONDITION;
461                 sense_key = MEDIUM_ERROR;
462                 asc = SCSI_ASC_UNRECOVERED_READ_ERROR;
463                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
464                 break;
465         case NVME_SC_GUARD_CHECK:
466                 status = SAM_STAT_CHECK_CONDITION;
467                 sense_key = MEDIUM_ERROR;
468                 asc = SCSI_ASC_LOG_BLOCK_GUARD_CHECK_FAILED;
469                 ascq = SCSI_ASCQ_LOG_BLOCK_GUARD_CHECK_FAILED;
470                 break;
471         case NVME_SC_APPTAG_CHECK:
472                 status = SAM_STAT_CHECK_CONDITION;
473                 sense_key = MEDIUM_ERROR;
474                 asc = SCSI_ASC_LOG_BLOCK_APPTAG_CHECK_FAILED;
475                 ascq = SCSI_ASCQ_LOG_BLOCK_APPTAG_CHECK_FAILED;
476                 break;
477         case NVME_SC_REFTAG_CHECK:
478                 status = SAM_STAT_CHECK_CONDITION;
479                 sense_key = MEDIUM_ERROR;
480                 asc = SCSI_ASC_LOG_BLOCK_REFTAG_CHECK_FAILED;
481                 ascq = SCSI_ASCQ_LOG_BLOCK_REFTAG_CHECK_FAILED;
482                 break;
483         case NVME_SC_COMPARE_FAILED:
484                 status = SAM_STAT_CHECK_CONDITION;
485                 sense_key = MISCOMPARE;
486                 asc = SCSI_ASC_MISCOMPARE_DURING_VERIFY;
487                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
488                 break;
489         case NVME_SC_ACCESS_DENIED:
490                 status = SAM_STAT_CHECK_CONDITION;
491                 sense_key = ILLEGAL_REQUEST;
492                 asc = SCSI_ASC_ACCESS_DENIED_INVALID_LUN_ID;
493                 ascq = SCSI_ASCQ_INVALID_LUN_ID;
494                 break;
495
496         /* Unspecified/Default */
497         case NVME_SC_CMDID_CONFLICT:
498         case NVME_SC_CMD_SEQ_ERROR:
499         case NVME_SC_CQ_INVALID:
500         case NVME_SC_QID_INVALID:
501         case NVME_SC_QUEUE_SIZE:
502         case NVME_SC_ABORT_LIMIT:
503         case NVME_SC_ABORT_MISSING:
504         case NVME_SC_ASYNC_LIMIT:
505         case NVME_SC_FIRMWARE_SLOT:
506         case NVME_SC_FIRMWARE_IMAGE:
507         case NVME_SC_INVALID_VECTOR:
508         case NVME_SC_INVALID_LOG_PAGE:
509         default:
510                 status = SAM_STAT_CHECK_CONDITION;
511                 sense_key = ILLEGAL_REQUEST;
512                 asc = SCSI_ASC_NO_SENSE;
513                 ascq = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
514                 break;
515         }
516
517         res = nvme_trans_completion(hdr, status, sense_key, asc, ascq);
518         return res ? res : nvme_sc;
519 }
520
521 /* INQUIRY Helper Functions */
522
523 static int nvme_trans_standard_inquiry_page(struct nvme_ns *ns,
524                                         struct sg_io_hdr *hdr, u8 *inq_response,
525                                         int alloc_len)
526 {
527         struct nvme_ctrl *ctrl = ns->ctrl;
528         struct nvme_id_ns *id_ns;
529         int res;
530         int nvme_sc;
531         int xfer_len;
532         u8 resp_data_format = 0x02;
533         u8 protect;
534         u8 cmdque = 0x01 << 1;
535         u8 fw_offset = sizeof(ctrl->firmware_rev);
536
537         /* nvme ns identify - use DPS value for PROTECT field */
538         nvme_sc = nvme_identify_ns(ctrl, ns->ns_id, &id_ns);
539         res = nvme_trans_status_code(hdr, nvme_sc);
540         if (res)
541                 return res;
542
543         if (id_ns->dps)
544                 protect = 0x01;
545         else
546                 protect = 0;
547         kfree(id_ns);
548
549         memset(inq_response, 0, STANDARD_INQUIRY_LENGTH);
550         inq_response[2] = VERSION_SPC_4;
551         inq_response[3] = resp_data_format;     /*normaca=0 | hisup=0 */
552         inq_response[4] = ADDITIONAL_STD_INQ_LENGTH;
553         inq_response[5] = protect;      /* sccs=0 | acc=0 | tpgs=0 | pc3=0 */
554         inq_response[7] = cmdque;       /* wbus16=0 | sync=0 | vs=0 */
555         strncpy(&inq_response[8], "NVMe    ", 8);
556         strncpy(&inq_response[16], ctrl->model, 16);
557
558         while (ctrl->firmware_rev[fw_offset - 1] == ' ' && fw_offset > 4)
559                 fw_offset--;
560         fw_offset -= 4;
561         strncpy(&inq_response[32], ctrl->firmware_rev + fw_offset, 4);
562
563         xfer_len = min(alloc_len, STANDARD_INQUIRY_LENGTH);
564         return nvme_trans_copy_to_user(hdr, inq_response, xfer_len);
565 }
566
567 static int nvme_trans_supported_vpd_pages(struct nvme_ns *ns,
568                                         struct sg_io_hdr *hdr, u8 *inq_response,
569                                         int alloc_len)
570 {
571         int xfer_len;
572
573         memset(inq_response, 0, STANDARD_INQUIRY_LENGTH);
574         inq_response[1] = INQ_SUPPORTED_VPD_PAGES_PAGE;   /* Page Code */
575         inq_response[3] = INQ_NUM_SUPPORTED_VPD_PAGES;    /* Page Length */
576         inq_response[4] = INQ_SUPPORTED_VPD_PAGES_PAGE;
577         inq_response[5] = INQ_UNIT_SERIAL_NUMBER_PAGE;
578         inq_response[6] = INQ_DEVICE_IDENTIFICATION_PAGE;
579         inq_response[7] = INQ_EXTENDED_INQUIRY_DATA_PAGE;
580         inq_response[8] = INQ_BDEV_CHARACTERISTICS_PAGE;
581         inq_response[9] = INQ_BDEV_LIMITS_PAGE;
582
583         xfer_len = min(alloc_len, STANDARD_INQUIRY_LENGTH);
584         return nvme_trans_copy_to_user(hdr, inq_response, xfer_len);
585 }
586
587 static int nvme_trans_unit_serial_page(struct nvme_ns *ns,
588                                         struct sg_io_hdr *hdr, u8 *inq_response,
589                                         int alloc_len)
590 {
591         int xfer_len;
592
593         memset(inq_response, 0, STANDARD_INQUIRY_LENGTH);
594         inq_response[1] = INQ_UNIT_SERIAL_NUMBER_PAGE; /* Page Code */
595         inq_response[3] = INQ_SERIAL_NUMBER_LENGTH;    /* Page Length */
596         strncpy(&inq_response[4], ns->ctrl->serial, INQ_SERIAL_NUMBER_LENGTH);
597
598         xfer_len = min(alloc_len, STANDARD_INQUIRY_LENGTH);
599         return nvme_trans_copy_to_user(hdr, inq_response, xfer_len);
600 }
601
602 static int nvme_fill_device_id_eui64(struct nvme_ns *ns, struct sg_io_hdr *hdr,
603                 u8 *inq_response, int alloc_len)
604 {
605         struct nvme_id_ns *id_ns;
606         int nvme_sc, res;
607         size_t len;
608         void *eui;
609
610         nvme_sc = nvme_identify_ns(ns->ctrl, ns->ns_id, &id_ns);
611         res = nvme_trans_status_code(hdr, nvme_sc);
612         if (res)
613                 return res;
614
615         eui = id_ns->eui64;
616         len = sizeof(id_ns->eui64);
617
618         if (ns->ctrl->vs >= NVME_VS(1, 2)) {
619                 if (bitmap_empty(eui, len * 8)) {
620                         eui = id_ns->nguid;
621                         len = sizeof(id_ns->nguid);
622                 }
623         }
624
625         if (bitmap_empty(eui, len * 8)) {
626                 res = -EOPNOTSUPP;
627                 goto out_free_id;
628         }
629
630         memset(inq_response, 0, alloc_len);
631         inq_response[1] = INQ_DEVICE_IDENTIFICATION_PAGE;
632         inq_response[3] = 4 + len; /* Page Length */
633
634         /* Designation Descriptor start */
635         inq_response[4] = 0x01; /* Proto ID=0h | Code set=1h */
636         inq_response[5] = 0x02; /* PIV=0b | Asso=00b | Designator Type=2h */
637         inq_response[6] = 0x00; /* Rsvd */
638         inq_response[7] = len;  /* Designator Length */
639         memcpy(&inq_response[8], eui, len);
640
641         res = nvme_trans_copy_to_user(hdr, inq_response, alloc_len);
642 out_free_id:
643         kfree(id_ns);
644         return res;
645 }
646
647 static int nvme_fill_device_id_scsi_string(struct nvme_ns *ns,
648                 struct sg_io_hdr *hdr, u8 *inq_response, int alloc_len)
649 {
650         struct nvme_ctrl *ctrl = ns->ctrl;
651         struct nvme_id_ctrl *id_ctrl;
652         int nvme_sc, res;
653
654         if (alloc_len < 72) {
655                 return nvme_trans_completion(hdr,
656                                 SAM_STAT_CHECK_CONDITION,
657                                 ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
658                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
659         }
660
661         nvme_sc = nvme_identify_ctrl(ctrl, &id_ctrl);
662         res = nvme_trans_status_code(hdr, nvme_sc);
663         if (res)
664                 return res;
665
666         memset(inq_response, 0, alloc_len);
667         inq_response[1] = INQ_DEVICE_IDENTIFICATION_PAGE;
668         inq_response[3] = 0x48; /* Page Length */
669
670         /* Designation Descriptor start */
671         inq_response[4] = 0x03; /* Proto ID=0h | Code set=3h */
672         inq_response[5] = 0x08; /* PIV=0b | Asso=00b | Designator Type=8h */
673         inq_response[6] = 0x00; /* Rsvd */
674         inq_response[7] = 0x44; /* Designator Length */
675
676         sprintf(&inq_response[8], "%04x", le16_to_cpu(id_ctrl->vid));
677         memcpy(&inq_response[12], ctrl->model, sizeof(ctrl->model));
678         sprintf(&inq_response[52], "%04x", cpu_to_be32(ns->ns_id));
679         memcpy(&inq_response[56], ctrl->serial, sizeof(ctrl->serial));
680
681         res = nvme_trans_copy_to_user(hdr, inq_response, alloc_len);
682         kfree(id_ctrl);
683         return res;
684 }
685
686 static int nvme_trans_device_id_page(struct nvme_ns *ns, struct sg_io_hdr *hdr,
687                                         u8 *resp, int alloc_len)
688 {
689         int res;
690
691         if (ns->ctrl->vs >= NVME_VS(1, 1)) {
692                 res = nvme_fill_device_id_eui64(ns, hdr, resp, alloc_len);
693                 if (res != -EOPNOTSUPP)
694                         return res;
695         }
696
697         return nvme_fill_device_id_scsi_string(ns, hdr, resp, alloc_len);
698 }
699
700 static int nvme_trans_ext_inq_page(struct nvme_ns *ns, struct sg_io_hdr *hdr,
701                                         int alloc_len)
702 {
703         u8 *inq_response;
704         int res;
705         int nvme_sc;
706         struct nvme_ctrl *ctrl = ns->ctrl;
707         struct nvme_id_ctrl *id_ctrl;
708         struct nvme_id_ns *id_ns;
709         int xfer_len;
710         u8 microcode = 0x80;
711         u8 spt;
712         u8 spt_lut[8] = {0, 0, 2, 1, 4, 6, 5, 7};
713         u8 grd_chk, app_chk, ref_chk, protect;
714         u8 uask_sup = 0x20;
715         u8 v_sup;
716         u8 luiclr = 0x01;
717
718         inq_response = kmalloc(EXTENDED_INQUIRY_DATA_PAGE_LENGTH, GFP_KERNEL);
719         if (inq_response == NULL)
720                 return -ENOMEM;
721
722         nvme_sc = nvme_identify_ns(ctrl, ns->ns_id, &id_ns);
723         res = nvme_trans_status_code(hdr, nvme_sc);
724         if (res)
725                 goto out_free_inq;
726
727         spt = spt_lut[id_ns->dpc & 0x07] << 3;
728         if (id_ns->dps)
729                 protect = 0x01;
730         else
731                 protect = 0;
732         kfree(id_ns);
733
734         grd_chk = protect << 2;
735         app_chk = protect << 1;
736         ref_chk = protect;
737
738         nvme_sc = nvme_identify_ctrl(ctrl, &id_ctrl);
739         res = nvme_trans_status_code(hdr, nvme_sc);
740         if (res)
741                 goto out_free_inq;
742
743         v_sup = id_ctrl->vwc;
744         kfree(id_ctrl);
745
746         memset(inq_response, 0, EXTENDED_INQUIRY_DATA_PAGE_LENGTH);
747         inq_response[1] = INQ_EXTENDED_INQUIRY_DATA_PAGE;    /* Page Code */
748         inq_response[2] = 0x00;    /* Page Length MSB */
749         inq_response[3] = 0x3C;    /* Page Length LSB */
750         inq_response[4] = microcode | spt | grd_chk | app_chk | ref_chk;
751         inq_response[5] = uask_sup;
752         inq_response[6] = v_sup;
753         inq_response[7] = luiclr;
754         inq_response[8] = 0;
755         inq_response[9] = 0;
756
757         xfer_len = min(alloc_len, EXTENDED_INQUIRY_DATA_PAGE_LENGTH);
758         res = nvme_trans_copy_to_user(hdr, inq_response, xfer_len);
759
760  out_free_inq:
761         kfree(inq_response);
762         return res;
763 }
764
765 static int nvme_trans_bdev_limits_page(struct nvme_ns *ns, struct sg_io_hdr *hdr,
766                                         u8 *inq_response, int alloc_len)
767 {
768         __be32 max_sectors = cpu_to_be32(
769                 nvme_block_nr(ns, queue_max_hw_sectors(ns->queue)));
770         __be32 max_discard = cpu_to_be32(ns->queue->limits.max_discard_sectors);
771         __be32 discard_desc_count = cpu_to_be32(0x100);
772
773         memset(inq_response, 0, STANDARD_INQUIRY_LENGTH);
774         inq_response[1] = VPD_BLOCK_LIMITS;
775         inq_response[3] = 0x3c; /* Page Length */
776         memcpy(&inq_response[8], &max_sectors, sizeof(u32));
777         memcpy(&inq_response[20], &max_discard, sizeof(u32));
778
779         if (max_discard)
780                 memcpy(&inq_response[24], &discard_desc_count, sizeof(u32));
781
782         return nvme_trans_copy_to_user(hdr, inq_response, 0x3c);
783 }
784
785 static int nvme_trans_bdev_char_page(struct nvme_ns *ns, struct sg_io_hdr *hdr,
786                                         int alloc_len)
787 {
788         u8 *inq_response;
789         int res;
790         int xfer_len;
791
792         inq_response = kzalloc(EXTENDED_INQUIRY_DATA_PAGE_LENGTH, GFP_KERNEL);
793         if (inq_response == NULL) {
794                 res = -ENOMEM;
795                 goto out_mem;
796         }
797
798         inq_response[1] = INQ_BDEV_CHARACTERISTICS_PAGE;    /* Page Code */
799         inq_response[2] = 0x00;    /* Page Length MSB */
800         inq_response[3] = 0x3C;    /* Page Length LSB */
801         inq_response[4] = 0x00;    /* Medium Rotation Rate MSB */
802         inq_response[5] = 0x01;    /* Medium Rotation Rate LSB */
803         inq_response[6] = 0x00;    /* Form Factor */
804
805         xfer_len = min(alloc_len, EXTENDED_INQUIRY_DATA_PAGE_LENGTH);
806         res = nvme_trans_copy_to_user(hdr, inq_response, xfer_len);
807
808         kfree(inq_response);
809  out_mem:
810         return res;
811 }
812
813 /* LOG SENSE Helper Functions */
814
815 static int nvme_trans_log_supp_pages(struct nvme_ns *ns, struct sg_io_hdr *hdr,
816                                         int alloc_len)
817 {
818         int res;
819         int xfer_len;
820         u8 *log_response;
821
822         log_response = kzalloc(LOG_PAGE_SUPPORTED_LOG_PAGES_LENGTH, GFP_KERNEL);
823         if (log_response == NULL) {
824                 res = -ENOMEM;
825                 goto out_mem;
826         }
827
828         log_response[0] = LOG_PAGE_SUPPORTED_LOG_PAGES_PAGE;
829         /* Subpage=0x00, Page Length MSB=0 */
830         log_response[3] = SUPPORTED_LOG_PAGES_PAGE_LENGTH;
831         log_response[4] = LOG_PAGE_SUPPORTED_LOG_PAGES_PAGE;
832         log_response[5] = LOG_PAGE_INFORMATIONAL_EXCEPTIONS_PAGE;
833         log_response[6] = LOG_PAGE_TEMPERATURE_PAGE;
834
835         xfer_len = min(alloc_len, LOG_PAGE_SUPPORTED_LOG_PAGES_LENGTH);
836         res = nvme_trans_copy_to_user(hdr, log_response, xfer_len);
837
838         kfree(log_response);
839  out_mem:
840         return res;
841 }
842
843 static int nvme_trans_log_info_exceptions(struct nvme_ns *ns,
844                                         struct sg_io_hdr *hdr, int alloc_len)
845 {
846         int res;
847         int xfer_len;
848         u8 *log_response;
849         struct nvme_smart_log *smart_log;
850         u8 temp_c;
851         u16 temp_k;
852
853         log_response = kzalloc(LOG_INFO_EXCP_PAGE_LENGTH, GFP_KERNEL);
854         if (log_response == NULL)
855                 return -ENOMEM;
856
857         res = nvme_get_log_page(ns->ctrl, &smart_log);
858         if (res < 0)
859                 goto out_free_response;
860
861         if (res != NVME_SC_SUCCESS) {
862                 temp_c = LOG_TEMP_UNKNOWN;
863         } else {
864                 temp_k = (smart_log->temperature[1] << 8) +
865                                 (smart_log->temperature[0]);
866                 temp_c = temp_k - KELVIN_TEMP_FACTOR;
867         }
868         kfree(smart_log);
869
870         log_response[0] = LOG_PAGE_INFORMATIONAL_EXCEPTIONS_PAGE;
871         /* Subpage=0x00, Page Length MSB=0 */
872         log_response[3] = REMAINING_INFO_EXCP_PAGE_LENGTH;
873         /* Informational Exceptions Log Parameter 1 Start */
874         /* Parameter Code=0x0000 bytes 4,5 */
875         log_response[6] = 0x23; /* DU=0, TSD=1, ETC=0, TMC=0, FMT_AND_LNK=11b */
876         log_response[7] = 0x04; /* PARAMETER LENGTH */
877         /* Add sense Code and qualifier = 0x00 each */
878         /* Use Temperature from NVMe Get Log Page, convert to C from K */
879         log_response[10] = temp_c;
880
881         xfer_len = min(alloc_len, LOG_INFO_EXCP_PAGE_LENGTH);
882         res = nvme_trans_copy_to_user(hdr, log_response, xfer_len);
883
884  out_free_response:
885         kfree(log_response);
886         return res;
887 }
888
889 static int nvme_trans_log_temperature(struct nvme_ns *ns, struct sg_io_hdr *hdr,
890                                         int alloc_len)
891 {
892         int res;
893         int xfer_len;
894         u8 *log_response;
895         struct nvme_smart_log *smart_log;
896         u32 feature_resp;
897         u8 temp_c_cur, temp_c_thresh;
898         u16 temp_k;
899
900         log_response = kzalloc(LOG_TEMP_PAGE_LENGTH, GFP_KERNEL);
901         if (log_response == NULL)
902                 return -ENOMEM;
903
904         res = nvme_get_log_page(ns->ctrl, &smart_log);
905         if (res < 0)
906                 goto out_free_response;
907
908         if (res != NVME_SC_SUCCESS) {
909                 temp_c_cur = LOG_TEMP_UNKNOWN;
910         } else {
911                 temp_k = (smart_log->temperature[1] << 8) +
912                                 (smart_log->temperature[0]);
913                 temp_c_cur = temp_k - KELVIN_TEMP_FACTOR;
914         }
915         kfree(smart_log);
916
917         /* Get Features for Temp Threshold */
918         res = nvme_get_features(ns->ctrl, NVME_FEAT_TEMP_THRESH, 0, 0,
919                                                                 &feature_resp);
920         if (res != NVME_SC_SUCCESS)
921                 temp_c_thresh = LOG_TEMP_UNKNOWN;
922         else
923                 temp_c_thresh = (feature_resp & 0xFFFF) - KELVIN_TEMP_FACTOR;
924
925         log_response[0] = LOG_PAGE_TEMPERATURE_PAGE;
926         /* Subpage=0x00, Page Length MSB=0 */
927         log_response[3] = REMAINING_TEMP_PAGE_LENGTH;
928         /* Temperature Log Parameter 1 (Temperature) Start */
929         /* Parameter Code = 0x0000 */
930         log_response[6] = 0x01;         /* Format and Linking = 01b */
931         log_response[7] = 0x02;         /* Parameter Length */
932         /* Use Temperature from NVMe Get Log Page, convert to C from K */
933         log_response[9] = temp_c_cur;
934         /* Temperature Log Parameter 2 (Reference Temperature) Start */
935         log_response[11] = 0x01;        /* Parameter Code = 0x0001 */
936         log_response[12] = 0x01;        /* Format and Linking = 01b */
937         log_response[13] = 0x02;        /* Parameter Length */
938         /* Use Temperature Thresh from NVMe Get Log Page, convert to C from K */
939         log_response[15] = temp_c_thresh;
940
941         xfer_len = min(alloc_len, LOG_TEMP_PAGE_LENGTH);
942         res = nvme_trans_copy_to_user(hdr, log_response, xfer_len);
943
944  out_free_response:
945         kfree(log_response);
946         return res;
947 }
948
949 /* MODE SENSE Helper Functions */
950
951 static int nvme_trans_fill_mode_parm_hdr(u8 *resp, int len, u8 cdb10, u8 llbaa,
952                                         u16 mode_data_length, u16 blk_desc_len)
953 {
954         /* Quick check to make sure I don't stomp on my own memory... */
955         if ((cdb10 && len < 8) || (!cdb10 && len < 4))
956                 return -EINVAL;
957
958         if (cdb10) {
959                 resp[0] = (mode_data_length & 0xFF00) >> 8;
960                 resp[1] = (mode_data_length & 0x00FF);
961                 resp[3] = 0x10 /* DPOFUA */;
962                 resp[4] = llbaa;
963                 resp[5] = RESERVED_FIELD;
964                 resp[6] = (blk_desc_len & 0xFF00) >> 8;
965                 resp[7] = (blk_desc_len & 0x00FF);
966         } else {
967                 resp[0] = (mode_data_length & 0x00FF);
968                 resp[2] = 0x10 /* DPOFUA */;
969                 resp[3] = (blk_desc_len & 0x00FF);
970         }
971
972         return 0;
973 }
974
975 static int nvme_trans_fill_blk_desc(struct nvme_ns *ns, struct sg_io_hdr *hdr,
976                                     u8 *resp, int len, u8 llbaa)
977 {
978         int res;
979         int nvme_sc;
980         struct nvme_id_ns *id_ns;
981         u8 flbas;
982         u32 lba_length;
983
984         if (llbaa == 0 && len < MODE_PAGE_BLK_DES_LEN)
985                 return -EINVAL;
986         else if (llbaa > 0 && len < MODE_PAGE_LLBAA_BLK_DES_LEN)
987                 return -EINVAL;
988
989         nvme_sc = nvme_identify_ns(ns->ctrl, ns->ns_id, &id_ns);
990         res = nvme_trans_status_code(hdr, nvme_sc);
991         if (res)
992                 return res;
993
994         flbas = (id_ns->flbas) & 0x0F;
995         lba_length = (1 << (id_ns->lbaf[flbas].ds));
996
997         if (llbaa == 0) {
998                 __be32 tmp_cap = cpu_to_be32(le64_to_cpu(id_ns->ncap));
999                 /* Byte 4 is reserved */
1000                 __be32 tmp_len = cpu_to_be32(lba_length & 0x00FFFFFF);
1001
1002                 memcpy(resp, &tmp_cap, sizeof(u32));
1003                 memcpy(&resp[4], &tmp_len, sizeof(u32));
1004         } else {
1005                 __be64 tmp_cap = cpu_to_be64(le64_to_cpu(id_ns->ncap));
1006                 __be32 tmp_len = cpu_to_be32(lba_length);
1007
1008                 memcpy(resp, &tmp_cap, sizeof(u64));
1009                 /* Bytes 8, 9, 10, 11 are reserved */
1010                 memcpy(&resp[12], &tmp_len, sizeof(u32));
1011         }
1012
1013         kfree(id_ns);
1014         return res;
1015 }
1016
1017 static int nvme_trans_fill_control_page(struct nvme_ns *ns,
1018                                         struct sg_io_hdr *hdr, u8 *resp,
1019                                         int len)
1020 {
1021         if (len < MODE_PAGE_CONTROL_LEN)
1022                 return -EINVAL;
1023
1024         resp[0] = MODE_PAGE_CONTROL;
1025         resp[1] = MODE_PAGE_CONTROL_LEN_FIELD;
1026         resp[2] = 0x0E;         /* TST=000b, TMF_ONLY=0, DPICZ=1,
1027                                  * D_SENSE=1, GLTSD=1, RLEC=0 */
1028         resp[3] = 0x12;         /* Q_ALGO_MODIFIER=1h, NUAR=0, QERR=01b */
1029         /* Byte 4:  VS=0, RAC=0, UA_INT=0, SWP=0 */
1030         resp[5] = 0x40;         /* ATO=0, TAS=1, ATMPE=0, RWWP=0, AUTOLOAD=0 */
1031         /* resp[6] and [7] are obsolete, thus zero */
1032         resp[8] = 0xFF;         /* Busy timeout period = 0xffff */
1033         resp[9] = 0xFF;
1034         /* Bytes 10,11: Extended selftest completion time = 0x0000 */
1035
1036         return 0;
1037 }
1038
1039 static int nvme_trans_fill_caching_page(struct nvme_ns *ns,
1040                                         struct sg_io_hdr *hdr,
1041                                         u8 *resp, int len)
1042 {
1043         int res = 0;
1044         int nvme_sc;
1045         u32 feature_resp;
1046         u8 vwc;
1047
1048         if (len < MODE_PAGE_CACHING_LEN)
1049                 return -EINVAL;
1050
1051         nvme_sc = nvme_get_features(ns->ctrl, NVME_FEAT_VOLATILE_WC, 0, 0,
1052                                                                 &feature_resp);
1053         res = nvme_trans_status_code(hdr, nvme_sc);
1054         if (res)
1055                 return res;
1056
1057         vwc = feature_resp & 0x00000001;
1058
1059         resp[0] = MODE_PAGE_CACHING;
1060         resp[1] = MODE_PAGE_CACHING_LEN_FIELD;
1061         resp[2] = vwc << 2;
1062         return 0;
1063 }
1064
1065 static int nvme_trans_fill_pow_cnd_page(struct nvme_ns *ns,
1066                                         struct sg_io_hdr *hdr, u8 *resp,
1067                                         int len)
1068 {
1069         if (len < MODE_PAGE_POW_CND_LEN)
1070                 return -EINVAL;
1071
1072         resp[0] = MODE_PAGE_POWER_CONDITION;
1073         resp[1] = MODE_PAGE_POW_CND_LEN_FIELD;
1074         /* All other bytes are zero */
1075
1076         return 0;
1077 }
1078
1079 static int nvme_trans_fill_inf_exc_page(struct nvme_ns *ns,
1080                                         struct sg_io_hdr *hdr, u8 *resp,
1081                                         int len)
1082 {
1083         if (len < MODE_PAGE_INF_EXC_LEN)
1084                 return -EINVAL;
1085
1086         resp[0] = MODE_PAGE_INFO_EXCEP;
1087         resp[1] = MODE_PAGE_INF_EXC_LEN_FIELD;
1088         resp[2] = 0x88;
1089         /* All other bytes are zero */
1090
1091         return 0;
1092 }
1093
1094 static int nvme_trans_fill_all_pages(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1095                                      u8 *resp, int len)
1096 {
1097         int res;
1098         u16 mode_pages_offset_1 = 0;
1099         u16 mode_pages_offset_2, mode_pages_offset_3, mode_pages_offset_4;
1100
1101         mode_pages_offset_2 = mode_pages_offset_1 + MODE_PAGE_CACHING_LEN;
1102         mode_pages_offset_3 = mode_pages_offset_2 + MODE_PAGE_CONTROL_LEN;
1103         mode_pages_offset_4 = mode_pages_offset_3 + MODE_PAGE_POW_CND_LEN;
1104
1105         res = nvme_trans_fill_caching_page(ns, hdr, &resp[mode_pages_offset_1],
1106                                         MODE_PAGE_CACHING_LEN);
1107         if (res)
1108                 return res;
1109         res = nvme_trans_fill_control_page(ns, hdr, &resp[mode_pages_offset_2],
1110                                         MODE_PAGE_CONTROL_LEN);
1111         if (res)
1112                 return res;
1113         res = nvme_trans_fill_pow_cnd_page(ns, hdr, &resp[mode_pages_offset_3],
1114                                         MODE_PAGE_POW_CND_LEN);
1115         if (res)
1116                 return res;
1117         return nvme_trans_fill_inf_exc_page(ns, hdr, &resp[mode_pages_offset_4],
1118                                         MODE_PAGE_INF_EXC_LEN);
1119 }
1120
1121 static inline int nvme_trans_get_blk_desc_len(u8 dbd, u8 llbaa)
1122 {
1123         if (dbd == MODE_SENSE_BLK_DESC_ENABLED) {
1124                 /* SPC-4: len = 8 x Num_of_descriptors if llbaa = 0, 16x if 1 */
1125                 return 8 * (llbaa + 1) * MODE_SENSE_BLK_DESC_COUNT;
1126         } else {
1127                 return 0;
1128         }
1129 }
1130
1131 static int nvme_trans_mode_page_create(struct nvme_ns *ns,
1132                                         struct sg_io_hdr *hdr, u8 *cmd,
1133                                         u16 alloc_len, u8 cdb10,
1134                                         int (*mode_page_fill_func)
1135                                         (struct nvme_ns *,
1136                                         struct sg_io_hdr *hdr, u8 *, int),
1137                                         u16 mode_pages_tot_len)
1138 {
1139         int res;
1140         int xfer_len;
1141         u8 *response;
1142         u8 dbd, llbaa;
1143         u16 resp_size;
1144         int mph_size;
1145         u16 mode_pages_offset_1;
1146         u16 blk_desc_len, blk_desc_offset, mode_data_length;
1147
1148         dbd = (cmd[1] & MODE_SENSE_DBD_MASK) >> MODE_SENSE_DBD_SHIFT;
1149         llbaa = (cmd[1] & MODE_SENSE_LLBAA_MASK) >> MODE_SENSE_LLBAA_SHIFT;
1150         mph_size = cdb10 ? MODE_SENSE10_MPH_SIZE : MODE_SENSE6_MPH_SIZE;
1151
1152         blk_desc_len = nvme_trans_get_blk_desc_len(dbd, llbaa);
1153
1154         resp_size = mph_size + blk_desc_len + mode_pages_tot_len;
1155         /* Refer spc4r34 Table 440 for calculation of Mode data Length field */
1156         mode_data_length = 3 + (3 * cdb10) + blk_desc_len + mode_pages_tot_len;
1157
1158         blk_desc_offset = mph_size;
1159         mode_pages_offset_1 = blk_desc_offset + blk_desc_len;
1160
1161         response = kzalloc(resp_size, GFP_KERNEL);
1162         if (response == NULL) {
1163                 res = -ENOMEM;
1164                 goto out_mem;
1165         }
1166
1167         res = nvme_trans_fill_mode_parm_hdr(&response[0], mph_size, cdb10,
1168                                         llbaa, mode_data_length, blk_desc_len);
1169         if (res)
1170                 goto out_free;
1171         if (blk_desc_len > 0) {
1172                 res = nvme_trans_fill_blk_desc(ns, hdr,
1173                                                &response[blk_desc_offset],
1174                                                blk_desc_len, llbaa);
1175                 if (res)
1176                         goto out_free;
1177         }
1178         res = mode_page_fill_func(ns, hdr, &response[mode_pages_offset_1],
1179                                         mode_pages_tot_len);
1180         if (res)
1181                 goto out_free;
1182
1183         xfer_len = min(alloc_len, resp_size);
1184         res = nvme_trans_copy_to_user(hdr, response, xfer_len);
1185
1186  out_free:
1187         kfree(response);
1188  out_mem:
1189         return res;
1190 }
1191
1192 /* Read Capacity Helper Functions */
1193
1194 static void nvme_trans_fill_read_cap(u8 *response, struct nvme_id_ns *id_ns,
1195                                                                 u8 cdb16)
1196 {
1197         u8 flbas;
1198         u32 lba_length;
1199         u64 rlba;
1200         u8 prot_en;
1201         u8 p_type_lut[4] = {0, 0, 1, 2};
1202         __be64 tmp_rlba;
1203         __be32 tmp_rlba_32;
1204         __be32 tmp_len;
1205
1206         flbas = (id_ns->flbas) & 0x0F;
1207         lba_length = (1 << (id_ns->lbaf[flbas].ds));
1208         rlba = le64_to_cpup(&id_ns->nsze) - 1;
1209         (id_ns->dps) ? (prot_en = 0x01) : (prot_en = 0);
1210
1211         if (!cdb16) {
1212                 if (rlba > 0xFFFFFFFF)
1213                         rlba = 0xFFFFFFFF;
1214                 tmp_rlba_32 = cpu_to_be32(rlba);
1215                 tmp_len = cpu_to_be32(lba_length);
1216                 memcpy(response, &tmp_rlba_32, sizeof(u32));
1217                 memcpy(&response[4], &tmp_len, sizeof(u32));
1218         } else {
1219                 tmp_rlba = cpu_to_be64(rlba);
1220                 tmp_len = cpu_to_be32(lba_length);
1221                 memcpy(response, &tmp_rlba, sizeof(u64));
1222                 memcpy(&response[8], &tmp_len, sizeof(u32));
1223                 response[12] = (p_type_lut[id_ns->dps & 0x3] << 1) | prot_en;
1224                 /* P_I_Exponent = 0x0 | LBPPBE = 0x0 */
1225                 /* LBPME = 0 | LBPRZ = 0 | LALBA = 0x00 */
1226                 /* Bytes 16-31 - Reserved */
1227         }
1228 }
1229
1230 /* Start Stop Unit Helper Functions */
1231
1232 static int nvme_trans_power_state(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1233                                                 u8 pc, u8 pcmod, u8 start)
1234 {
1235         int res;
1236         int nvme_sc;
1237         struct nvme_id_ctrl *id_ctrl;
1238         int lowest_pow_st;      /* max npss = lowest power consumption */
1239         unsigned ps_desired = 0;
1240
1241         nvme_sc = nvme_identify_ctrl(ns->ctrl, &id_ctrl);
1242         res = nvme_trans_status_code(hdr, nvme_sc);
1243         if (res)
1244                 return res;
1245
1246         lowest_pow_st = max(POWER_STATE_0, (int)(id_ctrl->npss - 1));
1247         kfree(id_ctrl);
1248
1249         switch (pc) {
1250         case NVME_POWER_STATE_START_VALID:
1251                 /* Action unspecified if POWER CONDITION MODIFIER != 0 */
1252                 if (pcmod == 0 && start == 0x1)
1253                         ps_desired = POWER_STATE_0;
1254                 if (pcmod == 0 && start == 0x0)
1255                         ps_desired = lowest_pow_st;
1256                 break;
1257         case NVME_POWER_STATE_ACTIVE:
1258                 /* Action unspecified if POWER CONDITION MODIFIER != 0 */
1259                 if (pcmod == 0)
1260                         ps_desired = POWER_STATE_0;
1261                 break;
1262         case NVME_POWER_STATE_IDLE:
1263                 /* Action unspecified if POWER CONDITION MODIFIER != [0,1,2] */
1264                 if (pcmod == 0x0)
1265                         ps_desired = POWER_STATE_1;
1266                 else if (pcmod == 0x1)
1267                         ps_desired = POWER_STATE_2;
1268                 else if (pcmod == 0x2)
1269                         ps_desired = POWER_STATE_3;
1270                 break;
1271         case NVME_POWER_STATE_STANDBY:
1272                 /* Action unspecified if POWER CONDITION MODIFIER != [0,1] */
1273                 if (pcmod == 0x0)
1274                         ps_desired = max(POWER_STATE_0, (lowest_pow_st - 2));
1275                 else if (pcmod == 0x1)
1276                         ps_desired = max(POWER_STATE_0, (lowest_pow_st - 1));
1277                 break;
1278         case NVME_POWER_STATE_LU_CONTROL:
1279         default:
1280                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1281                                 ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1282                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1283                 break;
1284         }
1285         nvme_sc = nvme_set_features(ns->ctrl, NVME_FEAT_POWER_MGMT, ps_desired, 0,
1286                                     NULL);
1287         return nvme_trans_status_code(hdr, nvme_sc);
1288 }
1289
1290 static int nvme_trans_send_activate_fw_cmd(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1291                                         u8 buffer_id)
1292 {
1293         struct nvme_command c;
1294         int nvme_sc;
1295
1296         memset(&c, 0, sizeof(c));
1297         c.common.opcode = nvme_admin_activate_fw;
1298         c.common.cdw10[0] = cpu_to_le32(buffer_id | NVME_FWACT_REPL_ACTV);
1299
1300         nvme_sc = nvme_submit_sync_cmd(ns->queue, &c, NULL, 0);
1301         return nvme_trans_status_code(hdr, nvme_sc);
1302 }
1303
1304 static int nvme_trans_send_download_fw_cmd(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1305                                         u8 opcode, u32 tot_len, u32 offset,
1306                                         u8 buffer_id)
1307 {
1308         int nvme_sc;
1309         struct nvme_command c;
1310
1311         if (hdr->iovec_count > 0) {
1312                 /* Assuming SGL is not allowed for this command */
1313                 return nvme_trans_completion(hdr,
1314                                         SAM_STAT_CHECK_CONDITION,
1315                                         ILLEGAL_REQUEST,
1316                                         SCSI_ASC_INVALID_CDB,
1317                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1318         }
1319
1320         memset(&c, 0, sizeof(c));
1321         c.common.opcode = nvme_admin_download_fw;
1322         c.dlfw.numd = cpu_to_le32((tot_len/BYTES_TO_DWORDS) - 1);
1323         c.dlfw.offset = cpu_to_le32(offset/BYTES_TO_DWORDS);
1324
1325         nvme_sc = nvme_submit_user_cmd(ns->ctrl->admin_q, &c,
1326                         hdr->dxferp, tot_len, NULL, 0);
1327         return nvme_trans_status_code(hdr, nvme_sc);
1328 }
1329
1330 /* Mode Select Helper Functions */
1331
1332 static inline void nvme_trans_modesel_get_bd_len(u8 *parm_list, u8 cdb10,
1333                                                 u16 *bd_len, u8 *llbaa)
1334 {
1335         if (cdb10) {
1336                 /* 10 Byte CDB */
1337                 *bd_len = (parm_list[MODE_SELECT_10_BD_OFFSET] << 8) +
1338                         parm_list[MODE_SELECT_10_BD_OFFSET + 1];
1339                 *llbaa = parm_list[MODE_SELECT_10_LLBAA_OFFSET] &
1340                                 MODE_SELECT_10_LLBAA_MASK;
1341         } else {
1342                 /* 6 Byte CDB */
1343                 *bd_len = parm_list[MODE_SELECT_6_BD_OFFSET];
1344         }
1345 }
1346
1347 static void nvme_trans_modesel_save_bd(struct nvme_ns *ns, u8 *parm_list,
1348                                         u16 idx, u16 bd_len, u8 llbaa)
1349 {
1350         u16 bd_num;
1351
1352         bd_num = bd_len / ((llbaa == 0) ?
1353                         SHORT_DESC_BLOCK : LONG_DESC_BLOCK);
1354         /* Store block descriptor info if a FORMAT UNIT comes later */
1355         /* TODO Saving 1st BD info; what to do if multiple BD received? */
1356         if (llbaa == 0) {
1357                 /* Standard Block Descriptor - spc4r34 7.5.5.1 */
1358                 ns->mode_select_num_blocks =
1359                                 (parm_list[idx + 1] << 16) +
1360                                 (parm_list[idx + 2] << 8) +
1361                                 (parm_list[idx + 3]);
1362
1363                 ns->mode_select_block_len =
1364                                 (parm_list[idx + 5] << 16) +
1365                                 (parm_list[idx + 6] << 8) +
1366                                 (parm_list[idx + 7]);
1367         } else {
1368                 /* Long LBA Block Descriptor - sbc3r27 6.4.2.3 */
1369                 ns->mode_select_num_blocks =
1370                                 (((u64)parm_list[idx + 0]) << 56) +
1371                                 (((u64)parm_list[idx + 1]) << 48) +
1372                                 (((u64)parm_list[idx + 2]) << 40) +
1373                                 (((u64)parm_list[idx + 3]) << 32) +
1374                                 (((u64)parm_list[idx + 4]) << 24) +
1375                                 (((u64)parm_list[idx + 5]) << 16) +
1376                                 (((u64)parm_list[idx + 6]) << 8) +
1377                                 ((u64)parm_list[idx + 7]);
1378
1379                 ns->mode_select_block_len =
1380                                 (parm_list[idx + 12] << 24) +
1381                                 (parm_list[idx + 13] << 16) +
1382                                 (parm_list[idx + 14] << 8) +
1383                                 (parm_list[idx + 15]);
1384         }
1385 }
1386
1387 static int nvme_trans_modesel_get_mp(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1388                                         u8 *mode_page, u8 page_code)
1389 {
1390         int res = 0;
1391         int nvme_sc;
1392         unsigned dword11;
1393
1394         switch (page_code) {
1395         case MODE_PAGE_CACHING:
1396                 dword11 = ((mode_page[2] & CACHING_MODE_PAGE_WCE_MASK) ? 1 : 0);
1397                 nvme_sc = nvme_set_features(ns->ctrl, NVME_FEAT_VOLATILE_WC,
1398                                             dword11, 0, NULL);
1399                 res = nvme_trans_status_code(hdr, nvme_sc);
1400                 break;
1401         case MODE_PAGE_CONTROL:
1402                 break;
1403         case MODE_PAGE_POWER_CONDITION:
1404                 /* Verify the OS is not trying to set timers */
1405                 if ((mode_page[2] & 0x01) != 0 || (mode_page[3] & 0x0F) != 0) {
1406                         res = nvme_trans_completion(hdr,
1407                                                 SAM_STAT_CHECK_CONDITION,
1408                                                 ILLEGAL_REQUEST,
1409                                                 SCSI_ASC_INVALID_PARAMETER,
1410                                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1411                         break;
1412                 }
1413                 break;
1414         default:
1415                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1416                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1417                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1418                 break;
1419         }
1420
1421         return res;
1422 }
1423
1424 static int nvme_trans_modesel_data(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1425                                         u8 *cmd, u16 parm_list_len, u8 pf,
1426                                         u8 sp, u8 cdb10)
1427 {
1428         int res;
1429         u8 *parm_list;
1430         u16 bd_len;
1431         u8 llbaa = 0;
1432         u16 index, saved_index;
1433         u8 page_code;
1434         u16 mp_size;
1435
1436         /* Get parm list from data-in/out buffer */
1437         parm_list = kmalloc(parm_list_len, GFP_KERNEL);
1438         if (parm_list == NULL) {
1439                 res = -ENOMEM;
1440                 goto out;
1441         }
1442
1443         res = nvme_trans_copy_from_user(hdr, parm_list, parm_list_len);
1444         if (res)
1445                 goto out_mem;
1446
1447         nvme_trans_modesel_get_bd_len(parm_list, cdb10, &bd_len, &llbaa);
1448         index = (cdb10) ? (MODE_SELECT_10_MPH_SIZE) : (MODE_SELECT_6_MPH_SIZE);
1449
1450         if (bd_len != 0) {
1451                 /* Block Descriptors present, parse */
1452                 nvme_trans_modesel_save_bd(ns, parm_list, index, bd_len, llbaa);
1453                 index += bd_len;
1454         }
1455         saved_index = index;
1456
1457         /* Multiple mode pages may be present; iterate through all */
1458         /* In 1st Iteration, don't do NVME Command, only check for CDB errors */
1459         do {
1460                 page_code = parm_list[index] & MODE_SELECT_PAGE_CODE_MASK;
1461                 mp_size = parm_list[index + 1] + 2;
1462                 if ((page_code != MODE_PAGE_CACHING) &&
1463                     (page_code != MODE_PAGE_CONTROL) &&
1464                     (page_code != MODE_PAGE_POWER_CONDITION)) {
1465                         res = nvme_trans_completion(hdr,
1466                                                 SAM_STAT_CHECK_CONDITION,
1467                                                 ILLEGAL_REQUEST,
1468                                                 SCSI_ASC_INVALID_CDB,
1469                                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1470                         goto out_mem;
1471                 }
1472                 index += mp_size;
1473         } while (index < parm_list_len);
1474
1475         /* In 2nd Iteration, do the NVME Commands */
1476         index = saved_index;
1477         do {
1478                 page_code = parm_list[index] & MODE_SELECT_PAGE_CODE_MASK;
1479                 mp_size = parm_list[index + 1] + 2;
1480                 res = nvme_trans_modesel_get_mp(ns, hdr, &parm_list[index],
1481                                                                 page_code);
1482                 if (res)
1483                         break;
1484                 index += mp_size;
1485         } while (index < parm_list_len);
1486
1487  out_mem:
1488         kfree(parm_list);
1489  out:
1490         return res;
1491 }
1492
1493 /* Format Unit Helper Functions */
1494
1495 static int nvme_trans_fmt_set_blk_size_count(struct nvme_ns *ns,
1496                                              struct sg_io_hdr *hdr)
1497 {
1498         int res = 0;
1499         int nvme_sc;
1500         u8 flbas;
1501
1502         /*
1503          * SCSI Expects a MODE SELECT would have been issued prior to
1504          * a FORMAT UNIT, and the block size and number would be used
1505          * from the block descriptor in it. If a MODE SELECT had not
1506          * been issued, FORMAT shall use the current values for both.
1507          */
1508
1509         if (ns->mode_select_num_blocks == 0 || ns->mode_select_block_len == 0) {
1510                 struct nvme_id_ns *id_ns;
1511
1512                 nvme_sc = nvme_identify_ns(ns->ctrl, ns->ns_id, &id_ns);
1513                 res = nvme_trans_status_code(hdr, nvme_sc);
1514                 if (res)
1515                         return res;
1516
1517                 if (ns->mode_select_num_blocks == 0)
1518                         ns->mode_select_num_blocks = le64_to_cpu(id_ns->ncap);
1519                 if (ns->mode_select_block_len == 0) {
1520                         flbas = (id_ns->flbas) & 0x0F;
1521                         ns->mode_select_block_len =
1522                                                 (1 << (id_ns->lbaf[flbas].ds));
1523                 }
1524
1525                 kfree(id_ns);
1526         }
1527
1528         return 0;
1529 }
1530
1531 static int nvme_trans_fmt_get_parm_header(struct sg_io_hdr *hdr, u8 len,
1532                                         u8 format_prot_info, u8 *nvme_pf_code)
1533 {
1534         int res;
1535         u8 *parm_list;
1536         u8 pf_usage, pf_code;
1537
1538         parm_list = kmalloc(len, GFP_KERNEL);
1539         if (parm_list == NULL) {
1540                 res = -ENOMEM;
1541                 goto out;
1542         }
1543         res = nvme_trans_copy_from_user(hdr, parm_list, len);
1544         if (res)
1545                 goto out_mem;
1546
1547         if ((parm_list[FORMAT_UNIT_IMMED_OFFSET] &
1548                                 FORMAT_UNIT_IMMED_MASK) != 0) {
1549                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1550                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1551                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1552                 goto out_mem;
1553         }
1554
1555         if (len == FORMAT_UNIT_LONG_PARM_LIST_LEN &&
1556             (parm_list[FORMAT_UNIT_PROT_INT_OFFSET] & 0x0F) != 0) {
1557                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1558                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1559                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1560                 goto out_mem;
1561         }
1562         pf_usage = parm_list[FORMAT_UNIT_PROT_FIELD_USAGE_OFFSET] &
1563                         FORMAT_UNIT_PROT_FIELD_USAGE_MASK;
1564         pf_code = (pf_usage << 2) | format_prot_info;
1565         switch (pf_code) {
1566         case 0:
1567                 *nvme_pf_code = 0;
1568                 break;
1569         case 2:
1570                 *nvme_pf_code = 1;
1571                 break;
1572         case 3:
1573                 *nvme_pf_code = 2;
1574                 break;
1575         case 7:
1576                 *nvme_pf_code = 3;
1577                 break;
1578         default:
1579                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1580                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1581                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1582                 break;
1583         }
1584
1585  out_mem:
1586         kfree(parm_list);
1587  out:
1588         return res;
1589 }
1590
1591 static int nvme_trans_fmt_send_cmd(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1592                                    u8 prot_info)
1593 {
1594         int res;
1595         int nvme_sc;
1596         struct nvme_id_ns *id_ns;
1597         u8 i;
1598         u8 flbas, nlbaf;
1599         u8 selected_lbaf = 0xFF;
1600         u32 cdw10 = 0;
1601         struct nvme_command c;
1602
1603         /* Loop thru LBAF's in id_ns to match reqd lbaf, put in cdw10 */
1604         nvme_sc = nvme_identify_ns(ns->ctrl, ns->ns_id, &id_ns);
1605         res = nvme_trans_status_code(hdr, nvme_sc);
1606         if (res)
1607                 return res;
1608
1609         flbas = (id_ns->flbas) & 0x0F;
1610         nlbaf = id_ns->nlbaf;
1611
1612         for (i = 0; i < nlbaf; i++) {
1613                 if (ns->mode_select_block_len == (1 << (id_ns->lbaf[i].ds))) {
1614                         selected_lbaf = i;
1615                         break;
1616                 }
1617         }
1618         if (selected_lbaf > 0x0F) {
1619                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1620                                 ILLEGAL_REQUEST, SCSI_ASC_INVALID_PARAMETER,
1621                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1622         }
1623         if (ns->mode_select_num_blocks != le64_to_cpu(id_ns->ncap)) {
1624                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1625                                 ILLEGAL_REQUEST, SCSI_ASC_INVALID_PARAMETER,
1626                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1627         }
1628
1629         cdw10 |= prot_info << 5;
1630         cdw10 |= selected_lbaf & 0x0F;
1631         memset(&c, 0, sizeof(c));
1632         c.format.opcode = nvme_admin_format_nvm;
1633         c.format.nsid = cpu_to_le32(ns->ns_id);
1634         c.format.cdw10 = cpu_to_le32(cdw10);
1635
1636         nvme_sc = nvme_submit_sync_cmd(ns->ctrl->admin_q, &c, NULL, 0);
1637         res = nvme_trans_status_code(hdr, nvme_sc);
1638
1639         kfree(id_ns);
1640         return res;
1641 }
1642
1643 static inline u32 nvme_trans_io_get_num_cmds(struct sg_io_hdr *hdr,
1644                                         struct nvme_trans_io_cdb *cdb_info,
1645                                         u32 max_blocks)
1646 {
1647         /* If using iovecs, send one nvme command per vector */
1648         if (hdr->iovec_count > 0)
1649                 return hdr->iovec_count;
1650         else if (cdb_info->xfer_len > max_blocks)
1651                 return ((cdb_info->xfer_len - 1) / max_blocks) + 1;
1652         else
1653                 return 1;
1654 }
1655
1656 static u16 nvme_trans_io_get_control(struct nvme_ns *ns,
1657                                         struct nvme_trans_io_cdb *cdb_info)
1658 {
1659         u16 control = 0;
1660
1661         /* When Protection information support is added, implement here */
1662
1663         if (cdb_info->fua > 0)
1664                 control |= NVME_RW_FUA;
1665
1666         return control;
1667 }
1668
1669 static int nvme_trans_do_nvme_io(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1670                                 struct nvme_trans_io_cdb *cdb_info, u8 is_write)
1671 {
1672         int nvme_sc = NVME_SC_SUCCESS;
1673         u32 num_cmds;
1674         u64 unit_len;
1675         u64 unit_num_blocks;    /* Number of blocks to xfer in each nvme cmd */
1676         u32 retcode;
1677         u32 i = 0;
1678         u64 nvme_offset = 0;
1679         void __user *next_mapping_addr;
1680         struct nvme_command c;
1681         u8 opcode = (is_write ? nvme_cmd_write : nvme_cmd_read);
1682         u16 control;
1683         u32 max_blocks = queue_max_hw_sectors(ns->queue);
1684
1685         num_cmds = nvme_trans_io_get_num_cmds(hdr, cdb_info, max_blocks);
1686
1687         /*
1688          * This loop handles two cases.
1689          * First, when an SGL is used in the form of an iovec list:
1690          *   - Use iov_base as the next mapping address for the nvme command_id
1691          *   - Use iov_len as the data transfer length for the command.
1692          * Second, when we have a single buffer
1693          *   - If larger than max_blocks, split into chunks, offset
1694          *        each nvme command accordingly.
1695          */
1696         for (i = 0; i < num_cmds; i++) {
1697                 memset(&c, 0, sizeof(c));
1698                 if (hdr->iovec_count > 0) {
1699                         struct sg_iovec sgl;
1700
1701                         retcode = copy_from_user(&sgl, hdr->dxferp +
1702                                         i * sizeof(struct sg_iovec),
1703                                         sizeof(struct sg_iovec));
1704                         if (retcode)
1705                                 return -EFAULT;
1706                         unit_len = sgl.iov_len;
1707                         unit_num_blocks = unit_len >> ns->lba_shift;
1708                         next_mapping_addr = sgl.iov_base;
1709                 } else {
1710                         unit_num_blocks = min((u64)max_blocks,
1711                                         (cdb_info->xfer_len - nvme_offset));
1712                         unit_len = unit_num_blocks << ns->lba_shift;
1713                         next_mapping_addr = hdr->dxferp +
1714                                         ((1 << ns->lba_shift) * nvme_offset);
1715                 }
1716
1717                 c.rw.opcode = opcode;
1718                 c.rw.nsid = cpu_to_le32(ns->ns_id);
1719                 c.rw.slba = cpu_to_le64(cdb_info->lba + nvme_offset);
1720                 c.rw.length = cpu_to_le16(unit_num_blocks - 1);
1721                 control = nvme_trans_io_get_control(ns, cdb_info);
1722                 c.rw.control = cpu_to_le16(control);
1723
1724                 if (get_capacity(ns->disk) - unit_num_blocks <
1725                                 cdb_info->lba + nvme_offset) {
1726                         nvme_sc = NVME_SC_LBA_RANGE;
1727                         break;
1728                 }
1729                 nvme_sc = nvme_submit_user_cmd(ns->queue, &c,
1730                                 next_mapping_addr, unit_len, NULL, 0);
1731                 if (nvme_sc)
1732                         break;
1733
1734                 nvme_offset += unit_num_blocks;
1735         }
1736
1737         return nvme_trans_status_code(hdr, nvme_sc);
1738 }
1739
1740
1741 /* SCSI Command Translation Functions */
1742
1743 static int nvme_trans_io(struct nvme_ns *ns, struct sg_io_hdr *hdr, u8 is_write,
1744                                                         u8 *cmd)
1745 {
1746         int res = 0;
1747         struct nvme_trans_io_cdb cdb_info = { 0, };
1748         u8 opcode = cmd[0];
1749         u64 xfer_bytes;
1750         u64 sum_iov_len = 0;
1751         struct sg_iovec sgl;
1752         int i;
1753         size_t not_copied;
1754
1755         /*
1756          * The FUA and WPROTECT fields are not supported in 6-byte CDBs,
1757          * but always in the same place for all others.
1758          */
1759         switch (opcode) {
1760         case WRITE_6:
1761         case READ_6:
1762                 break;
1763         default:
1764                 cdb_info.fua = cmd[1] & 0x8;
1765                 cdb_info.prot_info = (cmd[1] & 0xe0) >> 5;
1766                 if (cdb_info.prot_info && !ns->pi_type) {
1767                         return nvme_trans_completion(hdr,
1768                                         SAM_STAT_CHECK_CONDITION,
1769                                         ILLEGAL_REQUEST,
1770                                         SCSI_ASC_INVALID_CDB,
1771                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1772                 }
1773         }
1774
1775         switch (opcode) {
1776         case WRITE_6:
1777         case READ_6:
1778                 cdb_info.lba = get_unaligned_be24(&cmd[1]);
1779                 cdb_info.xfer_len = cmd[4];
1780                 if (cdb_info.xfer_len == 0)
1781                         cdb_info.xfer_len = 256;
1782                 break;
1783         case WRITE_10:
1784         case READ_10:
1785                 cdb_info.lba = get_unaligned_be32(&cmd[2]);
1786                 cdb_info.xfer_len = get_unaligned_be16(&cmd[7]);
1787                 break;
1788         case WRITE_12:
1789         case READ_12:
1790                 cdb_info.lba = get_unaligned_be32(&cmd[2]);
1791                 cdb_info.xfer_len = get_unaligned_be32(&cmd[6]);
1792                 break;
1793         case WRITE_16:
1794         case READ_16:
1795                 cdb_info.lba = get_unaligned_be64(&cmd[2]);
1796                 cdb_info.xfer_len = get_unaligned_be32(&cmd[10]);
1797                 break;
1798         default:
1799                 /* Will never really reach here */
1800                 res = -EIO;
1801                 goto out;
1802         }
1803
1804         /* Calculate total length of transfer (in bytes) */
1805         if (hdr->iovec_count > 0) {
1806                 for (i = 0; i < hdr->iovec_count; i++) {
1807                         not_copied = copy_from_user(&sgl, hdr->dxferp +
1808                                                 i * sizeof(struct sg_iovec),
1809                                                 sizeof(struct sg_iovec));
1810                         if (not_copied)
1811                                 return -EFAULT;
1812                         sum_iov_len += sgl.iov_len;
1813                         /* IO vector sizes should be multiples of block size */
1814                         if (sgl.iov_len % (1 << ns->lba_shift) != 0) {
1815                                 res = nvme_trans_completion(hdr,
1816                                                 SAM_STAT_CHECK_CONDITION,
1817                                                 ILLEGAL_REQUEST,
1818                                                 SCSI_ASC_INVALID_PARAMETER,
1819                                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1820                                 goto out;
1821                         }
1822                 }
1823         } else {
1824                 sum_iov_len = hdr->dxfer_len;
1825         }
1826
1827         /* As Per sg ioctl howto, if the lengths differ, use the lower one */
1828         xfer_bytes = min(((u64)hdr->dxfer_len), sum_iov_len);
1829
1830         /* If block count and actual data buffer size dont match, error out */
1831         if (xfer_bytes != (cdb_info.xfer_len << ns->lba_shift)) {
1832                 res = -EINVAL;
1833                 goto out;
1834         }
1835
1836         /* Check for 0 length transfer - it is not illegal */
1837         if (cdb_info.xfer_len == 0)
1838                 goto out;
1839
1840         /* Send NVMe IO Command(s) */
1841         res = nvme_trans_do_nvme_io(ns, hdr, &cdb_info, is_write);
1842         if (res)
1843                 goto out;
1844
1845  out:
1846         return res;
1847 }
1848
1849 static int nvme_trans_inquiry(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1850                                                         u8 *cmd)
1851 {
1852         int res = 0;
1853         u8 evpd;
1854         u8 page_code;
1855         int alloc_len;
1856         u8 *inq_response;
1857
1858         evpd = cmd[1] & 0x01;
1859         page_code = cmd[2];
1860         alloc_len = get_unaligned_be16(&cmd[3]);
1861
1862         inq_response = kmalloc(max(alloc_len, STANDARD_INQUIRY_LENGTH),
1863                                 GFP_KERNEL);
1864         if (inq_response == NULL) {
1865                 res = -ENOMEM;
1866                 goto out_mem;
1867         }
1868
1869         if (evpd == 0) {
1870                 if (page_code == INQ_STANDARD_INQUIRY_PAGE) {
1871                         res = nvme_trans_standard_inquiry_page(ns, hdr,
1872                                                 inq_response, alloc_len);
1873                 } else {
1874                         res = nvme_trans_completion(hdr,
1875                                                 SAM_STAT_CHECK_CONDITION,
1876                                                 ILLEGAL_REQUEST,
1877                                                 SCSI_ASC_INVALID_CDB,
1878                                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1879                 }
1880         } else {
1881                 switch (page_code) {
1882                 case VPD_SUPPORTED_PAGES:
1883                         res = nvme_trans_supported_vpd_pages(ns, hdr,
1884                                                 inq_response, alloc_len);
1885                         break;
1886                 case VPD_SERIAL_NUMBER:
1887                         res = nvme_trans_unit_serial_page(ns, hdr, inq_response,
1888                                                                 alloc_len);
1889                         break;
1890                 case VPD_DEVICE_IDENTIFIERS:
1891                         res = nvme_trans_device_id_page(ns, hdr, inq_response,
1892                                                                 alloc_len);
1893                         break;
1894                 case VPD_EXTENDED_INQUIRY:
1895                         res = nvme_trans_ext_inq_page(ns, hdr, alloc_len);
1896                         break;
1897                 case VPD_BLOCK_LIMITS:
1898                         res = nvme_trans_bdev_limits_page(ns, hdr, inq_response,
1899                                                                 alloc_len);
1900                         break;
1901                 case VPD_BLOCK_DEV_CHARACTERISTICS:
1902                         res = nvme_trans_bdev_char_page(ns, hdr, alloc_len);
1903                         break;
1904                 default:
1905                         res = nvme_trans_completion(hdr,
1906                                                 SAM_STAT_CHECK_CONDITION,
1907                                                 ILLEGAL_REQUEST,
1908                                                 SCSI_ASC_INVALID_CDB,
1909                                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1910                         break;
1911                 }
1912         }
1913         kfree(inq_response);
1914  out_mem:
1915         return res;
1916 }
1917
1918 static int nvme_trans_log_sense(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1919                                                         u8 *cmd)
1920 {
1921         int res;
1922         u16 alloc_len;
1923         u8 pc;
1924         u8 page_code;
1925
1926         if (cmd[1] != LOG_SENSE_CDB_SP_NOT_ENABLED) {
1927                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1928                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1929                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1930                 goto out;
1931         }
1932
1933         page_code = cmd[2] & LOG_SENSE_CDB_PAGE_CODE_MASK;
1934         pc = (cmd[2] & LOG_SENSE_CDB_PC_MASK) >> LOG_SENSE_CDB_PC_SHIFT;
1935         if (pc != LOG_SENSE_CDB_PC_CUMULATIVE_VALUES) {
1936                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1937                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1938                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1939                 goto out;
1940         }
1941         alloc_len = get_unaligned_be16(&cmd[7]);
1942         switch (page_code) {
1943         case LOG_PAGE_SUPPORTED_LOG_PAGES_PAGE:
1944                 res = nvme_trans_log_supp_pages(ns, hdr, alloc_len);
1945                 break;
1946         case LOG_PAGE_INFORMATIONAL_EXCEPTIONS_PAGE:
1947                 res = nvme_trans_log_info_exceptions(ns, hdr, alloc_len);
1948                 break;
1949         case LOG_PAGE_TEMPERATURE_PAGE:
1950                 res = nvme_trans_log_temperature(ns, hdr, alloc_len);
1951                 break;
1952         default:
1953                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
1954                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
1955                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
1956                 break;
1957         }
1958
1959  out:
1960         return res;
1961 }
1962
1963 static int nvme_trans_mode_select(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1964                                                         u8 *cmd)
1965 {
1966         u8 cdb10 = 0;
1967         u16 parm_list_len;
1968         u8 page_format;
1969         u8 save_pages;
1970
1971         page_format = cmd[1] & MODE_SELECT_CDB_PAGE_FORMAT_MASK;
1972         save_pages = cmd[1] & MODE_SELECT_CDB_SAVE_PAGES_MASK;
1973
1974         if (cmd[0] == MODE_SELECT) {
1975                 parm_list_len = cmd[4];
1976         } else {
1977                 parm_list_len = cmd[7];
1978                 cdb10 = 1;
1979         }
1980
1981         if (parm_list_len != 0) {
1982                 /*
1983                  * According to SPC-4 r24, a paramter list length field of 0
1984                  * shall not be considered an error
1985                  */
1986                 return nvme_trans_modesel_data(ns, hdr, cmd, parm_list_len,
1987                                                 page_format, save_pages, cdb10);
1988         }
1989
1990         return 0;
1991 }
1992
1993 static int nvme_trans_mode_sense(struct nvme_ns *ns, struct sg_io_hdr *hdr,
1994                                                         u8 *cmd)
1995 {
1996         int res = 0;
1997         u16 alloc_len;
1998         u8 cdb10 = 0;
1999
2000         if (cmd[0] == MODE_SENSE) {
2001                 alloc_len = cmd[4];
2002         } else {
2003                 alloc_len = get_unaligned_be16(&cmd[7]);
2004                 cdb10 = 1;
2005         }
2006
2007         if ((cmd[2] & MODE_SENSE_PAGE_CONTROL_MASK) !=
2008                         MODE_SENSE_PC_CURRENT_VALUES) {
2009                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2010                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2011                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2012                 goto out;
2013         }
2014
2015         switch (cmd[2] & MODE_SENSE_PAGE_CODE_MASK) {
2016         case MODE_PAGE_CACHING:
2017                 res = nvme_trans_mode_page_create(ns, hdr, cmd, alloc_len,
2018                                                 cdb10,
2019                                                 &nvme_trans_fill_caching_page,
2020                                                 MODE_PAGE_CACHING_LEN);
2021                 break;
2022         case MODE_PAGE_CONTROL:
2023                 res = nvme_trans_mode_page_create(ns, hdr, cmd, alloc_len,
2024                                                 cdb10,
2025                                                 &nvme_trans_fill_control_page,
2026                                                 MODE_PAGE_CONTROL_LEN);
2027                 break;
2028         case MODE_PAGE_POWER_CONDITION:
2029                 res = nvme_trans_mode_page_create(ns, hdr, cmd, alloc_len,
2030                                                 cdb10,
2031                                                 &nvme_trans_fill_pow_cnd_page,
2032                                                 MODE_PAGE_POW_CND_LEN);
2033                 break;
2034         case MODE_PAGE_INFO_EXCEP:
2035                 res = nvme_trans_mode_page_create(ns, hdr, cmd, alloc_len,
2036                                                 cdb10,
2037                                                 &nvme_trans_fill_inf_exc_page,
2038                                                 MODE_PAGE_INF_EXC_LEN);
2039                 break;
2040         case MODE_PAGE_RETURN_ALL:
2041                 res = nvme_trans_mode_page_create(ns, hdr, cmd, alloc_len,
2042                                                 cdb10,
2043                                                 &nvme_trans_fill_all_pages,
2044                                                 MODE_PAGE_ALL_LEN);
2045                 break;
2046         default:
2047                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2048                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2049                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2050                 break;
2051         }
2052
2053  out:
2054         return res;
2055 }
2056
2057 static int nvme_trans_read_capacity(struct nvme_ns *ns, struct sg_io_hdr *hdr,
2058                                                         u8 *cmd, u8 cdb16)
2059 {
2060         int res;
2061         int nvme_sc;
2062         u32 alloc_len;
2063         u32 resp_size;
2064         u32 xfer_len;
2065         struct nvme_id_ns *id_ns;
2066         u8 *response;
2067
2068         if (cdb16) {
2069                 alloc_len = get_unaligned_be32(&cmd[10]);
2070                 resp_size = READ_CAP_16_RESP_SIZE;
2071         } else {
2072                 alloc_len = READ_CAP_10_RESP_SIZE;
2073                 resp_size = READ_CAP_10_RESP_SIZE;
2074         }
2075
2076         nvme_sc = nvme_identify_ns(ns->ctrl, ns->ns_id, &id_ns);
2077         res = nvme_trans_status_code(hdr, nvme_sc);
2078         if (res)
2079                 return res;     
2080
2081         response = kzalloc(resp_size, GFP_KERNEL);
2082         if (response == NULL) {
2083                 res = -ENOMEM;
2084                 goto out_free_id;
2085         }
2086         nvme_trans_fill_read_cap(response, id_ns, cdb16);
2087
2088         xfer_len = min(alloc_len, resp_size);
2089         res = nvme_trans_copy_to_user(hdr, response, xfer_len);
2090
2091         kfree(response);
2092  out_free_id:
2093         kfree(id_ns);
2094         return res;
2095 }
2096
2097 static int nvme_trans_report_luns(struct nvme_ns *ns, struct sg_io_hdr *hdr,
2098                                                         u8 *cmd)
2099 {
2100         int res;
2101         int nvme_sc;
2102         u32 alloc_len, xfer_len, resp_size;
2103         u8 *response;
2104         struct nvme_id_ctrl *id_ctrl;
2105         u32 ll_length, lun_id;
2106         u8 lun_id_offset = REPORT_LUNS_FIRST_LUN_OFFSET;
2107         __be32 tmp_len;
2108
2109         switch (cmd[2]) {
2110         default:
2111                 return nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2112                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2113                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2114         case ALL_LUNS_RETURNED:
2115         case ALL_WELL_KNOWN_LUNS_RETURNED:
2116         case RESTRICTED_LUNS_RETURNED:
2117                 nvme_sc = nvme_identify_ctrl(ns->ctrl, &id_ctrl);
2118                 res = nvme_trans_status_code(hdr, nvme_sc);
2119                 if (res)
2120                         return res;
2121
2122                 ll_length = le32_to_cpu(id_ctrl->nn) * LUN_ENTRY_SIZE;
2123                 resp_size = ll_length + LUN_DATA_HEADER_SIZE;
2124
2125                 alloc_len = get_unaligned_be32(&cmd[6]);
2126                 if (alloc_len < resp_size) {
2127                         res = nvme_trans_completion(hdr,
2128                                         SAM_STAT_CHECK_CONDITION,
2129                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2130                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2131                         goto out_free_id;
2132                 }
2133
2134                 response = kzalloc(resp_size, GFP_KERNEL);
2135                 if (response == NULL) {
2136                         res = -ENOMEM;
2137                         goto out_free_id;
2138                 }
2139
2140                 /* The first LUN ID will always be 0 per the SAM spec */
2141                 for (lun_id = 0; lun_id < le32_to_cpu(id_ctrl->nn); lun_id++) {
2142                         /*
2143                          * Set the LUN Id and then increment to the next LUN
2144                          * location in the parameter data.
2145                          */
2146                         __be64 tmp_id = cpu_to_be64(lun_id);
2147                         memcpy(&response[lun_id_offset], &tmp_id, sizeof(u64));
2148                         lun_id_offset += LUN_ENTRY_SIZE;
2149                 }
2150                 tmp_len = cpu_to_be32(ll_length);
2151                 memcpy(response, &tmp_len, sizeof(u32));
2152         }
2153
2154         xfer_len = min(alloc_len, resp_size);
2155         res = nvme_trans_copy_to_user(hdr, response, xfer_len);
2156
2157         kfree(response);
2158  out_free_id:
2159         kfree(id_ctrl);
2160         return res;
2161 }
2162
2163 static int nvme_trans_request_sense(struct nvme_ns *ns, struct sg_io_hdr *hdr,
2164                                                         u8 *cmd)
2165 {
2166         int res;
2167         u8 alloc_len, xfer_len, resp_size;
2168         u8 desc_format;
2169         u8 *response;
2170
2171         desc_format = cmd[1] & 0x01;
2172         alloc_len = cmd[4];
2173
2174         resp_size = ((desc_format) ? (DESC_FMT_SENSE_DATA_SIZE) :
2175                                         (FIXED_FMT_SENSE_DATA_SIZE));
2176         response = kzalloc(resp_size, GFP_KERNEL);
2177         if (response == NULL) {
2178                 res = -ENOMEM;
2179                 goto out;
2180         }
2181
2182         if (desc_format) {
2183                 /* Descriptor Format Sense Data */
2184                 response[0] = DESC_FORMAT_SENSE_DATA;
2185                 response[1] = NO_SENSE;
2186                 /* TODO How is LOW POWER CONDITION ON handled? (byte 2) */
2187                 response[2] = SCSI_ASC_NO_SENSE;
2188                 response[3] = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
2189                 /* SDAT_OVFL = 0 | Additional Sense Length = 0 */
2190         } else {
2191                 /* Fixed Format Sense Data */
2192                 response[0] = FIXED_SENSE_DATA;
2193                 /* Byte 1 = Obsolete */
2194                 response[2] = NO_SENSE; /* FM, EOM, ILI, SDAT_OVFL = 0 */
2195                 /* Bytes 3-6 - Information - set to zero */
2196                 response[7] = FIXED_SENSE_DATA_ADD_LENGTH;
2197                 /* Bytes 8-11 - Cmd Specific Information - set to zero */
2198                 response[12] = SCSI_ASC_NO_SENSE;
2199                 response[13] = SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
2200                 /* Byte 14 = Field Replaceable Unit Code = 0 */
2201                 /* Bytes 15-17 - SKSV=0; Sense Key Specific = 0 */
2202         }
2203
2204         xfer_len = min(alloc_len, resp_size);
2205         res = nvme_trans_copy_to_user(hdr, response, xfer_len);
2206
2207         kfree(response);
2208  out:
2209         return res;
2210 }
2211
2212 static int nvme_trans_security_protocol(struct nvme_ns *ns,
2213                                         struct sg_io_hdr *hdr,
2214                                         u8 *cmd)
2215 {
2216         return nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2217                                 ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_COMMAND,
2218                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2219 }
2220
2221 static int nvme_trans_synchronize_cache(struct nvme_ns *ns,
2222                                         struct sg_io_hdr *hdr)
2223 {
2224         int nvme_sc;
2225         struct nvme_command c;
2226
2227         memset(&c, 0, sizeof(c));
2228         c.common.opcode = nvme_cmd_flush;
2229         c.common.nsid = cpu_to_le32(ns->ns_id);
2230
2231         nvme_sc = nvme_submit_sync_cmd(ns->queue, &c, NULL, 0);
2232         return nvme_trans_status_code(hdr, nvme_sc);
2233 }
2234
2235 static int nvme_trans_start_stop(struct nvme_ns *ns, struct sg_io_hdr *hdr,
2236                                                         u8 *cmd)
2237 {
2238         u8 immed, pcmod, pc, no_flush, start;
2239
2240         immed = cmd[1] & 0x01;
2241         pcmod = cmd[3] & 0x0f;
2242         pc = (cmd[4] & 0xf0) >> 4;
2243         no_flush = cmd[4] & 0x04;
2244         start = cmd[4] & 0x01;
2245
2246         if (immed != 0) {
2247                 return nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2248                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2249                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2250         } else {
2251                 if (no_flush == 0) {
2252                         /* Issue NVME FLUSH command prior to START STOP UNIT */
2253                         int res = nvme_trans_synchronize_cache(ns, hdr);
2254                         if (res)
2255                                 return res;
2256                 }
2257                 /* Setup the expected power state transition */
2258                 return nvme_trans_power_state(ns, hdr, pc, pcmod, start);
2259         }
2260 }
2261
2262 static int nvme_trans_format_unit(struct nvme_ns *ns, struct sg_io_hdr *hdr,
2263                                                         u8 *cmd)
2264 {
2265         int res;
2266         u8 parm_hdr_len = 0;
2267         u8 nvme_pf_code = 0;
2268         u8 format_prot_info, long_list, format_data;
2269
2270         format_prot_info = (cmd[1] & 0xc0) >> 6;
2271         long_list = cmd[1] & 0x20;
2272         format_data = cmd[1] & 0x10;
2273
2274         if (format_data != 0) {
2275                 if (format_prot_info != 0) {
2276                         if (long_list == 0)
2277                                 parm_hdr_len = FORMAT_UNIT_SHORT_PARM_LIST_LEN;
2278                         else
2279                                 parm_hdr_len = FORMAT_UNIT_LONG_PARM_LIST_LEN;
2280                 }
2281         } else if (format_data == 0 && format_prot_info != 0) {
2282                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2283                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2284                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2285                 goto out;
2286         }
2287
2288         /* Get parm header from data-in/out buffer */
2289         /*
2290          * According to the translation spec, the only fields in the parameter
2291          * list we are concerned with are in the header. So allocate only that.
2292          */
2293         if (parm_hdr_len > 0) {
2294                 res = nvme_trans_fmt_get_parm_header(hdr, parm_hdr_len,
2295                                         format_prot_info, &nvme_pf_code);
2296                 if (res)
2297                         goto out;
2298         }
2299
2300         /* Attempt to activate any previously downloaded firmware image */
2301         res = nvme_trans_send_activate_fw_cmd(ns, hdr, 0);
2302
2303         /* Determine Block size and count and send format command */
2304         res = nvme_trans_fmt_set_blk_size_count(ns, hdr);
2305         if (res)
2306                 goto out;
2307
2308         res = nvme_trans_fmt_send_cmd(ns, hdr, nvme_pf_code);
2309
2310  out:
2311         return res;
2312 }
2313
2314 static int nvme_trans_test_unit_ready(struct nvme_ns *ns,
2315                                         struct sg_io_hdr *hdr,
2316                                         u8 *cmd)
2317 {
2318         if (nvme_ctrl_ready(ns->ctrl))
2319                 return nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2320                                             NOT_READY, SCSI_ASC_LUN_NOT_READY,
2321                                             SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2322         else
2323                 return nvme_trans_completion(hdr, SAM_STAT_GOOD, NO_SENSE, 0, 0);
2324 }
2325
2326 static int nvme_trans_write_buffer(struct nvme_ns *ns, struct sg_io_hdr *hdr,
2327                                                         u8 *cmd)
2328 {
2329         int res = 0;
2330         u32 buffer_offset, parm_list_length;
2331         u8 buffer_id, mode;
2332
2333         parm_list_length = get_unaligned_be24(&cmd[6]);
2334         if (parm_list_length % BYTES_TO_DWORDS != 0) {
2335                 /* NVMe expects Firmware file to be a whole number of DWORDS */
2336                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2337                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2338                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2339                 goto out;
2340         }
2341         buffer_id = cmd[2];
2342         if (buffer_id > NVME_MAX_FIRMWARE_SLOT) {
2343                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2344                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2345                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2346                 goto out;
2347         }
2348         mode = cmd[1] & 0x1f;
2349         buffer_offset = get_unaligned_be24(&cmd[3]);
2350
2351         switch (mode) {
2352         case DOWNLOAD_SAVE_ACTIVATE:
2353                 res = nvme_trans_send_download_fw_cmd(ns, hdr, nvme_admin_download_fw,
2354                                                 parm_list_length, buffer_offset,
2355                                                 buffer_id);
2356                 if (res)
2357                         goto out;
2358                 res = nvme_trans_send_activate_fw_cmd(ns, hdr, buffer_id);
2359                 break;
2360         case DOWNLOAD_SAVE_DEFER_ACTIVATE:
2361                 res = nvme_trans_send_download_fw_cmd(ns, hdr, nvme_admin_download_fw,
2362                                                 parm_list_length, buffer_offset,
2363                                                 buffer_id);
2364                 break;
2365         case ACTIVATE_DEFERRED_MICROCODE:
2366                 res = nvme_trans_send_activate_fw_cmd(ns, hdr, buffer_id);
2367                 break;
2368         default:
2369                 res = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2370                                         ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB,
2371                                         SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2372                 break;
2373         }
2374
2375  out:
2376         return res;
2377 }
2378
2379 struct scsi_unmap_blk_desc {
2380         __be64  slba;
2381         __be32  nlb;
2382         u32     resv;
2383 };
2384
2385 struct scsi_unmap_parm_list {
2386         __be16  unmap_data_len;
2387         __be16  unmap_blk_desc_data_len;
2388         u32     resv;
2389         struct scsi_unmap_blk_desc desc[0];
2390 };
2391
2392 static int nvme_trans_unmap(struct nvme_ns *ns, struct sg_io_hdr *hdr,
2393                                                         u8 *cmd)
2394 {
2395         struct scsi_unmap_parm_list *plist;
2396         struct nvme_dsm_range *range;
2397         struct nvme_command c;
2398         int i, nvme_sc, res;
2399         u16 ndesc, list_len;
2400
2401         list_len = get_unaligned_be16(&cmd[7]);
2402         if (!list_len)
2403                 return -EINVAL;
2404
2405         plist = kmalloc(list_len, GFP_KERNEL);
2406         if (!plist)
2407                 return -ENOMEM;
2408
2409         res = nvme_trans_copy_from_user(hdr, plist, list_len);
2410         if (res)
2411                 goto out;
2412
2413         ndesc = be16_to_cpu(plist->unmap_blk_desc_data_len) >> 4;
2414         if (!ndesc || ndesc > 256) {
2415                 res = -EINVAL;
2416                 goto out;
2417         }
2418
2419         range = kcalloc(ndesc, sizeof(*range), GFP_KERNEL);
2420         if (!range) {
2421                 res = -ENOMEM;
2422                 goto out;
2423         }
2424
2425         for (i = 0; i < ndesc; i++) {
2426                 range[i].nlb = cpu_to_le32(be32_to_cpu(plist->desc[i].nlb));
2427                 range[i].slba = cpu_to_le64(be64_to_cpu(plist->desc[i].slba));
2428                 range[i].cattr = 0;
2429         }
2430
2431         memset(&c, 0, sizeof(c));
2432         c.dsm.opcode = nvme_cmd_dsm;
2433         c.dsm.nsid = cpu_to_le32(ns->ns_id);
2434         c.dsm.nr = cpu_to_le32(ndesc - 1);
2435         c.dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
2436
2437         nvme_sc = nvme_submit_sync_cmd(ns->queue, &c, range,
2438                         ndesc * sizeof(*range));
2439         res = nvme_trans_status_code(hdr, nvme_sc);
2440
2441         kfree(range);
2442  out:
2443         kfree(plist);
2444         return res;
2445 }
2446
2447 static int nvme_scsi_translate(struct nvme_ns *ns, struct sg_io_hdr *hdr)
2448 {
2449         u8 cmd[BLK_MAX_CDB];
2450         int retcode;
2451         unsigned int opcode;
2452
2453         if (hdr->cmdp == NULL)
2454                 return -EMSGSIZE;
2455         if (copy_from_user(cmd, hdr->cmdp, hdr->cmd_len))
2456                 return -EFAULT;
2457
2458         /*
2459          * Prime the hdr with good status for scsi commands that don't require
2460          * an nvme command for translation.
2461          */
2462         retcode = nvme_trans_status_code(hdr, NVME_SC_SUCCESS);
2463         if (retcode)
2464                 return retcode;
2465
2466         opcode = cmd[0];
2467
2468         switch (opcode) {
2469         case READ_6:
2470         case READ_10:
2471         case READ_12:
2472         case READ_16:
2473                 retcode = nvme_trans_io(ns, hdr, 0, cmd);
2474                 break;
2475         case WRITE_6:
2476         case WRITE_10:
2477         case WRITE_12:
2478         case WRITE_16:
2479                 retcode = nvme_trans_io(ns, hdr, 1, cmd);
2480                 break;
2481         case INQUIRY:
2482                 retcode = nvme_trans_inquiry(ns, hdr, cmd);
2483                 break;
2484         case LOG_SENSE:
2485                 retcode = nvme_trans_log_sense(ns, hdr, cmd);
2486                 break;
2487         case MODE_SELECT:
2488         case MODE_SELECT_10:
2489                 retcode = nvme_trans_mode_select(ns, hdr, cmd);
2490                 break;
2491         case MODE_SENSE:
2492         case MODE_SENSE_10:
2493                 retcode = nvme_trans_mode_sense(ns, hdr, cmd);
2494                 break;
2495         case READ_CAPACITY:
2496                 retcode = nvme_trans_read_capacity(ns, hdr, cmd, 0);
2497                 break;
2498         case SERVICE_ACTION_IN_16:
2499                 switch (cmd[1]) {
2500                 case SAI_READ_CAPACITY_16:
2501                         retcode = nvme_trans_read_capacity(ns, hdr, cmd, 1);
2502                         break;
2503                 default:
2504                         goto out;
2505                 }
2506                 break;
2507         case REPORT_LUNS:
2508                 retcode = nvme_trans_report_luns(ns, hdr, cmd);
2509                 break;
2510         case REQUEST_SENSE:
2511                 retcode = nvme_trans_request_sense(ns, hdr, cmd);
2512                 break;
2513         case SECURITY_PROTOCOL_IN:
2514         case SECURITY_PROTOCOL_OUT:
2515                 retcode = nvme_trans_security_protocol(ns, hdr, cmd);
2516                 break;
2517         case START_STOP:
2518                 retcode = nvme_trans_start_stop(ns, hdr, cmd);
2519                 break;
2520         case SYNCHRONIZE_CACHE:
2521                 retcode = nvme_trans_synchronize_cache(ns, hdr);
2522                 break;
2523         case FORMAT_UNIT:
2524                 retcode = nvme_trans_format_unit(ns, hdr, cmd);
2525                 break;
2526         case TEST_UNIT_READY:
2527                 retcode = nvme_trans_test_unit_ready(ns, hdr, cmd);
2528                 break;
2529         case WRITE_BUFFER:
2530                 retcode = nvme_trans_write_buffer(ns, hdr, cmd);
2531                 break;
2532         case UNMAP:
2533                 retcode = nvme_trans_unmap(ns, hdr, cmd);
2534                 break;
2535         default:
2536  out:
2537                 retcode = nvme_trans_completion(hdr, SAM_STAT_CHECK_CONDITION,
2538                                 ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_COMMAND,
2539                                 SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
2540                 break;
2541         }
2542         return retcode;
2543 }
2544
2545 int nvme_sg_io(struct nvme_ns *ns, struct sg_io_hdr __user *u_hdr)
2546 {
2547         struct sg_io_hdr hdr;
2548         int retcode;
2549
2550         if (!capable(CAP_SYS_ADMIN))
2551                 return -EACCES;
2552         if (copy_from_user(&hdr, u_hdr, sizeof(hdr)))
2553                 return -EFAULT;
2554         if (hdr.interface_id != 'S')
2555                 return -EINVAL;
2556         if (hdr.cmd_len > BLK_MAX_CDB)
2557                 return -EINVAL;
2558
2559         /*
2560          * A positive return code means a NVMe status, which has been
2561          * translated to sense data.
2562          */
2563         retcode = nvme_scsi_translate(ns, &hdr);
2564         if (retcode < 0)
2565                 return retcode;
2566         if (copy_to_user(u_hdr, &hdr, sizeof(sg_io_hdr_t)) > 0)
2567                 return -EFAULT;
2568         return 0;
2569 }
2570
2571 int nvme_sg_get_version_num(int __user *ip)
2572 {
2573         return put_user(sg_version_num, ip);
2574 }