• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <scsi/scsi.h>
20 #include <scsi/scsi_proto.h>
21 #include <scsi/sg.h>
22 #include <stdbool.h>
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <sys/un.h>
30 #include <unistd.h>
31 
32 #include <linux/major.h>
33 #include <linux/mmc/ioctl.h>
34 
35 #include <hardware_legacy/power.h>
36 
37 #include "ipc.h"
38 #include "log.h"
39 #include "rpmb.h"
40 #include "storage.h"
41 
42 #define MMC_READ_MULTIPLE_BLOCK 18
43 #define MMC_WRITE_MULTIPLE_BLOCK 25
44 #define MMC_RELIABLE_WRITE_FLAG (1 << 31)
45 
46 #define MMC_RSP_PRESENT (1 << 0)
47 #define MMC_RSP_CRC (1 << 2)
48 #define MMC_RSP_OPCODE (1 << 4)
49 #define MMC_CMD_ADTC (1 << 5)
50 #define MMC_RSP_SPI_S1 (1 << 7)
51 #define MMC_RSP_R1 (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE)
52 #define MMC_RSP_SPI_R1 (MMC_RSP_SPI_S1)
53 
54 #define MMC_WRITE_FLAG_R 0
55 #define MMC_WRITE_FLAG_W 1
56 #define MMC_WRITE_FLAG_RELW (MMC_WRITE_FLAG_W | MMC_RELIABLE_WRITE_FLAG)
57 
58 #define MMC_BLOCK_SIZE 512
59 
60 /*
61  * Number of retry attempts when an RPMB authenticated write triggers a UNIT
62  * ATTENTION
63  */
64 #define UFS_RPMB_WRITE_RETRY_COUNT 1
65 /*
66  * Number of retry attempts when an RPMB read operation triggers a UNIT
67  * ATTENTION
68  */
69 #define UFS_RPMB_READ_RETRY_COUNT 3
70 
71 /*
72  * There should be no timeout for security protocol ioctl call, so we choose a
73  * large number for timeout.
74  * 20000 millisecs == 20 seconds
75  */
76 #define TIMEOUT 20000
77 
78 /*
79  * The sg device driver that supports new interface has a major version number of "3".
80  * SG_GET_VERSION_NUM ioctl() will yield a number greater than or 30000.
81  */
82 #define RPMB_MIN_SG_VERSION_NUM 30000
83 
84 /*
85  * CDB format of SECURITY PROTOCOL IN/OUT commands
86  * (JEDEC Standard No. 220D, Page 264)
87  */
88 struct sec_proto_cdb {
89     /*
90      * OPERATION CODE = A2h for SECURITY PROTOCOL IN command,
91      * OPERATION CODE = B5h for SECURITY PROTOCOL OUT command.
92      */
93     uint8_t opcode;
94     /* SECURITY PROTOCOL = ECh (JEDEC Universal Flash Storage) */
95     uint8_t sec_proto;
96     /*
97      * The SECURITY PROTOCOL SPECIFIC field specifies the RPMB Protocol ID.
98      * CDB Byte 2 = 00h and CDB Byte 3 = 01h for RPMB Region 0.
99      */
100     uint8_t cdb_byte_2;
101     uint8_t cdb_byte_3;
102     /*
103      * Byte 4 and 5 are reserved.
104      */
105     uint8_t cdb_byte_4;
106     uint8_t cdb_byte_5;
107     /* ALLOCATION/TRANSFER LENGTH in big-endian */
108     uint32_t length;
109     /* Byte 9 is reserved. */
110     uint8_t cdb_byte_10;
111     /* CONTROL = 00h. */
112     uint8_t ctrl;
113 } __packed;
114 
115 static int rpmb_fd = -1;
116 static uint8_t read_buf[4096];
117 static enum dev_type dev_type = UNKNOWN_RPMB;
118 
119 static const char* UFS_WAKE_LOCK_NAME = "ufs_seq_wakelock";
120 
121 /**
122  * log_buf - Log a byte buffer to the android log.
123  * @priority: One of ANDROID_LOG_* priority levels from android_LogPriority in
124  *            android/log.h
125  * @prefix:   A null-terminated string that identifies this buffer. Must be less
126  *            than 128 bytes.
127  * @buf:      Buffer to dump.
128  * @size:     Length of @buf in bytes.
129  */
130 #define LOG_BUF_SIZE 256
log_buf(int priority,const char * prefix,const uint8_t * buf,size_t size)131 static int log_buf(int priority, const char* prefix, const uint8_t* buf, size_t size) {
132     int rc;
133     size_t i;
134     char line[LOG_BUF_SIZE] = {0};
135     char* cur = line;
136 
137     rc = snprintf(line, LOG_BUF_SIZE, "%s @%p [%zu]", prefix, buf, size);
138     if (rc < 0 || rc >= LOG_BUF_SIZE) {
139         goto err;
140     }
141     cur += rc;
142     for (i = 0; i < size; i++) {
143         if (i % 32 == 0) {
144             /*
145              * Flush the line out to the log after we have printed 32 bytes
146              * (also flushes the header line on the first iteration and sets up
147              * for printing the buffer itself)
148              */
149             LOG_PRI(priority, LOG_TAG, "%s", line);
150             memset(line, 0, LOG_BUF_SIZE);
151             cur = line;
152             /* Shift output over by the length of the prefix */
153             rc = snprintf(line, LOG_BUF_SIZE, "%*s", (int)strlen(prefix), "");
154             if (rc < 0 || rc >= LOG_BUF_SIZE) {
155                 goto err;
156             }
157             cur += rc;
158         }
159         rc = snprintf(cur, LOG_BUF_SIZE - (cur - line), "%02x ", buf[i]);
160         if (rc < 0 || rc >= LOG_BUF_SIZE - (cur - line)) {
161             goto err;
162         }
163         cur += rc;
164     }
165     LOG_PRI(priority, LOG_TAG, "%s", line);
166 
167     return 0;
168 
169 err:
170     if (rc < 0) {
171         return rc;
172     } else {
173         ALOGE("log_buf prefix was too long");
174         return -1;
175     }
176 }
177 
set_sg_io_hdr(sg_io_hdr_t * io_hdrp,int dxfer_direction,unsigned char cmd_len,unsigned char mx_sb_len,unsigned int dxfer_len,void * dxferp,unsigned char * cmdp,void * sbp)178 static void set_sg_io_hdr(sg_io_hdr_t* io_hdrp, int dxfer_direction, unsigned char cmd_len,
179                           unsigned char mx_sb_len, unsigned int dxfer_len, void* dxferp,
180                           unsigned char* cmdp, void* sbp) {
181     memset(io_hdrp, 0, sizeof(sg_io_hdr_t));
182     io_hdrp->interface_id = 'S';
183     io_hdrp->dxfer_direction = dxfer_direction;
184     io_hdrp->cmd_len = cmd_len;
185     io_hdrp->mx_sb_len = mx_sb_len;
186     io_hdrp->dxfer_len = dxfer_len;
187     io_hdrp->dxferp = dxferp;
188     io_hdrp->cmdp = cmdp;
189     io_hdrp->sbp = sbp;
190     io_hdrp->timeout = TIMEOUT;
191 }
192 
193 /**
194  * enum scsi_result - Results of checking the SCSI status and sense buffer
195  *
196  * @SCSI_RES_OK:    SCSI status and sense are good
197  * @SCSI_RES_ERR:   SCSI status or sense contain an unhandled error
198  * @SCSI_RES_RETRY: SCSI sense buffer contains a status that indicates that the
199  *                  command should be retried
200  */
201 enum scsi_result {
202     SCSI_RES_OK = 0,
203     SCSI_RES_ERR,
204     SCSI_RES_RETRY,
205 };
206 
check_scsi_sense(const uint8_t * sense_buf,size_t len)207 static enum scsi_result check_scsi_sense(const uint8_t* sense_buf, size_t len) {
208     uint8_t response_code = 0;
209     uint8_t sense_key = 0;
210     uint8_t additional_sense_code = 0;
211     uint8_t additional_sense_code_qualifier = 0;
212     uint8_t additional_length = 0;
213 
214     if (!sense_buf || len == 0) {
215         ALOGE("Invalid SCSI sense buffer, length: %zu\n", len);
216         return SCSI_RES_ERR;
217     }
218 
219     response_code = 0x7f & sense_buf[0];
220 
221     if (response_code < 0x70 || response_code > 0x73) {
222         ALOGE("Invalid SCSI sense response code: %hhu\n", response_code);
223         return SCSI_RES_ERR;
224     }
225 
226     if (response_code >= 0x72) {
227         /* descriptor format, SPC-6 4.4.2 */
228         if (len > 1) {
229             sense_key = 0xf & sense_buf[1];
230         }
231         if (len > 2) {
232             additional_sense_code = sense_buf[2];
233         }
234         if (len > 3) {
235             additional_sense_code_qualifier = sense_buf[3];
236         }
237         if (len > 7) {
238             additional_length = sense_buf[7];
239         }
240     } else {
241         /* fixed format, SPC-6 4.4.3 */
242         if (len > 2) {
243             sense_key = 0xf & sense_buf[2];
244         }
245         if (len > 7) {
246             additional_length = sense_buf[7];
247         }
248         if (len > 12) {
249             additional_sense_code = sense_buf[12];
250         }
251         if (len > 13) {
252             additional_sense_code_qualifier = sense_buf[13];
253         }
254     }
255 
256     switch (sense_key) {
257         case NO_SENSE:
258         case 0x0f: /* COMPLETED, not present in kernel headers */
259             ALOGD("SCSI success with sense data: key=%hhu, asc=%hhu, ascq=%hhu\n", sense_key,
260                   additional_sense_code, additional_sense_code_qualifier);
261             return SCSI_RES_OK;
262         case UNIT_ATTENTION:
263             ALOGD("UNIT ATTENTION with sense data: key=%hhu, asc=%hhu, ascq=%hhu\n", sense_key,
264                   additional_sense_code, additional_sense_code_qualifier);
265             if (additional_sense_code == 0x29) {
266                 /* POWER ON or RESET condition */
267                 return SCSI_RES_RETRY;
268             }
269 
270             /* treat this UNIT ATTENTION as an error if we don't recognize it */
271             break;
272     }
273 
274     ALOGE("Unexpected SCSI sense data: key=%hhu, asc=%hhu, ascq=%hhu\n", sense_key,
275           additional_sense_code, additional_sense_code_qualifier);
276     log_buf(ANDROID_LOG_ERROR, "sense buffer: ", sense_buf, len);
277     return SCSI_RES_ERR;
278 }
279 
check_sg_io_hdr(const sg_io_hdr_t * io_hdrp)280 static enum scsi_result check_sg_io_hdr(const sg_io_hdr_t* io_hdrp) {
281     if (io_hdrp->status == 0 && io_hdrp->host_status == 0 && io_hdrp->driver_status == 0) {
282         return SCSI_RES_OK;
283     }
284 
285     if (io_hdrp->status & 0x01) {
286         ALOGE("SG_IO received unknown status, LSB is set: %hhu", io_hdrp->status);
287     }
288 
289     if (io_hdrp->masked_status != GOOD && io_hdrp->sb_len_wr > 0) {
290         enum scsi_result scsi_res = check_scsi_sense(io_hdrp->sbp, io_hdrp->sb_len_wr);
291         if (scsi_res == SCSI_RES_RETRY) {
292             return SCSI_RES_RETRY;
293         } else if (scsi_res != SCSI_RES_OK) {
294             ALOGE("Unexpected SCSI sense. masked_status: %hhu, host_status: %hu, driver_status: "
295                   "%hu\n",
296                   io_hdrp->masked_status, io_hdrp->host_status, io_hdrp->driver_status);
297             return scsi_res;
298         }
299     }
300 
301     switch (io_hdrp->masked_status) {
302         case GOOD:
303             break;
304         case CHECK_CONDITION:
305             /* handled by check_sg_sense above */
306             break;
307         default:
308             ALOGE("SG_IO failed with masked_status: %hhu, host_status: %hu, driver_status: %hu\n",
309                   io_hdrp->masked_status, io_hdrp->host_status, io_hdrp->driver_status);
310             return SCSI_RES_ERR;
311     }
312 
313     if (io_hdrp->host_status != 0) {
314         ALOGE("SG_IO failed with host_status: %hu, driver_status: %hu\n", io_hdrp->host_status,
315               io_hdrp->driver_status);
316     }
317 
318     if (io_hdrp->resid != 0) {
319         ALOGE("SG_IO resid was non-zero: %d\n", io_hdrp->resid);
320     }
321     return SCSI_RES_ERR;
322 }
323 
send_mmc_rpmb_req(int mmc_fd,const struct storage_rpmb_send_req * req,struct watcher * watcher)324 static int send_mmc_rpmb_req(int mmc_fd, const struct storage_rpmb_send_req* req,
325                              struct watcher* watcher) {
326     union {
327         struct mmc_ioc_multi_cmd multi;
328         uint8_t raw[sizeof(struct mmc_ioc_multi_cmd) + sizeof(struct mmc_ioc_cmd) * 3];
329     } mmc = {};
330     struct mmc_ioc_cmd* cmd = mmc.multi.cmds;
331     int rc;
332 
333     const uint8_t* write_buf = req->payload;
334     if (req->reliable_write_size) {
335         cmd->write_flag = MMC_WRITE_FLAG_RELW;
336         cmd->opcode = MMC_WRITE_MULTIPLE_BLOCK;
337         cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
338         cmd->blksz = MMC_BLOCK_SIZE;
339         cmd->blocks = req->reliable_write_size / MMC_BLOCK_SIZE;
340         mmc_ioc_cmd_set_data((*cmd), write_buf);
341 #ifdef RPMB_DEBUG
342         ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
343         log_buf(ANDROID_LOG_INFO, "request: ", write_buf, req->reliable_write_size);
344 #endif
345         write_buf += req->reliable_write_size;
346         mmc.multi.num_of_cmds++;
347         cmd++;
348     }
349 
350     if (req->write_size) {
351         cmd->write_flag = MMC_WRITE_FLAG_W;
352         cmd->opcode = MMC_WRITE_MULTIPLE_BLOCK;
353         cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
354         cmd->blksz = MMC_BLOCK_SIZE;
355         cmd->blocks = req->write_size / MMC_BLOCK_SIZE;
356         mmc_ioc_cmd_set_data((*cmd), write_buf);
357 #ifdef RPMB_DEBUG
358         ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
359         log_buf(ANDROID_LOG_INFO, "request: ", write_buf, req->write_size);
360 #endif
361         write_buf += req->write_size;
362         mmc.multi.num_of_cmds++;
363         cmd++;
364     }
365 
366     if (req->read_size) {
367         cmd->write_flag = MMC_WRITE_FLAG_R;
368         cmd->opcode = MMC_READ_MULTIPLE_BLOCK;
369         cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC, cmd->blksz = MMC_BLOCK_SIZE;
370         cmd->blocks = req->read_size / MMC_BLOCK_SIZE;
371         mmc_ioc_cmd_set_data((*cmd), read_buf);
372 #ifdef RPMB_DEBUG
373         ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
374 #endif
375         mmc.multi.num_of_cmds++;
376         cmd++;
377     }
378 
379     watch_progress(watcher, "rpmb mmc ioctl");
380     rc = ioctl(mmc_fd, MMC_IOC_MULTI_CMD, &mmc.multi);
381     watch_progress(watcher, "rpmb mmc ioctl done");
382     if (rc < 0) {
383         ALOGE("%s: mmc ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
384     }
385     return rc;
386 }
387 
send_ufs_rpmb_req(int sg_fd,const struct storage_rpmb_send_req * req,struct watcher * watcher)388 static int send_ufs_rpmb_req(int sg_fd, const struct storage_rpmb_send_req* req,
389                              struct watcher* watcher) {
390     int rc;
391     int wl_rc;
392     const uint8_t* write_buf = req->payload;
393     /*
394      * Meaning of member values are stated on the definition of struct sec_proto_cdb.
395      */
396     struct sec_proto_cdb in_cdb = {0xA2, 0xEC, 0x00, 0x01, 0x00, 0x00, 0, 0x00, 0x00};
397     struct sec_proto_cdb out_cdb = {0xB5, 0xEC, 0x00, 0x01, 0x00, 0x00, 0, 0x00, 0x00};
398     unsigned char sense_buffer[32];
399 
400     bool is_request_write = req->reliable_write_size > 0;
401 
402     /*
403      * Internally this call connects to the suspend service, which will cause
404      * this service to start if not already running. If the binder thread pool
405      * has not been started at this point, this call will block and poll for the
406      * service every 1s. We need to make sure the thread pool is started to
407      * receive an async notification that the service is started to avoid
408      * blocking (see main).
409      */
410     wl_rc = acquire_wake_lock(PARTIAL_WAKE_LOCK, UFS_WAKE_LOCK_NAME);
411     if (wl_rc < 0) {
412         ALOGE("%s: failed to acquire wakelock: %d, %s\n", __func__, wl_rc, strerror(errno));
413         return wl_rc;
414     }
415 
416     if (req->reliable_write_size) {
417         /* Prepare SECURITY PROTOCOL OUT command. */
418         sg_io_hdr_t io_hdr;
419         int retry_count = UFS_RPMB_WRITE_RETRY_COUNT;
420         do {
421             out_cdb.length = __builtin_bswap32(req->reliable_write_size);
422             set_sg_io_hdr(&io_hdr, SG_DXFER_TO_DEV, sizeof(out_cdb), sizeof(sense_buffer),
423                           req->reliable_write_size, (void*)write_buf, (unsigned char*)&out_cdb,
424                           sense_buffer);
425             watch_progress(watcher, "rpmb ufs reliable write");
426             rc = ioctl(sg_fd, SG_IO, &io_hdr);
427             watch_progress(watcher, "rpmb ufs reliable write done");
428             if (rc < 0) {
429                 ALOGE("%s: ufs ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
430                 goto err_op;
431             }
432         } while (check_sg_io_hdr(&io_hdr) == SCSI_RES_RETRY && retry_count-- > 0);
433         write_buf += req->reliable_write_size;
434     }
435 
436     if (req->write_size) {
437         /* Prepare SECURITY PROTOCOL OUT command. */
438         sg_io_hdr_t io_hdr;
439         /*
440          * We don't retry write response request messages (is_request_write ==
441          * true) because a unit attention condition between the write and
442          * requesting a response means that the device was reset and we can't
443          * get a response to our original write. We can only retry this SG_IO
444          * call when it is the first call in our sequence.
445          */
446         int retry_count = is_request_write ? 0 : UFS_RPMB_READ_RETRY_COUNT;
447         do {
448             out_cdb.length = __builtin_bswap32(req->write_size);
449             set_sg_io_hdr(&io_hdr, SG_DXFER_TO_DEV, sizeof(out_cdb), sizeof(sense_buffer),
450                           req->write_size, (void*)write_buf, (unsigned char*)&out_cdb,
451                           sense_buffer);
452             watch_progress(watcher, "rpmb ufs write");
453             rc = ioctl(sg_fd, SG_IO, &io_hdr);
454             watch_progress(watcher, "rpmb ufs write done");
455             if (rc < 0) {
456                 ALOGE("%s: ufs ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
457                 goto err_op;
458             }
459         } while (check_sg_io_hdr(&io_hdr) == SCSI_RES_RETRY && retry_count-- > 0);
460         write_buf += req->write_size;
461     }
462 
463     if (req->read_size) {
464         /* Prepare SECURITY PROTOCOL IN command. */
465         in_cdb.length = __builtin_bswap32(req->read_size);
466         sg_io_hdr_t io_hdr;
467         set_sg_io_hdr(&io_hdr, SG_DXFER_FROM_DEV, sizeof(in_cdb), sizeof(sense_buffer),
468                       req->read_size, read_buf, (unsigned char*)&in_cdb, sense_buffer);
469         watch_progress(watcher, "rpmb ufs read");
470         rc = ioctl(sg_fd, SG_IO, &io_hdr);
471         watch_progress(watcher, "rpmb ufs read done");
472         if (rc < 0) {
473             ALOGE("%s: ufs ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
474         }
475         check_sg_io_hdr(&io_hdr);
476     }
477 
478 err_op:
479     wl_rc = release_wake_lock(UFS_WAKE_LOCK_NAME);
480     if (wl_rc < 0) {
481         ALOGE("%s: failed to release wakelock: %d, %s\n", __func__, wl_rc, strerror(errno));
482     }
483 
484     return rc;
485 }
486 
send_virt_rpmb_req(int rpmb_fd,void * read_buf,size_t read_size,const void * payload,size_t payload_size)487 static int send_virt_rpmb_req(int rpmb_fd, void* read_buf, size_t read_size, const void* payload,
488                               size_t payload_size) {
489     int rc;
490     uint16_t res_count = read_size / MMC_BLOCK_SIZE;
491     uint16_t cmd_count = payload_size / MMC_BLOCK_SIZE;
492     rc = write(rpmb_fd, &res_count, sizeof(res_count));
493     if (rc < 0) {
494         return rc;
495     }
496     rc = write(rpmb_fd, &cmd_count, sizeof(cmd_count));
497     if (rc < 0) {
498         return rc;
499     }
500     rc = write(rpmb_fd, payload, payload_size);
501     if (rc < 0) {
502         return rc;
503     }
504     rc = read(rpmb_fd, read_buf, read_size);
505     return rc;
506 }
507 
rpmb_send(struct storage_msg * msg,const void * r,size_t req_len,struct watcher * watcher)508 int rpmb_send(struct storage_msg* msg, const void* r, size_t req_len, struct watcher* watcher) {
509     int rc;
510     const struct storage_rpmb_send_req* req = r;
511 
512     if (req_len < sizeof(*req)) {
513         ALOGW("malformed rpmb request: invalid length (%zu < %zu)\n", req_len, sizeof(*req));
514         msg->result = STORAGE_ERR_NOT_VALID;
515         goto err_response;
516     }
517 
518     size_t expected_len = sizeof(*req) + req->reliable_write_size + req->write_size;
519     if (req_len != expected_len) {
520         ALOGW("malformed rpmb request: invalid length (%zu != %zu)\n", req_len, expected_len);
521         msg->result = STORAGE_ERR_NOT_VALID;
522         goto err_response;
523     }
524 
525     if ((req->reliable_write_size % MMC_BLOCK_SIZE) != 0) {
526         ALOGW("invalid reliable write size %u\n", req->reliable_write_size);
527         msg->result = STORAGE_ERR_NOT_VALID;
528         goto err_response;
529     }
530 
531     if ((req->write_size % MMC_BLOCK_SIZE) != 0) {
532         ALOGW("invalid write size %u\n", req->write_size);
533         msg->result = STORAGE_ERR_NOT_VALID;
534         goto err_response;
535     }
536 
537     if (req->read_size % MMC_BLOCK_SIZE != 0 || req->read_size > sizeof(read_buf)) {
538         ALOGE("%s: invalid read size %u\n", __func__, req->read_size);
539         msg->result = STORAGE_ERR_NOT_VALID;
540         goto err_response;
541     }
542 
543     if (dev_type == MMC_RPMB) {
544         rc = send_mmc_rpmb_req(rpmb_fd, req, watcher);
545         if (rc < 0) {
546             msg->result = STORAGE_ERR_GENERIC;
547             goto err_response;
548         }
549     } else if (dev_type == UFS_RPMB) {
550         rc = send_ufs_rpmb_req(rpmb_fd, req, watcher);
551         if (rc < 0) {
552             ALOGE("send_ufs_rpmb_req failed: %d, %s\n", rc, strerror(errno));
553             msg->result = STORAGE_ERR_GENERIC;
554             goto err_response;
555         }
556     } else if ((dev_type == VIRT_RPMB) || (dev_type == SOCK_RPMB)) {
557         size_t payload_size = req->reliable_write_size + req->write_size;
558         rc = send_virt_rpmb_req(rpmb_fd, read_buf, req->read_size, req->payload, payload_size);
559         if (rc < 0) {
560             ALOGE("send_virt_rpmb_req failed: %d, %s\n", rc, strerror(errno));
561             msg->result = STORAGE_ERR_GENERIC;
562             goto err_response;
563         }
564         if (rc != req->read_size) {
565             ALOGE("send_virt_rpmb_req got incomplete response: "
566                   "(size %d, expected %d)\n",
567                   rc, req->read_size);
568             msg->result = STORAGE_ERR_GENERIC;
569             goto err_response;
570         }
571     } else {
572         ALOGE("Unsupported dev_type\n");
573         msg->result = STORAGE_ERR_GENERIC;
574         goto err_response;
575     }
576 #ifdef RPMB_DEBUG
577     if (req->read_size) log_buf(ANDROID_LOG_INFO, "response: ", read_buf, req->read_size);
578 #endif
579 
580     if (msg->flags & STORAGE_MSG_FLAG_POST_COMMIT) {
581         /*
582          * Nothing todo for post msg commit request as MMC_IOC_MULTI_CMD
583          * is fully synchronous in this implementation.
584          */
585     }
586 
587     msg->result = STORAGE_NO_ERROR;
588     return ipc_respond(msg, read_buf, req->read_size);
589 
590 err_response:
591     return ipc_respond(msg, NULL, 0);
592 }
593 
rpmb_open(const char * rpmb_devname,enum dev_type open_dev_type)594 int rpmb_open(const char* rpmb_devname, enum dev_type open_dev_type) {
595     int rc, sg_version_num;
596     dev_type = open_dev_type;
597 
598     if (dev_type != SOCK_RPMB) {
599         rc = open(rpmb_devname, O_RDWR, 0);
600         if (rc < 0) {
601             ALOGE("unable (%d) to open rpmb device '%s': %s\n", errno, rpmb_devname, strerror(errno));
602             return rc;
603         }
604         rpmb_fd = rc;
605 
606         /* For UFS, it is prudent to check we have a sg device by calling an ioctl */
607         if (dev_type == UFS_RPMB) {
608             if ((ioctl(rpmb_fd, SG_GET_VERSION_NUM, &sg_version_num) < 0) ||
609                 (sg_version_num < RPMB_MIN_SG_VERSION_NUM)) {
610                 ALOGE("%s is not a sg device, or old sg driver\n", rpmb_devname);
611                 return -1;
612             }
613         }
614     } else {
615         struct sockaddr_un unaddr;
616         struct sockaddr *addr = (struct sockaddr *)&unaddr;
617         rc = socket(AF_UNIX, SOCK_STREAM, 0);
618         if (rc < 0) {
619             ALOGE("unable (%d) to create socket: %s\n", errno, strerror(errno));
620             return rc;
621         }
622         rpmb_fd = rc;
623 
624         memset(&unaddr, 0, sizeof(unaddr));
625         unaddr.sun_family = AF_UNIX;
626         // TODO if it overflowed, bail rather than connecting?
627         strncpy(unaddr.sun_path, rpmb_devname, sizeof(unaddr.sun_path)-1);
628         rc = connect(rpmb_fd, addr, sizeof(unaddr));
629         if (rc < 0) {
630             ALOGE("unable (%d) to connect to rpmb socket '%s': %s\n", errno, rpmb_devname, strerror(errno));
631             return rc;
632         }
633     }
634 
635     return 0;
636 }
637 
rpmb_close(void)638 void rpmb_close(void) {
639     close(rpmb_fd);
640     rpmb_fd = -1;
641 }
642