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