GNU Linux-libre 5.15.54-gnu
[releases.git] / drivers / scsi / libiscsi.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * iSCSI lib functions
4  *
5  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
6  * Copyright (C) 2004 - 2006 Mike Christie
7  * Copyright (C) 2004 - 2005 Dmitry Yusupov
8  * Copyright (C) 2004 - 2005 Alex Aizman
9  * maintained by open-iscsi@googlegroups.com
10  */
11 #include <linux/types.h>
12 #include <linux/kfifo.h>
13 #include <linux/delay.h>
14 #include <linux/log2.h>
15 #include <linux/slab.h>
16 #include <linux/sched/signal.h>
17 #include <linux/module.h>
18 #include <asm/unaligned.h>
19 #include <net/tcp.h>
20 #include <scsi/scsi_cmnd.h>
21 #include <scsi/scsi_device.h>
22 #include <scsi/scsi_eh.h>
23 #include <scsi/scsi_tcq.h>
24 #include <scsi/scsi_host.h>
25 #include <scsi/scsi.h>
26 #include <scsi/iscsi_proto.h>
27 #include <scsi/scsi_transport.h>
28 #include <scsi/scsi_transport_iscsi.h>
29 #include <scsi/libiscsi.h>
30 #include <trace/events/iscsi.h>
31
32 static int iscsi_dbg_lib_conn;
33 module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int,
34                    S_IRUGO | S_IWUSR);
35 MODULE_PARM_DESC(debug_libiscsi_conn,
36                  "Turn on debugging for connections in libiscsi module. "
37                  "Set to 1 to turn on, and zero to turn off. Default is off.");
38
39 static int iscsi_dbg_lib_session;
40 module_param_named(debug_libiscsi_session, iscsi_dbg_lib_session, int,
41                    S_IRUGO | S_IWUSR);
42 MODULE_PARM_DESC(debug_libiscsi_session,
43                  "Turn on debugging for sessions in libiscsi module. "
44                  "Set to 1 to turn on, and zero to turn off. Default is off.");
45
46 static int iscsi_dbg_lib_eh;
47 module_param_named(debug_libiscsi_eh, iscsi_dbg_lib_eh, int,
48                    S_IRUGO | S_IWUSR);
49 MODULE_PARM_DESC(debug_libiscsi_eh,
50                  "Turn on debugging for error handling in libiscsi module. "
51                  "Set to 1 to turn on, and zero to turn off. Default is off.");
52
53 #define ISCSI_DBG_CONN(_conn, dbg_fmt, arg...)                  \
54         do {                                                    \
55                 if (iscsi_dbg_lib_conn)                         \
56                         iscsi_conn_printk(KERN_INFO, _conn,     \
57                                              "%s " dbg_fmt,     \
58                                              __func__, ##arg);  \
59                 iscsi_dbg_trace(trace_iscsi_dbg_conn,           \
60                                 &(_conn)->cls_conn->dev,        \
61                                 "%s " dbg_fmt, __func__, ##arg);\
62         } while (0);
63
64 #define ISCSI_DBG_SESSION(_session, dbg_fmt, arg...)                    \
65         do {                                                            \
66                 if (iscsi_dbg_lib_session)                              \
67                         iscsi_session_printk(KERN_INFO, _session,       \
68                                              "%s " dbg_fmt,             \
69                                              __func__, ##arg);          \
70                 iscsi_dbg_trace(trace_iscsi_dbg_session,                \
71                                 &(_session)->cls_session->dev,          \
72                                 "%s " dbg_fmt, __func__, ##arg);        \
73         } while (0);
74
75 #define ISCSI_DBG_EH(_session, dbg_fmt, arg...)                         \
76         do {                                                            \
77                 if (iscsi_dbg_lib_eh)                                   \
78                         iscsi_session_printk(KERN_INFO, _session,       \
79                                              "%s " dbg_fmt,             \
80                                              __func__, ##arg);          \
81                 iscsi_dbg_trace(trace_iscsi_dbg_eh,                     \
82                                 &(_session)->cls_session->dev,          \
83                                 "%s " dbg_fmt, __func__, ##arg);        \
84         } while (0);
85
86 inline void iscsi_conn_queue_work(struct iscsi_conn *conn)
87 {
88         struct Scsi_Host *shost = conn->session->host;
89         struct iscsi_host *ihost = shost_priv(shost);
90
91         if (ihost->workq)
92                 queue_work(ihost->workq, &conn->xmitwork);
93 }
94 EXPORT_SYMBOL_GPL(iscsi_conn_queue_work);
95
96 static void __iscsi_update_cmdsn(struct iscsi_session *session,
97                                  uint32_t exp_cmdsn, uint32_t max_cmdsn)
98 {
99         /*
100          * standard specifies this check for when to update expected and
101          * max sequence numbers
102          */
103         if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
104                 return;
105
106         if (exp_cmdsn != session->exp_cmdsn &&
107             !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
108                 session->exp_cmdsn = exp_cmdsn;
109
110         if (max_cmdsn != session->max_cmdsn &&
111             !iscsi_sna_lt(max_cmdsn, session->max_cmdsn))
112                 session->max_cmdsn = max_cmdsn;
113 }
114
115 void iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
116 {
117         __iscsi_update_cmdsn(session, be32_to_cpu(hdr->exp_cmdsn),
118                              be32_to_cpu(hdr->max_cmdsn));
119 }
120 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
121
122 /**
123  * iscsi_prep_data_out_pdu - initialize Data-Out
124  * @task: scsi command task
125  * @r2t: R2T info
126  * @hdr: iscsi data in pdu
127  *
128  * Notes:
129  *      Initialize Data-Out within this R2T sequence and finds
130  *      proper data_offset within this SCSI command.
131  *
132  *      This function is called with connection lock taken.
133  **/
134 void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t,
135                            struct iscsi_data *hdr)
136 {
137         struct iscsi_conn *conn = task->conn;
138         unsigned int left = r2t->data_length - r2t->sent;
139
140         task->hdr_len = sizeof(struct iscsi_data);
141
142         memset(hdr, 0, sizeof(struct iscsi_data));
143         hdr->ttt = r2t->ttt;
144         hdr->datasn = cpu_to_be32(r2t->datasn);
145         r2t->datasn++;
146         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
147         hdr->lun = task->lun;
148         hdr->itt = task->hdr_itt;
149         hdr->exp_statsn = r2t->exp_statsn;
150         hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent);
151         if (left > conn->max_xmit_dlength) {
152                 hton24(hdr->dlength, conn->max_xmit_dlength);
153                 r2t->data_count = conn->max_xmit_dlength;
154                 hdr->flags = 0;
155         } else {
156                 hton24(hdr->dlength, left);
157                 r2t->data_count = left;
158                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
159         }
160         conn->dataout_pdus_cnt++;
161 }
162 EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu);
163
164 static int iscsi_add_hdr(struct iscsi_task *task, unsigned len)
165 {
166         unsigned exp_len = task->hdr_len + len;
167
168         if (exp_len > task->hdr_max) {
169                 WARN_ON(1);
170                 return -EINVAL;
171         }
172
173         WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */
174         task->hdr_len = exp_len;
175         return 0;
176 }
177
178 /*
179  * make an extended cdb AHS
180  */
181 static int iscsi_prep_ecdb_ahs(struct iscsi_task *task)
182 {
183         struct scsi_cmnd *cmd = task->sc;
184         unsigned rlen, pad_len;
185         unsigned short ahslength;
186         struct iscsi_ecdb_ahdr *ecdb_ahdr;
187         int rc;
188
189         ecdb_ahdr = iscsi_next_hdr(task);
190         rlen = cmd->cmd_len - ISCSI_CDB_SIZE;
191
192         BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb));
193         ahslength = rlen + sizeof(ecdb_ahdr->reserved);
194
195         pad_len = iscsi_padding(rlen);
196
197         rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) +
198                            sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len);
199         if (rc)
200                 return rc;
201
202         if (pad_len)
203                 memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len);
204
205         ecdb_ahdr->ahslength = cpu_to_be16(ahslength);
206         ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB;
207         ecdb_ahdr->reserved = 0;
208         memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen);
209
210         ISCSI_DBG_SESSION(task->conn->session,
211                           "iscsi_prep_ecdb_ahs: varlen_cdb_len %d "
212                           "rlen %d pad_len %d ahs_length %d iscsi_headers_size "
213                           "%u\n", cmd->cmd_len, rlen, pad_len, ahslength,
214                           task->hdr_len);
215         return 0;
216 }
217
218 /**
219  * iscsi_check_tmf_restrictions - check if a task is affected by TMF
220  * @task: iscsi task
221  * @opcode: opcode to check for
222  *
223  * During TMF a task has to be checked if it's affected.
224  * All unrelated I/O can be passed through, but I/O to the
225  * affected LUN should be restricted.
226  * If 'fast_abort' is set we won't be sending any I/O to the
227  * affected LUN.
228  * Otherwise the target is waiting for all TTTs to be completed,
229  * so we have to send all outstanding Data-Out PDUs to the target.
230  */
231 static int iscsi_check_tmf_restrictions(struct iscsi_task *task, int opcode)
232 {
233         struct iscsi_session *session = task->conn->session;
234         struct iscsi_tm *tmf = &session->tmhdr;
235         u64 hdr_lun;
236
237         if (session->tmf_state == TMF_INITIAL)
238                 return 0;
239
240         if ((tmf->opcode & ISCSI_OPCODE_MASK) != ISCSI_OP_SCSI_TMFUNC)
241                 return 0;
242
243         switch (ISCSI_TM_FUNC_VALUE(tmf)) {
244         case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
245                 /*
246                  * Allow PDUs for unrelated LUNs
247                  */
248                 hdr_lun = scsilun_to_int(&tmf->lun);
249                 if (hdr_lun != task->sc->device->lun)
250                         return 0;
251                 fallthrough;
252         case ISCSI_TM_FUNC_TARGET_WARM_RESET:
253                 /*
254                  * Fail all SCSI cmd PDUs
255                  */
256                 if (opcode != ISCSI_OP_SCSI_DATA_OUT) {
257                         iscsi_session_printk(KERN_INFO, session,
258                                              "task [op %x itt 0x%x/0x%x] rejected.\n",
259                                              opcode, task->itt, task->hdr_itt);
260                         return -EACCES;
261                 }
262                 /*
263                  * And also all data-out PDUs in response to R2T
264                  * if fast_abort is set.
265                  */
266                 if (session->fast_abort) {
267                         iscsi_session_printk(KERN_INFO, session,
268                                              "task [op %x itt 0x%x/0x%x] fast abort.\n",
269                                              opcode, task->itt, task->hdr_itt);
270                         return -EACCES;
271                 }
272                 break;
273         case ISCSI_TM_FUNC_ABORT_TASK:
274                 /*
275                  * the caller has already checked if the task
276                  * they want to abort was in the pending queue so if
277                  * we are here the cmd pdu has gone out already, and
278                  * we will only hit this for data-outs
279                  */
280                 if (opcode == ISCSI_OP_SCSI_DATA_OUT &&
281                     task->hdr_itt == tmf->rtt) {
282                         ISCSI_DBG_SESSION(session,
283                                           "Preventing task %x/%x from sending "
284                                           "data-out due to abort task in "
285                                           "progress\n", task->itt,
286                                           task->hdr_itt);
287                         return -EACCES;
288                 }
289                 break;
290         }
291
292         return 0;
293 }
294
295 /**
296  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
297  * @task: iscsi task
298  *
299  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
300  * fields like dlength or final based on how much data it sends
301  */
302 static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task)
303 {
304         struct iscsi_conn *conn = task->conn;
305         struct iscsi_session *session = conn->session;
306         struct scsi_cmnd *sc = task->sc;
307         struct iscsi_scsi_req *hdr;
308         unsigned hdrlength, cmd_len, transfer_length;
309         itt_t itt;
310         int rc;
311
312         rc = iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_CMD);
313         if (rc)
314                 return rc;
315
316         if (conn->session->tt->alloc_pdu) {
317                 rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_CMD);
318                 if (rc)
319                         return rc;
320         }
321         hdr = (struct iscsi_scsi_req *)task->hdr;
322         itt = hdr->itt;
323         memset(hdr, 0, sizeof(*hdr));
324
325         if (session->tt->parse_pdu_itt)
326                 hdr->itt = task->hdr_itt = itt;
327         else
328                 hdr->itt = task->hdr_itt = build_itt(task->itt,
329                                                      task->conn->session->age);
330         task->hdr_len = 0;
331         rc = iscsi_add_hdr(task, sizeof(*hdr));
332         if (rc)
333                 return rc;
334         hdr->opcode = ISCSI_OP_SCSI_CMD;
335         hdr->flags = ISCSI_ATTR_SIMPLE;
336         int_to_scsilun(sc->device->lun, &hdr->lun);
337         task->lun = hdr->lun;
338         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
339         cmd_len = sc->cmd_len;
340         if (cmd_len < ISCSI_CDB_SIZE)
341                 memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len);
342         else if (cmd_len > ISCSI_CDB_SIZE) {
343                 rc = iscsi_prep_ecdb_ahs(task);
344                 if (rc)
345                         return rc;
346                 cmd_len = ISCSI_CDB_SIZE;
347         }
348         memcpy(hdr->cdb, sc->cmnd, cmd_len);
349
350         task->imm_count = 0;
351         if (scsi_get_prot_op(sc) != SCSI_PROT_NORMAL)
352                 task->protected = true;
353
354         transfer_length = scsi_transfer_length(sc);
355         hdr->data_length = cpu_to_be32(transfer_length);
356         if (sc->sc_data_direction == DMA_TO_DEVICE) {
357                 struct iscsi_r2t_info *r2t = &task->unsol_r2t;
358
359                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
360                 /*
361                  * Write counters:
362                  *
363                  *      imm_count       bytes to be sent right after
364                  *                      SCSI PDU Header
365                  *
366                  *      unsol_count     bytes(as Data-Out) to be sent
367                  *                      without R2T ack right after
368                  *                      immediate data
369                  *
370                  *      r2t data_length bytes to be sent via R2T ack's
371                  *
372                  *      pad_count       bytes to be sent as zero-padding
373                  */
374                 memset(r2t, 0, sizeof(*r2t));
375
376                 if (session->imm_data_en) {
377                         if (transfer_length >= session->first_burst)
378                                 task->imm_count = min(session->first_burst,
379                                                         conn->max_xmit_dlength);
380                         else
381                                 task->imm_count = min(transfer_length,
382                                                       conn->max_xmit_dlength);
383                         hton24(hdr->dlength, task->imm_count);
384                 } else
385                         zero_data(hdr->dlength);
386
387                 if (!session->initial_r2t_en) {
388                         r2t->data_length = min(session->first_burst,
389                                                transfer_length) -
390                                                task->imm_count;
391                         r2t->data_offset = task->imm_count;
392                         r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
393                         r2t->exp_statsn = cpu_to_be32(conn->exp_statsn);
394                 }
395
396                 if (!task->unsol_r2t.data_length)
397                         /* No unsolicit Data-Out's */
398                         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
399         } else {
400                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
401                 zero_data(hdr->dlength);
402
403                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
404                         hdr->flags |= ISCSI_FLAG_CMD_READ;
405         }
406
407         /* calculate size of additional header segments (AHSs) */
408         hdrlength = task->hdr_len - sizeof(*hdr);
409
410         WARN_ON(hdrlength & (ISCSI_PAD_LEN-1));
411         hdrlength /= ISCSI_PAD_LEN;
412
413         WARN_ON(hdrlength >= 256);
414         hdr->hlength = hdrlength & 0xFF;
415         hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn);
416
417         if (session->tt->init_task && session->tt->init_task(task))
418                 return -EIO;
419
420         task->state = ISCSI_TASK_RUNNING;
421         session->cmdsn++;
422
423         conn->scsicmd_pdus_cnt++;
424         ISCSI_DBG_SESSION(session, "iscsi prep [%s cid %d sc %p cdb 0x%x "
425                           "itt 0x%x len %d cmdsn %d win %d]\n",
426                           sc->sc_data_direction == DMA_TO_DEVICE ?
427                           "write" : "read", conn->id, sc, sc->cmnd[0],
428                           task->itt, transfer_length,
429                           session->cmdsn,
430                           session->max_cmdsn - session->exp_cmdsn + 1);
431         return 0;
432 }
433
434 /**
435  * iscsi_free_task - free a task
436  * @task: iscsi cmd task
437  *
438  * Must be called with session back_lock.
439  * This function returns the scsi command to scsi-ml or cleans
440  * up mgmt tasks then returns the task to the pool.
441  */
442 static void iscsi_free_task(struct iscsi_task *task)
443 {
444         struct iscsi_conn *conn = task->conn;
445         struct iscsi_session *session = conn->session;
446         struct scsi_cmnd *sc = task->sc;
447         int oldstate = task->state;
448
449         ISCSI_DBG_SESSION(session, "freeing task itt 0x%x state %d sc %p\n",
450                           task->itt, task->state, task->sc);
451
452         session->tt->cleanup_task(task);
453         task->state = ISCSI_TASK_FREE;
454         task->sc = NULL;
455         /*
456          * login task is preallocated so do not free
457          */
458         if (conn->login_task == task)
459                 return;
460
461         kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*));
462
463         if (sc) {
464                 /* SCSI eh reuses commands to verify us */
465                 sc->SCp.ptr = NULL;
466                 /*
467                  * queue command may call this to free the task, so
468                  * it will decide how to return sc to scsi-ml.
469                  */
470                 if (oldstate != ISCSI_TASK_REQUEUE_SCSIQ)
471                         sc->scsi_done(sc);
472         }
473 }
474
475 void __iscsi_get_task(struct iscsi_task *task)
476 {
477         refcount_inc(&task->refcount);
478 }
479 EXPORT_SYMBOL_GPL(__iscsi_get_task);
480
481 void __iscsi_put_task(struct iscsi_task *task)
482 {
483         if (refcount_dec_and_test(&task->refcount))
484                 iscsi_free_task(task);
485 }
486 EXPORT_SYMBOL_GPL(__iscsi_put_task);
487
488 void iscsi_put_task(struct iscsi_task *task)
489 {
490         struct iscsi_session *session = task->conn->session;
491
492         /* regular RX path uses back_lock */
493         spin_lock_bh(&session->back_lock);
494         __iscsi_put_task(task);
495         spin_unlock_bh(&session->back_lock);
496 }
497 EXPORT_SYMBOL_GPL(iscsi_put_task);
498
499 /**
500  * iscsi_complete_task - finish a task
501  * @task: iscsi cmd task
502  * @state: state to complete task with
503  *
504  * Must be called with session back_lock.
505  */
506 static void iscsi_complete_task(struct iscsi_task *task, int state)
507 {
508         struct iscsi_conn *conn = task->conn;
509
510         ISCSI_DBG_SESSION(conn->session,
511                           "complete task itt 0x%x state %d sc %p\n",
512                           task->itt, task->state, task->sc);
513         if (task->state == ISCSI_TASK_COMPLETED ||
514             task->state == ISCSI_TASK_ABRT_TMF ||
515             task->state == ISCSI_TASK_ABRT_SESS_RECOV ||
516             task->state == ISCSI_TASK_REQUEUE_SCSIQ)
517                 return;
518         WARN_ON_ONCE(task->state == ISCSI_TASK_FREE);
519         task->state = state;
520
521         if (READ_ONCE(conn->ping_task) == task)
522                 WRITE_ONCE(conn->ping_task, NULL);
523
524         /* release get from queueing */
525         __iscsi_put_task(task);
526 }
527
528 /**
529  * iscsi_complete_scsi_task - finish scsi task normally
530  * @task: iscsi task for scsi cmd
531  * @exp_cmdsn: expected cmd sn in cpu format
532  * @max_cmdsn: max cmd sn in cpu format
533  *
534  * This is used when drivers do not need or cannot perform
535  * lower level pdu processing.
536  *
537  * Called with session back_lock
538  */
539 void iscsi_complete_scsi_task(struct iscsi_task *task,
540                               uint32_t exp_cmdsn, uint32_t max_cmdsn)
541 {
542         struct iscsi_conn *conn = task->conn;
543
544         ISCSI_DBG_SESSION(conn->session, "[itt 0x%x]\n", task->itt);
545
546         conn->last_recv = jiffies;
547         __iscsi_update_cmdsn(conn->session, exp_cmdsn, max_cmdsn);
548         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
549 }
550 EXPORT_SYMBOL_GPL(iscsi_complete_scsi_task);
551
552 /*
553  * Must be called with back and frwd lock
554  */
555 static bool cleanup_queued_task(struct iscsi_task *task)
556 {
557         struct iscsi_conn *conn = task->conn;
558         bool early_complete = false;
559
560         /* Bad target might have completed task while it was still running */
561         if (task->state == ISCSI_TASK_COMPLETED)
562                 early_complete = true;
563
564         if (!list_empty(&task->running)) {
565                 list_del_init(&task->running);
566                 /*
567                  * If it's on a list but still running, this could be from
568                  * a bad target sending a rsp early, cleanup from a TMF, or
569                  * session recovery.
570                  */
571                 if (task->state == ISCSI_TASK_RUNNING ||
572                     task->state == ISCSI_TASK_COMPLETED)
573                         __iscsi_put_task(task);
574         }
575
576         if (conn->session->running_aborted_task == task) {
577                 conn->session->running_aborted_task = NULL;
578                 __iscsi_put_task(task);
579         }
580
581         if (conn->task == task) {
582                 conn->task = NULL;
583                 __iscsi_put_task(task);
584         }
585
586         return early_complete;
587 }
588
589 /*
590  * session frwd lock must be held and if not called for a task that is still
591  * pending or from the xmit thread, then xmit thread must be suspended
592  */
593 static void fail_scsi_task(struct iscsi_task *task, int err)
594 {
595         struct iscsi_conn *conn = task->conn;
596         struct scsi_cmnd *sc;
597         int state;
598
599         spin_lock_bh(&conn->session->back_lock);
600         if (cleanup_queued_task(task)) {
601                 spin_unlock_bh(&conn->session->back_lock);
602                 return;
603         }
604
605         if (task->state == ISCSI_TASK_PENDING) {
606                 /*
607                  * cmd never made it to the xmit thread, so we should not count
608                  * the cmd in the sequencing
609                  */
610                 conn->session->queued_cmdsn--;
611                 /* it was never sent so just complete like normal */
612                 state = ISCSI_TASK_COMPLETED;
613         } else if (err == DID_TRANSPORT_DISRUPTED)
614                 state = ISCSI_TASK_ABRT_SESS_RECOV;
615         else
616                 state = ISCSI_TASK_ABRT_TMF;
617
618         sc = task->sc;
619         sc->result = err << 16;
620         scsi_set_resid(sc, scsi_bufflen(sc));
621         iscsi_complete_task(task, state);
622         spin_unlock_bh(&conn->session->back_lock);
623 }
624
625 static int iscsi_prep_mgmt_task(struct iscsi_conn *conn,
626                                 struct iscsi_task *task)
627 {
628         struct iscsi_session *session = conn->session;
629         struct iscsi_hdr *hdr = task->hdr;
630         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
631         uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
632
633         if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
634                 return -ENOTCONN;
635
636         if (opcode != ISCSI_OP_LOGIN && opcode != ISCSI_OP_TEXT)
637                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
638         /*
639          * pre-format CmdSN for outgoing PDU.
640          */
641         nop->cmdsn = cpu_to_be32(session->cmdsn);
642         if (hdr->itt != RESERVED_ITT) {
643                 /*
644                  * TODO: We always use immediate for normal session pdus.
645                  * If we start to send tmfs or nops as non-immediate then
646                  * we should start checking the cmdsn numbers for mgmt tasks.
647                  *
648                  * During discovery sessions iscsid sends TEXT as non immediate,
649                  * but we always only send one PDU at a time.
650                  */
651                 if (conn->c_stage == ISCSI_CONN_STARTED &&
652                     !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
653                         session->queued_cmdsn++;
654                         session->cmdsn++;
655                 }
656         }
657
658         if (session->tt->init_task && session->tt->init_task(task))
659                 return -EIO;
660
661         if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT)
662                 session->state = ISCSI_STATE_LOGGING_OUT;
663
664         task->state = ISCSI_TASK_RUNNING;
665         ISCSI_DBG_SESSION(session, "mgmtpdu [op 0x%x hdr->itt 0x%x "
666                           "datalen %d]\n", hdr->opcode & ISCSI_OPCODE_MASK,
667                           hdr->itt, task->data_count);
668         return 0;
669 }
670
671 static struct iscsi_task *
672 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
673                       char *data, uint32_t data_size)
674 {
675         struct iscsi_session *session = conn->session;
676         struct iscsi_host *ihost = shost_priv(session->host);
677         uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
678         struct iscsi_task *task;
679         itt_t itt;
680
681         if (session->state == ISCSI_STATE_TERMINATE ||
682             !test_bit(ISCSI_CONN_FLAG_BOUND, &conn->flags))
683                 return NULL;
684
685         if (opcode == ISCSI_OP_LOGIN || opcode == ISCSI_OP_TEXT) {
686                 /*
687                  * Login and Text are sent serially, in
688                  * request-followed-by-response sequence.
689                  * Same task can be used. Same ITT must be used.
690                  * Note that login_task is preallocated at conn_create().
691                  */
692                 if (conn->login_task->state != ISCSI_TASK_FREE) {
693                         iscsi_conn_printk(KERN_ERR, conn, "Login/Text in "
694                                           "progress. Cannot start new task.\n");
695                         return NULL;
696                 }
697
698                 if (data_size > ISCSI_DEF_MAX_RECV_SEG_LEN) {
699                         iscsi_conn_printk(KERN_ERR, conn, "Invalid buffer len of %u for login task. Max len is %u\n", data_size, ISCSI_DEF_MAX_RECV_SEG_LEN);
700                         return NULL;
701                 }
702
703                 task = conn->login_task;
704         } else {
705                 if (session->state != ISCSI_STATE_LOGGED_IN)
706                         return NULL;
707
708                 if (data_size != 0) {
709                         iscsi_conn_printk(KERN_ERR, conn, "Can not send data buffer of len %u for op 0x%x\n", data_size, opcode);
710                         return NULL;
711                 }
712
713                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
714                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
715
716                 if (!kfifo_out(&session->cmdpool.queue,
717                                  (void*)&task, sizeof(void*)))
718                         return NULL;
719         }
720         /*
721          * released in complete pdu for task we expect a response for, and
722          * released by the lld when it has transmitted the task for
723          * pdus we do not expect a response for.
724          */
725         refcount_set(&task->refcount, 1);
726         task->conn = conn;
727         task->sc = NULL;
728         INIT_LIST_HEAD(&task->running);
729         task->state = ISCSI_TASK_PENDING;
730
731         if (data_size) {
732                 memcpy(task->data, data, data_size);
733                 task->data_count = data_size;
734         } else
735                 task->data_count = 0;
736
737         if (conn->session->tt->alloc_pdu) {
738                 if (conn->session->tt->alloc_pdu(task, hdr->opcode)) {
739                         iscsi_conn_printk(KERN_ERR, conn, "Could not allocate "
740                                          "pdu for mgmt task.\n");
741                         goto free_task;
742                 }
743         }
744
745         itt = task->hdr->itt;
746         task->hdr_len = sizeof(struct iscsi_hdr);
747         memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr));
748
749         if (hdr->itt != RESERVED_ITT) {
750                 if (session->tt->parse_pdu_itt)
751                         task->hdr->itt = itt;
752                 else
753                         task->hdr->itt = build_itt(task->itt,
754                                                    task->conn->session->age);
755         }
756
757         if (unlikely(READ_ONCE(conn->ping_task) == INVALID_SCSI_TASK))
758                 WRITE_ONCE(conn->ping_task, task);
759
760         if (!ihost->workq) {
761                 if (iscsi_prep_mgmt_task(conn, task))
762                         goto free_task;
763
764                 if (session->tt->xmit_task(task))
765                         goto free_task;
766         } else {
767                 list_add_tail(&task->running, &conn->mgmtqueue);
768                 iscsi_conn_queue_work(conn);
769         }
770
771         return task;
772
773 free_task:
774         /* regular RX path uses back_lock */
775         spin_lock(&session->back_lock);
776         __iscsi_put_task(task);
777         spin_unlock(&session->back_lock);
778         return NULL;
779 }
780
781 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
782                         char *data, uint32_t data_size)
783 {
784         struct iscsi_conn *conn = cls_conn->dd_data;
785         struct iscsi_session *session = conn->session;
786         int err = 0;
787
788         spin_lock_bh(&session->frwd_lock);
789         if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
790                 err = -EPERM;
791         spin_unlock_bh(&session->frwd_lock);
792         return err;
793 }
794 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
795
796 /**
797  * iscsi_scsi_cmd_rsp - SCSI Command Response processing
798  * @conn: iscsi connection
799  * @hdr: iscsi header
800  * @task: scsi command task
801  * @data: cmd data buffer
802  * @datalen: len of buffer
803  *
804  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
805  * then completes the command and task. called under back_lock
806  **/
807 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
808                                struct iscsi_task *task, char *data,
809                                int datalen)
810 {
811         struct iscsi_scsi_rsp *rhdr = (struct iscsi_scsi_rsp *)hdr;
812         struct iscsi_session *session = conn->session;
813         struct scsi_cmnd *sc = task->sc;
814
815         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
816         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
817
818         sc->result = (DID_OK << 16) | rhdr->cmd_status;
819
820         if (task->protected) {
821                 sector_t sector;
822                 u8 ascq;
823
824                 /**
825                  * Transports that didn't implement check_protection
826                  * callback but still published T10-PI support to scsi-mid
827                  * deserve this BUG_ON.
828                  **/
829                 BUG_ON(!session->tt->check_protection);
830
831                 ascq = session->tt->check_protection(task, &sector);
832                 if (ascq) {
833                         scsi_build_sense(sc, 1, ILLEGAL_REQUEST, 0x10, ascq);
834                         scsi_set_sense_information(sc->sense_buffer,
835                                                    SCSI_SENSE_BUFFERSIZE,
836                                                    sector);
837                         goto out;
838                 }
839         }
840
841         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
842                 sc->result = DID_ERROR << 16;
843                 goto out;
844         }
845
846         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
847                 uint16_t senselen;
848
849                 if (datalen < 2) {
850 invalid_datalen:
851                         iscsi_conn_printk(KERN_ERR,  conn,
852                                          "Got CHECK_CONDITION but invalid data "
853                                          "buffer size of %d\n", datalen);
854                         sc->result = DID_BAD_TARGET << 16;
855                         goto out;
856                 }
857
858                 senselen = get_unaligned_be16(data);
859                 if (datalen < senselen)
860                         goto invalid_datalen;
861
862                 memcpy(sc->sense_buffer, data + 2,
863                        min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
864                 ISCSI_DBG_SESSION(session, "copied %d bytes of sense\n",
865                                   min_t(uint16_t, senselen,
866                                   SCSI_SENSE_BUFFERSIZE));
867         }
868
869         if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW |
870                            ISCSI_FLAG_CMD_BIDI_OVERFLOW)) {
871                 sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
872         }
873
874         if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW |
875                            ISCSI_FLAG_CMD_OVERFLOW)) {
876                 int res_count = be32_to_cpu(rhdr->residual_count);
877
878                 if (res_count > 0 &&
879                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
880                      res_count <= scsi_bufflen(sc)))
881                         /* write side for bidi or uni-io set_resid */
882                         scsi_set_resid(sc, res_count);
883                 else
884                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
885         }
886 out:
887         ISCSI_DBG_SESSION(session, "cmd rsp done [sc %p res %d itt 0x%x]\n",
888                           sc, sc->result, task->itt);
889         conn->scsirsp_pdus_cnt++;
890         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
891 }
892
893 /**
894  * iscsi_data_in_rsp - SCSI Data-In Response processing
895  * @conn: iscsi connection
896  * @hdr:  iscsi pdu
897  * @task: scsi command task
898  *
899  * iscsi_data_in_rsp sets up the scsi_cmnd fields based on the data received
900  * then completes the command and task. called under back_lock
901  **/
902 static void
903 iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
904                   struct iscsi_task *task)
905 {
906         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr;
907         struct scsi_cmnd *sc = task->sc;
908
909         if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS))
910                 return;
911
912         iscsi_update_cmdsn(conn->session, (struct iscsi_nopin *)hdr);
913         sc->result = (DID_OK << 16) | rhdr->cmd_status;
914         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
915         if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW |
916                            ISCSI_FLAG_DATA_OVERFLOW)) {
917                 int res_count = be32_to_cpu(rhdr->residual_count);
918
919                 if (res_count > 0 &&
920                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
921                      res_count <= sc->sdb.length))
922                         scsi_set_resid(sc, res_count);
923                 else
924                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
925         }
926
927         ISCSI_DBG_SESSION(conn->session, "data in with status done "
928                           "[sc %p res %d itt 0x%x]\n",
929                           sc, sc->result, task->itt);
930         conn->scsirsp_pdus_cnt++;
931         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
932 }
933
934 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
935 {
936         struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
937         struct iscsi_session *session = conn->session;
938
939         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
940         conn->tmfrsp_pdus_cnt++;
941
942         if (session->tmf_state != TMF_QUEUED)
943                 return;
944
945         if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
946                 session->tmf_state = TMF_SUCCESS;
947         else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
948                 session->tmf_state = TMF_NOT_FOUND;
949         else
950                 session->tmf_state = TMF_FAILED;
951         wake_up(&session->ehwait);
952 }
953
954 static int iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr)
955 {
956         struct iscsi_nopout hdr;
957         struct iscsi_task *task;
958
959         if (!rhdr) {
960                 if (READ_ONCE(conn->ping_task))
961                         return -EINVAL;
962                 WRITE_ONCE(conn->ping_task, INVALID_SCSI_TASK);
963         }
964
965         memset(&hdr, 0, sizeof(struct iscsi_nopout));
966         hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE;
967         hdr.flags = ISCSI_FLAG_CMD_FINAL;
968
969         if (rhdr) {
970                 hdr.lun = rhdr->lun;
971                 hdr.ttt = rhdr->ttt;
972                 hdr.itt = RESERVED_ITT;
973         } else
974                 hdr.ttt = RESERVED_ITT;
975
976         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0);
977         if (!task) {
978                 if (!rhdr)
979                         WRITE_ONCE(conn->ping_task, NULL);
980                 iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n");
981                 return -EIO;
982         } else if (!rhdr) {
983                 /* only track our nops */
984                 conn->last_ping = jiffies;
985         }
986
987         return 0;
988 }
989
990 /**
991  * iscsi_nop_out_rsp - SCSI NOP Response processing
992  * @task: scsi command task
993  * @nop: the nop structure
994  * @data: where to put the data
995  * @datalen: length of data
996  *
997  * iscsi_nop_out_rsp handles nop response from use or
998  * from user space. called under back_lock
999  **/
1000 static int iscsi_nop_out_rsp(struct iscsi_task *task,
1001                              struct iscsi_nopin *nop, char *data, int datalen)
1002 {
1003         struct iscsi_conn *conn = task->conn;
1004         int rc = 0;
1005
1006         if (READ_ONCE(conn->ping_task) != task) {
1007                 /*
1008                  * If this is not in response to one of our
1009                  * nops then it must be from userspace.
1010                  */
1011                 if (iscsi_recv_pdu(conn->cls_conn, (struct iscsi_hdr *)nop,
1012                                    data, datalen))
1013                         rc = ISCSI_ERR_CONN_FAILED;
1014         } else
1015                 mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout);
1016         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1017         return rc;
1018 }
1019
1020 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1021                                char *data, int datalen)
1022 {
1023         struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
1024         struct iscsi_hdr rejected_pdu;
1025         int opcode, rc = 0;
1026
1027         conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
1028
1029         if (ntoh24(reject->dlength) > datalen ||
1030             ntoh24(reject->dlength) < sizeof(struct iscsi_hdr)) {
1031                 iscsi_conn_printk(KERN_ERR, conn, "Cannot handle rejected "
1032                                   "pdu. Invalid data length (pdu dlength "
1033                                   "%u, datalen %d\n", ntoh24(reject->dlength),
1034                                   datalen);
1035                 return ISCSI_ERR_PROTO;
1036         }
1037         memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
1038         opcode = rejected_pdu.opcode & ISCSI_OPCODE_MASK;
1039
1040         switch (reject->reason) {
1041         case ISCSI_REASON_DATA_DIGEST_ERROR:
1042                 iscsi_conn_printk(KERN_ERR, conn,
1043                                   "pdu (op 0x%x itt 0x%x) rejected "
1044                                   "due to DataDigest error.\n",
1045                                   opcode, rejected_pdu.itt);
1046                 break;
1047         case ISCSI_REASON_IMM_CMD_REJECT:
1048                 iscsi_conn_printk(KERN_ERR, conn,
1049                                   "pdu (op 0x%x itt 0x%x) rejected. Too many "
1050                                   "immediate commands.\n",
1051                                   opcode, rejected_pdu.itt);
1052                 /*
1053                  * We only send one TMF at a time so if the target could not
1054                  * handle it, then it should get fixed (RFC mandates that
1055                  * a target can handle one immediate TMF per conn).
1056                  *
1057                  * For nops-outs, we could have sent more than one if
1058                  * the target is sending us lots of nop-ins
1059                  */
1060                 if (opcode != ISCSI_OP_NOOP_OUT)
1061                         return 0;
1062
1063                 if (rejected_pdu.itt == cpu_to_be32(ISCSI_RESERVED_TAG)) {
1064                         /*
1065                          * nop-out in response to target's nop-out rejected.
1066                          * Just resend.
1067                          */
1068                         /* In RX path we are under back lock */
1069                         spin_unlock(&conn->session->back_lock);
1070                         spin_lock(&conn->session->frwd_lock);
1071                         iscsi_send_nopout(conn,
1072                                           (struct iscsi_nopin*)&rejected_pdu);
1073                         spin_unlock(&conn->session->frwd_lock);
1074                         spin_lock(&conn->session->back_lock);
1075                 } else {
1076                         struct iscsi_task *task;
1077                         /*
1078                          * Our nop as ping got dropped. We know the target
1079                          * and transport are ok so just clean up
1080                          */
1081                         task = iscsi_itt_to_task(conn, rejected_pdu.itt);
1082                         if (!task) {
1083                                 iscsi_conn_printk(KERN_ERR, conn,
1084                                                  "Invalid pdu reject. Could "
1085                                                  "not lookup rejected task.\n");
1086                                 rc = ISCSI_ERR_BAD_ITT;
1087                         } else
1088                                 rc = iscsi_nop_out_rsp(task,
1089                                         (struct iscsi_nopin*)&rejected_pdu,
1090                                         NULL, 0);
1091                 }
1092                 break;
1093         default:
1094                 iscsi_conn_printk(KERN_ERR, conn,
1095                                   "pdu (op 0x%x itt 0x%x) rejected. Reason "
1096                                   "code 0x%x\n", rejected_pdu.opcode,
1097                                   rejected_pdu.itt, reject->reason);
1098                 break;
1099         }
1100         return rc;
1101 }
1102
1103 /**
1104  * iscsi_itt_to_task - look up task by itt
1105  * @conn: iscsi connection
1106  * @itt: itt
1107  *
1108  * This should be used for mgmt tasks like login and nops, or if
1109  * the LDD's itt space does not include the session age.
1110  *
1111  * The session back_lock must be held.
1112  */
1113 struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
1114 {
1115         struct iscsi_session *session = conn->session;
1116         int i;
1117
1118         if (itt == RESERVED_ITT)
1119                 return NULL;
1120
1121         if (session->tt->parse_pdu_itt)
1122                 session->tt->parse_pdu_itt(conn, itt, &i, NULL);
1123         else
1124                 i = get_itt(itt);
1125         if (i >= session->cmds_max)
1126                 return NULL;
1127
1128         return session->cmds[i];
1129 }
1130 EXPORT_SYMBOL_GPL(iscsi_itt_to_task);
1131
1132 /**
1133  * __iscsi_complete_pdu - complete pdu
1134  * @conn: iscsi conn
1135  * @hdr: iscsi header
1136  * @data: data buffer
1137  * @datalen: len of data buffer
1138  *
1139  * Completes pdu processing by freeing any resources allocated at
1140  * queuecommand or send generic. session back_lock must be held and verify
1141  * itt must have been called.
1142  */
1143 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1144                          char *data, int datalen)
1145 {
1146         struct iscsi_session *session = conn->session;
1147         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
1148         struct iscsi_task *task;
1149         uint32_t itt;
1150
1151         conn->last_recv = jiffies;
1152         rc = iscsi_verify_itt(conn, hdr->itt);
1153         if (rc)
1154                 return rc;
1155
1156         if (hdr->itt != RESERVED_ITT)
1157                 itt = get_itt(hdr->itt);
1158         else
1159                 itt = ~0U;
1160
1161         ISCSI_DBG_SESSION(session, "[op 0x%x cid %d itt 0x%x len %d]\n",
1162                           opcode, conn->id, itt, datalen);
1163
1164         if (itt == ~0U) {
1165                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1166
1167                 switch(opcode) {
1168                 case ISCSI_OP_NOOP_IN:
1169                         if (datalen) {
1170                                 rc = ISCSI_ERR_PROTO;
1171                                 break;
1172                         }
1173
1174                         if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
1175                                 break;
1176
1177                         /* In RX path we are under back lock */
1178                         spin_unlock(&session->back_lock);
1179                         spin_lock(&session->frwd_lock);
1180                         iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr);
1181                         spin_unlock(&session->frwd_lock);
1182                         spin_lock(&session->back_lock);
1183                         break;
1184                 case ISCSI_OP_REJECT:
1185                         rc = iscsi_handle_reject(conn, hdr, data, datalen);
1186                         break;
1187                 case ISCSI_OP_ASYNC_EVENT:
1188                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1189                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1190                                 rc = ISCSI_ERR_CONN_FAILED;
1191                         break;
1192                 default:
1193                         rc = ISCSI_ERR_BAD_OPCODE;
1194                         break;
1195                 }
1196                 goto out;
1197         }
1198
1199         switch(opcode) {
1200         case ISCSI_OP_SCSI_CMD_RSP:
1201         case ISCSI_OP_SCSI_DATA_IN:
1202                 task = iscsi_itt_to_ctask(conn, hdr->itt);
1203                 if (!task)
1204                         return ISCSI_ERR_BAD_ITT;
1205                 task->last_xfer = jiffies;
1206                 break;
1207         case ISCSI_OP_R2T:
1208                 /*
1209                  * LLD handles R2Ts if they need to.
1210                  */
1211                 return 0;
1212         case ISCSI_OP_LOGOUT_RSP:
1213         case ISCSI_OP_LOGIN_RSP:
1214         case ISCSI_OP_TEXT_RSP:
1215         case ISCSI_OP_SCSI_TMFUNC_RSP:
1216         case ISCSI_OP_NOOP_IN:
1217                 task = iscsi_itt_to_task(conn, hdr->itt);
1218                 if (!task)
1219                         return ISCSI_ERR_BAD_ITT;
1220                 break;
1221         default:
1222                 return ISCSI_ERR_BAD_OPCODE;
1223         }
1224
1225         switch(opcode) {
1226         case ISCSI_OP_SCSI_CMD_RSP:
1227                 iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen);
1228                 break;
1229         case ISCSI_OP_SCSI_DATA_IN:
1230                 iscsi_data_in_rsp(conn, hdr, task);
1231                 break;
1232         case ISCSI_OP_LOGOUT_RSP:
1233                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1234                 if (datalen) {
1235                         rc = ISCSI_ERR_PROTO;
1236                         break;
1237                 }
1238                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1239                 goto recv_pdu;
1240         case ISCSI_OP_LOGIN_RSP:
1241         case ISCSI_OP_TEXT_RSP:
1242                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1243                 /*
1244                  * login related PDU's exp_statsn is handled in
1245                  * userspace
1246                  */
1247                 goto recv_pdu;
1248         case ISCSI_OP_SCSI_TMFUNC_RSP:
1249                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1250                 if (datalen) {
1251                         rc = ISCSI_ERR_PROTO;
1252                         break;
1253                 }
1254
1255                 iscsi_tmf_rsp(conn, hdr);
1256                 iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1257                 break;
1258         case ISCSI_OP_NOOP_IN:
1259                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1260                 if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) {
1261                         rc = ISCSI_ERR_PROTO;
1262                         break;
1263                 }
1264                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1265
1266                 rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)hdr,
1267                                        data, datalen);
1268                 break;
1269         default:
1270                 rc = ISCSI_ERR_BAD_OPCODE;
1271                 break;
1272         }
1273
1274 out:
1275         return rc;
1276 recv_pdu:
1277         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1278                 rc = ISCSI_ERR_CONN_FAILED;
1279         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1280         return rc;
1281 }
1282 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
1283
1284 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1285                        char *data, int datalen)
1286 {
1287         int rc;
1288
1289         spin_lock(&conn->session->back_lock);
1290         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
1291         spin_unlock(&conn->session->back_lock);
1292         return rc;
1293 }
1294 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
1295
1296 int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt)
1297 {
1298         struct iscsi_session *session = conn->session;
1299         int age = 0, i = 0;
1300
1301         if (itt == RESERVED_ITT)
1302                 return 0;
1303
1304         if (session->tt->parse_pdu_itt)
1305                 session->tt->parse_pdu_itt(conn, itt, &i, &age);
1306         else {
1307                 i = get_itt(itt);
1308                 age = ((__force u32)itt >> ISCSI_AGE_SHIFT) & ISCSI_AGE_MASK;
1309         }
1310
1311         if (age != session->age) {
1312                 iscsi_conn_printk(KERN_ERR, conn,
1313                                   "received itt %x expected session age (%x)\n",
1314                                   (__force u32)itt, session->age);
1315                 return ISCSI_ERR_BAD_ITT;
1316         }
1317
1318         if (i >= session->cmds_max) {
1319                 iscsi_conn_printk(KERN_ERR, conn,
1320                                   "received invalid itt index %u (max cmds "
1321                                    "%u.\n", i, session->cmds_max);
1322                 return ISCSI_ERR_BAD_ITT;
1323         }
1324         return 0;
1325 }
1326 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
1327
1328 /**
1329  * iscsi_itt_to_ctask - look up ctask by itt
1330  * @conn: iscsi connection
1331  * @itt: itt
1332  *
1333  * This should be used for cmd tasks.
1334  *
1335  * The session back_lock must be held.
1336  */
1337 struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
1338 {
1339         struct iscsi_task *task;
1340
1341         if (iscsi_verify_itt(conn, itt))
1342                 return NULL;
1343
1344         task = iscsi_itt_to_task(conn, itt);
1345         if (!task || !task->sc)
1346                 return NULL;
1347
1348         if (task->sc->SCp.phase != conn->session->age) {
1349                 iscsi_session_printk(KERN_ERR, conn->session,
1350                                   "task's session age %d, expected %d\n",
1351                                   task->sc->SCp.phase, conn->session->age);
1352                 return NULL;
1353         }
1354
1355         return task;
1356 }
1357 EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask);
1358
1359 void iscsi_session_failure(struct iscsi_session *session,
1360                            enum iscsi_err err)
1361 {
1362         struct iscsi_conn *conn;
1363
1364         spin_lock_bh(&session->frwd_lock);
1365         conn = session->leadconn;
1366         if (session->state == ISCSI_STATE_TERMINATE || !conn) {
1367                 spin_unlock_bh(&session->frwd_lock);
1368                 return;
1369         }
1370
1371         iscsi_get_conn(conn->cls_conn);
1372         spin_unlock_bh(&session->frwd_lock);
1373         /*
1374          * if the host is being removed bypass the connection
1375          * recovery initialization because we are going to kill
1376          * the session.
1377          */
1378         if (err == ISCSI_ERR_INVALID_HOST)
1379                 iscsi_conn_error_event(conn->cls_conn, err);
1380         else
1381                 iscsi_conn_failure(conn, err);
1382         iscsi_put_conn(conn->cls_conn);
1383 }
1384 EXPORT_SYMBOL_GPL(iscsi_session_failure);
1385
1386 static bool iscsi_set_conn_failed(struct iscsi_conn *conn)
1387 {
1388         struct iscsi_session *session = conn->session;
1389
1390         if (session->state == ISCSI_STATE_FAILED)
1391                 return false;
1392
1393         if (conn->stop_stage == 0)
1394                 session->state = ISCSI_STATE_FAILED;
1395
1396         set_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags);
1397         set_bit(ISCSI_CONN_FLAG_SUSPEND_RX, &conn->flags);
1398         return true;
1399 }
1400
1401 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
1402 {
1403         struct iscsi_session *session = conn->session;
1404         bool needs_evt;
1405
1406         spin_lock_bh(&session->frwd_lock);
1407         needs_evt = iscsi_set_conn_failed(conn);
1408         spin_unlock_bh(&session->frwd_lock);
1409
1410         if (needs_evt)
1411                 iscsi_conn_error_event(conn->cls_conn, err);
1412 }
1413 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
1414
1415 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
1416 {
1417         struct iscsi_session *session = conn->session;
1418
1419         /*
1420          * Check for iSCSI window and take care of CmdSN wrap-around
1421          */
1422         if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
1423                 ISCSI_DBG_SESSION(session, "iSCSI CmdSN closed. ExpCmdSn "
1424                                   "%u MaxCmdSN %u CmdSN %u/%u\n",
1425                                   session->exp_cmdsn, session->max_cmdsn,
1426                                   session->cmdsn, session->queued_cmdsn);
1427                 return -ENOSPC;
1428         }
1429         return 0;
1430 }
1431
1432 static int iscsi_xmit_task(struct iscsi_conn *conn, struct iscsi_task *task,
1433                            bool was_requeue)
1434 {
1435         int rc;
1436
1437         spin_lock_bh(&conn->session->back_lock);
1438
1439         if (!conn->task) {
1440                 /* Take a ref so we can access it after xmit_task() */
1441                 __iscsi_get_task(task);
1442         } else {
1443                 /* Already have a ref from when we failed to send it last call */
1444                 conn->task = NULL;
1445         }
1446
1447         /*
1448          * If this was a requeue for a R2T we have an extra ref on the task in
1449          * case a bad target sends a cmd rsp before we have handled the task.
1450          */
1451         if (was_requeue)
1452                 __iscsi_put_task(task);
1453
1454         /*
1455          * Do this after dropping the extra ref because if this was a requeue
1456          * it's removed from that list and cleanup_queued_task would miss it.
1457          */
1458         if (test_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags)) {
1459                 /*
1460                  * Save the task and ref in case we weren't cleaning up this
1461                  * task and get woken up again.
1462                  */
1463                 conn->task = task;
1464                 spin_unlock_bh(&conn->session->back_lock);
1465                 return -ENODATA;
1466         }
1467         spin_unlock_bh(&conn->session->back_lock);
1468
1469         spin_unlock_bh(&conn->session->frwd_lock);
1470         rc = conn->session->tt->xmit_task(task);
1471         spin_lock_bh(&conn->session->frwd_lock);
1472         if (!rc) {
1473                 /* done with this task */
1474                 task->last_xfer = jiffies;
1475         }
1476         /* regular RX path uses back_lock */
1477         spin_lock(&conn->session->back_lock);
1478         if (rc && task->state == ISCSI_TASK_RUNNING) {
1479                 /*
1480                  * get an extra ref that is released next time we access it
1481                  * as conn->task above.
1482                  */
1483                 __iscsi_get_task(task);
1484                 conn->task = task;
1485         }
1486
1487         __iscsi_put_task(task);
1488         spin_unlock(&conn->session->back_lock);
1489         return rc;
1490 }
1491
1492 /**
1493  * iscsi_requeue_task - requeue task to run from session workqueue
1494  * @task: task to requeue
1495  *
1496  * Callers must have taken a ref to the task that is going to be requeued.
1497  */
1498 void iscsi_requeue_task(struct iscsi_task *task)
1499 {
1500         struct iscsi_conn *conn = task->conn;
1501
1502         /*
1503          * this may be on the requeue list already if the xmit_task callout
1504          * is handling the r2ts while we are adding new ones
1505          */
1506         spin_lock_bh(&conn->session->frwd_lock);
1507         if (list_empty(&task->running)) {
1508                 list_add_tail(&task->running, &conn->requeue);
1509         } else {
1510                 /*
1511                  * Don't need the extra ref since it's already requeued and
1512                  * has a ref.
1513                  */
1514                 iscsi_put_task(task);
1515         }
1516         iscsi_conn_queue_work(conn);
1517         spin_unlock_bh(&conn->session->frwd_lock);
1518 }
1519 EXPORT_SYMBOL_GPL(iscsi_requeue_task);
1520
1521 /**
1522  * iscsi_data_xmit - xmit any command into the scheduled connection
1523  * @conn: iscsi connection
1524  *
1525  * Notes:
1526  *      The function can return -EAGAIN in which case the caller must
1527  *      re-schedule it again later or recover. '0' return code means
1528  *      successful xmit.
1529  **/
1530 static int iscsi_data_xmit(struct iscsi_conn *conn)
1531 {
1532         struct iscsi_task *task;
1533         int rc = 0;
1534
1535         spin_lock_bh(&conn->session->frwd_lock);
1536         if (test_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags)) {
1537                 ISCSI_DBG_SESSION(conn->session, "Tx suspended!\n");
1538                 spin_unlock_bh(&conn->session->frwd_lock);
1539                 return -ENODATA;
1540         }
1541
1542         if (conn->task) {
1543                 rc = iscsi_xmit_task(conn, conn->task, false);
1544                 if (rc)
1545                         goto done;
1546         }
1547
1548         /*
1549          * process mgmt pdus like nops before commands since we should
1550          * only have one nop-out as a ping from us and targets should not
1551          * overflow us with nop-ins
1552          */
1553 check_mgmt:
1554         while (!list_empty(&conn->mgmtqueue)) {
1555                 task = list_entry(conn->mgmtqueue.next, struct iscsi_task,
1556                                   running);
1557                 list_del_init(&task->running);
1558                 if (iscsi_prep_mgmt_task(conn, task)) {
1559                         /* regular RX path uses back_lock */
1560                         spin_lock_bh(&conn->session->back_lock);
1561                         __iscsi_put_task(task);
1562                         spin_unlock_bh(&conn->session->back_lock);
1563                         continue;
1564                 }
1565                 rc = iscsi_xmit_task(conn, task, false);
1566                 if (rc)
1567                         goto done;
1568         }
1569
1570         /* process pending command queue */
1571         while (!list_empty(&conn->cmdqueue)) {
1572                 task = list_entry(conn->cmdqueue.next, struct iscsi_task,
1573                                   running);
1574                 list_del_init(&task->running);
1575                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT) {
1576                         fail_scsi_task(task, DID_IMM_RETRY);
1577                         continue;
1578                 }
1579                 rc = iscsi_prep_scsi_cmd_pdu(task);
1580                 if (rc) {
1581                         if (rc == -ENOMEM || rc == -EACCES)
1582                                 fail_scsi_task(task, DID_IMM_RETRY);
1583                         else
1584                                 fail_scsi_task(task, DID_ABORT);
1585                         continue;
1586                 }
1587                 rc = iscsi_xmit_task(conn, task, false);
1588                 if (rc)
1589                         goto done;
1590                 /*
1591                  * we could continuously get new task requests so
1592                  * we need to check the mgmt queue for nops that need to
1593                  * be sent to aviod starvation
1594                  */
1595                 if (!list_empty(&conn->mgmtqueue))
1596                         goto check_mgmt;
1597         }
1598
1599         while (!list_empty(&conn->requeue)) {
1600                 /*
1601                  * we always do fastlogout - conn stop code will clean up.
1602                  */
1603                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
1604                         break;
1605
1606                 task = list_entry(conn->requeue.next, struct iscsi_task,
1607                                   running);
1608
1609                 if (iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_DATA_OUT))
1610                         break;
1611
1612                 list_del_init(&task->running);
1613                 rc = iscsi_xmit_task(conn, task, true);
1614                 if (rc)
1615                         goto done;
1616                 if (!list_empty(&conn->mgmtqueue))
1617                         goto check_mgmt;
1618         }
1619         spin_unlock_bh(&conn->session->frwd_lock);
1620         return -ENODATA;
1621
1622 done:
1623         spin_unlock_bh(&conn->session->frwd_lock);
1624         return rc;
1625 }
1626
1627 static void iscsi_xmitworker(struct work_struct *work)
1628 {
1629         struct iscsi_conn *conn =
1630                 container_of(work, struct iscsi_conn, xmitwork);
1631         int rc;
1632         /*
1633          * serialize Xmit worker on a per-connection basis.
1634          */
1635         do {
1636                 rc = iscsi_data_xmit(conn);
1637         } while (rc >= 0 || rc == -EAGAIN);
1638 }
1639
1640 static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn,
1641                                                   struct scsi_cmnd *sc)
1642 {
1643         struct iscsi_task *task;
1644
1645         if (!kfifo_out(&conn->session->cmdpool.queue,
1646                          (void *) &task, sizeof(void *)))
1647                 return NULL;
1648
1649         sc->SCp.phase = conn->session->age;
1650         sc->SCp.ptr = (char *) task;
1651
1652         refcount_set(&task->refcount, 1);
1653         task->state = ISCSI_TASK_PENDING;
1654         task->conn = conn;
1655         task->sc = sc;
1656         task->have_checked_conn = false;
1657         task->last_timeout = jiffies;
1658         task->last_xfer = jiffies;
1659         task->protected = false;
1660         INIT_LIST_HEAD(&task->running);
1661         return task;
1662 }
1663
1664 enum {
1665         FAILURE_BAD_HOST = 1,
1666         FAILURE_SESSION_FAILED,
1667         FAILURE_SESSION_FREED,
1668         FAILURE_WINDOW_CLOSED,
1669         FAILURE_OOM,
1670         FAILURE_SESSION_TERMINATE,
1671         FAILURE_SESSION_IN_RECOVERY,
1672         FAILURE_SESSION_RECOVERY_TIMEOUT,
1673         FAILURE_SESSION_LOGGING_OUT,
1674         FAILURE_SESSION_NOT_READY,
1675 };
1676
1677 int iscsi_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *sc)
1678 {
1679         struct iscsi_cls_session *cls_session;
1680         struct iscsi_host *ihost;
1681         int reason = 0;
1682         struct iscsi_session *session;
1683         struct iscsi_conn *conn;
1684         struct iscsi_task *task = NULL;
1685
1686         sc->result = 0;
1687         sc->SCp.ptr = NULL;
1688
1689         ihost = shost_priv(host);
1690
1691         cls_session = starget_to_session(scsi_target(sc->device));
1692         session = cls_session->dd_data;
1693         spin_lock_bh(&session->frwd_lock);
1694
1695         reason = iscsi_session_chkready(cls_session);
1696         if (reason) {
1697                 sc->result = reason;
1698                 goto fault;
1699         }
1700
1701         if (session->state != ISCSI_STATE_LOGGED_IN) {
1702                 /*
1703                  * to handle the race between when we set the recovery state
1704                  * and block the session we requeue here (commands could
1705                  * be entering our queuecommand while a block is starting
1706                  * up because the block code is not locked)
1707                  */
1708                 switch (session->state) {
1709                 case ISCSI_STATE_FAILED:
1710                         /*
1711                          * cmds should fail during shutdown, if the session
1712                          * state is bad, allowing completion to happen
1713                          */
1714                         if (unlikely(system_state != SYSTEM_RUNNING)) {
1715                                 reason = FAILURE_SESSION_FAILED;
1716                                 sc->result = DID_NO_CONNECT << 16;
1717                                 break;
1718                         }
1719                         fallthrough;
1720                 case ISCSI_STATE_IN_RECOVERY:
1721                         reason = FAILURE_SESSION_IN_RECOVERY;
1722                         sc->result = DID_IMM_RETRY << 16;
1723                         break;
1724                 case ISCSI_STATE_LOGGING_OUT:
1725                         reason = FAILURE_SESSION_LOGGING_OUT;
1726                         sc->result = DID_IMM_RETRY << 16;
1727                         break;
1728                 case ISCSI_STATE_RECOVERY_FAILED:
1729                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
1730                         sc->result = DID_TRANSPORT_FAILFAST << 16;
1731                         break;
1732                 case ISCSI_STATE_TERMINATE:
1733                         reason = FAILURE_SESSION_TERMINATE;
1734                         sc->result = DID_NO_CONNECT << 16;
1735                         break;
1736                 default:
1737                         reason = FAILURE_SESSION_FREED;
1738                         sc->result = DID_NO_CONNECT << 16;
1739                 }
1740                 goto fault;
1741         }
1742
1743         conn = session->leadconn;
1744         if (!conn) {
1745                 reason = FAILURE_SESSION_FREED;
1746                 sc->result = DID_NO_CONNECT << 16;
1747                 goto fault;
1748         }
1749
1750         if (test_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags)) {
1751                 reason = FAILURE_SESSION_IN_RECOVERY;
1752                 sc->result = DID_REQUEUE << 16;
1753                 goto fault;
1754         }
1755
1756         if (iscsi_check_cmdsn_window_closed(conn)) {
1757                 reason = FAILURE_WINDOW_CLOSED;
1758                 goto reject;
1759         }
1760
1761         task = iscsi_alloc_task(conn, sc);
1762         if (!task) {
1763                 reason = FAILURE_OOM;
1764                 goto reject;
1765         }
1766
1767         if (!ihost->workq) {
1768                 reason = iscsi_prep_scsi_cmd_pdu(task);
1769                 if (reason) {
1770                         if (reason == -ENOMEM ||  reason == -EACCES) {
1771                                 reason = FAILURE_OOM;
1772                                 goto prepd_reject;
1773                         } else {
1774                                 sc->result = DID_ABORT << 16;
1775                                 goto prepd_fault;
1776                         }
1777                 }
1778                 if (session->tt->xmit_task(task)) {
1779                         session->cmdsn--;
1780                         reason = FAILURE_SESSION_NOT_READY;
1781                         goto prepd_reject;
1782                 }
1783         } else {
1784                 list_add_tail(&task->running, &conn->cmdqueue);
1785                 iscsi_conn_queue_work(conn);
1786         }
1787
1788         session->queued_cmdsn++;
1789         spin_unlock_bh(&session->frwd_lock);
1790         return 0;
1791
1792 prepd_reject:
1793         spin_lock_bh(&session->back_lock);
1794         iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ);
1795         spin_unlock_bh(&session->back_lock);
1796 reject:
1797         spin_unlock_bh(&session->frwd_lock);
1798         ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n",
1799                           sc->cmnd[0], reason);
1800         return SCSI_MLQUEUE_TARGET_BUSY;
1801
1802 prepd_fault:
1803         spin_lock_bh(&session->back_lock);
1804         iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ);
1805         spin_unlock_bh(&session->back_lock);
1806 fault:
1807         spin_unlock_bh(&session->frwd_lock);
1808         ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n",
1809                           sc->cmnd[0], reason);
1810         scsi_set_resid(sc, scsi_bufflen(sc));
1811         sc->scsi_done(sc);
1812         return 0;
1813 }
1814 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
1815
1816 int iscsi_target_alloc(struct scsi_target *starget)
1817 {
1818         struct iscsi_cls_session *cls_session = starget_to_session(starget);
1819         struct iscsi_session *session = cls_session->dd_data;
1820
1821         starget->can_queue = session->scsi_cmds_max;
1822         return 0;
1823 }
1824 EXPORT_SYMBOL_GPL(iscsi_target_alloc);
1825
1826 static void iscsi_tmf_timedout(struct timer_list *t)
1827 {
1828         struct iscsi_session *session = from_timer(session, t, tmf_timer);
1829
1830         spin_lock(&session->frwd_lock);
1831         if (session->tmf_state == TMF_QUEUED) {
1832                 session->tmf_state = TMF_TIMEDOUT;
1833                 ISCSI_DBG_EH(session, "tmf timedout\n");
1834                 /* unblock eh_abort() */
1835                 wake_up(&session->ehwait);
1836         }
1837         spin_unlock(&session->frwd_lock);
1838 }
1839
1840 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1841                                    struct iscsi_tm *hdr, int age,
1842                                    int timeout)
1843         __must_hold(&session->frwd_lock)
1844 {
1845         struct iscsi_session *session = conn->session;
1846         struct iscsi_task *task;
1847
1848         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1849                                       NULL, 0);
1850         if (!task) {
1851                 spin_unlock_bh(&session->frwd_lock);
1852                 iscsi_conn_printk(KERN_ERR, conn, "Could not send TMF.\n");
1853                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1854                 spin_lock_bh(&session->frwd_lock);
1855                 return -EPERM;
1856         }
1857         conn->tmfcmd_pdus_cnt++;
1858         session->tmf_timer.expires = timeout * HZ + jiffies;
1859         add_timer(&session->tmf_timer);
1860         ISCSI_DBG_EH(session, "tmf set timeout\n");
1861
1862         spin_unlock_bh(&session->frwd_lock);
1863         mutex_unlock(&session->eh_mutex);
1864
1865         /*
1866          * block eh thread until:
1867          *
1868          * 1) tmf response
1869          * 2) tmf timeout
1870          * 3) session is terminated or restarted or userspace has
1871          * given up on recovery
1872          */
1873         wait_event_interruptible(session->ehwait, age != session->age ||
1874                                  session->state != ISCSI_STATE_LOGGED_IN ||
1875                                  session->tmf_state != TMF_QUEUED);
1876         if (signal_pending(current))
1877                 flush_signals(current);
1878         del_timer_sync(&session->tmf_timer);
1879
1880         mutex_lock(&session->eh_mutex);
1881         spin_lock_bh(&session->frwd_lock);
1882         /* if the session drops it will clean up the task */
1883         if (age != session->age ||
1884             session->state != ISCSI_STATE_LOGGED_IN)
1885                 return -ENOTCONN;
1886         return 0;
1887 }
1888
1889 /*
1890  * Fail commands. session frwd lock held and xmit thread flushed.
1891  */
1892 static void fail_scsi_tasks(struct iscsi_conn *conn, u64 lun, int error)
1893 {
1894         struct iscsi_session *session = conn->session;
1895         struct iscsi_task *task;
1896         int i;
1897
1898         spin_lock_bh(&session->back_lock);
1899         for (i = 0; i < session->cmds_max; i++) {
1900                 task = session->cmds[i];
1901                 if (!task->sc || task->state == ISCSI_TASK_FREE)
1902                         continue;
1903
1904                 if (lun != -1 && lun != task->sc->device->lun)
1905                         continue;
1906
1907                 __iscsi_get_task(task);
1908                 spin_unlock_bh(&session->back_lock);
1909
1910                 ISCSI_DBG_SESSION(session,
1911                                   "failing sc %p itt 0x%x state %d\n",
1912                                   task->sc, task->itt, task->state);
1913                 fail_scsi_task(task, error);
1914
1915                 spin_unlock_bh(&session->frwd_lock);
1916                 iscsi_put_task(task);
1917                 spin_lock_bh(&session->frwd_lock);
1918
1919                 spin_lock_bh(&session->back_lock);
1920         }
1921
1922         spin_unlock_bh(&session->back_lock);
1923 }
1924
1925 /**
1926  * iscsi_suspend_queue - suspend iscsi_queuecommand
1927  * @conn: iscsi conn to stop queueing IO on
1928  *
1929  * This grabs the session frwd_lock to make sure no one is in
1930  * xmit_task/queuecommand, and then sets suspend to prevent
1931  * new commands from being queued. This only needs to be called
1932  * by offload drivers that need to sync a path like ep disconnect
1933  * with the iscsi_queuecommand/xmit_task. To start IO again libiscsi
1934  * will call iscsi_start_tx and iscsi_unblock_session when in FFP.
1935  */
1936 void iscsi_suspend_queue(struct iscsi_conn *conn)
1937 {
1938         spin_lock_bh(&conn->session->frwd_lock);
1939         set_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags);
1940         spin_unlock_bh(&conn->session->frwd_lock);
1941 }
1942 EXPORT_SYMBOL_GPL(iscsi_suspend_queue);
1943
1944 /**
1945  * iscsi_suspend_tx - suspend iscsi_data_xmit
1946  * @conn: iscsi conn tp stop processing IO on.
1947  *
1948  * This function sets the suspend bit to prevent iscsi_data_xmit
1949  * from sending new IO, and if work is queued on the xmit thread
1950  * it will wait for it to be completed.
1951  */
1952 void iscsi_suspend_tx(struct iscsi_conn *conn)
1953 {
1954         struct Scsi_Host *shost = conn->session->host;
1955         struct iscsi_host *ihost = shost_priv(shost);
1956
1957         set_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags);
1958         if (ihost->workq)
1959                 flush_workqueue(ihost->workq);
1960 }
1961 EXPORT_SYMBOL_GPL(iscsi_suspend_tx);
1962
1963 static void iscsi_start_tx(struct iscsi_conn *conn)
1964 {
1965         clear_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags);
1966         iscsi_conn_queue_work(conn);
1967 }
1968
1969 /*
1970  * We want to make sure a ping is in flight. It has timed out.
1971  * And we are not busy processing a pdu that is making
1972  * progress but got started before the ping and is taking a while
1973  * to complete so the ping is just stuck behind it in a queue.
1974  */
1975 static int iscsi_has_ping_timed_out(struct iscsi_conn *conn)
1976 {
1977         if (READ_ONCE(conn->ping_task) &&
1978             time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) +
1979                            (conn->ping_timeout * HZ), jiffies))
1980                 return 1;
1981         else
1982                 return 0;
1983 }
1984
1985 enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *sc)
1986 {
1987         enum blk_eh_timer_return rc = BLK_EH_DONE;
1988         struct iscsi_task *task = NULL, *running_task;
1989         struct iscsi_cls_session *cls_session;
1990         struct iscsi_session *session;
1991         struct iscsi_conn *conn;
1992         int i;
1993
1994         cls_session = starget_to_session(scsi_target(sc->device));
1995         session = cls_session->dd_data;
1996
1997         ISCSI_DBG_EH(session, "scsi cmd %p timedout\n", sc);
1998
1999         spin_lock_bh(&session->frwd_lock);
2000         spin_lock(&session->back_lock);
2001         task = (struct iscsi_task *)sc->SCp.ptr;
2002         if (!task) {
2003                 /*
2004                  * Raced with completion. Blk layer has taken ownership
2005                  * so let timeout code complete it now.
2006                  */
2007                 rc = BLK_EH_DONE;
2008                 spin_unlock(&session->back_lock);
2009                 goto done;
2010         }
2011         __iscsi_get_task(task);
2012         spin_unlock(&session->back_lock);
2013
2014         if (session->state != ISCSI_STATE_LOGGED_IN) {
2015                 /*
2016                  * During shutdown, if session is prematurely disconnected,
2017                  * recovery won't happen and there will be hung cmds. Not
2018                  * handling cmds would trigger EH, also bad in this case.
2019                  * Instead, handle cmd, allow completion to happen and let
2020                  * upper layer to deal with the result.
2021                  */
2022                 if (unlikely(system_state != SYSTEM_RUNNING)) {
2023                         sc->result = DID_NO_CONNECT << 16;
2024                         ISCSI_DBG_EH(session, "sc on shutdown, handled\n");
2025                         rc = BLK_EH_DONE;
2026                         goto done;
2027                 }
2028                 /*
2029                  * We are probably in the middle of iscsi recovery so let
2030                  * that complete and handle the error.
2031                  */
2032                 rc = BLK_EH_RESET_TIMER;
2033                 goto done;
2034         }
2035
2036         conn = session->leadconn;
2037         if (!conn) {
2038                 /* In the middle of shuting down */
2039                 rc = BLK_EH_RESET_TIMER;
2040                 goto done;
2041         }
2042
2043         /*
2044          * If we have sent (at least queued to the network layer) a pdu or
2045          * recvd one for the task since the last timeout ask for
2046          * more time. If on the next timeout we have not made progress
2047          * we can check if it is the task or connection when we send the
2048          * nop as a ping.
2049          */
2050         if (time_after(task->last_xfer, task->last_timeout)) {
2051                 ISCSI_DBG_EH(session, "Command making progress. Asking "
2052                              "scsi-ml for more time to complete. "
2053                              "Last data xfer at %lu. Last timeout was at "
2054                              "%lu\n.", task->last_xfer, task->last_timeout);
2055                 task->have_checked_conn = false;
2056                 rc = BLK_EH_RESET_TIMER;
2057                 goto done;
2058         }
2059
2060         if (!conn->recv_timeout && !conn->ping_timeout)
2061                 goto done;
2062         /*
2063          * if the ping timedout then we are in the middle of cleaning up
2064          * and can let the iscsi eh handle it
2065          */
2066         if (iscsi_has_ping_timed_out(conn)) {
2067                 rc = BLK_EH_RESET_TIMER;
2068                 goto done;
2069         }
2070
2071         spin_lock(&session->back_lock);
2072         for (i = 0; i < conn->session->cmds_max; i++) {
2073                 running_task = conn->session->cmds[i];
2074                 if (!running_task->sc || running_task == task ||
2075                      running_task->state != ISCSI_TASK_RUNNING)
2076                         continue;
2077
2078                 /*
2079                  * Only check if cmds started before this one have made
2080                  * progress, or this could never fail
2081                  */
2082                 if (time_after(running_task->sc->jiffies_at_alloc,
2083                                task->sc->jiffies_at_alloc))
2084                         continue;
2085
2086                 if (time_after(running_task->last_xfer, task->last_timeout)) {
2087                         /*
2088                          * This task has not made progress, but a task
2089                          * started before us has transferred data since
2090                          * we started/last-checked. We could be queueing
2091                          * too many tasks or the LU is bad.
2092                          *
2093                          * If the device is bad the cmds ahead of us on
2094                          * other devs will complete, and this loop will
2095                          * eventually fail starting the scsi eh.
2096                          */
2097                         ISCSI_DBG_EH(session, "Command has not made progress "
2098                                      "but commands ahead of it have. "
2099                                      "Asking scsi-ml for more time to "
2100                                      "complete. Our last xfer vs running task "
2101                                      "last xfer %lu/%lu. Last check %lu.\n",
2102                                      task->last_xfer, running_task->last_xfer,
2103                                      task->last_timeout);
2104                         spin_unlock(&session->back_lock);
2105                         rc = BLK_EH_RESET_TIMER;
2106                         goto done;
2107                 }
2108         }
2109         spin_unlock(&session->back_lock);
2110
2111         /* Assumes nop timeout is shorter than scsi cmd timeout */
2112         if (task->have_checked_conn)
2113                 goto done;
2114
2115         /*
2116          * Checking the transport already or nop from a cmd timeout still
2117          * running
2118          */
2119         if (READ_ONCE(conn->ping_task)) {
2120                 task->have_checked_conn = true;
2121                 rc = BLK_EH_RESET_TIMER;
2122                 goto done;
2123         }
2124
2125         /* Make sure there is a transport check done */
2126         iscsi_send_nopout(conn, NULL);
2127         task->have_checked_conn = true;
2128         rc = BLK_EH_RESET_TIMER;
2129
2130 done:
2131         spin_unlock_bh(&session->frwd_lock);
2132
2133         if (task) {
2134                 task->last_timeout = jiffies;
2135                 iscsi_put_task(task);
2136         }
2137         ISCSI_DBG_EH(session, "return %s\n", rc == BLK_EH_RESET_TIMER ?
2138                      "timer reset" : "shutdown or nh");
2139         return rc;
2140 }
2141 EXPORT_SYMBOL_GPL(iscsi_eh_cmd_timed_out);
2142
2143 static void iscsi_check_transport_timeouts(struct timer_list *t)
2144 {
2145         struct iscsi_conn *conn = from_timer(conn, t, transport_timer);
2146         struct iscsi_session *session = conn->session;
2147         unsigned long recv_timeout, next_timeout = 0, last_recv;
2148
2149         spin_lock(&session->frwd_lock);
2150         if (session->state != ISCSI_STATE_LOGGED_IN)
2151                 goto done;
2152
2153         recv_timeout = conn->recv_timeout;
2154         if (!recv_timeout)
2155                 goto done;
2156
2157         recv_timeout *= HZ;
2158         last_recv = conn->last_recv;
2159
2160         if (iscsi_has_ping_timed_out(conn)) {
2161                 iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs "
2162                                   "expired, recv timeout %d, last rx %lu, "
2163                                   "last ping %lu, now %lu\n",
2164                                   conn->ping_timeout, conn->recv_timeout,
2165                                   last_recv, conn->last_ping, jiffies);
2166                 spin_unlock(&session->frwd_lock);
2167                 iscsi_conn_failure(conn, ISCSI_ERR_NOP_TIMEDOUT);
2168                 return;
2169         }
2170
2171         if (time_before_eq(last_recv + recv_timeout, jiffies)) {
2172                 /* send a ping to try to provoke some traffic */
2173                 ISCSI_DBG_CONN(conn, "Sending nopout as ping\n");
2174                 if (iscsi_send_nopout(conn, NULL))
2175                         next_timeout = jiffies + (1 * HZ);
2176                 else
2177                         next_timeout = conn->last_ping + (conn->ping_timeout * HZ);
2178         } else
2179                 next_timeout = last_recv + recv_timeout;
2180
2181         ISCSI_DBG_CONN(conn, "Setting next tmo %lu\n", next_timeout);
2182         mod_timer(&conn->transport_timer, next_timeout);
2183 done:
2184         spin_unlock(&session->frwd_lock);
2185 }
2186
2187 /**
2188  * iscsi_conn_unbind - prevent queueing to conn.
2189  * @cls_conn: iscsi conn ep is bound to.
2190  * @is_active: is the conn in use for boot or is this for EH/termination
2191  *
2192  * This must be called by drivers implementing the ep_disconnect callout.
2193  * It disables queueing to the connection from libiscsi in preparation for
2194  * an ep_disconnect call.
2195  */
2196 void iscsi_conn_unbind(struct iscsi_cls_conn *cls_conn, bool is_active)
2197 {
2198         struct iscsi_session *session;
2199         struct iscsi_conn *conn;
2200
2201         if (!cls_conn)
2202                 return;
2203
2204         conn = cls_conn->dd_data;
2205         session = conn->session;
2206         /*
2207          * Wait for iscsi_eh calls to exit. We don't wait for the tmf to
2208          * complete or timeout. The caller just wants to know what's running
2209          * is everything that needs to be cleaned up, and no cmds will be
2210          * queued.
2211          */
2212         mutex_lock(&session->eh_mutex);
2213
2214         iscsi_suspend_queue(conn);
2215         iscsi_suspend_tx(conn);
2216
2217         spin_lock_bh(&session->frwd_lock);
2218         clear_bit(ISCSI_CONN_FLAG_BOUND, &conn->flags);
2219
2220         if (!is_active) {
2221                 /*
2222                  * if logout timed out before userspace could even send a PDU
2223                  * the state might still be in ISCSI_STATE_LOGGED_IN and
2224                  * allowing new cmds and TMFs.
2225                  */
2226                 if (session->state == ISCSI_STATE_LOGGED_IN)
2227                         iscsi_set_conn_failed(conn);
2228         }
2229         spin_unlock_bh(&session->frwd_lock);
2230         mutex_unlock(&session->eh_mutex);
2231 }
2232 EXPORT_SYMBOL_GPL(iscsi_conn_unbind);
2233
2234 static void iscsi_prep_abort_task_pdu(struct iscsi_task *task,
2235                                       struct iscsi_tm *hdr)
2236 {
2237         memset(hdr, 0, sizeof(*hdr));
2238         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2239         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
2240         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2241         hdr->lun = task->lun;
2242         hdr->rtt = task->hdr_itt;
2243         hdr->refcmdsn = task->cmdsn;
2244 }
2245
2246 int iscsi_eh_abort(struct scsi_cmnd *sc)
2247 {
2248         struct iscsi_cls_session *cls_session;
2249         struct iscsi_session *session;
2250         struct iscsi_conn *conn;
2251         struct iscsi_task *task;
2252         struct iscsi_tm *hdr;
2253         int age;
2254
2255         cls_session = starget_to_session(scsi_target(sc->device));
2256         session = cls_session->dd_data;
2257
2258         ISCSI_DBG_EH(session, "aborting sc %p\n", sc);
2259
2260         mutex_lock(&session->eh_mutex);
2261         spin_lock_bh(&session->frwd_lock);
2262         /*
2263          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
2264          * got the command.
2265          */
2266         if (!sc->SCp.ptr) {
2267                 ISCSI_DBG_EH(session, "sc never reached iscsi layer or "
2268                                       "it completed.\n");
2269                 spin_unlock_bh(&session->frwd_lock);
2270                 mutex_unlock(&session->eh_mutex);
2271                 return SUCCESS;
2272         }
2273
2274         /*
2275          * If we are not logged in or we have started a new session
2276          * then let the host reset code handle this
2277          */
2278         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
2279             sc->SCp.phase != session->age) {
2280                 spin_unlock_bh(&session->frwd_lock);
2281                 mutex_unlock(&session->eh_mutex);
2282                 ISCSI_DBG_EH(session, "failing abort due to dropped "
2283                                   "session.\n");
2284                 return FAILED;
2285         }
2286
2287         spin_lock(&session->back_lock);
2288         task = (struct iscsi_task *)sc->SCp.ptr;
2289         if (!task || !task->sc) {
2290                 /* task completed before time out */
2291                 ISCSI_DBG_EH(session, "sc completed while abort in progress\n");
2292
2293                 spin_unlock(&session->back_lock);
2294                 spin_unlock_bh(&session->frwd_lock);
2295                 mutex_unlock(&session->eh_mutex);
2296                 return SUCCESS;
2297         }
2298
2299         conn = session->leadconn;
2300         iscsi_get_conn(conn->cls_conn);
2301         conn->eh_abort_cnt++;
2302         age = session->age;
2303
2304         ISCSI_DBG_EH(session, "aborting [sc %p itt 0x%x]\n", sc, task->itt);
2305         __iscsi_get_task(task);
2306         spin_unlock(&session->back_lock);
2307
2308         if (task->state == ISCSI_TASK_PENDING) {
2309                 fail_scsi_task(task, DID_ABORT);
2310                 goto success;
2311         }
2312
2313         /* only have one tmf outstanding at a time */
2314         if (session->tmf_state != TMF_INITIAL)
2315                 goto failed;
2316         session->tmf_state = TMF_QUEUED;
2317
2318         hdr = &session->tmhdr;
2319         iscsi_prep_abort_task_pdu(task, hdr);
2320
2321         if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout))
2322                 goto failed;
2323
2324         switch (session->tmf_state) {
2325         case TMF_SUCCESS:
2326                 spin_unlock_bh(&session->frwd_lock);
2327                 /*
2328                  * stop tx side incase the target had sent a abort rsp but
2329                  * the initiator was still writing out data.
2330                  */
2331                 iscsi_suspend_tx(conn);
2332                 /*
2333                  * we do not stop the recv side because targets have been
2334                  * good and have never sent us a successful tmf response
2335                  * then sent more data for the cmd.
2336                  */
2337                 spin_lock_bh(&session->frwd_lock);
2338                 fail_scsi_task(task, DID_ABORT);
2339                 session->tmf_state = TMF_INITIAL;
2340                 memset(hdr, 0, sizeof(*hdr));
2341                 spin_unlock_bh(&session->frwd_lock);
2342                 iscsi_start_tx(conn);
2343                 goto success_unlocked;
2344         case TMF_TIMEDOUT:
2345                 session->running_aborted_task = task;
2346                 spin_unlock_bh(&session->frwd_lock);
2347                 iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2348                 goto failed_unlocked;
2349         case TMF_NOT_FOUND:
2350                 if (iscsi_task_is_completed(task)) {
2351                         session->tmf_state = TMF_INITIAL;
2352                         memset(hdr, 0, sizeof(*hdr));
2353                         /* task completed before tmf abort response */
2354                         ISCSI_DBG_EH(session, "sc completed while abort in "
2355                                               "progress\n");
2356                         goto success;
2357                 }
2358                 fallthrough;
2359         default:
2360                 session->tmf_state = TMF_INITIAL;
2361                 goto failed;
2362         }
2363
2364 success:
2365         spin_unlock_bh(&session->frwd_lock);
2366 success_unlocked:
2367         ISCSI_DBG_EH(session, "abort success [sc %p itt 0x%x]\n",
2368                      sc, task->itt);
2369         iscsi_put_task(task);
2370         iscsi_put_conn(conn->cls_conn);
2371         mutex_unlock(&session->eh_mutex);
2372         return SUCCESS;
2373
2374 failed:
2375         spin_unlock_bh(&session->frwd_lock);
2376 failed_unlocked:
2377         ISCSI_DBG_EH(session, "abort failed [sc %p itt 0x%x]\n", sc,
2378                      task ? task->itt : 0);
2379         /*
2380          * The driver might be accessing the task so hold the ref. The conn
2381          * stop cleanup will drop the ref after ep_disconnect so we know the
2382          * driver's no longer touching the task.
2383          */
2384         if (!session->running_aborted_task)
2385                 iscsi_put_task(task);
2386
2387         iscsi_put_conn(conn->cls_conn);
2388         mutex_unlock(&session->eh_mutex);
2389         return FAILED;
2390 }
2391 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
2392
2393 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2394 {
2395         memset(hdr, 0, sizeof(*hdr));
2396         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2397         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2398         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2399         int_to_scsilun(sc->device->lun, &hdr->lun);
2400         hdr->rtt = RESERVED_ITT;
2401 }
2402
2403 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
2404 {
2405         struct iscsi_cls_session *cls_session;
2406         struct iscsi_session *session;
2407         struct iscsi_conn *conn;
2408         struct iscsi_tm *hdr;
2409         int rc = FAILED;
2410
2411         cls_session = starget_to_session(scsi_target(sc->device));
2412         session = cls_session->dd_data;
2413
2414         ISCSI_DBG_EH(session, "LU Reset [sc %p lun %llu]\n", sc,
2415                      sc->device->lun);
2416
2417         mutex_lock(&session->eh_mutex);
2418         spin_lock_bh(&session->frwd_lock);
2419         /*
2420          * Just check if we are not logged in. We cannot check for
2421          * the phase because the reset could come from a ioctl.
2422          */
2423         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2424                 goto unlock;
2425         conn = session->leadconn;
2426
2427         /* only have one tmf outstanding at a time */
2428         if (session->tmf_state != TMF_INITIAL)
2429                 goto unlock;
2430         session->tmf_state = TMF_QUEUED;
2431
2432         hdr = &session->tmhdr;
2433         iscsi_prep_lun_reset_pdu(sc, hdr);
2434
2435         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2436                                     session->lu_reset_timeout)) {
2437                 rc = FAILED;
2438                 goto unlock;
2439         }
2440
2441         switch (session->tmf_state) {
2442         case TMF_SUCCESS:
2443                 break;
2444         case TMF_TIMEDOUT:
2445                 spin_unlock_bh(&session->frwd_lock);
2446                 iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2447                 goto done;
2448         default:
2449                 session->tmf_state = TMF_INITIAL;
2450                 goto unlock;
2451         }
2452
2453         rc = SUCCESS;
2454         spin_unlock_bh(&session->frwd_lock);
2455
2456         iscsi_suspend_tx(conn);
2457
2458         spin_lock_bh(&session->frwd_lock);
2459         memset(hdr, 0, sizeof(*hdr));
2460         fail_scsi_tasks(conn, sc->device->lun, DID_ERROR);
2461         session->tmf_state = TMF_INITIAL;
2462         spin_unlock_bh(&session->frwd_lock);
2463
2464         iscsi_start_tx(conn);
2465         goto done;
2466
2467 unlock:
2468         spin_unlock_bh(&session->frwd_lock);
2469 done:
2470         ISCSI_DBG_EH(session, "dev reset result = %s\n",
2471                      rc == SUCCESS ? "SUCCESS" : "FAILED");
2472         mutex_unlock(&session->eh_mutex);
2473         return rc;
2474 }
2475 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
2476
2477 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
2478 {
2479         struct iscsi_session *session = cls_session->dd_data;
2480
2481         spin_lock_bh(&session->frwd_lock);
2482         if (session->state != ISCSI_STATE_LOGGED_IN) {
2483                 session->state = ISCSI_STATE_RECOVERY_FAILED;
2484                 wake_up(&session->ehwait);
2485         }
2486         spin_unlock_bh(&session->frwd_lock);
2487 }
2488 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
2489
2490 /**
2491  * iscsi_eh_session_reset - drop session and attempt relogin
2492  * @sc: scsi command
2493  *
2494  * This function will wait for a relogin, session termination from
2495  * userspace, or a recovery/replacement timeout.
2496  */
2497 int iscsi_eh_session_reset(struct scsi_cmnd *sc)
2498 {
2499         struct iscsi_cls_session *cls_session;
2500         struct iscsi_session *session;
2501         struct iscsi_conn *conn;
2502
2503         cls_session = starget_to_session(scsi_target(sc->device));
2504         session = cls_session->dd_data;
2505
2506         mutex_lock(&session->eh_mutex);
2507         spin_lock_bh(&session->frwd_lock);
2508         if (session->state == ISCSI_STATE_TERMINATE) {
2509 failed:
2510                 ISCSI_DBG_EH(session,
2511                              "failing session reset: Could not log back into "
2512                              "%s [age %d]\n", session->targetname,
2513                              session->age);
2514                 spin_unlock_bh(&session->frwd_lock);
2515                 mutex_unlock(&session->eh_mutex);
2516                 return FAILED;
2517         }
2518
2519         conn = session->leadconn;
2520         iscsi_get_conn(conn->cls_conn);
2521
2522         spin_unlock_bh(&session->frwd_lock);
2523         mutex_unlock(&session->eh_mutex);
2524
2525         iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2526         iscsi_put_conn(conn->cls_conn);
2527
2528         ISCSI_DBG_EH(session, "wait for relogin\n");
2529         wait_event_interruptible(session->ehwait,
2530                                  session->state == ISCSI_STATE_TERMINATE ||
2531                                  session->state == ISCSI_STATE_LOGGED_IN ||
2532                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
2533         if (signal_pending(current))
2534                 flush_signals(current);
2535
2536         mutex_lock(&session->eh_mutex);
2537         spin_lock_bh(&session->frwd_lock);
2538         if (session->state == ISCSI_STATE_LOGGED_IN) {
2539                 ISCSI_DBG_EH(session,
2540                              "session reset succeeded for %s,%s\n",
2541                              session->targetname, conn->persistent_address);
2542         } else
2543                 goto failed;
2544         spin_unlock_bh(&session->frwd_lock);
2545         mutex_unlock(&session->eh_mutex);
2546         return SUCCESS;
2547 }
2548 EXPORT_SYMBOL_GPL(iscsi_eh_session_reset);
2549
2550 static void iscsi_prep_tgt_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2551 {
2552         memset(hdr, 0, sizeof(*hdr));
2553         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2554         hdr->flags = ISCSI_TM_FUNC_TARGET_WARM_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2555         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2556         hdr->rtt = RESERVED_ITT;
2557 }
2558
2559 /**
2560  * iscsi_eh_target_reset - reset target
2561  * @sc: scsi command
2562  *
2563  * This will attempt to send a warm target reset.
2564  */
2565 static int iscsi_eh_target_reset(struct scsi_cmnd *sc)
2566 {
2567         struct iscsi_cls_session *cls_session;
2568         struct iscsi_session *session;
2569         struct iscsi_conn *conn;
2570         struct iscsi_tm *hdr;
2571         int rc = FAILED;
2572
2573         cls_session = starget_to_session(scsi_target(sc->device));
2574         session = cls_session->dd_data;
2575
2576         ISCSI_DBG_EH(session, "tgt Reset [sc %p tgt %s]\n", sc,
2577                      session->targetname);
2578
2579         mutex_lock(&session->eh_mutex);
2580         spin_lock_bh(&session->frwd_lock);
2581         /*
2582          * Just check if we are not logged in. We cannot check for
2583          * the phase because the reset could come from a ioctl.
2584          */
2585         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2586                 goto unlock;
2587         conn = session->leadconn;
2588
2589         /* only have one tmf outstanding at a time */
2590         if (session->tmf_state != TMF_INITIAL)
2591                 goto unlock;
2592         session->tmf_state = TMF_QUEUED;
2593
2594         hdr = &session->tmhdr;
2595         iscsi_prep_tgt_reset_pdu(sc, hdr);
2596
2597         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2598                                     session->tgt_reset_timeout)) {
2599                 rc = FAILED;
2600                 goto unlock;
2601         }
2602
2603         switch (session->tmf_state) {
2604         case TMF_SUCCESS:
2605                 break;
2606         case TMF_TIMEDOUT:
2607                 spin_unlock_bh(&session->frwd_lock);
2608                 iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2609                 goto done;
2610         default:
2611                 session->tmf_state = TMF_INITIAL;
2612                 goto unlock;
2613         }
2614
2615         rc = SUCCESS;
2616         spin_unlock_bh(&session->frwd_lock);
2617
2618         iscsi_suspend_tx(conn);
2619
2620         spin_lock_bh(&session->frwd_lock);
2621         memset(hdr, 0, sizeof(*hdr));
2622         fail_scsi_tasks(conn, -1, DID_ERROR);
2623         session->tmf_state = TMF_INITIAL;
2624         spin_unlock_bh(&session->frwd_lock);
2625
2626         iscsi_start_tx(conn);
2627         goto done;
2628
2629 unlock:
2630         spin_unlock_bh(&session->frwd_lock);
2631 done:
2632         ISCSI_DBG_EH(session, "tgt %s reset result = %s\n", session->targetname,
2633                      rc == SUCCESS ? "SUCCESS" : "FAILED");
2634         mutex_unlock(&session->eh_mutex);
2635         return rc;
2636 }
2637
2638 /**
2639  * iscsi_eh_recover_target - reset target and possibly the session
2640  * @sc: scsi command
2641  *
2642  * This will attempt to send a warm target reset. If that fails,
2643  * we will escalate to ERL0 session recovery.
2644  */
2645 int iscsi_eh_recover_target(struct scsi_cmnd *sc)
2646 {
2647         int rc;
2648
2649         rc = iscsi_eh_target_reset(sc);
2650         if (rc == FAILED)
2651                 rc = iscsi_eh_session_reset(sc);
2652         return rc;
2653 }
2654 EXPORT_SYMBOL_GPL(iscsi_eh_recover_target);
2655
2656 /*
2657  * Pre-allocate a pool of @max items of @item_size. By default, the pool
2658  * should be accessed via kfifo_{get,put} on q->queue.
2659  * Optionally, the caller can obtain the array of object pointers
2660  * by passing in a non-NULL @items pointer
2661  */
2662 int
2663 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
2664 {
2665         int i, num_arrays = 1;
2666
2667         memset(q, 0, sizeof(*q));
2668
2669         q->max = max;
2670
2671         /* If the user passed an items pointer, he wants a copy of
2672          * the array. */
2673         if (items)
2674                 num_arrays++;
2675         q->pool = kvcalloc(num_arrays * max, sizeof(void *), GFP_KERNEL);
2676         if (q->pool == NULL)
2677                 return -ENOMEM;
2678
2679         kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*));
2680
2681         for (i = 0; i < max; i++) {
2682                 q->pool[i] = kzalloc(item_size, GFP_KERNEL);
2683                 if (q->pool[i] == NULL) {
2684                         q->max = i;
2685                         goto enomem;
2686                 }
2687                 kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*));
2688         }
2689
2690         if (items) {
2691                 *items = q->pool + max;
2692                 memcpy(*items, q->pool, max * sizeof(void *));
2693         }
2694
2695         return 0;
2696
2697 enomem:
2698         iscsi_pool_free(q);
2699         return -ENOMEM;
2700 }
2701 EXPORT_SYMBOL_GPL(iscsi_pool_init);
2702
2703 void iscsi_pool_free(struct iscsi_pool *q)
2704 {
2705         int i;
2706
2707         for (i = 0; i < q->max; i++)
2708                 kfree(q->pool[i]);
2709         kvfree(q->pool);
2710 }
2711 EXPORT_SYMBOL_GPL(iscsi_pool_free);
2712
2713 int iscsi_host_get_max_scsi_cmds(struct Scsi_Host *shost,
2714                                  uint16_t requested_cmds_max)
2715 {
2716         int scsi_cmds, total_cmds = requested_cmds_max;
2717
2718 check:
2719         if (!total_cmds)
2720                 total_cmds = ISCSI_DEF_XMIT_CMDS_MAX;
2721         /*
2722          * The iscsi layer needs some tasks for nop handling and tmfs,
2723          * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX
2724          * + 1 command for scsi IO.
2725          */
2726         if (total_cmds < ISCSI_TOTAL_CMDS_MIN) {
2727                 printk(KERN_ERR "iscsi: invalid max cmds of %d. Must be a power of two that is at least %d.\n",
2728                        total_cmds, ISCSI_TOTAL_CMDS_MIN);
2729                 return -EINVAL;
2730         }
2731
2732         if (total_cmds > ISCSI_TOTAL_CMDS_MAX) {
2733                 printk(KERN_INFO "iscsi: invalid max cmds of %d. Must be a power of 2 less than or equal to %d. Using %d.\n",
2734                        requested_cmds_max, ISCSI_TOTAL_CMDS_MAX,
2735                        ISCSI_TOTAL_CMDS_MAX);
2736                 total_cmds = ISCSI_TOTAL_CMDS_MAX;
2737         }
2738
2739         if (!is_power_of_2(total_cmds)) {
2740                 total_cmds = rounddown_pow_of_two(total_cmds);
2741                 if (total_cmds < ISCSI_TOTAL_CMDS_MIN) {
2742                         printk(KERN_ERR "iscsi: invalid max cmds of %d. Must be a power of 2 greater than %d.\n", requested_cmds_max, ISCSI_TOTAL_CMDS_MIN);
2743                         return -EINVAL;
2744                 }
2745
2746                 printk(KERN_INFO "iscsi: invalid max cmds %d. Must be a power of 2. Rounding max cmds down to %d.\n",
2747                        requested_cmds_max, total_cmds);
2748         }
2749
2750         scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX;
2751         if (shost->can_queue && scsi_cmds > shost->can_queue) {
2752                 total_cmds = shost->can_queue;
2753
2754                 printk(KERN_INFO "iscsi: requested max cmds %u is higher than driver limit. Using driver limit %u\n",
2755                        requested_cmds_max, shost->can_queue);
2756                 goto check;
2757         }
2758
2759         return scsi_cmds;
2760 }
2761 EXPORT_SYMBOL_GPL(iscsi_host_get_max_scsi_cmds);
2762
2763 /**
2764  * iscsi_host_add - add host to system
2765  * @shost: scsi host
2766  * @pdev: parent device
2767  *
2768  * This should be called by partial offload and software iscsi drivers
2769  * to add a host to the system.
2770  */
2771 int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
2772 {
2773         if (!shost->can_queue)
2774                 shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX;
2775
2776         if (!shost->cmd_per_lun)
2777                 shost->cmd_per_lun = ISCSI_DEF_CMD_PER_LUN;
2778
2779         return scsi_add_host(shost, pdev);
2780 }
2781 EXPORT_SYMBOL_GPL(iscsi_host_add);
2782
2783 /**
2784  * iscsi_host_alloc - allocate a host and driver data
2785  * @sht: scsi host template
2786  * @dd_data_size: driver host data size
2787  * @xmit_can_sleep: bool indicating if LLD will queue IO from a work queue
2788  *
2789  * This should be called by partial offload and software iscsi drivers.
2790  * To access the driver specific memory use the iscsi_host_priv() macro.
2791  */
2792 struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht,
2793                                    int dd_data_size, bool xmit_can_sleep)
2794 {
2795         struct Scsi_Host *shost;
2796         struct iscsi_host *ihost;
2797
2798         shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size);
2799         if (!shost)
2800                 return NULL;
2801         ihost = shost_priv(shost);
2802
2803         if (xmit_can_sleep) {
2804                 snprintf(ihost->workq_name, sizeof(ihost->workq_name),
2805                         "iscsi_q_%d", shost->host_no);
2806                 ihost->workq = alloc_workqueue("%s",
2807                         WQ_SYSFS | __WQ_LEGACY | WQ_MEM_RECLAIM | WQ_UNBOUND,
2808                         1, ihost->workq_name);
2809                 if (!ihost->workq)
2810                         goto free_host;
2811         }
2812
2813         spin_lock_init(&ihost->lock);
2814         ihost->state = ISCSI_HOST_SETUP;
2815         ihost->num_sessions = 0;
2816         init_waitqueue_head(&ihost->session_removal_wq);
2817         return shost;
2818
2819 free_host:
2820         scsi_host_put(shost);
2821         return NULL;
2822 }
2823 EXPORT_SYMBOL_GPL(iscsi_host_alloc);
2824
2825 static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session)
2826 {
2827         iscsi_session_failure(cls_session->dd_data, ISCSI_ERR_INVALID_HOST);
2828 }
2829
2830 /**
2831  * iscsi_host_remove - remove host and sessions
2832  * @shost: scsi host
2833  *
2834  * If there are any sessions left, this will initiate the removal and wait
2835  * for the completion.
2836  */
2837 void iscsi_host_remove(struct Scsi_Host *shost)
2838 {
2839         struct iscsi_host *ihost = shost_priv(shost);
2840         unsigned long flags;
2841
2842         spin_lock_irqsave(&ihost->lock, flags);
2843         ihost->state = ISCSI_HOST_REMOVED;
2844         spin_unlock_irqrestore(&ihost->lock, flags);
2845
2846         iscsi_host_for_each_session(shost, iscsi_notify_host_removed);
2847         wait_event_interruptible(ihost->session_removal_wq,
2848                                  ihost->num_sessions == 0);
2849         if (signal_pending(current))
2850                 flush_signals(current);
2851
2852         scsi_remove_host(shost);
2853 }
2854 EXPORT_SYMBOL_GPL(iscsi_host_remove);
2855
2856 void iscsi_host_free(struct Scsi_Host *shost)
2857 {
2858         struct iscsi_host *ihost = shost_priv(shost);
2859
2860         if (ihost->workq)
2861                 destroy_workqueue(ihost->workq);
2862
2863         kfree(ihost->netdev);
2864         kfree(ihost->hwaddress);
2865         kfree(ihost->initiatorname);
2866         scsi_host_put(shost);
2867 }
2868 EXPORT_SYMBOL_GPL(iscsi_host_free);
2869
2870 static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost)
2871 {
2872         struct iscsi_host *ihost = shost_priv(shost);
2873         unsigned long flags;
2874
2875         shost = scsi_host_get(shost);
2876         if (!shost) {
2877                 printk(KERN_ERR "Invalid state. Cannot notify host removal "
2878                       "of session teardown event because host already "
2879                       "removed.\n");
2880                 return;
2881         }
2882
2883         spin_lock_irqsave(&ihost->lock, flags);
2884         ihost->num_sessions--;
2885         if (ihost->num_sessions == 0)
2886                 wake_up(&ihost->session_removal_wq);
2887         spin_unlock_irqrestore(&ihost->lock, flags);
2888         scsi_host_put(shost);
2889 }
2890
2891 /**
2892  * iscsi_session_setup - create iscsi cls session and host and session
2893  * @iscsit: iscsi transport template
2894  * @shost: scsi host
2895  * @cmds_max: session can queue
2896  * @dd_size: private driver data size, added to session allocation size
2897  * @cmd_task_size: LLD task private data size
2898  * @initial_cmdsn: initial CmdSN
2899  * @id: target ID to add to this session
2900  *
2901  * This can be used by software iscsi_transports that allocate
2902  * a session per scsi host.
2903  *
2904  * Callers should set cmds_max to the largest total numer (mgmt + scsi) of
2905  * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
2906  * for nop handling and login/logout requests.
2907  */
2908 struct iscsi_cls_session *
2909 iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost,
2910                     uint16_t cmds_max, int dd_size, int cmd_task_size,
2911                     uint32_t initial_cmdsn, unsigned int id)
2912 {
2913         struct iscsi_host *ihost = shost_priv(shost);
2914         struct iscsi_session *session;
2915         struct iscsi_cls_session *cls_session;
2916         int cmd_i, scsi_cmds;
2917         unsigned long flags;
2918
2919         spin_lock_irqsave(&ihost->lock, flags);
2920         if (ihost->state == ISCSI_HOST_REMOVED) {
2921                 spin_unlock_irqrestore(&ihost->lock, flags);
2922                 return NULL;
2923         }
2924         ihost->num_sessions++;
2925         spin_unlock_irqrestore(&ihost->lock, flags);
2926
2927         scsi_cmds = iscsi_host_get_max_scsi_cmds(shost, cmds_max);
2928         if (scsi_cmds < 0)
2929                 goto dec_session_count;
2930
2931         cls_session = iscsi_alloc_session(shost, iscsit,
2932                                           sizeof(struct iscsi_session) +
2933                                           dd_size);
2934         if (!cls_session)
2935                 goto dec_session_count;
2936         session = cls_session->dd_data;
2937         session->cls_session = cls_session;
2938         session->host = shost;
2939         session->state = ISCSI_STATE_FREE;
2940         session->fast_abort = 1;
2941         session->tgt_reset_timeout = 30;
2942         session->lu_reset_timeout = 15;
2943         session->abort_timeout = 10;
2944         session->scsi_cmds_max = scsi_cmds;
2945         session->cmds_max = scsi_cmds + ISCSI_MGMT_CMDS_MAX;
2946         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
2947         session->exp_cmdsn = initial_cmdsn + 1;
2948         session->max_cmdsn = initial_cmdsn + 1;
2949         session->max_r2t = 1;
2950         session->tt = iscsit;
2951         session->dd_data = cls_session->dd_data + sizeof(*session);
2952
2953         session->tmf_state = TMF_INITIAL;
2954         timer_setup(&session->tmf_timer, iscsi_tmf_timedout, 0);
2955         mutex_init(&session->eh_mutex);
2956
2957         spin_lock_init(&session->frwd_lock);
2958         spin_lock_init(&session->back_lock);
2959
2960         /* initialize SCSI PDU commands pool */
2961         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
2962                             (void***)&session->cmds,
2963                             cmd_task_size + sizeof(struct iscsi_task)))
2964                 goto cmdpool_alloc_fail;
2965
2966         /* pre-format cmds pool with ITT */
2967         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2968                 struct iscsi_task *task = session->cmds[cmd_i];
2969
2970                 if (cmd_task_size)
2971                         task->dd_data = &task[1];
2972                 task->itt = cmd_i;
2973                 task->state = ISCSI_TASK_FREE;
2974                 INIT_LIST_HEAD(&task->running);
2975         }
2976
2977         if (!try_module_get(iscsit->owner))
2978                 goto module_get_fail;
2979
2980         if (iscsi_add_session(cls_session, id))
2981                 goto cls_session_fail;
2982
2983         return cls_session;
2984
2985 cls_session_fail:
2986         module_put(iscsit->owner);
2987 module_get_fail:
2988         iscsi_pool_free(&session->cmdpool);
2989 cmdpool_alloc_fail:
2990         iscsi_free_session(cls_session);
2991 dec_session_count:
2992         iscsi_host_dec_session_cnt(shost);
2993         return NULL;
2994 }
2995 EXPORT_SYMBOL_GPL(iscsi_session_setup);
2996
2997 /**
2998  * iscsi_session_teardown - destroy session, host, and cls_session
2999  * @cls_session: iscsi session
3000  */
3001 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
3002 {
3003         struct iscsi_session *session = cls_session->dd_data;
3004         struct module *owner = cls_session->transport->owner;
3005         struct Scsi_Host *shost = session->host;
3006
3007         iscsi_remove_session(cls_session);
3008
3009         iscsi_pool_free(&session->cmdpool);
3010         kfree(session->password);
3011         kfree(session->password_in);
3012         kfree(session->username);
3013         kfree(session->username_in);
3014         kfree(session->targetname);
3015         kfree(session->targetalias);
3016         kfree(session->initiatorname);
3017         kfree(session->boot_root);
3018         kfree(session->boot_nic);
3019         kfree(session->boot_target);
3020         kfree(session->ifacename);
3021         kfree(session->portal_type);
3022         kfree(session->discovery_parent_type);
3023
3024         iscsi_free_session(cls_session);
3025
3026         iscsi_host_dec_session_cnt(shost);
3027         module_put(owner);
3028 }
3029 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
3030
3031 /**
3032  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
3033  * @cls_session: iscsi_cls_session
3034  * @dd_size: private driver data size
3035  * @conn_idx: cid
3036  */
3037 struct iscsi_cls_conn *
3038 iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size,
3039                  uint32_t conn_idx)
3040 {
3041         struct iscsi_session *session = cls_session->dd_data;
3042         struct iscsi_conn *conn;
3043         struct iscsi_cls_conn *cls_conn;
3044         char *data;
3045
3046         cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size,
3047                                      conn_idx);
3048         if (!cls_conn)
3049                 return NULL;
3050         conn = cls_conn->dd_data;
3051         memset(conn, 0, sizeof(*conn) + dd_size);
3052
3053         conn->dd_data = cls_conn->dd_data + sizeof(*conn);
3054         conn->session = session;
3055         conn->cls_conn = cls_conn;
3056         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
3057         conn->id = conn_idx;
3058         conn->exp_statsn = 0;
3059
3060         timer_setup(&conn->transport_timer, iscsi_check_transport_timeouts, 0);
3061
3062         INIT_LIST_HEAD(&conn->mgmtqueue);
3063         INIT_LIST_HEAD(&conn->cmdqueue);
3064         INIT_LIST_HEAD(&conn->requeue);
3065         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
3066
3067         /* allocate login_task used for the login/text sequences */
3068         spin_lock_bh(&session->frwd_lock);
3069         if (!kfifo_out(&session->cmdpool.queue,
3070                          (void*)&conn->login_task,
3071                          sizeof(void*))) {
3072                 spin_unlock_bh(&session->frwd_lock);
3073                 goto login_task_alloc_fail;
3074         }
3075         spin_unlock_bh(&session->frwd_lock);
3076
3077         data = (char *) __get_free_pages(GFP_KERNEL,
3078                                          get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
3079         if (!data)
3080                 goto login_task_data_alloc_fail;
3081         conn->login_task->data = conn->data = data;
3082
3083         init_waitqueue_head(&session->ehwait);
3084
3085         return cls_conn;
3086
3087 login_task_data_alloc_fail:
3088         kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
3089                     sizeof(void*));
3090 login_task_alloc_fail:
3091         iscsi_destroy_conn(cls_conn);
3092         return NULL;
3093 }
3094 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
3095
3096 /**
3097  * iscsi_conn_teardown - teardown iscsi connection
3098  * @cls_conn: iscsi class connection
3099  *
3100  * TODO: we may need to make this into a two step process
3101  * like scsi-mls remove + put host
3102  */
3103 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
3104 {
3105         struct iscsi_conn *conn = cls_conn->dd_data;
3106         struct iscsi_session *session = conn->session;
3107         char *tmp_persistent_address = conn->persistent_address;
3108         char *tmp_local_ipaddr = conn->local_ipaddr;
3109
3110         del_timer_sync(&conn->transport_timer);
3111
3112         mutex_lock(&session->eh_mutex);
3113         spin_lock_bh(&session->frwd_lock);
3114         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
3115         if (session->leadconn == conn) {
3116                 /*
3117                  * leading connection? then give up on recovery.
3118                  */
3119                 session->state = ISCSI_STATE_TERMINATE;
3120                 wake_up(&session->ehwait);
3121         }
3122         spin_unlock_bh(&session->frwd_lock);
3123
3124         /* flush queued up work because we free the connection below */
3125         iscsi_suspend_tx(conn);
3126
3127         spin_lock_bh(&session->frwd_lock);
3128         free_pages((unsigned long) conn->data,
3129                    get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
3130         /* regular RX path uses back_lock */
3131         spin_lock_bh(&session->back_lock);
3132         kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
3133                     sizeof(void*));
3134         spin_unlock_bh(&session->back_lock);
3135         if (session->leadconn == conn)
3136                 session->leadconn = NULL;
3137         spin_unlock_bh(&session->frwd_lock);
3138         mutex_unlock(&session->eh_mutex);
3139
3140         iscsi_destroy_conn(cls_conn);
3141         kfree(tmp_persistent_address);
3142         kfree(tmp_local_ipaddr);
3143 }
3144 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
3145
3146 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
3147 {
3148         struct iscsi_conn *conn = cls_conn->dd_data;
3149         struct iscsi_session *session = conn->session;
3150
3151         if (!session) {
3152                 iscsi_conn_printk(KERN_ERR, conn,
3153                                   "can't start unbound connection\n");
3154                 return -EPERM;
3155         }
3156
3157         if ((session->imm_data_en || !session->initial_r2t_en) &&
3158              session->first_burst > session->max_burst) {
3159                 iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: "
3160                                   "first_burst %d max_burst %d\n",
3161                                   session->first_burst, session->max_burst);
3162                 return -EINVAL;
3163         }
3164
3165         if (conn->ping_timeout && !conn->recv_timeout) {
3166                 iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of "
3167                                   "zero. Using 5 seconds\n.");
3168                 conn->recv_timeout = 5;
3169         }
3170
3171         if (conn->recv_timeout && !conn->ping_timeout) {
3172                 iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of "
3173                                   "zero. Using 5 seconds.\n");
3174                 conn->ping_timeout = 5;
3175         }
3176
3177         spin_lock_bh(&session->frwd_lock);
3178         conn->c_stage = ISCSI_CONN_STARTED;
3179         session->state = ISCSI_STATE_LOGGED_IN;
3180         session->queued_cmdsn = session->cmdsn;
3181
3182         conn->last_recv = jiffies;
3183         conn->last_ping = jiffies;
3184         if (conn->recv_timeout && conn->ping_timeout)
3185                 mod_timer(&conn->transport_timer,
3186                           jiffies + (conn->recv_timeout * HZ));
3187
3188         switch(conn->stop_stage) {
3189         case STOP_CONN_RECOVER:
3190                 /*
3191                  * unblock eh_abort() if it is blocked. re-try all
3192                  * commands after successful recovery
3193                  */
3194                 conn->stop_stage = 0;
3195                 session->tmf_state = TMF_INITIAL;
3196                 session->age++;
3197                 if (session->age == 16)
3198                         session->age = 0;
3199                 break;
3200         case STOP_CONN_TERM:
3201                 conn->stop_stage = 0;
3202                 break;
3203         default:
3204                 break;
3205         }
3206         spin_unlock_bh(&session->frwd_lock);
3207
3208         iscsi_unblock_session(session->cls_session);
3209         wake_up(&session->ehwait);
3210         return 0;
3211 }
3212 EXPORT_SYMBOL_GPL(iscsi_conn_start);
3213
3214 static void
3215 fail_mgmt_tasks(struct iscsi_session *session, struct iscsi_conn *conn)
3216 {
3217         struct iscsi_task *task;
3218         int i, state;
3219
3220         for (i = 0; i < conn->session->cmds_max; i++) {
3221                 task = conn->session->cmds[i];
3222                 if (task->sc)
3223                         continue;
3224
3225                 if (task->state == ISCSI_TASK_FREE)
3226                         continue;
3227
3228                 ISCSI_DBG_SESSION(conn->session,
3229                                   "failing mgmt itt 0x%x state %d\n",
3230                                   task->itt, task->state);
3231
3232                 spin_lock_bh(&session->back_lock);
3233                 if (cleanup_queued_task(task)) {
3234                         spin_unlock_bh(&session->back_lock);
3235                         continue;
3236                 }
3237
3238                 state = ISCSI_TASK_ABRT_SESS_RECOV;
3239                 if (task->state == ISCSI_TASK_PENDING)
3240                         state = ISCSI_TASK_COMPLETED;
3241                 iscsi_complete_task(task, state);
3242                 spin_unlock_bh(&session->back_lock);
3243         }
3244 }
3245
3246 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
3247 {
3248         struct iscsi_conn *conn = cls_conn->dd_data;
3249         struct iscsi_session *session = conn->session;
3250         int old_stop_stage;
3251
3252         mutex_lock(&session->eh_mutex);
3253         spin_lock_bh(&session->frwd_lock);
3254         if (conn->stop_stage == STOP_CONN_TERM) {
3255                 spin_unlock_bh(&session->frwd_lock);
3256                 mutex_unlock(&session->eh_mutex);
3257                 return;
3258         }
3259
3260         /*
3261          * When this is called for the in_login state, we only want to clean
3262          * up the login task and connection. We do not need to block and set
3263          * the recovery state again
3264          */
3265         if (flag == STOP_CONN_TERM)
3266                 session->state = ISCSI_STATE_TERMINATE;
3267         else if (conn->stop_stage != STOP_CONN_RECOVER)
3268                 session->state = ISCSI_STATE_IN_RECOVERY;
3269
3270         old_stop_stage = conn->stop_stage;
3271         conn->stop_stage = flag;
3272         spin_unlock_bh(&session->frwd_lock);
3273
3274         del_timer_sync(&conn->transport_timer);
3275         iscsi_suspend_tx(conn);
3276
3277         spin_lock_bh(&session->frwd_lock);
3278         conn->c_stage = ISCSI_CONN_STOPPED;
3279         spin_unlock_bh(&session->frwd_lock);
3280
3281         /*
3282          * for connection level recovery we should not calculate
3283          * header digest. conn->hdr_size used for optimization
3284          * in hdr_extract() and will be re-negotiated at
3285          * set_param() time.
3286          */
3287         if (flag == STOP_CONN_RECOVER) {
3288                 conn->hdrdgst_en = 0;
3289                 conn->datadgst_en = 0;
3290                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
3291                     old_stop_stage != STOP_CONN_RECOVER) {
3292                         ISCSI_DBG_SESSION(session, "blocking session\n");
3293                         iscsi_block_session(session->cls_session);
3294                 }
3295         }
3296
3297         /*
3298          * flush queues.
3299          */
3300         spin_lock_bh(&session->frwd_lock);
3301         fail_scsi_tasks(conn, -1, DID_TRANSPORT_DISRUPTED);
3302         fail_mgmt_tasks(session, conn);
3303         memset(&session->tmhdr, 0, sizeof(session->tmhdr));
3304         spin_unlock_bh(&session->frwd_lock);
3305         mutex_unlock(&session->eh_mutex);
3306 }
3307 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
3308
3309 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
3310                     struct iscsi_cls_conn *cls_conn, int is_leading)
3311 {
3312         struct iscsi_session *session = cls_session->dd_data;
3313         struct iscsi_conn *conn = cls_conn->dd_data;
3314
3315         spin_lock_bh(&session->frwd_lock);
3316         if (is_leading)
3317                 session->leadconn = conn;
3318
3319         set_bit(ISCSI_CONN_FLAG_BOUND, &conn->flags);
3320         spin_unlock_bh(&session->frwd_lock);
3321
3322         /*
3323          * The target could have reduced it's window size between logins, so
3324          * we have to reset max/exp cmdsn so we can see the new values.
3325          */
3326         spin_lock_bh(&session->back_lock);
3327         session->max_cmdsn = session->exp_cmdsn = session->cmdsn + 1;
3328         spin_unlock_bh(&session->back_lock);
3329         /*
3330          * Unblock xmitworker(), Login Phase will pass through.
3331          */
3332         clear_bit(ISCSI_CONN_FLAG_SUSPEND_RX, &conn->flags);
3333         clear_bit(ISCSI_CONN_FLAG_SUSPEND_TX, &conn->flags);
3334         return 0;
3335 }
3336 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
3337
3338 int iscsi_switch_str_param(char **param, char *new_val_buf)
3339 {
3340         char *new_val;
3341
3342         if (*param) {
3343                 if (!strcmp(*param, new_val_buf))
3344                         return 0;
3345         }
3346
3347         new_val = kstrdup(new_val_buf, GFP_NOIO);
3348         if (!new_val)
3349                 return -ENOMEM;
3350
3351         kfree(*param);
3352         *param = new_val;
3353         return 0;
3354 }
3355 EXPORT_SYMBOL_GPL(iscsi_switch_str_param);
3356
3357 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
3358                     enum iscsi_param param, char *buf, int buflen)
3359 {
3360         struct iscsi_conn *conn = cls_conn->dd_data;
3361         struct iscsi_session *session = conn->session;
3362         int val;
3363
3364         switch(param) {
3365         case ISCSI_PARAM_FAST_ABORT:
3366                 sscanf(buf, "%d", &session->fast_abort);
3367                 break;
3368         case ISCSI_PARAM_ABORT_TMO:
3369                 sscanf(buf, "%d", &session->abort_timeout);
3370                 break;
3371         case ISCSI_PARAM_LU_RESET_TMO:
3372                 sscanf(buf, "%d", &session->lu_reset_timeout);
3373                 break;
3374         case ISCSI_PARAM_TGT_RESET_TMO:
3375                 sscanf(buf, "%d", &session->tgt_reset_timeout);
3376                 break;
3377         case ISCSI_PARAM_PING_TMO:
3378                 sscanf(buf, "%d", &conn->ping_timeout);
3379                 break;
3380         case ISCSI_PARAM_RECV_TMO:
3381                 sscanf(buf, "%d", &conn->recv_timeout);
3382                 break;
3383         case ISCSI_PARAM_MAX_RECV_DLENGTH:
3384                 sscanf(buf, "%d", &conn->max_recv_dlength);
3385                 break;
3386         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3387                 sscanf(buf, "%d", &conn->max_xmit_dlength);
3388                 break;
3389         case ISCSI_PARAM_HDRDGST_EN:
3390                 sscanf(buf, "%d", &conn->hdrdgst_en);
3391                 break;
3392         case ISCSI_PARAM_DATADGST_EN:
3393                 sscanf(buf, "%d", &conn->datadgst_en);
3394                 break;
3395         case ISCSI_PARAM_INITIAL_R2T_EN:
3396                 sscanf(buf, "%d", &session->initial_r2t_en);
3397                 break;
3398         case ISCSI_PARAM_MAX_R2T:
3399                 sscanf(buf, "%hu", &session->max_r2t);
3400                 break;
3401         case ISCSI_PARAM_IMM_DATA_EN:
3402                 sscanf(buf, "%d", &session->imm_data_en);
3403                 break;
3404         case ISCSI_PARAM_FIRST_BURST:
3405                 sscanf(buf, "%d", &session->first_burst);
3406                 break;
3407         case ISCSI_PARAM_MAX_BURST:
3408                 sscanf(buf, "%d", &session->max_burst);
3409                 break;
3410         case ISCSI_PARAM_PDU_INORDER_EN:
3411                 sscanf(buf, "%d", &session->pdu_inorder_en);
3412                 break;
3413         case ISCSI_PARAM_DATASEQ_INORDER_EN:
3414                 sscanf(buf, "%d", &session->dataseq_inorder_en);
3415                 break;
3416         case ISCSI_PARAM_ERL:
3417                 sscanf(buf, "%d", &session->erl);
3418                 break;
3419         case ISCSI_PARAM_EXP_STATSN:
3420                 sscanf(buf, "%u", &conn->exp_statsn);
3421                 break;
3422         case ISCSI_PARAM_USERNAME:
3423                 return iscsi_switch_str_param(&session->username, buf);
3424         case ISCSI_PARAM_USERNAME_IN:
3425                 return iscsi_switch_str_param(&session->username_in, buf);
3426         case ISCSI_PARAM_PASSWORD:
3427                 return iscsi_switch_str_param(&session->password, buf);
3428         case ISCSI_PARAM_PASSWORD_IN:
3429                 return iscsi_switch_str_param(&session->password_in, buf);
3430         case ISCSI_PARAM_TARGET_NAME:
3431                 return iscsi_switch_str_param(&session->targetname, buf);
3432         case ISCSI_PARAM_TARGET_ALIAS:
3433                 return iscsi_switch_str_param(&session->targetalias, buf);
3434         case ISCSI_PARAM_TPGT:
3435                 sscanf(buf, "%d", &session->tpgt);
3436                 break;
3437         case ISCSI_PARAM_PERSISTENT_PORT:
3438                 sscanf(buf, "%d", &conn->persistent_port);
3439                 break;
3440         case ISCSI_PARAM_PERSISTENT_ADDRESS:
3441                 return iscsi_switch_str_param(&conn->persistent_address, buf);
3442         case ISCSI_PARAM_IFACE_NAME:
3443                 return iscsi_switch_str_param(&session->ifacename, buf);
3444         case ISCSI_PARAM_INITIATOR_NAME:
3445                 return iscsi_switch_str_param(&session->initiatorname, buf);
3446         case ISCSI_PARAM_BOOT_ROOT:
3447                 return iscsi_switch_str_param(&session->boot_root, buf);
3448         case ISCSI_PARAM_BOOT_NIC:
3449                 return iscsi_switch_str_param(&session->boot_nic, buf);
3450         case ISCSI_PARAM_BOOT_TARGET:
3451                 return iscsi_switch_str_param(&session->boot_target, buf);
3452         case ISCSI_PARAM_PORTAL_TYPE:
3453                 return iscsi_switch_str_param(&session->portal_type, buf);
3454         case ISCSI_PARAM_DISCOVERY_PARENT_TYPE:
3455                 return iscsi_switch_str_param(&session->discovery_parent_type,
3456                                               buf);
3457         case ISCSI_PARAM_DISCOVERY_SESS:
3458                 sscanf(buf, "%d", &val);
3459                 session->discovery_sess = !!val;
3460                 break;
3461         case ISCSI_PARAM_LOCAL_IPADDR:
3462                 return iscsi_switch_str_param(&conn->local_ipaddr, buf);
3463         default:
3464                 return -ENOSYS;
3465         }
3466
3467         return 0;
3468 }
3469 EXPORT_SYMBOL_GPL(iscsi_set_param);
3470
3471 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
3472                             enum iscsi_param param, char *buf)
3473 {
3474         struct iscsi_session *session = cls_session->dd_data;
3475         int len;
3476
3477         switch(param) {
3478         case ISCSI_PARAM_FAST_ABORT:
3479                 len = sysfs_emit(buf, "%d\n", session->fast_abort);
3480                 break;
3481         case ISCSI_PARAM_ABORT_TMO:
3482                 len = sysfs_emit(buf, "%d\n", session->abort_timeout);
3483                 break;
3484         case ISCSI_PARAM_LU_RESET_TMO:
3485                 len = sysfs_emit(buf, "%d\n", session->lu_reset_timeout);
3486                 break;
3487         case ISCSI_PARAM_TGT_RESET_TMO:
3488                 len = sysfs_emit(buf, "%d\n", session->tgt_reset_timeout);
3489                 break;
3490         case ISCSI_PARAM_INITIAL_R2T_EN:
3491                 len = sysfs_emit(buf, "%d\n", session->initial_r2t_en);
3492                 break;
3493         case ISCSI_PARAM_MAX_R2T:
3494                 len = sysfs_emit(buf, "%hu\n", session->max_r2t);
3495                 break;
3496         case ISCSI_PARAM_IMM_DATA_EN:
3497                 len = sysfs_emit(buf, "%d\n", session->imm_data_en);
3498                 break;
3499         case ISCSI_PARAM_FIRST_BURST:
3500                 len = sysfs_emit(buf, "%u\n", session->first_burst);
3501                 break;
3502         case ISCSI_PARAM_MAX_BURST:
3503                 len = sysfs_emit(buf, "%u\n", session->max_burst);
3504                 break;
3505         case ISCSI_PARAM_PDU_INORDER_EN:
3506                 len = sysfs_emit(buf, "%d\n", session->pdu_inorder_en);
3507                 break;
3508         case ISCSI_PARAM_DATASEQ_INORDER_EN:
3509                 len = sysfs_emit(buf, "%d\n", session->dataseq_inorder_en);
3510                 break;
3511         case ISCSI_PARAM_DEF_TASKMGMT_TMO:
3512                 len = sysfs_emit(buf, "%d\n", session->def_taskmgmt_tmo);
3513                 break;
3514         case ISCSI_PARAM_ERL:
3515                 len = sysfs_emit(buf, "%d\n", session->erl);
3516                 break;
3517         case ISCSI_PARAM_TARGET_NAME:
3518                 len = sysfs_emit(buf, "%s\n", session->targetname);
3519                 break;
3520         case ISCSI_PARAM_TARGET_ALIAS:
3521                 len = sysfs_emit(buf, "%s\n", session->targetalias);
3522                 break;
3523         case ISCSI_PARAM_TPGT:
3524                 len = sysfs_emit(buf, "%d\n", session->tpgt);
3525                 break;
3526         case ISCSI_PARAM_USERNAME:
3527                 len = sysfs_emit(buf, "%s\n", session->username);
3528                 break;
3529         case ISCSI_PARAM_USERNAME_IN:
3530                 len = sysfs_emit(buf, "%s\n", session->username_in);
3531                 break;
3532         case ISCSI_PARAM_PASSWORD:
3533                 len = sysfs_emit(buf, "%s\n", session->password);
3534                 break;
3535         case ISCSI_PARAM_PASSWORD_IN:
3536                 len = sysfs_emit(buf, "%s\n", session->password_in);
3537                 break;
3538         case ISCSI_PARAM_IFACE_NAME:
3539                 len = sysfs_emit(buf, "%s\n", session->ifacename);
3540                 break;
3541         case ISCSI_PARAM_INITIATOR_NAME:
3542                 len = sysfs_emit(buf, "%s\n", session->initiatorname);
3543                 break;
3544         case ISCSI_PARAM_BOOT_ROOT:
3545                 len = sysfs_emit(buf, "%s\n", session->boot_root);
3546                 break;
3547         case ISCSI_PARAM_BOOT_NIC:
3548                 len = sysfs_emit(buf, "%s\n", session->boot_nic);
3549                 break;
3550         case ISCSI_PARAM_BOOT_TARGET:
3551                 len = sysfs_emit(buf, "%s\n", session->boot_target);
3552                 break;
3553         case ISCSI_PARAM_AUTO_SND_TGT_DISABLE:
3554                 len = sysfs_emit(buf, "%u\n", session->auto_snd_tgt_disable);
3555                 break;
3556         case ISCSI_PARAM_DISCOVERY_SESS:
3557                 len = sysfs_emit(buf, "%u\n", session->discovery_sess);
3558                 break;
3559         case ISCSI_PARAM_PORTAL_TYPE:
3560                 len = sysfs_emit(buf, "%s\n", session->portal_type);
3561                 break;
3562         case ISCSI_PARAM_CHAP_AUTH_EN:
3563                 len = sysfs_emit(buf, "%u\n", session->chap_auth_en);
3564                 break;
3565         case ISCSI_PARAM_DISCOVERY_LOGOUT_EN:
3566                 len = sysfs_emit(buf, "%u\n", session->discovery_logout_en);
3567                 break;
3568         case ISCSI_PARAM_BIDI_CHAP_EN:
3569                 len = sysfs_emit(buf, "%u\n", session->bidi_chap_en);
3570                 break;
3571         case ISCSI_PARAM_DISCOVERY_AUTH_OPTIONAL:
3572                 len = sysfs_emit(buf, "%u\n", session->discovery_auth_optional);
3573                 break;
3574         case ISCSI_PARAM_DEF_TIME2WAIT:
3575                 len = sysfs_emit(buf, "%d\n", session->time2wait);
3576                 break;
3577         case ISCSI_PARAM_DEF_TIME2RETAIN:
3578                 len = sysfs_emit(buf, "%d\n", session->time2retain);
3579                 break;
3580         case ISCSI_PARAM_TSID:
3581                 len = sysfs_emit(buf, "%u\n", session->tsid);
3582                 break;
3583         case ISCSI_PARAM_ISID:
3584                 len = sysfs_emit(buf, "%02x%02x%02x%02x%02x%02x\n",
3585                               session->isid[0], session->isid[1],
3586                               session->isid[2], session->isid[3],
3587                               session->isid[4], session->isid[5]);
3588                 break;
3589         case ISCSI_PARAM_DISCOVERY_PARENT_IDX:
3590                 len = sysfs_emit(buf, "%u\n", session->discovery_parent_idx);
3591                 break;
3592         case ISCSI_PARAM_DISCOVERY_PARENT_TYPE:
3593                 if (session->discovery_parent_type)
3594                         len = sysfs_emit(buf, "%s\n",
3595                                       session->discovery_parent_type);
3596                 else
3597                         len = sysfs_emit(buf, "\n");
3598                 break;
3599         default:
3600                 return -ENOSYS;
3601         }
3602
3603         return len;
3604 }
3605 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
3606
3607 int iscsi_conn_get_addr_param(struct sockaddr_storage *addr,
3608                               enum iscsi_param param, char *buf)
3609 {
3610         struct sockaddr_in6 *sin6 = NULL;
3611         struct sockaddr_in *sin = NULL;
3612         int len;
3613
3614         switch (addr->ss_family) {
3615         case AF_INET:
3616                 sin = (struct sockaddr_in *)addr;
3617                 break;
3618         case AF_INET6:
3619                 sin6 = (struct sockaddr_in6 *)addr;
3620                 break;
3621         default:
3622                 return -EINVAL;
3623         }
3624
3625         switch (param) {
3626         case ISCSI_PARAM_CONN_ADDRESS:
3627         case ISCSI_HOST_PARAM_IPADDRESS:
3628                 if (sin)
3629                         len = sysfs_emit(buf, "%pI4\n", &sin->sin_addr.s_addr);
3630                 else
3631                         len = sysfs_emit(buf, "%pI6\n", &sin6->sin6_addr);
3632                 break;
3633         case ISCSI_PARAM_CONN_PORT:
3634         case ISCSI_PARAM_LOCAL_PORT:
3635                 if (sin)
3636                         len = sysfs_emit(buf, "%hu\n", be16_to_cpu(sin->sin_port));
3637                 else
3638                         len = sysfs_emit(buf, "%hu\n",
3639                                       be16_to_cpu(sin6->sin6_port));
3640                 break;
3641         default:
3642                 return -EINVAL;
3643         }
3644
3645         return len;
3646 }
3647 EXPORT_SYMBOL_GPL(iscsi_conn_get_addr_param);
3648
3649 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
3650                          enum iscsi_param param, char *buf)
3651 {
3652         struct iscsi_conn *conn = cls_conn->dd_data;
3653         int len;
3654
3655         switch(param) {
3656         case ISCSI_PARAM_PING_TMO:
3657                 len = sysfs_emit(buf, "%u\n", conn->ping_timeout);
3658                 break;
3659         case ISCSI_PARAM_RECV_TMO:
3660                 len = sysfs_emit(buf, "%u\n", conn->recv_timeout);
3661                 break;
3662         case ISCSI_PARAM_MAX_RECV_DLENGTH:
3663                 len = sysfs_emit(buf, "%u\n", conn->max_recv_dlength);
3664                 break;
3665         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3666                 len = sysfs_emit(buf, "%u\n", conn->max_xmit_dlength);
3667                 break;
3668         case ISCSI_PARAM_HDRDGST_EN:
3669                 len = sysfs_emit(buf, "%d\n", conn->hdrdgst_en);
3670                 break;
3671         case ISCSI_PARAM_DATADGST_EN:
3672                 len = sysfs_emit(buf, "%d\n", conn->datadgst_en);
3673                 break;
3674         case ISCSI_PARAM_IFMARKER_EN:
3675                 len = sysfs_emit(buf, "%d\n", conn->ifmarker_en);
3676                 break;
3677         case ISCSI_PARAM_OFMARKER_EN:
3678                 len = sysfs_emit(buf, "%d\n", conn->ofmarker_en);
3679                 break;
3680         case ISCSI_PARAM_EXP_STATSN:
3681                 len = sysfs_emit(buf, "%u\n", conn->exp_statsn);
3682                 break;
3683         case ISCSI_PARAM_PERSISTENT_PORT:
3684                 len = sysfs_emit(buf, "%d\n", conn->persistent_port);
3685                 break;
3686         case ISCSI_PARAM_PERSISTENT_ADDRESS:
3687                 len = sysfs_emit(buf, "%s\n", conn->persistent_address);
3688                 break;
3689         case ISCSI_PARAM_STATSN:
3690                 len = sysfs_emit(buf, "%u\n", conn->statsn);
3691                 break;
3692         case ISCSI_PARAM_MAX_SEGMENT_SIZE:
3693                 len = sysfs_emit(buf, "%u\n", conn->max_segment_size);
3694                 break;
3695         case ISCSI_PARAM_KEEPALIVE_TMO:
3696                 len = sysfs_emit(buf, "%u\n", conn->keepalive_tmo);
3697                 break;
3698         case ISCSI_PARAM_LOCAL_PORT:
3699                 len = sysfs_emit(buf, "%u\n", conn->local_port);
3700                 break;
3701         case ISCSI_PARAM_TCP_TIMESTAMP_STAT:
3702                 len = sysfs_emit(buf, "%u\n", conn->tcp_timestamp_stat);
3703                 break;
3704         case ISCSI_PARAM_TCP_NAGLE_DISABLE:
3705                 len = sysfs_emit(buf, "%u\n", conn->tcp_nagle_disable);
3706                 break;
3707         case ISCSI_PARAM_TCP_WSF_DISABLE:
3708                 len = sysfs_emit(buf, "%u\n", conn->tcp_wsf_disable);
3709                 break;
3710         case ISCSI_PARAM_TCP_TIMER_SCALE:
3711                 len = sysfs_emit(buf, "%u\n", conn->tcp_timer_scale);
3712                 break;
3713         case ISCSI_PARAM_TCP_TIMESTAMP_EN:
3714                 len = sysfs_emit(buf, "%u\n", conn->tcp_timestamp_en);
3715                 break;
3716         case ISCSI_PARAM_IP_FRAGMENT_DISABLE:
3717                 len = sysfs_emit(buf, "%u\n", conn->fragment_disable);
3718                 break;
3719         case ISCSI_PARAM_IPV4_TOS:
3720                 len = sysfs_emit(buf, "%u\n", conn->ipv4_tos);
3721                 break;
3722         case ISCSI_PARAM_IPV6_TC:
3723                 len = sysfs_emit(buf, "%u\n", conn->ipv6_traffic_class);
3724                 break;
3725         case ISCSI_PARAM_IPV6_FLOW_LABEL:
3726                 len = sysfs_emit(buf, "%u\n", conn->ipv6_flow_label);
3727                 break;
3728         case ISCSI_PARAM_IS_FW_ASSIGNED_IPV6:
3729                 len = sysfs_emit(buf, "%u\n", conn->is_fw_assigned_ipv6);
3730                 break;
3731         case ISCSI_PARAM_TCP_XMIT_WSF:
3732                 len = sysfs_emit(buf, "%u\n", conn->tcp_xmit_wsf);
3733                 break;
3734         case ISCSI_PARAM_TCP_RECV_WSF:
3735                 len = sysfs_emit(buf, "%u\n", conn->tcp_recv_wsf);
3736                 break;
3737         case ISCSI_PARAM_LOCAL_IPADDR:
3738                 len = sysfs_emit(buf, "%s\n", conn->local_ipaddr);
3739                 break;
3740         default:
3741                 return -ENOSYS;
3742         }
3743
3744         return len;
3745 }
3746 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
3747
3748 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3749                          char *buf)
3750 {
3751         struct iscsi_host *ihost = shost_priv(shost);
3752         int len;
3753
3754         switch (param) {
3755         case ISCSI_HOST_PARAM_NETDEV_NAME:
3756                 len = sysfs_emit(buf, "%s\n", ihost->netdev);
3757                 break;
3758         case ISCSI_HOST_PARAM_HWADDRESS:
3759                 len = sysfs_emit(buf, "%s\n", ihost->hwaddress);
3760                 break;
3761         case ISCSI_HOST_PARAM_INITIATOR_NAME:
3762                 len = sysfs_emit(buf, "%s\n", ihost->initiatorname);
3763                 break;
3764         default:
3765                 return -ENOSYS;
3766         }
3767
3768         return len;
3769 }
3770 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
3771
3772 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3773                          char *buf, int buflen)
3774 {
3775         struct iscsi_host *ihost = shost_priv(shost);
3776
3777         switch (param) {
3778         case ISCSI_HOST_PARAM_NETDEV_NAME:
3779                 return iscsi_switch_str_param(&ihost->netdev, buf);
3780         case ISCSI_HOST_PARAM_HWADDRESS:
3781                 return iscsi_switch_str_param(&ihost->hwaddress, buf);
3782         case ISCSI_HOST_PARAM_INITIATOR_NAME:
3783                 return iscsi_switch_str_param(&ihost->initiatorname, buf);
3784         default:
3785                 return -ENOSYS;
3786         }
3787
3788         return 0;
3789 }
3790 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
3791
3792 MODULE_AUTHOR("Mike Christie");
3793 MODULE_DESCRIPTION("iSCSI library functions");
3794 MODULE_LICENSE("GPL");