scsi: target: core: Add workqueue based cmd submission
[linux-2.6-microblaze.git] / drivers / target / target_core_transport.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*******************************************************************************
3  * Filename:  target_core_transport.c
4  *
5  * This file contains the Generic Target Engine Core.
6  *
7  * (c) Copyright 2002-2013 Datera, Inc.
8  *
9  * Nicholas A. Bellinger <nab@kernel.org>
10  *
11  ******************************************************************************/
12
13 #include <linux/net.h>
14 #include <linux/delay.h>
15 #include <linux/string.h>
16 #include <linux/timer.h>
17 #include <linux/slab.h>
18 #include <linux/spinlock.h>
19 #include <linux/kthread.h>
20 #include <linux/in.h>
21 #include <linux/cdrom.h>
22 #include <linux/module.h>
23 #include <linux/ratelimit.h>
24 #include <linux/vmalloc.h>
25 #include <asm/unaligned.h>
26 #include <net/sock.h>
27 #include <net/tcp.h>
28 #include <scsi/scsi_proto.h>
29 #include <scsi/scsi_common.h>
30
31 #include <target/target_core_base.h>
32 #include <target/target_core_backend.h>
33 #include <target/target_core_fabric.h>
34
35 #include "target_core_internal.h"
36 #include "target_core_alua.h"
37 #include "target_core_pr.h"
38 #include "target_core_ua.h"
39
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/target.h>
42
43 static struct workqueue_struct *target_completion_wq;
44 static struct workqueue_struct *target_submission_wq;
45 static struct kmem_cache *se_sess_cache;
46 struct kmem_cache *se_ua_cache;
47 struct kmem_cache *t10_pr_reg_cache;
48 struct kmem_cache *t10_alua_lu_gp_cache;
49 struct kmem_cache *t10_alua_lu_gp_mem_cache;
50 struct kmem_cache *t10_alua_tg_pt_gp_cache;
51 struct kmem_cache *t10_alua_lba_map_cache;
52 struct kmem_cache *t10_alua_lba_map_mem_cache;
53
54 static void transport_complete_task_attr(struct se_cmd *cmd);
55 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason);
56 static void transport_handle_queue_full(struct se_cmd *cmd,
57                 struct se_device *dev, int err, bool write_pending);
58 static void target_complete_ok_work(struct work_struct *work);
59
60 int init_se_kmem_caches(void)
61 {
62         se_sess_cache = kmem_cache_create("se_sess_cache",
63                         sizeof(struct se_session), __alignof__(struct se_session),
64                         0, NULL);
65         if (!se_sess_cache) {
66                 pr_err("kmem_cache_create() for struct se_session"
67                                 " failed\n");
68                 goto out;
69         }
70         se_ua_cache = kmem_cache_create("se_ua_cache",
71                         sizeof(struct se_ua), __alignof__(struct se_ua),
72                         0, NULL);
73         if (!se_ua_cache) {
74                 pr_err("kmem_cache_create() for struct se_ua failed\n");
75                 goto out_free_sess_cache;
76         }
77         t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
78                         sizeof(struct t10_pr_registration),
79                         __alignof__(struct t10_pr_registration), 0, NULL);
80         if (!t10_pr_reg_cache) {
81                 pr_err("kmem_cache_create() for struct t10_pr_registration"
82                                 " failed\n");
83                 goto out_free_ua_cache;
84         }
85         t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
86                         sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
87                         0, NULL);
88         if (!t10_alua_lu_gp_cache) {
89                 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
90                                 " failed\n");
91                 goto out_free_pr_reg_cache;
92         }
93         t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
94                         sizeof(struct t10_alua_lu_gp_member),
95                         __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
96         if (!t10_alua_lu_gp_mem_cache) {
97                 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
98                                 "cache failed\n");
99                 goto out_free_lu_gp_cache;
100         }
101         t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
102                         sizeof(struct t10_alua_tg_pt_gp),
103                         __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
104         if (!t10_alua_tg_pt_gp_cache) {
105                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
106                                 "cache failed\n");
107                 goto out_free_lu_gp_mem_cache;
108         }
109         t10_alua_lba_map_cache = kmem_cache_create(
110                         "t10_alua_lba_map_cache",
111                         sizeof(struct t10_alua_lba_map),
112                         __alignof__(struct t10_alua_lba_map), 0, NULL);
113         if (!t10_alua_lba_map_cache) {
114                 pr_err("kmem_cache_create() for t10_alua_lba_map_"
115                                 "cache failed\n");
116                 goto out_free_tg_pt_gp_cache;
117         }
118         t10_alua_lba_map_mem_cache = kmem_cache_create(
119                         "t10_alua_lba_map_mem_cache",
120                         sizeof(struct t10_alua_lba_map_member),
121                         __alignof__(struct t10_alua_lba_map_member), 0, NULL);
122         if (!t10_alua_lba_map_mem_cache) {
123                 pr_err("kmem_cache_create() for t10_alua_lba_map_mem_"
124                                 "cache failed\n");
125                 goto out_free_lba_map_cache;
126         }
127
128         target_completion_wq = alloc_workqueue("target_completion",
129                                                WQ_MEM_RECLAIM, 0);
130         if (!target_completion_wq)
131                 goto out_free_lba_map_mem_cache;
132
133         target_submission_wq = alloc_workqueue("target_submission",
134                                                WQ_MEM_RECLAIM, 0);
135         if (!target_submission_wq)
136                 goto out_free_completion_wq;
137
138         return 0;
139
140 out_free_completion_wq:
141         destroy_workqueue(target_completion_wq);
142 out_free_lba_map_mem_cache:
143         kmem_cache_destroy(t10_alua_lba_map_mem_cache);
144 out_free_lba_map_cache:
145         kmem_cache_destroy(t10_alua_lba_map_cache);
146 out_free_tg_pt_gp_cache:
147         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
148 out_free_lu_gp_mem_cache:
149         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
150 out_free_lu_gp_cache:
151         kmem_cache_destroy(t10_alua_lu_gp_cache);
152 out_free_pr_reg_cache:
153         kmem_cache_destroy(t10_pr_reg_cache);
154 out_free_ua_cache:
155         kmem_cache_destroy(se_ua_cache);
156 out_free_sess_cache:
157         kmem_cache_destroy(se_sess_cache);
158 out:
159         return -ENOMEM;
160 }
161
162 void release_se_kmem_caches(void)
163 {
164         destroy_workqueue(target_submission_wq);
165         destroy_workqueue(target_completion_wq);
166         kmem_cache_destroy(se_sess_cache);
167         kmem_cache_destroy(se_ua_cache);
168         kmem_cache_destroy(t10_pr_reg_cache);
169         kmem_cache_destroy(t10_alua_lu_gp_cache);
170         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
171         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
172         kmem_cache_destroy(t10_alua_lba_map_cache);
173         kmem_cache_destroy(t10_alua_lba_map_mem_cache);
174 }
175
176 /* This code ensures unique mib indexes are handed out. */
177 static DEFINE_SPINLOCK(scsi_mib_index_lock);
178 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
179
180 /*
181  * Allocate a new row index for the entry type specified
182  */
183 u32 scsi_get_new_index(scsi_index_t type)
184 {
185         u32 new_index;
186
187         BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
188
189         spin_lock(&scsi_mib_index_lock);
190         new_index = ++scsi_mib_index[type];
191         spin_unlock(&scsi_mib_index_lock);
192
193         return new_index;
194 }
195
196 void transport_subsystem_check_init(void)
197 {
198         int ret;
199         static int sub_api_initialized;
200
201         if (sub_api_initialized)
202                 return;
203
204         ret = IS_ENABLED(CONFIG_TCM_IBLOCK) && request_module("target_core_iblock");
205         if (ret != 0)
206                 pr_err("Unable to load target_core_iblock\n");
207
208         ret = IS_ENABLED(CONFIG_TCM_FILEIO) && request_module("target_core_file");
209         if (ret != 0)
210                 pr_err("Unable to load target_core_file\n");
211
212         ret = IS_ENABLED(CONFIG_TCM_PSCSI) && request_module("target_core_pscsi");
213         if (ret != 0)
214                 pr_err("Unable to load target_core_pscsi\n");
215
216         ret = IS_ENABLED(CONFIG_TCM_USER2) && request_module("target_core_user");
217         if (ret != 0)
218                 pr_err("Unable to load target_core_user\n");
219
220         sub_api_initialized = 1;
221 }
222
223 static void target_release_sess_cmd_refcnt(struct percpu_ref *ref)
224 {
225         struct se_session *sess = container_of(ref, typeof(*sess), cmd_count);
226
227         wake_up(&sess->cmd_count_wq);
228 }
229
230 /**
231  * transport_init_session - initialize a session object
232  * @se_sess: Session object pointer.
233  *
234  * The caller must have zero-initialized @se_sess before calling this function.
235  */
236 int transport_init_session(struct se_session *se_sess)
237 {
238         INIT_LIST_HEAD(&se_sess->sess_list);
239         INIT_LIST_HEAD(&se_sess->sess_acl_list);
240         spin_lock_init(&se_sess->sess_cmd_lock);
241         init_waitqueue_head(&se_sess->cmd_count_wq);
242         init_completion(&se_sess->stop_done);
243         atomic_set(&se_sess->stopped, 0);
244         return percpu_ref_init(&se_sess->cmd_count,
245                                target_release_sess_cmd_refcnt, 0, GFP_KERNEL);
246 }
247 EXPORT_SYMBOL(transport_init_session);
248
249 void transport_uninit_session(struct se_session *se_sess)
250 {
251         /*
252          * Drivers like iscsi and loop do not call target_stop_session
253          * during session shutdown so we have to drop the ref taken at init
254          * time here.
255          */
256         if (!atomic_read(&se_sess->stopped))
257                 percpu_ref_put(&se_sess->cmd_count);
258
259         percpu_ref_exit(&se_sess->cmd_count);
260 }
261
262 /**
263  * transport_alloc_session - allocate a session object and initialize it
264  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
265  */
266 struct se_session *transport_alloc_session(enum target_prot_op sup_prot_ops)
267 {
268         struct se_session *se_sess;
269         int ret;
270
271         se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
272         if (!se_sess) {
273                 pr_err("Unable to allocate struct se_session from"
274                                 " se_sess_cache\n");
275                 return ERR_PTR(-ENOMEM);
276         }
277         ret = transport_init_session(se_sess);
278         if (ret < 0) {
279                 kmem_cache_free(se_sess_cache, se_sess);
280                 return ERR_PTR(ret);
281         }
282         se_sess->sup_prot_ops = sup_prot_ops;
283
284         return se_sess;
285 }
286 EXPORT_SYMBOL(transport_alloc_session);
287
288 /**
289  * transport_alloc_session_tags - allocate target driver private data
290  * @se_sess:  Session pointer.
291  * @tag_num:  Maximum number of in-flight commands between initiator and target.
292  * @tag_size: Size in bytes of the private data a target driver associates with
293  *            each command.
294  */
295 int transport_alloc_session_tags(struct se_session *se_sess,
296                                  unsigned int tag_num, unsigned int tag_size)
297 {
298         int rc;
299
300         se_sess->sess_cmd_map = kvcalloc(tag_size, tag_num,
301                                          GFP_KERNEL | __GFP_RETRY_MAYFAIL);
302         if (!se_sess->sess_cmd_map) {
303                 pr_err("Unable to allocate se_sess->sess_cmd_map\n");
304                 return -ENOMEM;
305         }
306
307         rc = sbitmap_queue_init_node(&se_sess->sess_tag_pool, tag_num, -1,
308                         false, GFP_KERNEL, NUMA_NO_NODE);
309         if (rc < 0) {
310                 pr_err("Unable to init se_sess->sess_tag_pool,"
311                         " tag_num: %u\n", tag_num);
312                 kvfree(se_sess->sess_cmd_map);
313                 se_sess->sess_cmd_map = NULL;
314                 return -ENOMEM;
315         }
316
317         return 0;
318 }
319 EXPORT_SYMBOL(transport_alloc_session_tags);
320
321 /**
322  * transport_init_session_tags - allocate a session and target driver private data
323  * @tag_num:  Maximum number of in-flight commands between initiator and target.
324  * @tag_size: Size in bytes of the private data a target driver associates with
325  *            each command.
326  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
327  */
328 static struct se_session *
329 transport_init_session_tags(unsigned int tag_num, unsigned int tag_size,
330                             enum target_prot_op sup_prot_ops)
331 {
332         struct se_session *se_sess;
333         int rc;
334
335         if (tag_num != 0 && !tag_size) {
336                 pr_err("init_session_tags called with percpu-ida tag_num:"
337                        " %u, but zero tag_size\n", tag_num);
338                 return ERR_PTR(-EINVAL);
339         }
340         if (!tag_num && tag_size) {
341                 pr_err("init_session_tags called with percpu-ida tag_size:"
342                        " %u, but zero tag_num\n", tag_size);
343                 return ERR_PTR(-EINVAL);
344         }
345
346         se_sess = transport_alloc_session(sup_prot_ops);
347         if (IS_ERR(se_sess))
348                 return se_sess;
349
350         rc = transport_alloc_session_tags(se_sess, tag_num, tag_size);
351         if (rc < 0) {
352                 transport_free_session(se_sess);
353                 return ERR_PTR(-ENOMEM);
354         }
355
356         return se_sess;
357 }
358
359 /*
360  * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
361  */
362 void __transport_register_session(
363         struct se_portal_group *se_tpg,
364         struct se_node_acl *se_nacl,
365         struct se_session *se_sess,
366         void *fabric_sess_ptr)
367 {
368         const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo;
369         unsigned char buf[PR_REG_ISID_LEN];
370         unsigned long flags;
371
372         se_sess->se_tpg = se_tpg;
373         se_sess->fabric_sess_ptr = fabric_sess_ptr;
374         /*
375          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
376          *
377          * Only set for struct se_session's that will actually be moving I/O.
378          * eg: *NOT* discovery sessions.
379          */
380         if (se_nacl) {
381                 /*
382                  *
383                  * Determine if fabric allows for T10-PI feature bits exposed to
384                  * initiators for device backends with !dev->dev_attrib.pi_prot_type.
385                  *
386                  * If so, then always save prot_type on a per se_node_acl node
387                  * basis and re-instate the previous sess_prot_type to avoid
388                  * disabling PI from below any previously initiator side
389                  * registered LUNs.
390                  */
391                 if (se_nacl->saved_prot_type)
392                         se_sess->sess_prot_type = se_nacl->saved_prot_type;
393                 else if (tfo->tpg_check_prot_fabric_only)
394                         se_sess->sess_prot_type = se_nacl->saved_prot_type =
395                                         tfo->tpg_check_prot_fabric_only(se_tpg);
396                 /*
397                  * If the fabric module supports an ISID based TransportID,
398                  * save this value in binary from the fabric I_T Nexus now.
399                  */
400                 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
401                         memset(&buf[0], 0, PR_REG_ISID_LEN);
402                         se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
403                                         &buf[0], PR_REG_ISID_LEN);
404                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
405                 }
406
407                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
408                 /*
409                  * The se_nacl->nacl_sess pointer will be set to the
410                  * last active I_T Nexus for each struct se_node_acl.
411                  */
412                 se_nacl->nacl_sess = se_sess;
413
414                 list_add_tail(&se_sess->sess_acl_list,
415                               &se_nacl->acl_sess_list);
416                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
417         }
418         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
419
420         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
421                 se_tpg->se_tpg_tfo->fabric_name, se_sess->fabric_sess_ptr);
422 }
423 EXPORT_SYMBOL(__transport_register_session);
424
425 void transport_register_session(
426         struct se_portal_group *se_tpg,
427         struct se_node_acl *se_nacl,
428         struct se_session *se_sess,
429         void *fabric_sess_ptr)
430 {
431         unsigned long flags;
432
433         spin_lock_irqsave(&se_tpg->session_lock, flags);
434         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
435         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
436 }
437 EXPORT_SYMBOL(transport_register_session);
438
439 struct se_session *
440 target_setup_session(struct se_portal_group *tpg,
441                      unsigned int tag_num, unsigned int tag_size,
442                      enum target_prot_op prot_op,
443                      const char *initiatorname, void *private,
444                      int (*callback)(struct se_portal_group *,
445                                      struct se_session *, void *))
446 {
447         struct se_session *sess;
448
449         /*
450          * If the fabric driver is using percpu-ida based pre allocation
451          * of I/O descriptor tags, go ahead and perform that setup now..
452          */
453         if (tag_num != 0)
454                 sess = transport_init_session_tags(tag_num, tag_size, prot_op);
455         else
456                 sess = transport_alloc_session(prot_op);
457
458         if (IS_ERR(sess))
459                 return sess;
460
461         sess->se_node_acl = core_tpg_check_initiator_node_acl(tpg,
462                                         (unsigned char *)initiatorname);
463         if (!sess->se_node_acl) {
464                 transport_free_session(sess);
465                 return ERR_PTR(-EACCES);
466         }
467         /*
468          * Go ahead and perform any remaining fabric setup that is
469          * required before transport_register_session().
470          */
471         if (callback != NULL) {
472                 int rc = callback(tpg, sess, private);
473                 if (rc) {
474                         transport_free_session(sess);
475                         return ERR_PTR(rc);
476                 }
477         }
478
479         transport_register_session(tpg, sess->se_node_acl, sess, private);
480         return sess;
481 }
482 EXPORT_SYMBOL(target_setup_session);
483
484 ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page)
485 {
486         struct se_session *se_sess;
487         ssize_t len = 0;
488
489         spin_lock_bh(&se_tpg->session_lock);
490         list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) {
491                 if (!se_sess->se_node_acl)
492                         continue;
493                 if (!se_sess->se_node_acl->dynamic_node_acl)
494                         continue;
495                 if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE)
496                         break;
497
498                 len += snprintf(page + len, PAGE_SIZE - len, "%s\n",
499                                 se_sess->se_node_acl->initiatorname);
500                 len += 1; /* Include NULL terminator */
501         }
502         spin_unlock_bh(&se_tpg->session_lock);
503
504         return len;
505 }
506 EXPORT_SYMBOL(target_show_dynamic_sessions);
507
508 static void target_complete_nacl(struct kref *kref)
509 {
510         struct se_node_acl *nacl = container_of(kref,
511                                 struct se_node_acl, acl_kref);
512         struct se_portal_group *se_tpg = nacl->se_tpg;
513
514         if (!nacl->dynamic_stop) {
515                 complete(&nacl->acl_free_comp);
516                 return;
517         }
518
519         mutex_lock(&se_tpg->acl_node_mutex);
520         list_del_init(&nacl->acl_list);
521         mutex_unlock(&se_tpg->acl_node_mutex);
522
523         core_tpg_wait_for_nacl_pr_ref(nacl);
524         core_free_device_list_for_node(nacl, se_tpg);
525         kfree(nacl);
526 }
527
528 void target_put_nacl(struct se_node_acl *nacl)
529 {
530         kref_put(&nacl->acl_kref, target_complete_nacl);
531 }
532 EXPORT_SYMBOL(target_put_nacl);
533
534 void transport_deregister_session_configfs(struct se_session *se_sess)
535 {
536         struct se_node_acl *se_nacl;
537         unsigned long flags;
538         /*
539          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
540          */
541         se_nacl = se_sess->se_node_acl;
542         if (se_nacl) {
543                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
544                 if (!list_empty(&se_sess->sess_acl_list))
545                         list_del_init(&se_sess->sess_acl_list);
546                 /*
547                  * If the session list is empty, then clear the pointer.
548                  * Otherwise, set the struct se_session pointer from the tail
549                  * element of the per struct se_node_acl active session list.
550                  */
551                 if (list_empty(&se_nacl->acl_sess_list))
552                         se_nacl->nacl_sess = NULL;
553                 else {
554                         se_nacl->nacl_sess = container_of(
555                                         se_nacl->acl_sess_list.prev,
556                                         struct se_session, sess_acl_list);
557                 }
558                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
559         }
560 }
561 EXPORT_SYMBOL(transport_deregister_session_configfs);
562
563 void transport_free_session(struct se_session *se_sess)
564 {
565         struct se_node_acl *se_nacl = se_sess->se_node_acl;
566
567         /*
568          * Drop the se_node_acl->nacl_kref obtained from within
569          * core_tpg_get_initiator_node_acl().
570          */
571         if (se_nacl) {
572                 struct se_portal_group *se_tpg = se_nacl->se_tpg;
573                 const struct target_core_fabric_ops *se_tfo = se_tpg->se_tpg_tfo;
574                 unsigned long flags;
575
576                 se_sess->se_node_acl = NULL;
577
578                 /*
579                  * Also determine if we need to drop the extra ->cmd_kref if
580                  * it had been previously dynamically generated, and
581                  * the endpoint is not caching dynamic ACLs.
582                  */
583                 mutex_lock(&se_tpg->acl_node_mutex);
584                 if (se_nacl->dynamic_node_acl &&
585                     !se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
586                         spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
587                         if (list_empty(&se_nacl->acl_sess_list))
588                                 se_nacl->dynamic_stop = true;
589                         spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
590
591                         if (se_nacl->dynamic_stop)
592                                 list_del_init(&se_nacl->acl_list);
593                 }
594                 mutex_unlock(&se_tpg->acl_node_mutex);
595
596                 if (se_nacl->dynamic_stop)
597                         target_put_nacl(se_nacl);
598
599                 target_put_nacl(se_nacl);
600         }
601         if (se_sess->sess_cmd_map) {
602                 sbitmap_queue_free(&se_sess->sess_tag_pool);
603                 kvfree(se_sess->sess_cmd_map);
604         }
605         transport_uninit_session(se_sess);
606         kmem_cache_free(se_sess_cache, se_sess);
607 }
608 EXPORT_SYMBOL(transport_free_session);
609
610 static int target_release_res(struct se_device *dev, void *data)
611 {
612         struct se_session *sess = data;
613
614         if (dev->reservation_holder == sess)
615                 target_release_reservation(dev);
616         return 0;
617 }
618
619 void transport_deregister_session(struct se_session *se_sess)
620 {
621         struct se_portal_group *se_tpg = se_sess->se_tpg;
622         unsigned long flags;
623
624         if (!se_tpg) {
625                 transport_free_session(se_sess);
626                 return;
627         }
628
629         spin_lock_irqsave(&se_tpg->session_lock, flags);
630         list_del(&se_sess->sess_list);
631         se_sess->se_tpg = NULL;
632         se_sess->fabric_sess_ptr = NULL;
633         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
634
635         /*
636          * Since the session is being removed, release SPC-2
637          * reservations held by the session that is disappearing.
638          */
639         target_for_each_device(target_release_res, se_sess);
640
641         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
642                 se_tpg->se_tpg_tfo->fabric_name);
643         /*
644          * If last kref is dropping now for an explicit NodeACL, awake sleeping
645          * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
646          * removal context from within transport_free_session() code.
647          *
648          * For dynamic ACL, target_put_nacl() uses target_complete_nacl()
649          * to release all remaining generate_node_acl=1 created ACL resources.
650          */
651
652         transport_free_session(se_sess);
653 }
654 EXPORT_SYMBOL(transport_deregister_session);
655
656 void target_remove_session(struct se_session *se_sess)
657 {
658         transport_deregister_session_configfs(se_sess);
659         transport_deregister_session(se_sess);
660 }
661 EXPORT_SYMBOL(target_remove_session);
662
663 static void target_remove_from_state_list(struct se_cmd *cmd)
664 {
665         struct se_device *dev = cmd->se_dev;
666         unsigned long flags;
667
668         if (!dev)
669                 return;
670
671         spin_lock_irqsave(&dev->queues[cmd->cpuid].lock, flags);
672         if (cmd->state_active) {
673                 list_del(&cmd->state_list);
674                 cmd->state_active = false;
675         }
676         spin_unlock_irqrestore(&dev->queues[cmd->cpuid].lock, flags);
677 }
678
679 /*
680  * This function is called by the target core after the target core has
681  * finished processing a SCSI command or SCSI TMF. Both the regular command
682  * processing code and the code for aborting commands can call this
683  * function. CMD_T_STOP is set if and only if another thread is waiting
684  * inside transport_wait_for_tasks() for t_transport_stop_comp.
685  */
686 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
687 {
688         unsigned long flags;
689
690         target_remove_from_state_list(cmd);
691
692         /*
693          * Clear struct se_cmd->se_lun before the handoff to FE.
694          */
695         cmd->se_lun = NULL;
696
697         spin_lock_irqsave(&cmd->t_state_lock, flags);
698         /*
699          * Determine if frontend context caller is requesting the stopping of
700          * this command for frontend exceptions.
701          */
702         if (cmd->transport_state & CMD_T_STOP) {
703                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
704                         __func__, __LINE__, cmd->tag);
705
706                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
707
708                 complete_all(&cmd->t_transport_stop_comp);
709                 return 1;
710         }
711         cmd->transport_state &= ~CMD_T_ACTIVE;
712         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
713
714         /*
715          * Some fabric modules like tcm_loop can release their internally
716          * allocated I/O reference and struct se_cmd now.
717          *
718          * Fabric modules are expected to return '1' here if the se_cmd being
719          * passed is released at this point, or zero if not being released.
720          */
721         return cmd->se_tfo->check_stop_free(cmd);
722 }
723
724 static void transport_lun_remove_cmd(struct se_cmd *cmd)
725 {
726         struct se_lun *lun = cmd->se_lun;
727
728         if (!lun)
729                 return;
730
731         if (cmpxchg(&cmd->lun_ref_active, true, false))
732                 percpu_ref_put(&lun->lun_ref);
733 }
734
735 static void target_complete_failure_work(struct work_struct *work)
736 {
737         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
738
739         transport_generic_request_failure(cmd,
740                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
741 }
742
743 /*
744  * Used when asking transport to copy Sense Data from the underlying
745  * Linux/SCSI struct scsi_cmnd
746  */
747 static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
748 {
749         struct se_device *dev = cmd->se_dev;
750
751         WARN_ON(!cmd->se_lun);
752
753         if (!dev)
754                 return NULL;
755
756         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
757                 return NULL;
758
759         cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
760
761         pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
762                 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
763         return cmd->sense_buffer;
764 }
765
766 void transport_copy_sense_to_cmd(struct se_cmd *cmd, unsigned char *sense)
767 {
768         unsigned char *cmd_sense_buf;
769         unsigned long flags;
770
771         spin_lock_irqsave(&cmd->t_state_lock, flags);
772         cmd_sense_buf = transport_get_sense_buffer(cmd);
773         if (!cmd_sense_buf) {
774                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
775                 return;
776         }
777
778         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
779         memcpy(cmd_sense_buf, sense, cmd->scsi_sense_length);
780         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
781 }
782 EXPORT_SYMBOL(transport_copy_sense_to_cmd);
783
784 static void target_handle_abort(struct se_cmd *cmd)
785 {
786         bool tas = cmd->transport_state & CMD_T_TAS;
787         bool ack_kref = cmd->se_cmd_flags & SCF_ACK_KREF;
788         int ret;
789
790         pr_debug("tag %#llx: send_abort_response = %d\n", cmd->tag, tas);
791
792         if (tas) {
793                 if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
794                         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
795                         pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x, ITT: 0x%08llx\n",
796                                  cmd->t_task_cdb[0], cmd->tag);
797                         trace_target_cmd_complete(cmd);
798                         ret = cmd->se_tfo->queue_status(cmd);
799                         if (ret) {
800                                 transport_handle_queue_full(cmd, cmd->se_dev,
801                                                             ret, false);
802                                 return;
803                         }
804                 } else {
805                         cmd->se_tmr_req->response = TMR_FUNCTION_REJECTED;
806                         cmd->se_tfo->queue_tm_rsp(cmd);
807                 }
808         } else {
809                 /*
810                  * Allow the fabric driver to unmap any resources before
811                  * releasing the descriptor via TFO->release_cmd().
812                  */
813                 cmd->se_tfo->aborted_task(cmd);
814                 if (ack_kref)
815                         WARN_ON_ONCE(target_put_sess_cmd(cmd) != 0);
816                 /*
817                  * To do: establish a unit attention condition on the I_T
818                  * nexus associated with cmd. See also the paragraph "Aborting
819                  * commands" in SAM.
820                  */
821         }
822
823         WARN_ON_ONCE(kref_read(&cmd->cmd_kref) == 0);
824
825         transport_lun_remove_cmd(cmd);
826
827         transport_cmd_check_stop_to_fabric(cmd);
828 }
829
830 static void target_abort_work(struct work_struct *work)
831 {
832         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
833
834         target_handle_abort(cmd);
835 }
836
837 static bool target_cmd_interrupted(struct se_cmd *cmd)
838 {
839         int post_ret;
840
841         if (cmd->transport_state & CMD_T_ABORTED) {
842                 if (cmd->transport_complete_callback)
843                         cmd->transport_complete_callback(cmd, false, &post_ret);
844                 INIT_WORK(&cmd->work, target_abort_work);
845                 queue_work(target_completion_wq, &cmd->work);
846                 return true;
847         } else if (cmd->transport_state & CMD_T_STOP) {
848                 if (cmd->transport_complete_callback)
849                         cmd->transport_complete_callback(cmd, false, &post_ret);
850                 complete_all(&cmd->t_transport_stop_comp);
851                 return true;
852         }
853
854         return false;
855 }
856
857 /* May be called from interrupt context so must not sleep. */
858 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
859 {
860         int success;
861         unsigned long flags;
862
863         if (target_cmd_interrupted(cmd))
864                 return;
865
866         cmd->scsi_status = scsi_status;
867
868         spin_lock_irqsave(&cmd->t_state_lock, flags);
869         switch (cmd->scsi_status) {
870         case SAM_STAT_CHECK_CONDITION:
871                 if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
872                         success = 1;
873                 else
874                         success = 0;
875                 break;
876         default:
877                 success = 1;
878                 break;
879         }
880
881         cmd->t_state = TRANSPORT_COMPLETE;
882         cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
883         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
884
885         INIT_WORK(&cmd->work, success ? target_complete_ok_work :
886                   target_complete_failure_work);
887         queue_work_on(cmd->cpuid, target_completion_wq, &cmd->work);
888 }
889 EXPORT_SYMBOL(target_complete_cmd);
890
891 void target_set_cmd_data_length(struct se_cmd *cmd, int length)
892 {
893         if (length < cmd->data_length) {
894                 if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
895                         cmd->residual_count += cmd->data_length - length;
896                 } else {
897                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
898                         cmd->residual_count = cmd->data_length - length;
899                 }
900
901                 cmd->data_length = length;
902         }
903 }
904 EXPORT_SYMBOL(target_set_cmd_data_length);
905
906 void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length)
907 {
908         if (scsi_status == SAM_STAT_GOOD ||
909             cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) {
910                 target_set_cmd_data_length(cmd, length);
911         }
912
913         target_complete_cmd(cmd, scsi_status);
914 }
915 EXPORT_SYMBOL(target_complete_cmd_with_length);
916
917 static void target_add_to_state_list(struct se_cmd *cmd)
918 {
919         struct se_device *dev = cmd->se_dev;
920         unsigned long flags;
921
922         spin_lock_irqsave(&dev->queues[cmd->cpuid].lock, flags);
923         if (!cmd->state_active) {
924                 list_add_tail(&cmd->state_list,
925                               &dev->queues[cmd->cpuid].state_list);
926                 cmd->state_active = true;
927         }
928         spin_unlock_irqrestore(&dev->queues[cmd->cpuid].lock, flags);
929 }
930
931 /*
932  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
933  */
934 static void transport_write_pending_qf(struct se_cmd *cmd);
935 static void transport_complete_qf(struct se_cmd *cmd);
936
937 void target_qf_do_work(struct work_struct *work)
938 {
939         struct se_device *dev = container_of(work, struct se_device,
940                                         qf_work_queue);
941         LIST_HEAD(qf_cmd_list);
942         struct se_cmd *cmd, *cmd_tmp;
943
944         spin_lock_irq(&dev->qf_cmd_lock);
945         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
946         spin_unlock_irq(&dev->qf_cmd_lock);
947
948         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
949                 list_del(&cmd->se_qf_node);
950                 atomic_dec_mb(&dev->dev_qf_count);
951
952                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
953                         " context: %s\n", cmd->se_tfo->fabric_name, cmd,
954                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
955                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
956                         : "UNKNOWN");
957
958                 if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
959                         transport_write_pending_qf(cmd);
960                 else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK ||
961                          cmd->t_state == TRANSPORT_COMPLETE_QF_ERR)
962                         transport_complete_qf(cmd);
963         }
964 }
965
966 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
967 {
968         switch (cmd->data_direction) {
969         case DMA_NONE:
970                 return "NONE";
971         case DMA_FROM_DEVICE:
972                 return "READ";
973         case DMA_TO_DEVICE:
974                 return "WRITE";
975         case DMA_BIDIRECTIONAL:
976                 return "BIDI";
977         default:
978                 break;
979         }
980
981         return "UNKNOWN";
982 }
983
984 void transport_dump_dev_state(
985         struct se_device *dev,
986         char *b,
987         int *bl)
988 {
989         *bl += sprintf(b + *bl, "Status: ");
990         if (dev->export_count)
991                 *bl += sprintf(b + *bl, "ACTIVATED");
992         else
993                 *bl += sprintf(b + *bl, "DEACTIVATED");
994
995         *bl += sprintf(b + *bl, "  Max Queue Depth: %d", dev->queue_depth);
996         *bl += sprintf(b + *bl, "  SectorSize: %u  HwMaxSectors: %u\n",
997                 dev->dev_attrib.block_size,
998                 dev->dev_attrib.hw_max_sectors);
999         *bl += sprintf(b + *bl, "        ");
1000 }
1001
1002 void transport_dump_vpd_proto_id(
1003         struct t10_vpd *vpd,
1004         unsigned char *p_buf,
1005         int p_buf_len)
1006 {
1007         unsigned char buf[VPD_TMP_BUF_SIZE];
1008         int len;
1009
1010         memset(buf, 0, VPD_TMP_BUF_SIZE);
1011         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
1012
1013         switch (vpd->protocol_identifier) {
1014         case 0x00:
1015                 sprintf(buf+len, "Fibre Channel\n");
1016                 break;
1017         case 0x10:
1018                 sprintf(buf+len, "Parallel SCSI\n");
1019                 break;
1020         case 0x20:
1021                 sprintf(buf+len, "SSA\n");
1022                 break;
1023         case 0x30:
1024                 sprintf(buf+len, "IEEE 1394\n");
1025                 break;
1026         case 0x40:
1027                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
1028                                 " Protocol\n");
1029                 break;
1030         case 0x50:
1031                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1032                 break;
1033         case 0x60:
1034                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1035                 break;
1036         case 0x70:
1037                 sprintf(buf+len, "Automation/Drive Interface Transport"
1038                                 " Protocol\n");
1039                 break;
1040         case 0x80:
1041                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1042                 break;
1043         default:
1044                 sprintf(buf+len, "Unknown 0x%02x\n",
1045                                 vpd->protocol_identifier);
1046                 break;
1047         }
1048
1049         if (p_buf)
1050                 strncpy(p_buf, buf, p_buf_len);
1051         else
1052                 pr_debug("%s", buf);
1053 }
1054
1055 void
1056 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1057 {
1058         /*
1059          * Check if the Protocol Identifier Valid (PIV) bit is set..
1060          *
1061          * from spc3r23.pdf section 7.5.1
1062          */
1063          if (page_83[1] & 0x80) {
1064                 vpd->protocol_identifier = (page_83[0] & 0xf0);
1065                 vpd->protocol_identifier_set = 1;
1066                 transport_dump_vpd_proto_id(vpd, NULL, 0);
1067         }
1068 }
1069 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1070
1071 int transport_dump_vpd_assoc(
1072         struct t10_vpd *vpd,
1073         unsigned char *p_buf,
1074         int p_buf_len)
1075 {
1076         unsigned char buf[VPD_TMP_BUF_SIZE];
1077         int ret = 0;
1078         int len;
1079
1080         memset(buf, 0, VPD_TMP_BUF_SIZE);
1081         len = sprintf(buf, "T10 VPD Identifier Association: ");
1082
1083         switch (vpd->association) {
1084         case 0x00:
1085                 sprintf(buf+len, "addressed logical unit\n");
1086                 break;
1087         case 0x10:
1088                 sprintf(buf+len, "target port\n");
1089                 break;
1090         case 0x20:
1091                 sprintf(buf+len, "SCSI target device\n");
1092                 break;
1093         default:
1094                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1095                 ret = -EINVAL;
1096                 break;
1097         }
1098
1099         if (p_buf)
1100                 strncpy(p_buf, buf, p_buf_len);
1101         else
1102                 pr_debug("%s", buf);
1103
1104         return ret;
1105 }
1106
1107 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1108 {
1109         /*
1110          * The VPD identification association..
1111          *
1112          * from spc3r23.pdf Section 7.6.3.1 Table 297
1113          */
1114         vpd->association = (page_83[1] & 0x30);
1115         return transport_dump_vpd_assoc(vpd, NULL, 0);
1116 }
1117 EXPORT_SYMBOL(transport_set_vpd_assoc);
1118
1119 int transport_dump_vpd_ident_type(
1120         struct t10_vpd *vpd,
1121         unsigned char *p_buf,
1122         int p_buf_len)
1123 {
1124         unsigned char buf[VPD_TMP_BUF_SIZE];
1125         int ret = 0;
1126         int len;
1127
1128         memset(buf, 0, VPD_TMP_BUF_SIZE);
1129         len = sprintf(buf, "T10 VPD Identifier Type: ");
1130
1131         switch (vpd->device_identifier_type) {
1132         case 0x00:
1133                 sprintf(buf+len, "Vendor specific\n");
1134                 break;
1135         case 0x01:
1136                 sprintf(buf+len, "T10 Vendor ID based\n");
1137                 break;
1138         case 0x02:
1139                 sprintf(buf+len, "EUI-64 based\n");
1140                 break;
1141         case 0x03:
1142                 sprintf(buf+len, "NAA\n");
1143                 break;
1144         case 0x04:
1145                 sprintf(buf+len, "Relative target port identifier\n");
1146                 break;
1147         case 0x08:
1148                 sprintf(buf+len, "SCSI name string\n");
1149                 break;
1150         default:
1151                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1152                                 vpd->device_identifier_type);
1153                 ret = -EINVAL;
1154                 break;
1155         }
1156
1157         if (p_buf) {
1158                 if (p_buf_len < strlen(buf)+1)
1159                         return -EINVAL;
1160                 strncpy(p_buf, buf, p_buf_len);
1161         } else {
1162                 pr_debug("%s", buf);
1163         }
1164
1165         return ret;
1166 }
1167
1168 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1169 {
1170         /*
1171          * The VPD identifier type..
1172          *
1173          * from spc3r23.pdf Section 7.6.3.1 Table 298
1174          */
1175         vpd->device_identifier_type = (page_83[1] & 0x0f);
1176         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1177 }
1178 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1179
1180 int transport_dump_vpd_ident(
1181         struct t10_vpd *vpd,
1182         unsigned char *p_buf,
1183         int p_buf_len)
1184 {
1185         unsigned char buf[VPD_TMP_BUF_SIZE];
1186         int ret = 0;
1187
1188         memset(buf, 0, VPD_TMP_BUF_SIZE);
1189
1190         switch (vpd->device_identifier_code_set) {
1191         case 0x01: /* Binary */
1192                 snprintf(buf, sizeof(buf),
1193                         "T10 VPD Binary Device Identifier: %s\n",
1194                         &vpd->device_identifier[0]);
1195                 break;
1196         case 0x02: /* ASCII */
1197                 snprintf(buf, sizeof(buf),
1198                         "T10 VPD ASCII Device Identifier: %s\n",
1199                         &vpd->device_identifier[0]);
1200                 break;
1201         case 0x03: /* UTF-8 */
1202                 snprintf(buf, sizeof(buf),
1203                         "T10 VPD UTF-8 Device Identifier: %s\n",
1204                         &vpd->device_identifier[0]);
1205                 break;
1206         default:
1207                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1208                         " 0x%02x", vpd->device_identifier_code_set);
1209                 ret = -EINVAL;
1210                 break;
1211         }
1212
1213         if (p_buf)
1214                 strncpy(p_buf, buf, p_buf_len);
1215         else
1216                 pr_debug("%s", buf);
1217
1218         return ret;
1219 }
1220
1221 int
1222 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1223 {
1224         static const char hex_str[] = "0123456789abcdef";
1225         int j = 0, i = 4; /* offset to start of the identifier */
1226
1227         /*
1228          * The VPD Code Set (encoding)
1229          *
1230          * from spc3r23.pdf Section 7.6.3.1 Table 296
1231          */
1232         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1233         switch (vpd->device_identifier_code_set) {
1234         case 0x01: /* Binary */
1235                 vpd->device_identifier[j++] =
1236                                 hex_str[vpd->device_identifier_type];
1237                 while (i < (4 + page_83[3])) {
1238                         vpd->device_identifier[j++] =
1239                                 hex_str[(page_83[i] & 0xf0) >> 4];
1240                         vpd->device_identifier[j++] =
1241                                 hex_str[page_83[i] & 0x0f];
1242                         i++;
1243                 }
1244                 break;
1245         case 0x02: /* ASCII */
1246         case 0x03: /* UTF-8 */
1247                 while (i < (4 + page_83[3]))
1248                         vpd->device_identifier[j++] = page_83[i++];
1249                 break;
1250         default:
1251                 break;
1252         }
1253
1254         return transport_dump_vpd_ident(vpd, NULL, 0);
1255 }
1256 EXPORT_SYMBOL(transport_set_vpd_ident);
1257
1258 static sense_reason_t
1259 target_check_max_data_sg_nents(struct se_cmd *cmd, struct se_device *dev,
1260                                unsigned int size)
1261 {
1262         u32 mtl;
1263
1264         if (!cmd->se_tfo->max_data_sg_nents)
1265                 return TCM_NO_SENSE;
1266         /*
1267          * Check if fabric enforced maximum SGL entries per I/O descriptor
1268          * exceeds se_cmd->data_length.  If true, set SCF_UNDERFLOW_BIT +
1269          * residual_count and reduce original cmd->data_length to maximum
1270          * length based on single PAGE_SIZE entry scatter-lists.
1271          */
1272         mtl = (cmd->se_tfo->max_data_sg_nents * PAGE_SIZE);
1273         if (cmd->data_length > mtl) {
1274                 /*
1275                  * If an existing CDB overflow is present, calculate new residual
1276                  * based on CDB size minus fabric maximum transfer length.
1277                  *
1278                  * If an existing CDB underflow is present, calculate new residual
1279                  * based on original cmd->data_length minus fabric maximum transfer
1280                  * length.
1281                  *
1282                  * Otherwise, set the underflow residual based on cmd->data_length
1283                  * minus fabric maximum transfer length.
1284                  */
1285                 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1286                         cmd->residual_count = (size - mtl);
1287                 } else if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1288                         u32 orig_dl = size + cmd->residual_count;
1289                         cmd->residual_count = (orig_dl - mtl);
1290                 } else {
1291                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1292                         cmd->residual_count = (cmd->data_length - mtl);
1293                 }
1294                 cmd->data_length = mtl;
1295                 /*
1296                  * Reset sbc_check_prot() calculated protection payload
1297                  * length based upon the new smaller MTL.
1298                  */
1299                 if (cmd->prot_length) {
1300                         u32 sectors = (mtl / dev->dev_attrib.block_size);
1301                         cmd->prot_length = dev->prot_length * sectors;
1302                 }
1303         }
1304         return TCM_NO_SENSE;
1305 }
1306
1307 /**
1308  * target_cmd_size_check - Check whether there will be a residual.
1309  * @cmd: SCSI command.
1310  * @size: Data buffer size derived from CDB. The data buffer size provided by
1311  *   the SCSI transport driver is available in @cmd->data_length.
1312  *
1313  * Compare the data buffer size from the CDB with the data buffer limit from the transport
1314  * header. Set @cmd->residual_count and SCF_OVERFLOW_BIT or SCF_UNDERFLOW_BIT if necessary.
1315  *
1316  * Note: target drivers set @cmd->data_length by calling __target_init_cmd().
1317  *
1318  * Return: TCM_NO_SENSE
1319  */
1320 sense_reason_t
1321 target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1322 {
1323         struct se_device *dev = cmd->se_dev;
1324
1325         if (cmd->unknown_data_length) {
1326                 cmd->data_length = size;
1327         } else if (size != cmd->data_length) {
1328                 pr_warn_ratelimited("TARGET_CORE[%s]: Expected Transfer Length:"
1329                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1330                         " 0x%02x\n", cmd->se_tfo->fabric_name,
1331                                 cmd->data_length, size, cmd->t_task_cdb[0]);
1332                 /*
1333                  * For READ command for the overflow case keep the existing
1334                  * fabric provided ->data_length. Otherwise for the underflow
1335                  * case, reset ->data_length to the smaller SCSI expected data
1336                  * transfer length.
1337                  */
1338                 if (size > cmd->data_length) {
1339                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1340                         cmd->residual_count = (size - cmd->data_length);
1341                 } else {
1342                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1343                         cmd->residual_count = (cmd->data_length - size);
1344                         /*
1345                          * Do not truncate ->data_length for WRITE command to
1346                          * dump all payload
1347                          */
1348                         if (cmd->data_direction == DMA_FROM_DEVICE) {
1349                                 cmd->data_length = size;
1350                         }
1351                 }
1352
1353                 if (cmd->data_direction == DMA_TO_DEVICE) {
1354                         if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1355                                 pr_err_ratelimited("Rejecting underflow/overflow"
1356                                                    " for WRITE data CDB\n");
1357                                 return TCM_INVALID_FIELD_IN_COMMAND_IU;
1358                         }
1359                         /*
1360                          * Some fabric drivers like iscsi-target still expect to
1361                          * always reject overflow writes.  Reject this case until
1362                          * full fabric driver level support for overflow writes
1363                          * is introduced tree-wide.
1364                          */
1365                         if (size > cmd->data_length) {
1366                                 pr_err_ratelimited("Rejecting overflow for"
1367                                                    " WRITE control CDB\n");
1368                                 return TCM_INVALID_CDB_FIELD;
1369                         }
1370                 }
1371         }
1372
1373         return target_check_max_data_sg_nents(cmd, dev, size);
1374
1375 }
1376
1377 /*
1378  * Used by fabric modules containing a local struct se_cmd within their
1379  * fabric dependent per I/O descriptor.
1380  *
1381  * Preserves the value of @cmd->tag.
1382  */
1383 void __target_init_cmd(
1384         struct se_cmd *cmd,
1385         const struct target_core_fabric_ops *tfo,
1386         struct se_session *se_sess,
1387         u32 data_length,
1388         int data_direction,
1389         int task_attr,
1390         unsigned char *sense_buffer, u64 unpacked_lun)
1391 {
1392         INIT_LIST_HEAD(&cmd->se_delayed_node);
1393         INIT_LIST_HEAD(&cmd->se_qf_node);
1394         INIT_LIST_HEAD(&cmd->state_list);
1395         init_completion(&cmd->t_transport_stop_comp);
1396         cmd->free_compl = NULL;
1397         cmd->abrt_compl = NULL;
1398         spin_lock_init(&cmd->t_state_lock);
1399         INIT_WORK(&cmd->work, NULL);
1400         kref_init(&cmd->cmd_kref);
1401
1402         cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1403         cmd->se_tfo = tfo;
1404         cmd->se_sess = se_sess;
1405         cmd->data_length = data_length;
1406         cmd->data_direction = data_direction;
1407         cmd->sam_task_attr = task_attr;
1408         cmd->sense_buffer = sense_buffer;
1409         cmd->orig_fe_lun = unpacked_lun;
1410
1411         if (!(cmd->se_cmd_flags & SCF_USE_CPUID))
1412                 cmd->cpuid = smp_processor_id();
1413
1414         cmd->state_active = false;
1415 }
1416 EXPORT_SYMBOL(__target_init_cmd);
1417
1418 static sense_reason_t
1419 transport_check_alloc_task_attr(struct se_cmd *cmd)
1420 {
1421         struct se_device *dev = cmd->se_dev;
1422
1423         /*
1424          * Check if SAM Task Attribute emulation is enabled for this
1425          * struct se_device storage object
1426          */
1427         if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1428                 return 0;
1429
1430         if (cmd->sam_task_attr == TCM_ACA_TAG) {
1431                 pr_debug("SAM Task Attribute ACA"
1432                         " emulation is not supported\n");
1433                 return TCM_INVALID_CDB_FIELD;
1434         }
1435
1436         return 0;
1437 }
1438
1439 sense_reason_t
1440 target_cmd_init_cdb(struct se_cmd *cmd, unsigned char *cdb, gfp_t gfp)
1441 {
1442         sense_reason_t ret;
1443
1444         /*
1445          * Ensure that the received CDB is less than the max (252 + 8) bytes
1446          * for VARIABLE_LENGTH_CMD
1447          */
1448         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1449                 pr_err("Received SCSI CDB with command_size: %d that"
1450                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1451                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1452                 ret = TCM_INVALID_CDB_FIELD;
1453                 goto err;
1454         }
1455         /*
1456          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1457          * allocate the additional extended CDB buffer now..  Otherwise
1458          * setup the pointer from __t_task_cdb to t_task_cdb.
1459          */
1460         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1461                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb), gfp);
1462                 if (!cmd->t_task_cdb) {
1463                         pr_err("Unable to allocate cmd->t_task_cdb"
1464                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1465                                 scsi_command_size(cdb),
1466                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1467                         ret = TCM_OUT_OF_RESOURCES;
1468                         goto err;
1469                 }
1470         }
1471         /*
1472          * Copy the original CDB into cmd->
1473          */
1474         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1475
1476         trace_target_sequencer_start(cmd);
1477         return 0;
1478
1479 err:
1480         /*
1481          * Copy the CDB here to allow trace_target_cmd_complete() to
1482          * print the cdb to the trace buffers.
1483          */
1484         memcpy(cmd->t_task_cdb, cdb, min(scsi_command_size(cdb),
1485                                          (unsigned int)TCM_MAX_COMMAND_SIZE));
1486         return ret;
1487 }
1488 EXPORT_SYMBOL(target_cmd_init_cdb);
1489
1490 sense_reason_t
1491 target_cmd_parse_cdb(struct se_cmd *cmd)
1492 {
1493         struct se_device *dev = cmd->se_dev;
1494         sense_reason_t ret;
1495
1496         ret = dev->transport->parse_cdb(cmd);
1497         if (ret == TCM_UNSUPPORTED_SCSI_OPCODE)
1498                 pr_warn_ratelimited("%s/%s: Unsupported SCSI Opcode 0x%02x, sending CHECK_CONDITION.\n",
1499                                     cmd->se_tfo->fabric_name,
1500                                     cmd->se_sess->se_node_acl->initiatorname,
1501                                     cmd->t_task_cdb[0]);
1502         if (ret)
1503                 return ret;
1504
1505         ret = transport_check_alloc_task_attr(cmd);
1506         if (ret)
1507                 return ret;
1508
1509         cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1510         atomic_long_inc(&cmd->se_lun->lun_stats.cmd_pdus);
1511         return 0;
1512 }
1513 EXPORT_SYMBOL(target_cmd_parse_cdb);
1514
1515 /*
1516  * Used by fabric module frontends to queue tasks directly.
1517  * May only be used from process context.
1518  */
1519 int transport_handle_cdb_direct(
1520         struct se_cmd *cmd)
1521 {
1522         sense_reason_t ret;
1523
1524         might_sleep();
1525
1526         if (!cmd->se_lun) {
1527                 dump_stack();
1528                 pr_err("cmd->se_lun is NULL\n");
1529                 return -EINVAL;
1530         }
1531
1532         /*
1533          * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1534          * outstanding descriptors are handled correctly during shutdown via
1535          * transport_wait_for_tasks()
1536          *
1537          * Also, we don't take cmd->t_state_lock here as we only expect
1538          * this to be called for initial descriptor submission.
1539          */
1540         cmd->t_state = TRANSPORT_NEW_CMD;
1541         cmd->transport_state |= CMD_T_ACTIVE;
1542
1543         /*
1544          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1545          * so follow TRANSPORT_NEW_CMD processing thread context usage
1546          * and call transport_generic_request_failure() if necessary..
1547          */
1548         ret = transport_generic_new_cmd(cmd);
1549         if (ret)
1550                 transport_generic_request_failure(cmd, ret);
1551         return 0;
1552 }
1553 EXPORT_SYMBOL(transport_handle_cdb_direct);
1554
1555 sense_reason_t
1556 transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl,
1557                 u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count)
1558 {
1559         if (!sgl || !sgl_count)
1560                 return 0;
1561
1562         /*
1563          * Reject SCSI data overflow with map_mem_to_cmd() as incoming
1564          * scatterlists already have been set to follow what the fabric
1565          * passes for the original expected data transfer length.
1566          */
1567         if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1568                 pr_warn("Rejecting SCSI DATA overflow for fabric using"
1569                         " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
1570                 return TCM_INVALID_CDB_FIELD;
1571         }
1572
1573         cmd->t_data_sg = sgl;
1574         cmd->t_data_nents = sgl_count;
1575         cmd->t_bidi_data_sg = sgl_bidi;
1576         cmd->t_bidi_data_nents = sgl_bidi_count;
1577
1578         cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
1579         return 0;
1580 }
1581
1582 /**
1583  * target_init_cmd - initialize se_cmd
1584  * @se_cmd: command descriptor to init
1585  * @se_sess: associated se_sess for endpoint
1586  * @sense: pointer to SCSI sense buffer
1587  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1588  * @data_length: fabric expected data transfer length
1589  * @task_attr: SAM task attribute
1590  * @data_dir: DMA data direction
1591  * @flags: flags for command submission from target_sc_flags_tables
1592  *
1593  * Task tags are supported if the caller has set @se_cmd->tag.
1594  *
1595  * Returns:
1596  *      - less than zero to signal active I/O shutdown failure.
1597  *      - zero on success.
1598  *
1599  * If the fabric driver calls target_stop_session, then it must check the
1600  * return code and handle failures. This will never fail for other drivers,
1601  * and the return code can be ignored.
1602  */
1603 int target_init_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1604                     unsigned char *sense, u64 unpacked_lun,
1605                     u32 data_length, int task_attr, int data_dir, int flags)
1606 {
1607         struct se_portal_group *se_tpg;
1608
1609         se_tpg = se_sess->se_tpg;
1610         BUG_ON(!se_tpg);
1611         BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1612
1613         if (flags & TARGET_SCF_USE_CPUID)
1614                 se_cmd->se_cmd_flags |= SCF_USE_CPUID;
1615         /*
1616          * Signal bidirectional data payloads to target-core
1617          */
1618         if (flags & TARGET_SCF_BIDI_OP)
1619                 se_cmd->se_cmd_flags |= SCF_BIDI;
1620
1621         if (flags & TARGET_SCF_UNKNOWN_SIZE)
1622                 se_cmd->unknown_data_length = 1;
1623         /*
1624          * Initialize se_cmd for target operation.  From this point
1625          * exceptions are handled by sending exception status via
1626          * target_core_fabric_ops->queue_status() callback
1627          */
1628         __target_init_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, data_length,
1629                           data_dir, task_attr, sense, unpacked_lun);
1630
1631         /*
1632          * Obtain struct se_cmd->cmd_kref reference. A second kref_get here is
1633          * necessary for fabrics using TARGET_SCF_ACK_KREF that expect a second
1634          * kref_put() to happen during fabric packet acknowledgement.
1635          */
1636         return target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1637 }
1638 EXPORT_SYMBOL_GPL(target_init_cmd);
1639
1640 /**
1641  * target_submit_prep - prepare cmd for submission
1642  * @se_cmd: command descriptor to prep
1643  * @cdb: pointer to SCSI CDB
1644  * @sgl: struct scatterlist memory for unidirectional mapping
1645  * @sgl_count: scatterlist count for unidirectional mapping
1646  * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping
1647  * @sgl_bidi_count: scatterlist count for bidirectional READ mapping
1648  * @sgl_prot: struct scatterlist memory protection information
1649  * @sgl_prot_count: scatterlist count for protection information
1650  * @gfp: gfp allocation type
1651  *
1652  * Returns:
1653  *      - less than zero to signal failure.
1654  *      - zero on success.
1655  * If failure is returned, lio will the callers queue_status to complete
1656  * the cmd.
1657  */
1658 int target_submit_prep(struct se_cmd *se_cmd, unsigned char *cdb,
1659                        struct scatterlist *sgl, u32 sgl_count,
1660                        struct scatterlist *sgl_bidi, u32 sgl_bidi_count,
1661                        struct scatterlist *sgl_prot, u32 sgl_prot_count,
1662                        gfp_t gfp)
1663 {
1664         sense_reason_t rc;
1665
1666         rc = target_cmd_init_cdb(se_cmd, cdb, gfp);
1667         if (rc)
1668                 goto send_cc_direct;
1669
1670         /*
1671          * Locate se_lun pointer and attach it to struct se_cmd
1672          */
1673         rc = transport_lookup_cmd_lun(se_cmd);
1674         if (rc)
1675                 goto send_cc_direct;
1676
1677         rc = target_cmd_parse_cdb(se_cmd);
1678         if (rc != 0)
1679                 goto generic_fail;
1680
1681         /*
1682          * Save pointers for SGLs containing protection information,
1683          * if present.
1684          */
1685         if (sgl_prot_count) {
1686                 se_cmd->t_prot_sg = sgl_prot;
1687                 se_cmd->t_prot_nents = sgl_prot_count;
1688                 se_cmd->se_cmd_flags |= SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC;
1689         }
1690
1691         /*
1692          * When a non zero sgl_count has been passed perform SGL passthrough
1693          * mapping for pre-allocated fabric memory instead of having target
1694          * core perform an internal SGL allocation..
1695          */
1696         if (sgl_count != 0) {
1697                 BUG_ON(!sgl);
1698
1699                 rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count,
1700                                 sgl_bidi, sgl_bidi_count);
1701                 if (rc != 0)
1702                         goto generic_fail;
1703         }
1704
1705         return 0;
1706
1707 send_cc_direct:
1708         transport_send_check_condition_and_sense(se_cmd, rc, 0);
1709         target_put_sess_cmd(se_cmd);
1710         return -EIO;
1711
1712 generic_fail:
1713         transport_generic_request_failure(se_cmd, rc);
1714         return -EIO;
1715 }
1716 EXPORT_SYMBOL_GPL(target_submit_prep);
1717
1718 /**
1719  * target_submit - perform final initialization and submit cmd to LIO core
1720  * @se_cmd: command descriptor to submit
1721  *
1722  * target_submit_prep must have been called on the cmd, and this must be
1723  * called from process context.
1724  */
1725 void target_submit(struct se_cmd *se_cmd)
1726 {
1727         struct scatterlist *sgl = se_cmd->t_data_sg;
1728         unsigned char *buf = NULL;
1729
1730         might_sleep();
1731
1732         if (se_cmd->t_data_nents != 0) {
1733                 BUG_ON(!sgl);
1734                 /*
1735                  * A work-around for tcm_loop as some userspace code via
1736                  * scsi-generic do not memset their associated read buffers,
1737                  * so go ahead and do that here for type non-data CDBs.  Also
1738                  * note that this is currently guaranteed to be a single SGL
1739                  * for this case by target core in target_setup_cmd_from_cdb()
1740                  * -> transport_generic_cmd_sequencer().
1741                  */
1742                 if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) &&
1743                      se_cmd->data_direction == DMA_FROM_DEVICE) {
1744                         if (sgl)
1745                                 buf = kmap(sg_page(sgl)) + sgl->offset;
1746
1747                         if (buf) {
1748                                 memset(buf, 0, sgl->length);
1749                                 kunmap(sg_page(sgl));
1750                         }
1751                 }
1752
1753         }
1754
1755         /*
1756          * Check if we need to delay processing because of ALUA
1757          * Active/NonOptimized primary access state..
1758          */
1759         core_alua_check_nonop_delay(se_cmd);
1760
1761         transport_handle_cdb_direct(se_cmd);
1762 }
1763 EXPORT_SYMBOL_GPL(target_submit);
1764
1765 /**
1766  * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1767  *
1768  * @se_cmd: command descriptor to submit
1769  * @se_sess: associated se_sess for endpoint
1770  * @cdb: pointer to SCSI CDB
1771  * @sense: pointer to SCSI sense buffer
1772  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1773  * @data_length: fabric expected data transfer length
1774  * @task_attr: SAM task attribute
1775  * @data_dir: DMA data direction
1776  * @flags: flags for command submission from target_sc_flags_tables
1777  *
1778  * Task tags are supported if the caller has set @se_cmd->tag.
1779  *
1780  * This may only be called from process context, and also currently
1781  * assumes internal allocation of fabric payload buffer by target-core.
1782  *
1783  * It also assumes interal target core SGL memory allocation.
1784  *
1785  * This function must only be used by drivers that do their own
1786  * sync during shutdown and does not use target_stop_session. If there
1787  * is a failure this function will call into the fabric driver's
1788  * queue_status with a CHECK_CONDITION.
1789  */
1790 void target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1791                 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1792                 u32 data_length, int task_attr, int data_dir, int flags)
1793 {
1794         int rc;
1795
1796         rc = target_init_cmd(se_cmd, se_sess, sense, unpacked_lun, data_length,
1797                              task_attr, data_dir, flags);
1798         WARN(rc, "Invalid target_submit_cmd use. Driver must not use target_stop_session or call target_init_cmd directly.\n");
1799         if (rc)
1800                 return;
1801
1802         if (target_submit_prep(se_cmd, cdb, NULL, 0, NULL, 0, NULL, 0,
1803                                GFP_KERNEL))
1804                 return;
1805
1806         target_submit(se_cmd);
1807 }
1808 EXPORT_SYMBOL(target_submit_cmd);
1809
1810 void target_queued_submit_work(struct work_struct *work)
1811 {
1812         struct se_cmd_queue *sq = container_of(work, struct se_cmd_queue, work);
1813         struct se_cmd *se_cmd, *next_cmd;
1814         struct llist_node *cmd_list;
1815
1816         cmd_list = llist_del_all(&sq->cmd_list);
1817         if (!cmd_list)
1818                 /* Previous call took what we were queued to submit */
1819                 return;
1820
1821         cmd_list = llist_reverse_order(cmd_list);
1822         llist_for_each_entry_safe(se_cmd, next_cmd, cmd_list, se_cmd_list)
1823                 target_submit(se_cmd);
1824 }
1825
1826 /**
1827  * target_queue_submission - queue the cmd to run on the LIO workqueue
1828  * @se_cmd: command descriptor to submit
1829  */
1830 void target_queue_submission(struct se_cmd *se_cmd)
1831 {
1832         struct se_device *se_dev = se_cmd->se_dev;
1833         int cpu = se_cmd->cpuid;
1834         struct se_cmd_queue *sq;
1835
1836         sq = &se_dev->queues[cpu].sq;
1837         llist_add(&se_cmd->se_cmd_list, &sq->cmd_list);
1838         queue_work_on(cpu, target_submission_wq, &sq->work);
1839 }
1840 EXPORT_SYMBOL_GPL(target_queue_submission);
1841
1842 static void target_complete_tmr_failure(struct work_struct *work)
1843 {
1844         struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1845
1846         se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1847         se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1848
1849         transport_lun_remove_cmd(se_cmd);
1850         transport_cmd_check_stop_to_fabric(se_cmd);
1851 }
1852
1853 /**
1854  * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1855  *                     for TMR CDBs
1856  *
1857  * @se_cmd: command descriptor to submit
1858  * @se_sess: associated se_sess for endpoint
1859  * @sense: pointer to SCSI sense buffer
1860  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1861  * @fabric_tmr_ptr: fabric context for TMR req
1862  * @tm_type: Type of TM request
1863  * @gfp: gfp type for caller
1864  * @tag: referenced task tag for TMR_ABORT_TASK
1865  * @flags: submit cmd flags
1866  *
1867  * Callable from all contexts.
1868  **/
1869
1870 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1871                 unsigned char *sense, u64 unpacked_lun,
1872                 void *fabric_tmr_ptr, unsigned char tm_type,
1873                 gfp_t gfp, u64 tag, int flags)
1874 {
1875         struct se_portal_group *se_tpg;
1876         int ret;
1877
1878         se_tpg = se_sess->se_tpg;
1879         BUG_ON(!se_tpg);
1880
1881         __target_init_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1882                           0, DMA_NONE, TCM_SIMPLE_TAG, sense, unpacked_lun);
1883         /*
1884          * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1885          * allocation failure.
1886          */
1887         ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1888         if (ret < 0)
1889                 return -ENOMEM;
1890
1891         if (tm_type == TMR_ABORT_TASK)
1892                 se_cmd->se_tmr_req->ref_task_tag = tag;
1893
1894         /* See target_submit_cmd for commentary */
1895         ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1896         if (ret) {
1897                 core_tmr_release_req(se_cmd->se_tmr_req);
1898                 return ret;
1899         }
1900
1901         ret = transport_lookup_tmr_lun(se_cmd);
1902         if (ret)
1903                 goto failure;
1904
1905         transport_generic_handle_tmr(se_cmd);
1906         return 0;
1907
1908         /*
1909          * For callback during failure handling, push this work off
1910          * to process context with TMR_LUN_DOES_NOT_EXIST status.
1911          */
1912 failure:
1913         INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1914         schedule_work(&se_cmd->work);
1915         return 0;
1916 }
1917 EXPORT_SYMBOL(target_submit_tmr);
1918
1919 /*
1920  * Handle SAM-esque emulation for generic transport request failures.
1921  */
1922 void transport_generic_request_failure(struct se_cmd *cmd,
1923                 sense_reason_t sense_reason)
1924 {
1925         int ret = 0, post_ret;
1926
1927         pr_debug("-----[ Storage Engine Exception; sense_reason %d\n",
1928                  sense_reason);
1929         target_show_cmd("-----[ ", cmd);
1930
1931         /*
1932          * For SAM Task Attribute emulation for failed struct se_cmd
1933          */
1934         transport_complete_task_attr(cmd);
1935
1936         if (cmd->transport_complete_callback)
1937                 cmd->transport_complete_callback(cmd, false, &post_ret);
1938
1939         if (cmd->transport_state & CMD_T_ABORTED) {
1940                 INIT_WORK(&cmd->work, target_abort_work);
1941                 queue_work(target_completion_wq, &cmd->work);
1942                 return;
1943         }
1944
1945         switch (sense_reason) {
1946         case TCM_NON_EXISTENT_LUN:
1947         case TCM_UNSUPPORTED_SCSI_OPCODE:
1948         case TCM_INVALID_CDB_FIELD:
1949         case TCM_INVALID_PARAMETER_LIST:
1950         case TCM_PARAMETER_LIST_LENGTH_ERROR:
1951         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1952         case TCM_UNKNOWN_MODE_PAGE:
1953         case TCM_WRITE_PROTECTED:
1954         case TCM_ADDRESS_OUT_OF_RANGE:
1955         case TCM_CHECK_CONDITION_ABORT_CMD:
1956         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1957         case TCM_CHECK_CONDITION_NOT_READY:
1958         case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED:
1959         case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED:
1960         case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED:
1961         case TCM_COPY_TARGET_DEVICE_NOT_REACHABLE:
1962         case TCM_TOO_MANY_TARGET_DESCS:
1963         case TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE:
1964         case TCM_TOO_MANY_SEGMENT_DESCS:
1965         case TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE:
1966         case TCM_INVALID_FIELD_IN_COMMAND_IU:
1967                 break;
1968         case TCM_OUT_OF_RESOURCES:
1969                 cmd->scsi_status = SAM_STAT_TASK_SET_FULL;
1970                 goto queue_status;
1971         case TCM_LUN_BUSY:
1972                 cmd->scsi_status = SAM_STAT_BUSY;
1973                 goto queue_status;
1974         case TCM_RESERVATION_CONFLICT:
1975                 /*
1976                  * No SENSE Data payload for this case, set SCSI Status
1977                  * and queue the response to $FABRIC_MOD.
1978                  *
1979                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1980                  */
1981                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1982                 /*
1983                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1984                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1985                  * CONFLICT STATUS.
1986                  *
1987                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1988                  */
1989                 if (cmd->se_sess &&
1990                     cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl
1991                                         == TARGET_UA_INTLCK_CTRL_ESTABLISH_UA) {
1992                         target_ua_allocate_lun(cmd->se_sess->se_node_acl,
1993                                                cmd->orig_fe_lun, 0x2C,
1994                                         ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1995                 }
1996
1997                 goto queue_status;
1998         default:
1999                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
2000                         cmd->t_task_cdb[0], sense_reason);
2001                 sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
2002                 break;
2003         }
2004
2005         ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0);
2006         if (ret)
2007                 goto queue_full;
2008
2009 check_stop:
2010         transport_lun_remove_cmd(cmd);
2011         transport_cmd_check_stop_to_fabric(cmd);
2012         return;
2013
2014 queue_status:
2015         trace_target_cmd_complete(cmd);
2016         ret = cmd->se_tfo->queue_status(cmd);
2017         if (!ret)
2018                 goto check_stop;
2019 queue_full:
2020         transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2021 }
2022 EXPORT_SYMBOL(transport_generic_request_failure);
2023
2024 void __target_execute_cmd(struct se_cmd *cmd, bool do_checks)
2025 {
2026         sense_reason_t ret;
2027
2028         if (!cmd->execute_cmd) {
2029                 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2030                 goto err;
2031         }
2032         if (do_checks) {
2033                 /*
2034                  * Check for an existing UNIT ATTENTION condition after
2035                  * target_handle_task_attr() has done SAM task attr
2036                  * checking, and possibly have already defered execution
2037                  * out to target_restart_delayed_cmds() context.
2038                  */
2039                 ret = target_scsi3_ua_check(cmd);
2040                 if (ret)
2041                         goto err;
2042
2043                 ret = target_alua_state_check(cmd);
2044                 if (ret)
2045                         goto err;
2046
2047                 ret = target_check_reservation(cmd);
2048                 if (ret) {
2049                         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2050                         goto err;
2051                 }
2052         }
2053
2054         ret = cmd->execute_cmd(cmd);
2055         if (!ret)
2056                 return;
2057 err:
2058         spin_lock_irq(&cmd->t_state_lock);
2059         cmd->transport_state &= ~CMD_T_SENT;
2060         spin_unlock_irq(&cmd->t_state_lock);
2061
2062         transport_generic_request_failure(cmd, ret);
2063 }
2064
2065 static int target_write_prot_action(struct se_cmd *cmd)
2066 {
2067         u32 sectors;
2068         /*
2069          * Perform WRITE_INSERT of PI using software emulation when backend
2070          * device has PI enabled, if the transport has not already generated
2071          * PI using hardware WRITE_INSERT offload.
2072          */
2073         switch (cmd->prot_op) {
2074         case TARGET_PROT_DOUT_INSERT:
2075                 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT))
2076                         sbc_dif_generate(cmd);
2077                 break;
2078         case TARGET_PROT_DOUT_STRIP:
2079                 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP)
2080                         break;
2081
2082                 sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size);
2083                 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2084                                              sectors, 0, cmd->t_prot_sg, 0);
2085                 if (unlikely(cmd->pi_err)) {
2086                         spin_lock_irq(&cmd->t_state_lock);
2087                         cmd->transport_state &= ~CMD_T_SENT;
2088                         spin_unlock_irq(&cmd->t_state_lock);
2089                         transport_generic_request_failure(cmd, cmd->pi_err);
2090                         return -1;
2091                 }
2092                 break;
2093         default:
2094                 break;
2095         }
2096
2097         return 0;
2098 }
2099
2100 static bool target_handle_task_attr(struct se_cmd *cmd)
2101 {
2102         struct se_device *dev = cmd->se_dev;
2103
2104         if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2105                 return false;
2106
2107         cmd->se_cmd_flags |= SCF_TASK_ATTR_SET;
2108
2109         /*
2110          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
2111          * to allow the passed struct se_cmd list of tasks to the front of the list.
2112          */
2113         switch (cmd->sam_task_attr) {
2114         case TCM_HEAD_TAG:
2115                 pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x\n",
2116                          cmd->t_task_cdb[0]);
2117                 return false;
2118         case TCM_ORDERED_TAG:
2119                 atomic_inc_mb(&dev->dev_ordered_sync);
2120
2121                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered list\n",
2122                          cmd->t_task_cdb[0]);
2123
2124                 /*
2125                  * Execute an ORDERED command if no other older commands
2126                  * exist that need to be completed first.
2127                  */
2128                 if (!atomic_read(&dev->simple_cmds))
2129                         return false;
2130                 break;
2131         default:
2132                 /*
2133                  * For SIMPLE and UNTAGGED Task Attribute commands
2134                  */
2135                 atomic_inc_mb(&dev->simple_cmds);
2136                 break;
2137         }
2138
2139         if (atomic_read(&dev->dev_ordered_sync) == 0)
2140                 return false;
2141
2142         spin_lock(&dev->delayed_cmd_lock);
2143         list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
2144         spin_unlock(&dev->delayed_cmd_lock);
2145
2146         pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to delayed CMD listn",
2147                 cmd->t_task_cdb[0], cmd->sam_task_attr);
2148         return true;
2149 }
2150
2151 void target_execute_cmd(struct se_cmd *cmd)
2152 {
2153         /*
2154          * Determine if frontend context caller is requesting the stopping of
2155          * this command for frontend exceptions.
2156          *
2157          * If the received CDB has already been aborted stop processing it here.
2158          */
2159         if (target_cmd_interrupted(cmd))
2160                 return;
2161
2162         spin_lock_irq(&cmd->t_state_lock);
2163         cmd->t_state = TRANSPORT_PROCESSING;
2164         cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
2165         spin_unlock_irq(&cmd->t_state_lock);
2166
2167         if (target_write_prot_action(cmd))
2168                 return;
2169
2170         if (target_handle_task_attr(cmd)) {
2171                 spin_lock_irq(&cmd->t_state_lock);
2172                 cmd->transport_state &= ~CMD_T_SENT;
2173                 spin_unlock_irq(&cmd->t_state_lock);
2174                 return;
2175         }
2176
2177         __target_execute_cmd(cmd, true);
2178 }
2179 EXPORT_SYMBOL(target_execute_cmd);
2180
2181 /*
2182  * Process all commands up to the last received ORDERED task attribute which
2183  * requires another blocking boundary
2184  */
2185 static void target_restart_delayed_cmds(struct se_device *dev)
2186 {
2187         for (;;) {
2188                 struct se_cmd *cmd;
2189
2190                 spin_lock(&dev->delayed_cmd_lock);
2191                 if (list_empty(&dev->delayed_cmd_list)) {
2192                         spin_unlock(&dev->delayed_cmd_lock);
2193                         break;
2194                 }
2195
2196                 cmd = list_entry(dev->delayed_cmd_list.next,
2197                                  struct se_cmd, se_delayed_node);
2198                 list_del(&cmd->se_delayed_node);
2199                 spin_unlock(&dev->delayed_cmd_lock);
2200
2201                 cmd->transport_state |= CMD_T_SENT;
2202
2203                 __target_execute_cmd(cmd, true);
2204
2205                 if (cmd->sam_task_attr == TCM_ORDERED_TAG)
2206                         break;
2207         }
2208 }
2209
2210 /*
2211  * Called from I/O completion to determine which dormant/delayed
2212  * and ordered cmds need to have their tasks added to the execution queue.
2213  */
2214 static void transport_complete_task_attr(struct se_cmd *cmd)
2215 {
2216         struct se_device *dev = cmd->se_dev;
2217
2218         if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2219                 return;
2220
2221         if (!(cmd->se_cmd_flags & SCF_TASK_ATTR_SET))
2222                 goto restart;
2223
2224         if (cmd->sam_task_attr == TCM_SIMPLE_TAG) {
2225                 atomic_dec_mb(&dev->simple_cmds);
2226                 dev->dev_cur_ordered_id++;
2227         } else if (cmd->sam_task_attr == TCM_HEAD_TAG) {
2228                 dev->dev_cur_ordered_id++;
2229                 pr_debug("Incremented dev_cur_ordered_id: %u for HEAD_OF_QUEUE\n",
2230                          dev->dev_cur_ordered_id);
2231         } else if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2232                 atomic_dec_mb(&dev->dev_ordered_sync);
2233
2234                 dev->dev_cur_ordered_id++;
2235                 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED\n",
2236                          dev->dev_cur_ordered_id);
2237         }
2238         cmd->se_cmd_flags &= ~SCF_TASK_ATTR_SET;
2239
2240 restart:
2241         target_restart_delayed_cmds(dev);
2242 }
2243
2244 static void transport_complete_qf(struct se_cmd *cmd)
2245 {
2246         int ret = 0;
2247
2248         transport_complete_task_attr(cmd);
2249         /*
2250          * If a fabric driver ->write_pending() or ->queue_data_in() callback
2251          * has returned neither -ENOMEM or -EAGAIN, assume it's fatal and
2252          * the same callbacks should not be retried.  Return CHECK_CONDITION
2253          * if a scsi_status is not already set.
2254          *
2255          * If a fabric driver ->queue_status() has returned non zero, always
2256          * keep retrying no matter what..
2257          */
2258         if (cmd->t_state == TRANSPORT_COMPLETE_QF_ERR) {
2259                 if (cmd->scsi_status)
2260                         goto queue_status;
2261
2262                 translate_sense_reason(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
2263                 goto queue_status;
2264         }
2265
2266         /*
2267          * Check if we need to send a sense buffer from
2268          * the struct se_cmd in question. We do NOT want
2269          * to take this path of the IO has been marked as
2270          * needing to be treated like a "normal read". This
2271          * is the case if it's a tape read, and either the
2272          * FM, EOM, or ILI bits are set, but there is no
2273          * sense data.
2274          */
2275         if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2276             cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
2277                 goto queue_status;
2278
2279         switch (cmd->data_direction) {
2280         case DMA_FROM_DEVICE:
2281                 /* queue status if not treating this as a normal read */
2282                 if (cmd->scsi_status &&
2283                     !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2284                         goto queue_status;
2285
2286                 trace_target_cmd_complete(cmd);
2287                 ret = cmd->se_tfo->queue_data_in(cmd);
2288                 break;
2289         case DMA_TO_DEVICE:
2290                 if (cmd->se_cmd_flags & SCF_BIDI) {
2291                         ret = cmd->se_tfo->queue_data_in(cmd);
2292                         break;
2293                 }
2294                 fallthrough;
2295         case DMA_NONE:
2296 queue_status:
2297                 trace_target_cmd_complete(cmd);
2298                 ret = cmd->se_tfo->queue_status(cmd);
2299                 break;
2300         default:
2301                 break;
2302         }
2303
2304         if (ret < 0) {
2305                 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2306                 return;
2307         }
2308         transport_lun_remove_cmd(cmd);
2309         transport_cmd_check_stop_to_fabric(cmd);
2310 }
2311
2312 static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev,
2313                                         int err, bool write_pending)
2314 {
2315         /*
2316          * -EAGAIN or -ENOMEM signals retry of ->write_pending() and/or
2317          * ->queue_data_in() callbacks from new process context.
2318          *
2319          * Otherwise for other errors, transport_complete_qf() will send
2320          * CHECK_CONDITION via ->queue_status() instead of attempting to
2321          * retry associated fabric driver data-transfer callbacks.
2322          */
2323         if (err == -EAGAIN || err == -ENOMEM) {
2324                 cmd->t_state = (write_pending) ? TRANSPORT_COMPLETE_QF_WP :
2325                                                  TRANSPORT_COMPLETE_QF_OK;
2326         } else {
2327                 pr_warn_ratelimited("Got unknown fabric queue status: %d\n", err);
2328                 cmd->t_state = TRANSPORT_COMPLETE_QF_ERR;
2329         }
2330
2331         spin_lock_irq(&dev->qf_cmd_lock);
2332         list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2333         atomic_inc_mb(&dev->dev_qf_count);
2334         spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2335
2336         schedule_work(&cmd->se_dev->qf_work_queue);
2337 }
2338
2339 static bool target_read_prot_action(struct se_cmd *cmd)
2340 {
2341         switch (cmd->prot_op) {
2342         case TARGET_PROT_DIN_STRIP:
2343                 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) {
2344                         u32 sectors = cmd->data_length >>
2345                                   ilog2(cmd->se_dev->dev_attrib.block_size);
2346
2347                         cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2348                                                      sectors, 0, cmd->t_prot_sg,
2349                                                      0);
2350                         if (cmd->pi_err)
2351                                 return true;
2352                 }
2353                 break;
2354         case TARGET_PROT_DIN_INSERT:
2355                 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT)
2356                         break;
2357
2358                 sbc_dif_generate(cmd);
2359                 break;
2360         default:
2361                 break;
2362         }
2363
2364         return false;
2365 }
2366
2367 static void target_complete_ok_work(struct work_struct *work)
2368 {
2369         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2370         int ret;
2371
2372         /*
2373          * Check if we need to move delayed/dormant tasks from cmds on the
2374          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2375          * Attribute.
2376          */
2377         transport_complete_task_attr(cmd);
2378
2379         /*
2380          * Check to schedule QUEUE_FULL work, or execute an existing
2381          * cmd->transport_qf_callback()
2382          */
2383         if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2384                 schedule_work(&cmd->se_dev->qf_work_queue);
2385
2386         /*
2387          * Check if we need to send a sense buffer from
2388          * the struct se_cmd in question. We do NOT want
2389          * to take this path of the IO has been marked as
2390          * needing to be treated like a "normal read". This
2391          * is the case if it's a tape read, and either the
2392          * FM, EOM, or ILI bits are set, but there is no
2393          * sense data.
2394          */
2395         if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2396             cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2397                 WARN_ON(!cmd->scsi_status);
2398                 ret = transport_send_check_condition_and_sense(
2399                                         cmd, 0, 1);
2400                 if (ret)
2401                         goto queue_full;
2402
2403                 transport_lun_remove_cmd(cmd);
2404                 transport_cmd_check_stop_to_fabric(cmd);
2405                 return;
2406         }
2407         /*
2408          * Check for a callback, used by amongst other things
2409          * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation.
2410          */
2411         if (cmd->transport_complete_callback) {
2412                 sense_reason_t rc;
2413                 bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE);
2414                 bool zero_dl = !(cmd->data_length);
2415                 int post_ret = 0;
2416
2417                 rc = cmd->transport_complete_callback(cmd, true, &post_ret);
2418                 if (!rc && !post_ret) {
2419                         if (caw && zero_dl)
2420                                 goto queue_rsp;
2421
2422                         return;
2423                 } else if (rc) {
2424                         ret = transport_send_check_condition_and_sense(cmd,
2425                                                 rc, 0);
2426                         if (ret)
2427                                 goto queue_full;
2428
2429                         transport_lun_remove_cmd(cmd);
2430                         transport_cmd_check_stop_to_fabric(cmd);
2431                         return;
2432                 }
2433         }
2434
2435 queue_rsp:
2436         switch (cmd->data_direction) {
2437         case DMA_FROM_DEVICE:
2438                 /*
2439                  * if this is a READ-type IO, but SCSI status
2440                  * is set, then skip returning data and just
2441                  * return the status -- unless this IO is marked
2442                  * as needing to be treated as a normal read,
2443                  * in which case we want to go ahead and return
2444                  * the data. This happens, for example, for tape
2445                  * reads with the FM, EOM, or ILI bits set, with
2446                  * no sense data.
2447                  */
2448                 if (cmd->scsi_status &&
2449                     !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2450                         goto queue_status;
2451
2452                 atomic_long_add(cmd->data_length,
2453                                 &cmd->se_lun->lun_stats.tx_data_octets);
2454                 /*
2455                  * Perform READ_STRIP of PI using software emulation when
2456                  * backend had PI enabled, if the transport will not be
2457                  * performing hardware READ_STRIP offload.
2458                  */
2459                 if (target_read_prot_action(cmd)) {
2460                         ret = transport_send_check_condition_and_sense(cmd,
2461                                                 cmd->pi_err, 0);
2462                         if (ret)
2463                                 goto queue_full;
2464
2465                         transport_lun_remove_cmd(cmd);
2466                         transport_cmd_check_stop_to_fabric(cmd);
2467                         return;
2468                 }
2469
2470                 trace_target_cmd_complete(cmd);
2471                 ret = cmd->se_tfo->queue_data_in(cmd);
2472                 if (ret)
2473                         goto queue_full;
2474                 break;
2475         case DMA_TO_DEVICE:
2476                 atomic_long_add(cmd->data_length,
2477                                 &cmd->se_lun->lun_stats.rx_data_octets);
2478                 /*
2479                  * Check if we need to send READ payload for BIDI-COMMAND
2480                  */
2481                 if (cmd->se_cmd_flags & SCF_BIDI) {
2482                         atomic_long_add(cmd->data_length,
2483                                         &cmd->se_lun->lun_stats.tx_data_octets);
2484                         ret = cmd->se_tfo->queue_data_in(cmd);
2485                         if (ret)
2486                                 goto queue_full;
2487                         break;
2488                 }
2489                 fallthrough;
2490         case DMA_NONE:
2491 queue_status:
2492                 trace_target_cmd_complete(cmd);
2493                 ret = cmd->se_tfo->queue_status(cmd);
2494                 if (ret)
2495                         goto queue_full;
2496                 break;
2497         default:
2498                 break;
2499         }
2500
2501         transport_lun_remove_cmd(cmd);
2502         transport_cmd_check_stop_to_fabric(cmd);
2503         return;
2504
2505 queue_full:
2506         pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2507                 " data_direction: %d\n", cmd, cmd->data_direction);
2508
2509         transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2510 }
2511
2512 void target_free_sgl(struct scatterlist *sgl, int nents)
2513 {
2514         sgl_free_n_order(sgl, nents, 0);
2515 }
2516 EXPORT_SYMBOL(target_free_sgl);
2517
2518 static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
2519 {
2520         /*
2521          * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
2522          * emulation, and free + reset pointers if necessary..
2523          */
2524         if (!cmd->t_data_sg_orig)
2525                 return;
2526
2527         kfree(cmd->t_data_sg);
2528         cmd->t_data_sg = cmd->t_data_sg_orig;
2529         cmd->t_data_sg_orig = NULL;
2530         cmd->t_data_nents = cmd->t_data_nents_orig;
2531         cmd->t_data_nents_orig = 0;
2532 }
2533
2534 static inline void transport_free_pages(struct se_cmd *cmd)
2535 {
2536         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2537                 target_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents);
2538                 cmd->t_prot_sg = NULL;
2539                 cmd->t_prot_nents = 0;
2540         }
2541
2542         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) {
2543                 /*
2544                  * Release special case READ buffer payload required for
2545                  * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE
2546                  */
2547                 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
2548                         target_free_sgl(cmd->t_bidi_data_sg,
2549                                            cmd->t_bidi_data_nents);
2550                         cmd->t_bidi_data_sg = NULL;
2551                         cmd->t_bidi_data_nents = 0;
2552                 }
2553                 transport_reset_sgl_orig(cmd);
2554                 return;
2555         }
2556         transport_reset_sgl_orig(cmd);
2557
2558         target_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2559         cmd->t_data_sg = NULL;
2560         cmd->t_data_nents = 0;
2561
2562         target_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2563         cmd->t_bidi_data_sg = NULL;
2564         cmd->t_bidi_data_nents = 0;
2565 }
2566
2567 void *transport_kmap_data_sg(struct se_cmd *cmd)
2568 {
2569         struct scatterlist *sg = cmd->t_data_sg;
2570         struct page **pages;
2571         int i;
2572
2573         /*
2574          * We need to take into account a possible offset here for fabrics like
2575          * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2576          * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2577          */
2578         if (!cmd->t_data_nents)
2579                 return NULL;
2580
2581         BUG_ON(!sg);
2582         if (cmd->t_data_nents == 1)
2583                 return kmap(sg_page(sg)) + sg->offset;
2584
2585         /* >1 page. use vmap */
2586         pages = kmalloc_array(cmd->t_data_nents, sizeof(*pages), GFP_KERNEL);
2587         if (!pages)
2588                 return NULL;
2589
2590         /* convert sg[] to pages[] */
2591         for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2592                 pages[i] = sg_page(sg);
2593         }
2594
2595         cmd->t_data_vmap = vmap(pages, cmd->t_data_nents,  VM_MAP, PAGE_KERNEL);
2596         kfree(pages);
2597         if (!cmd->t_data_vmap)
2598                 return NULL;
2599
2600         return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2601 }
2602 EXPORT_SYMBOL(transport_kmap_data_sg);
2603
2604 void transport_kunmap_data_sg(struct se_cmd *cmd)
2605 {
2606         if (!cmd->t_data_nents) {
2607                 return;
2608         } else if (cmd->t_data_nents == 1) {
2609                 kunmap(sg_page(cmd->t_data_sg));
2610                 return;
2611         }
2612
2613         vunmap(cmd->t_data_vmap);
2614         cmd->t_data_vmap = NULL;
2615 }
2616 EXPORT_SYMBOL(transport_kunmap_data_sg);
2617
2618 int
2619 target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length,
2620                  bool zero_page, bool chainable)
2621 {
2622         gfp_t gfp = GFP_KERNEL | (zero_page ? __GFP_ZERO : 0);
2623
2624         *sgl = sgl_alloc_order(length, 0, chainable, gfp, nents);
2625         return *sgl ? 0 : -ENOMEM;
2626 }
2627 EXPORT_SYMBOL(target_alloc_sgl);
2628
2629 /*
2630  * Allocate any required resources to execute the command.  For writes we
2631  * might not have the payload yet, so notify the fabric via a call to
2632  * ->write_pending instead. Otherwise place it on the execution queue.
2633  */
2634 sense_reason_t
2635 transport_generic_new_cmd(struct se_cmd *cmd)
2636 {
2637         unsigned long flags;
2638         int ret = 0;
2639         bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB);
2640
2641         if (cmd->prot_op != TARGET_PROT_NORMAL &&
2642             !(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2643                 ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents,
2644                                        cmd->prot_length, true, false);
2645                 if (ret < 0)
2646                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2647         }
2648
2649         /*
2650          * Determine if the TCM fabric module has already allocated physical
2651          * memory, and is directly calling transport_generic_map_mem_to_cmd()
2652          * beforehand.
2653          */
2654         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2655             cmd->data_length) {
2656
2657                 if ((cmd->se_cmd_flags & SCF_BIDI) ||
2658                     (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) {
2659                         u32 bidi_length;
2660
2661                         if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)
2662                                 bidi_length = cmd->t_task_nolb *
2663                                               cmd->se_dev->dev_attrib.block_size;
2664                         else
2665                                 bidi_length = cmd->data_length;
2666
2667                         ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2668                                                &cmd->t_bidi_data_nents,
2669                                                bidi_length, zero_flag, false);
2670                         if (ret < 0)
2671                                 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2672                 }
2673
2674                 ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
2675                                        cmd->data_length, zero_flag, false);
2676                 if (ret < 0)
2677                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2678         } else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
2679                     cmd->data_length) {
2680                 /*
2681                  * Special case for COMPARE_AND_WRITE with fabrics
2682                  * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC.
2683                  */
2684                 u32 caw_length = cmd->t_task_nolb *
2685                                  cmd->se_dev->dev_attrib.block_size;
2686
2687                 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2688                                        &cmd->t_bidi_data_nents,
2689                                        caw_length, zero_flag, false);
2690                 if (ret < 0)
2691                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2692         }
2693         /*
2694          * If this command is not a write we can execute it right here,
2695          * for write buffers we need to notify the fabric driver first
2696          * and let it call back once the write buffers are ready.
2697          */
2698         target_add_to_state_list(cmd);
2699         if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) {
2700                 target_execute_cmd(cmd);
2701                 return 0;
2702         }
2703
2704         spin_lock_irqsave(&cmd->t_state_lock, flags);
2705         cmd->t_state = TRANSPORT_WRITE_PENDING;
2706         /*
2707          * Determine if frontend context caller is requesting the stopping of
2708          * this command for frontend exceptions.
2709          */
2710         if (cmd->transport_state & CMD_T_STOP &&
2711             !cmd->se_tfo->write_pending_must_be_called) {
2712                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2713                          __func__, __LINE__, cmd->tag);
2714
2715                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2716
2717                 complete_all(&cmd->t_transport_stop_comp);
2718                 return 0;
2719         }
2720         cmd->transport_state &= ~CMD_T_ACTIVE;
2721         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2722
2723         ret = cmd->se_tfo->write_pending(cmd);
2724         if (ret)
2725                 goto queue_full;
2726
2727         return 0;
2728
2729 queue_full:
2730         pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2731         transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2732         return 0;
2733 }
2734 EXPORT_SYMBOL(transport_generic_new_cmd);
2735
2736 static void transport_write_pending_qf(struct se_cmd *cmd)
2737 {
2738         unsigned long flags;
2739         int ret;
2740         bool stop;
2741
2742         spin_lock_irqsave(&cmd->t_state_lock, flags);
2743         stop = (cmd->transport_state & (CMD_T_STOP | CMD_T_ABORTED));
2744         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2745
2746         if (stop) {
2747                 pr_debug("%s:%d CMD_T_STOP|CMD_T_ABORTED for ITT: 0x%08llx\n",
2748                         __func__, __LINE__, cmd->tag);
2749                 complete_all(&cmd->t_transport_stop_comp);
2750                 return;
2751         }
2752
2753         ret = cmd->se_tfo->write_pending(cmd);
2754         if (ret) {
2755                 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2756                          cmd);
2757                 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2758         }
2759 }
2760
2761 static bool
2762 __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *,
2763                            unsigned long *flags);
2764
2765 static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas)
2766 {
2767         unsigned long flags;
2768
2769         spin_lock_irqsave(&cmd->t_state_lock, flags);
2770         __transport_wait_for_tasks(cmd, true, aborted, tas, &flags);
2771         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2772 }
2773
2774 /*
2775  * Call target_put_sess_cmd() and wait until target_release_cmd_kref(@cmd) has
2776  * finished.
2777  */
2778 void target_put_cmd_and_wait(struct se_cmd *cmd)
2779 {
2780         DECLARE_COMPLETION_ONSTACK(compl);
2781
2782         WARN_ON_ONCE(cmd->abrt_compl);
2783         cmd->abrt_compl = &compl;
2784         target_put_sess_cmd(cmd);
2785         wait_for_completion(&compl);
2786 }
2787
2788 /*
2789  * This function is called by frontend drivers after processing of a command
2790  * has finished.
2791  *
2792  * The protocol for ensuring that either the regular frontend command
2793  * processing flow or target_handle_abort() code drops one reference is as
2794  * follows:
2795  * - Calling .queue_data_in(), .queue_status() or queue_tm_rsp() will cause
2796  *   the frontend driver to call this function synchronously or asynchronously.
2797  *   That will cause one reference to be dropped.
2798  * - During regular command processing the target core sets CMD_T_COMPLETE
2799  *   before invoking one of the .queue_*() functions.
2800  * - The code that aborts commands skips commands and TMFs for which
2801  *   CMD_T_COMPLETE has been set.
2802  * - CMD_T_ABORTED is set atomically after the CMD_T_COMPLETE check for
2803  *   commands that will be aborted.
2804  * - If the CMD_T_ABORTED flag is set but CMD_T_TAS has not been set
2805  *   transport_generic_free_cmd() skips its call to target_put_sess_cmd().
2806  * - For aborted commands for which CMD_T_TAS has been set .queue_status() will
2807  *   be called and will drop a reference.
2808  * - For aborted commands for which CMD_T_TAS has not been set .aborted_task()
2809  *   will be called. target_handle_abort() will drop the final reference.
2810  */
2811 int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2812 {
2813         DECLARE_COMPLETION_ONSTACK(compl);
2814         int ret = 0;
2815         bool aborted = false, tas = false;
2816
2817         if (wait_for_tasks)
2818                 target_wait_free_cmd(cmd, &aborted, &tas);
2819
2820         if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) {
2821                 /*
2822                  * Handle WRITE failure case where transport_generic_new_cmd()
2823                  * has already added se_cmd to state_list, but fabric has
2824                  * failed command before I/O submission.
2825                  */
2826                 if (cmd->state_active)
2827                         target_remove_from_state_list(cmd);
2828
2829                 if (cmd->se_lun)
2830                         transport_lun_remove_cmd(cmd);
2831         }
2832         if (aborted)
2833                 cmd->free_compl = &compl;
2834         ret = target_put_sess_cmd(cmd);
2835         if (aborted) {
2836                 pr_debug("Detected CMD_T_ABORTED for ITT: %llu\n", cmd->tag);
2837                 wait_for_completion(&compl);
2838                 ret = 1;
2839         }
2840         return ret;
2841 }
2842 EXPORT_SYMBOL(transport_generic_free_cmd);
2843
2844 /**
2845  * target_get_sess_cmd - Verify the session is accepting cmds and take ref
2846  * @se_cmd:     command descriptor to add
2847  * @ack_kref:   Signal that fabric will perform an ack target_put_sess_cmd()
2848  */
2849 int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
2850 {
2851         struct se_session *se_sess = se_cmd->se_sess;
2852         int ret = 0;
2853
2854         /*
2855          * Add a second kref if the fabric caller is expecting to handle
2856          * fabric acknowledgement that requires two target_put_sess_cmd()
2857          * invocations before se_cmd descriptor release.
2858          */
2859         if (ack_kref) {
2860                 kref_get(&se_cmd->cmd_kref);
2861                 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2862         }
2863
2864         if (!percpu_ref_tryget_live(&se_sess->cmd_count))
2865                 ret = -ESHUTDOWN;
2866
2867         if (ret && ack_kref)
2868                 target_put_sess_cmd(se_cmd);
2869
2870         return ret;
2871 }
2872 EXPORT_SYMBOL(target_get_sess_cmd);
2873
2874 static void target_free_cmd_mem(struct se_cmd *cmd)
2875 {
2876         transport_free_pages(cmd);
2877
2878         if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2879                 core_tmr_release_req(cmd->se_tmr_req);
2880         if (cmd->t_task_cdb != cmd->__t_task_cdb)
2881                 kfree(cmd->t_task_cdb);
2882 }
2883
2884 static void target_release_cmd_kref(struct kref *kref)
2885 {
2886         struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2887         struct se_session *se_sess = se_cmd->se_sess;
2888         struct completion *free_compl = se_cmd->free_compl;
2889         struct completion *abrt_compl = se_cmd->abrt_compl;
2890
2891         target_free_cmd_mem(se_cmd);
2892         se_cmd->se_tfo->release_cmd(se_cmd);
2893         if (free_compl)
2894                 complete(free_compl);
2895         if (abrt_compl)
2896                 complete(abrt_compl);
2897
2898         percpu_ref_put(&se_sess->cmd_count);
2899 }
2900
2901 /**
2902  * target_put_sess_cmd - decrease the command reference count
2903  * @se_cmd:     command to drop a reference from
2904  *
2905  * Returns 1 if and only if this target_put_sess_cmd() call caused the
2906  * refcount to drop to zero. Returns zero otherwise.
2907  */
2908 int target_put_sess_cmd(struct se_cmd *se_cmd)
2909 {
2910         return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2911 }
2912 EXPORT_SYMBOL(target_put_sess_cmd);
2913
2914 static const char *data_dir_name(enum dma_data_direction d)
2915 {
2916         switch (d) {
2917         case DMA_BIDIRECTIONAL: return "BIDI";
2918         case DMA_TO_DEVICE:     return "WRITE";
2919         case DMA_FROM_DEVICE:   return "READ";
2920         case DMA_NONE:          return "NONE";
2921         }
2922
2923         return "(?)";
2924 }
2925
2926 static const char *cmd_state_name(enum transport_state_table t)
2927 {
2928         switch (t) {
2929         case TRANSPORT_NO_STATE:        return "NO_STATE";
2930         case TRANSPORT_NEW_CMD:         return "NEW_CMD";
2931         case TRANSPORT_WRITE_PENDING:   return "WRITE_PENDING";
2932         case TRANSPORT_PROCESSING:      return "PROCESSING";
2933         case TRANSPORT_COMPLETE:        return "COMPLETE";
2934         case TRANSPORT_ISTATE_PROCESSING:
2935                                         return "ISTATE_PROCESSING";
2936         case TRANSPORT_COMPLETE_QF_WP:  return "COMPLETE_QF_WP";
2937         case TRANSPORT_COMPLETE_QF_OK:  return "COMPLETE_QF_OK";
2938         case TRANSPORT_COMPLETE_QF_ERR: return "COMPLETE_QF_ERR";
2939         }
2940
2941         return "(?)";
2942 }
2943
2944 static void target_append_str(char **str, const char *txt)
2945 {
2946         char *prev = *str;
2947
2948         *str = *str ? kasprintf(GFP_ATOMIC, "%s,%s", *str, txt) :
2949                 kstrdup(txt, GFP_ATOMIC);
2950         kfree(prev);
2951 }
2952
2953 /*
2954  * Convert a transport state bitmask into a string. The caller is
2955  * responsible for freeing the returned pointer.
2956  */
2957 static char *target_ts_to_str(u32 ts)
2958 {
2959         char *str = NULL;
2960
2961         if (ts & CMD_T_ABORTED)
2962                 target_append_str(&str, "aborted");
2963         if (ts & CMD_T_ACTIVE)
2964                 target_append_str(&str, "active");
2965         if (ts & CMD_T_COMPLETE)
2966                 target_append_str(&str, "complete");
2967         if (ts & CMD_T_SENT)
2968                 target_append_str(&str, "sent");
2969         if (ts & CMD_T_STOP)
2970                 target_append_str(&str, "stop");
2971         if (ts & CMD_T_FABRIC_STOP)
2972                 target_append_str(&str, "fabric_stop");
2973
2974         return str;
2975 }
2976
2977 static const char *target_tmf_name(enum tcm_tmreq_table tmf)
2978 {
2979         switch (tmf) {
2980         case TMR_ABORT_TASK:            return "ABORT_TASK";
2981         case TMR_ABORT_TASK_SET:        return "ABORT_TASK_SET";
2982         case TMR_CLEAR_ACA:             return "CLEAR_ACA";
2983         case TMR_CLEAR_TASK_SET:        return "CLEAR_TASK_SET";
2984         case TMR_LUN_RESET:             return "LUN_RESET";
2985         case TMR_TARGET_WARM_RESET:     return "TARGET_WARM_RESET";
2986         case TMR_TARGET_COLD_RESET:     return "TARGET_COLD_RESET";
2987         case TMR_LUN_RESET_PRO:         return "LUN_RESET_PRO";
2988         case TMR_UNKNOWN:               break;
2989         }
2990         return "(?)";
2991 }
2992
2993 void target_show_cmd(const char *pfx, struct se_cmd *cmd)
2994 {
2995         char *ts_str = target_ts_to_str(cmd->transport_state);
2996         const u8 *cdb = cmd->t_task_cdb;
2997         struct se_tmr_req *tmf = cmd->se_tmr_req;
2998
2999         if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
3000                 pr_debug("%scmd %#02x:%#02x with tag %#llx dir %s i_state %d t_state %s len %d refcnt %d transport_state %s\n",
3001                          pfx, cdb[0], cdb[1], cmd->tag,
3002                          data_dir_name(cmd->data_direction),
3003                          cmd->se_tfo->get_cmd_state(cmd),
3004                          cmd_state_name(cmd->t_state), cmd->data_length,
3005                          kref_read(&cmd->cmd_kref), ts_str);
3006         } else {
3007                 pr_debug("%stmf %s with tag %#llx ref_task_tag %#llx i_state %d t_state %s refcnt %d transport_state %s\n",
3008                          pfx, target_tmf_name(tmf->function), cmd->tag,
3009                          tmf->ref_task_tag, cmd->se_tfo->get_cmd_state(cmd),
3010                          cmd_state_name(cmd->t_state),
3011                          kref_read(&cmd->cmd_kref), ts_str);
3012         }
3013         kfree(ts_str);
3014 }
3015 EXPORT_SYMBOL(target_show_cmd);
3016
3017 static void target_stop_session_confirm(struct percpu_ref *ref)
3018 {
3019         struct se_session *se_sess = container_of(ref, struct se_session,
3020                                                   cmd_count);
3021         complete_all(&se_sess->stop_done);
3022 }
3023
3024 /**
3025  * target_stop_session - Stop new IO from being queued on the session.
3026  * @se_sess:    session to stop
3027  */
3028 void target_stop_session(struct se_session *se_sess)
3029 {
3030         pr_debug("Stopping session queue.\n");
3031         if (atomic_cmpxchg(&se_sess->stopped, 0, 1) == 0)
3032                 percpu_ref_kill_and_confirm(&se_sess->cmd_count,
3033                                             target_stop_session_confirm);
3034 }
3035 EXPORT_SYMBOL(target_stop_session);
3036
3037 /**
3038  * target_wait_for_sess_cmds - Wait for outstanding commands
3039  * @se_sess:    session to wait for active I/O
3040  */
3041 void target_wait_for_sess_cmds(struct se_session *se_sess)
3042 {
3043         int ret;
3044
3045         WARN_ON_ONCE(!atomic_read(&se_sess->stopped));
3046
3047         do {
3048                 pr_debug("Waiting for running cmds to complete.\n");
3049                 ret = wait_event_timeout(se_sess->cmd_count_wq,
3050                                 percpu_ref_is_zero(&se_sess->cmd_count),
3051                                 180 * HZ);
3052         } while (ret <= 0);
3053
3054         wait_for_completion(&se_sess->stop_done);
3055         pr_debug("Waiting for cmds done.\n");
3056 }
3057 EXPORT_SYMBOL(target_wait_for_sess_cmds);
3058
3059 /*
3060  * Prevent that new percpu_ref_tryget_live() calls succeed and wait until
3061  * all references to the LUN have been released. Called during LUN shutdown.
3062  */
3063 void transport_clear_lun_ref(struct se_lun *lun)
3064 {
3065         percpu_ref_kill(&lun->lun_ref);
3066         wait_for_completion(&lun->lun_shutdown_comp);
3067 }
3068
3069 static bool
3070 __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop,
3071                            bool *aborted, bool *tas, unsigned long *flags)
3072         __releases(&cmd->t_state_lock)
3073         __acquires(&cmd->t_state_lock)
3074 {
3075
3076         assert_spin_locked(&cmd->t_state_lock);
3077         WARN_ON_ONCE(!irqs_disabled());
3078
3079         if (fabric_stop)
3080                 cmd->transport_state |= CMD_T_FABRIC_STOP;
3081
3082         if (cmd->transport_state & CMD_T_ABORTED)
3083                 *aborted = true;
3084
3085         if (cmd->transport_state & CMD_T_TAS)
3086                 *tas = true;
3087
3088         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
3089             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3090                 return false;
3091
3092         if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
3093             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3094                 return false;
3095
3096         if (!(cmd->transport_state & CMD_T_ACTIVE))
3097                 return false;
3098
3099         if (fabric_stop && *aborted)
3100                 return false;
3101
3102         cmd->transport_state |= CMD_T_STOP;
3103
3104         target_show_cmd("wait_for_tasks: Stopping ", cmd);
3105
3106         spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
3107
3108         while (!wait_for_completion_timeout(&cmd->t_transport_stop_comp,
3109                                             180 * HZ))
3110                 target_show_cmd("wait for tasks: ", cmd);
3111
3112         spin_lock_irqsave(&cmd->t_state_lock, *flags);
3113         cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
3114
3115         pr_debug("wait_for_tasks: Stopped wait_for_completion(&cmd->"
3116                  "t_transport_stop_comp) for ITT: 0x%08llx\n", cmd->tag);
3117
3118         return true;
3119 }
3120
3121 /**
3122  * transport_wait_for_tasks - set CMD_T_STOP and wait for t_transport_stop_comp
3123  * @cmd: command to wait on
3124  */
3125 bool transport_wait_for_tasks(struct se_cmd *cmd)
3126 {
3127         unsigned long flags;
3128         bool ret, aborted = false, tas = false;
3129
3130         spin_lock_irqsave(&cmd->t_state_lock, flags);
3131         ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags);
3132         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3133
3134         return ret;
3135 }
3136 EXPORT_SYMBOL(transport_wait_for_tasks);
3137
3138 struct sense_detail {
3139         u8 key;
3140         u8 asc;
3141         u8 ascq;
3142         bool add_sense_info;
3143 };
3144
3145 static const struct sense_detail sense_detail_table[] = {
3146         [TCM_NO_SENSE] = {
3147                 .key = NOT_READY
3148         },
3149         [TCM_NON_EXISTENT_LUN] = {
3150                 .key = ILLEGAL_REQUEST,
3151                 .asc = 0x25 /* LOGICAL UNIT NOT SUPPORTED */
3152         },
3153         [TCM_UNSUPPORTED_SCSI_OPCODE] = {
3154                 .key = ILLEGAL_REQUEST,
3155                 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3156         },
3157         [TCM_SECTOR_COUNT_TOO_MANY] = {
3158                 .key = ILLEGAL_REQUEST,
3159                 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3160         },
3161         [TCM_UNKNOWN_MODE_PAGE] = {
3162                 .key = ILLEGAL_REQUEST,
3163                 .asc = 0x24, /* INVALID FIELD IN CDB */
3164         },
3165         [TCM_CHECK_CONDITION_ABORT_CMD] = {
3166                 .key = ABORTED_COMMAND,
3167                 .asc = 0x29, /* BUS DEVICE RESET FUNCTION OCCURRED */
3168                 .ascq = 0x03,
3169         },
3170         [TCM_INCORRECT_AMOUNT_OF_DATA] = {
3171                 .key = ABORTED_COMMAND,
3172                 .asc = 0x0c, /* WRITE ERROR */
3173                 .ascq = 0x0d, /* NOT ENOUGH UNSOLICITED DATA */
3174         },
3175         [TCM_INVALID_CDB_FIELD] = {
3176                 .key = ILLEGAL_REQUEST,
3177                 .asc = 0x24, /* INVALID FIELD IN CDB */
3178         },
3179         [TCM_INVALID_PARAMETER_LIST] = {
3180                 .key = ILLEGAL_REQUEST,
3181                 .asc = 0x26, /* INVALID FIELD IN PARAMETER LIST */
3182         },
3183         [TCM_TOO_MANY_TARGET_DESCS] = {
3184                 .key = ILLEGAL_REQUEST,
3185                 .asc = 0x26,
3186                 .ascq = 0x06, /* TOO MANY TARGET DESCRIPTORS */
3187         },
3188         [TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE] = {
3189                 .key = ILLEGAL_REQUEST,
3190                 .asc = 0x26,
3191                 .ascq = 0x07, /* UNSUPPORTED TARGET DESCRIPTOR TYPE CODE */
3192         },
3193         [TCM_TOO_MANY_SEGMENT_DESCS] = {
3194                 .key = ILLEGAL_REQUEST,
3195                 .asc = 0x26,
3196                 .ascq = 0x08, /* TOO MANY SEGMENT DESCRIPTORS */
3197         },
3198         [TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE] = {
3199                 .key = ILLEGAL_REQUEST,
3200                 .asc = 0x26,
3201                 .ascq = 0x09, /* UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE */
3202         },
3203         [TCM_PARAMETER_LIST_LENGTH_ERROR] = {
3204                 .key = ILLEGAL_REQUEST,
3205                 .asc = 0x1a, /* PARAMETER LIST LENGTH ERROR */
3206         },
3207         [TCM_UNEXPECTED_UNSOLICITED_DATA] = {
3208                 .key = ILLEGAL_REQUEST,
3209                 .asc = 0x0c, /* WRITE ERROR */
3210                 .ascq = 0x0c, /* UNEXPECTED_UNSOLICITED_DATA */
3211         },
3212         [TCM_SERVICE_CRC_ERROR] = {
3213                 .key = ABORTED_COMMAND,
3214                 .asc = 0x47, /* PROTOCOL SERVICE CRC ERROR */
3215                 .ascq = 0x05, /* N/A */
3216         },
3217         [TCM_SNACK_REJECTED] = {
3218                 .key = ABORTED_COMMAND,
3219                 .asc = 0x11, /* READ ERROR */
3220                 .ascq = 0x13, /* FAILED RETRANSMISSION REQUEST */
3221         },
3222         [TCM_WRITE_PROTECTED] = {
3223                 .key = DATA_PROTECT,
3224                 .asc = 0x27, /* WRITE PROTECTED */
3225         },
3226         [TCM_ADDRESS_OUT_OF_RANGE] = {
3227                 .key = ILLEGAL_REQUEST,
3228                 .asc = 0x21, /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3229         },
3230         [TCM_CHECK_CONDITION_UNIT_ATTENTION] = {
3231                 .key = UNIT_ATTENTION,
3232         },
3233         [TCM_CHECK_CONDITION_NOT_READY] = {
3234                 .key = NOT_READY,
3235         },
3236         [TCM_MISCOMPARE_VERIFY] = {
3237                 .key = MISCOMPARE,
3238                 .asc = 0x1d, /* MISCOMPARE DURING VERIFY OPERATION */
3239                 .ascq = 0x00,
3240                 .add_sense_info = true,
3241         },
3242         [TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED] = {
3243                 .key = ABORTED_COMMAND,
3244                 .asc = 0x10,
3245                 .ascq = 0x01, /* LOGICAL BLOCK GUARD CHECK FAILED */
3246                 .add_sense_info = true,
3247         },
3248         [TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED] = {
3249                 .key = ABORTED_COMMAND,
3250                 .asc = 0x10,
3251                 .ascq = 0x02, /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */
3252                 .add_sense_info = true,
3253         },
3254         [TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED] = {
3255                 .key = ABORTED_COMMAND,
3256                 .asc = 0x10,
3257                 .ascq = 0x03, /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */
3258                 .add_sense_info = true,
3259         },
3260         [TCM_COPY_TARGET_DEVICE_NOT_REACHABLE] = {
3261                 .key = COPY_ABORTED,
3262                 .asc = 0x0d,
3263                 .ascq = 0x02, /* COPY TARGET DEVICE NOT REACHABLE */
3264
3265         },
3266         [TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE] = {
3267                 /*
3268                  * Returning ILLEGAL REQUEST would cause immediate IO errors on
3269                  * Solaris initiators.  Returning NOT READY instead means the
3270                  * operations will be retried a finite number of times and we
3271                  * can survive intermittent errors.
3272                  */
3273                 .key = NOT_READY,
3274                 .asc = 0x08, /* LOGICAL UNIT COMMUNICATION FAILURE */
3275         },
3276         [TCM_INSUFFICIENT_REGISTRATION_RESOURCES] = {
3277                 /*
3278                  * From spc4r22 section5.7.7,5.7.8
3279                  * If a PERSISTENT RESERVE OUT command with a REGISTER service action
3280                  * or a REGISTER AND IGNORE EXISTING KEY service action or
3281                  * REGISTER AND MOVE service actionis attempted,
3282                  * but there are insufficient device server resources to complete the
3283                  * operation, then the command shall be terminated with CHECK CONDITION
3284                  * status, with the sense key set to ILLEGAL REQUEST,and the additonal
3285                  * sense code set to INSUFFICIENT REGISTRATION RESOURCES.
3286                  */
3287                 .key = ILLEGAL_REQUEST,
3288                 .asc = 0x55,
3289                 .ascq = 0x04, /* INSUFFICIENT REGISTRATION RESOURCES */
3290         },
3291         [TCM_INVALID_FIELD_IN_COMMAND_IU] = {
3292                 .key = ILLEGAL_REQUEST,
3293                 .asc = 0x0e,
3294                 .ascq = 0x03, /* INVALID FIELD IN COMMAND INFORMATION UNIT */
3295         },
3296 };
3297
3298 /**
3299  * translate_sense_reason - translate a sense reason into T10 key, asc and ascq
3300  * @cmd: SCSI command in which the resulting sense buffer or SCSI status will
3301  *   be stored.
3302  * @reason: LIO sense reason code. If this argument has the value
3303  *   TCM_CHECK_CONDITION_UNIT_ATTENTION, try to dequeue a unit attention. If
3304  *   dequeuing a unit attention fails due to multiple commands being processed
3305  *   concurrently, set the command status to BUSY.
3306  *
3307  * Return: 0 upon success or -EINVAL if the sense buffer is too small.
3308  */
3309 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason)
3310 {
3311         const struct sense_detail *sd;
3312         u8 *buffer = cmd->sense_buffer;
3313         int r = (__force int)reason;
3314         u8 key, asc, ascq;
3315         bool desc_format = target_sense_desc_format(cmd->se_dev);
3316
3317         if (r < ARRAY_SIZE(sense_detail_table) && sense_detail_table[r].key)
3318                 sd = &sense_detail_table[r];
3319         else
3320                 sd = &sense_detail_table[(__force int)
3321                                        TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE];
3322
3323         key = sd->key;
3324         if (reason == TCM_CHECK_CONDITION_UNIT_ATTENTION) {
3325                 if (!core_scsi3_ua_for_check_condition(cmd, &key, &asc,
3326                                                        &ascq)) {
3327                         cmd->scsi_status = SAM_STAT_BUSY;
3328                         return;
3329                 }
3330         } else if (sd->asc == 0) {
3331                 WARN_ON_ONCE(cmd->scsi_asc == 0);
3332                 asc = cmd->scsi_asc;
3333                 ascq = cmd->scsi_ascq;
3334         } else {
3335                 asc = sd->asc;
3336                 ascq = sd->ascq;
3337         }
3338
3339         cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3340         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3341         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER;
3342         scsi_build_sense_buffer(desc_format, buffer, key, asc, ascq);
3343         if (sd->add_sense_info)
3344                 WARN_ON_ONCE(scsi_set_sense_information(buffer,
3345                                                         cmd->scsi_sense_length,
3346                                                         cmd->sense_info) < 0);
3347 }
3348
3349 int
3350 transport_send_check_condition_and_sense(struct se_cmd *cmd,
3351                 sense_reason_t reason, int from_transport)
3352 {
3353         unsigned long flags;
3354
3355         WARN_ON_ONCE(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB);
3356
3357         spin_lock_irqsave(&cmd->t_state_lock, flags);
3358         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3359                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3360                 return 0;
3361         }
3362         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3363         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3364
3365         if (!from_transport)
3366                 translate_sense_reason(cmd, reason);
3367
3368         trace_target_cmd_complete(cmd);
3369         return cmd->se_tfo->queue_status(cmd);
3370 }
3371 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3372
3373 /**
3374  * target_send_busy - Send SCSI BUSY status back to the initiator
3375  * @cmd: SCSI command for which to send a BUSY reply.
3376  *
3377  * Note: Only call this function if target_submit_cmd*() failed.
3378  */
3379 int target_send_busy(struct se_cmd *cmd)
3380 {
3381         WARN_ON_ONCE(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB);
3382
3383         cmd->scsi_status = SAM_STAT_BUSY;
3384         trace_target_cmd_complete(cmd);
3385         return cmd->se_tfo->queue_status(cmd);
3386 }
3387 EXPORT_SYMBOL(target_send_busy);
3388
3389 static void target_tmr_work(struct work_struct *work)
3390 {
3391         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3392         struct se_device *dev = cmd->se_dev;
3393         struct se_tmr_req *tmr = cmd->se_tmr_req;
3394         int ret;
3395
3396         if (cmd->transport_state & CMD_T_ABORTED)
3397                 goto aborted;
3398
3399         switch (tmr->function) {
3400         case TMR_ABORT_TASK:
3401                 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3402                 break;
3403         case TMR_ABORT_TASK_SET:
3404         case TMR_CLEAR_ACA:
3405         case TMR_CLEAR_TASK_SET:
3406                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3407                 break;
3408         case TMR_LUN_RESET:
3409                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3410                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3411                                          TMR_FUNCTION_REJECTED;
3412                 if (tmr->response == TMR_FUNCTION_COMPLETE) {
3413                         target_ua_allocate_lun(cmd->se_sess->se_node_acl,
3414                                                cmd->orig_fe_lun, 0x29,
3415                                                ASCQ_29H_BUS_DEVICE_RESET_FUNCTION_OCCURRED);
3416                 }
3417                 break;
3418         case TMR_TARGET_WARM_RESET:
3419                 tmr->response = TMR_FUNCTION_REJECTED;
3420                 break;
3421         case TMR_TARGET_COLD_RESET:
3422                 tmr->response = TMR_FUNCTION_REJECTED;
3423                 break;
3424         default:
3425                 pr_err("Unknown TMR function: 0x%02x.\n",
3426                                 tmr->function);
3427                 tmr->response = TMR_FUNCTION_REJECTED;
3428                 break;
3429         }
3430
3431         if (cmd->transport_state & CMD_T_ABORTED)
3432                 goto aborted;
3433
3434         cmd->se_tfo->queue_tm_rsp(cmd);
3435
3436         transport_lun_remove_cmd(cmd);
3437         transport_cmd_check_stop_to_fabric(cmd);
3438         return;
3439
3440 aborted:
3441         target_handle_abort(cmd);
3442 }
3443
3444 int transport_generic_handle_tmr(
3445         struct se_cmd *cmd)
3446 {
3447         unsigned long flags;
3448         bool aborted = false;
3449
3450         spin_lock_irqsave(&cmd->t_state_lock, flags);
3451         if (cmd->transport_state & CMD_T_ABORTED) {
3452                 aborted = true;
3453         } else {
3454                 cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3455                 cmd->transport_state |= CMD_T_ACTIVE;
3456         }
3457         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3458
3459         if (aborted) {
3460                 pr_warn_ratelimited("handle_tmr caught CMD_T_ABORTED TMR %d ref_tag: %llu tag: %llu\n",
3461                                     cmd->se_tmr_req->function,
3462                                     cmd->se_tmr_req->ref_task_tag, cmd->tag);
3463                 target_handle_abort(cmd);
3464                 return 0;
3465         }
3466
3467         INIT_WORK(&cmd->work, target_tmr_work);
3468         schedule_work(&cmd->work);
3469         return 0;
3470 }
3471 EXPORT_SYMBOL(transport_generic_handle_tmr);
3472
3473 bool
3474 target_check_wce(struct se_device *dev)
3475 {
3476         bool wce = false;
3477
3478         if (dev->transport->get_write_cache)
3479                 wce = dev->transport->get_write_cache(dev);
3480         else if (dev->dev_attrib.emulate_write_cache > 0)
3481                 wce = true;
3482
3483         return wce;
3484 }
3485
3486 bool
3487 target_check_fua(struct se_device *dev)
3488 {
3489         return target_check_wce(dev) && dev->dev_attrib.emulate_fua_write > 0;
3490 }