GNU Linux-libre 4.4.289-gnu1
[releases.git] / drivers / target / iscsi / iscsi_target_login.c
1 /*******************************************************************************
2  * This file contains the login functions used by the iSCSI Target driver.
3  *
4  * (c) Copyright 2007-2013 Datera, Inc.
5  *
6  * Author: Nicholas A. Bellinger <nab@linux-iscsi.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  ******************************************************************************/
18
19 #include <linux/string.h>
20 #include <linux/kthread.h>
21 #include <linux/crypto.h>
22 #include <linux/idr.h>
23 #include <scsi/iscsi_proto.h>
24 #include <target/target_core_base.h>
25 #include <target/target_core_fabric.h>
26
27 #include <target/iscsi/iscsi_target_core.h>
28 #include <target/iscsi/iscsi_target_stat.h>
29 #include "iscsi_target_device.h"
30 #include "iscsi_target_nego.h"
31 #include "iscsi_target_erl0.h"
32 #include "iscsi_target_erl2.h"
33 #include "iscsi_target_login.h"
34 #include "iscsi_target_tpg.h"
35 #include "iscsi_target_util.h"
36 #include "iscsi_target.h"
37 #include "iscsi_target_parameters.h"
38
39 #include <target/iscsi/iscsi_transport.h>
40
41 static struct iscsi_login *iscsi_login_init_conn(struct iscsi_conn *conn)
42 {
43         struct iscsi_login *login;
44
45         login = kzalloc(sizeof(struct iscsi_login), GFP_KERNEL);
46         if (!login) {
47                 pr_err("Unable to allocate memory for struct iscsi_login.\n");
48                 return NULL;
49         }
50         conn->login = login;
51         login->conn = conn;
52         login->first_request = 1;
53
54         login->req_buf = kzalloc(MAX_KEY_VALUE_PAIRS, GFP_KERNEL);
55         if (!login->req_buf) {
56                 pr_err("Unable to allocate memory for response buffer.\n");
57                 goto out_login;
58         }
59
60         login->rsp_buf = kzalloc(MAX_KEY_VALUE_PAIRS, GFP_KERNEL);
61         if (!login->rsp_buf) {
62                 pr_err("Unable to allocate memory for request buffer.\n");
63                 goto out_req_buf;
64         }
65
66         conn->conn_ops = kzalloc(sizeof(struct iscsi_conn_ops), GFP_KERNEL);
67         if (!conn->conn_ops) {
68                 pr_err("Unable to allocate memory for"
69                         " struct iscsi_conn_ops.\n");
70                 goto out_rsp_buf;
71         }
72
73         init_waitqueue_head(&conn->queues_wq);
74         INIT_LIST_HEAD(&conn->conn_list);
75         INIT_LIST_HEAD(&conn->conn_cmd_list);
76         INIT_LIST_HEAD(&conn->immed_queue_list);
77         INIT_LIST_HEAD(&conn->response_queue_list);
78         init_completion(&conn->conn_post_wait_comp);
79         init_completion(&conn->conn_wait_comp);
80         init_completion(&conn->conn_wait_rcfr_comp);
81         init_completion(&conn->conn_waiting_on_uc_comp);
82         init_completion(&conn->conn_logout_comp);
83         init_completion(&conn->rx_half_close_comp);
84         init_completion(&conn->tx_half_close_comp);
85         init_completion(&conn->rx_login_comp);
86         spin_lock_init(&conn->cmd_lock);
87         spin_lock_init(&conn->conn_usage_lock);
88         spin_lock_init(&conn->immed_queue_lock);
89         spin_lock_init(&conn->nopin_timer_lock);
90         spin_lock_init(&conn->response_queue_lock);
91         spin_lock_init(&conn->state_lock);
92
93         if (!zalloc_cpumask_var(&conn->conn_cpumask, GFP_KERNEL)) {
94                 pr_err("Unable to allocate conn->conn_cpumask\n");
95                 goto out_conn_ops;
96         }
97         conn->conn_login = login;
98
99         return login;
100
101 out_conn_ops:
102         kfree(conn->conn_ops);
103 out_rsp_buf:
104         kfree(login->rsp_buf);
105 out_req_buf:
106         kfree(login->req_buf);
107 out_login:
108         kfree(login);
109         return NULL;
110 }
111
112 /*
113  * Used by iscsi_target_nego.c:iscsi_target_locate_portal() to setup
114  * per struct iscsi_conn libcrypto contexts for crc32c and crc32-intel
115  */
116 int iscsi_login_setup_crypto(struct iscsi_conn *conn)
117 {
118         /*
119          * Setup slicing by CRC32C algorithm for RX and TX libcrypto contexts
120          * which will default to crc32c_intel.ko for cpu_has_xmm4_2, or fallback
121          * to software 1x8 byte slicing from crc32c.ko
122          */
123         conn->conn_rx_hash.flags = 0;
124         conn->conn_rx_hash.tfm = crypto_alloc_hash("crc32c", 0,
125                                                 CRYPTO_ALG_ASYNC);
126         if (IS_ERR(conn->conn_rx_hash.tfm)) {
127                 pr_err("crypto_alloc_hash() failed for conn_rx_tfm\n");
128                 return -ENOMEM;
129         }
130
131         conn->conn_tx_hash.flags = 0;
132         conn->conn_tx_hash.tfm = crypto_alloc_hash("crc32c", 0,
133                                                 CRYPTO_ALG_ASYNC);
134         if (IS_ERR(conn->conn_tx_hash.tfm)) {
135                 pr_err("crypto_alloc_hash() failed for conn_tx_tfm\n");
136                 crypto_free_hash(conn->conn_rx_hash.tfm);
137                 return -ENOMEM;
138         }
139
140         return 0;
141 }
142
143 static int iscsi_login_check_initiator_version(
144         struct iscsi_conn *conn,
145         u8 version_max,
146         u8 version_min)
147 {
148         if ((version_max != 0x00) || (version_min != 0x00)) {
149                 pr_err("Unsupported iSCSI IETF Pre-RFC Revision,"
150                         " version Min/Max 0x%02x/0x%02x, rejecting login.\n",
151                         version_min, version_max);
152                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_INITIATOR_ERR,
153                                 ISCSI_LOGIN_STATUS_NO_VERSION);
154                 return -1;
155         }
156
157         return 0;
158 }
159
160 int iscsi_check_for_session_reinstatement(struct iscsi_conn *conn)
161 {
162         int sessiontype;
163         struct iscsi_param *initiatorname_param = NULL, *sessiontype_param = NULL;
164         struct iscsi_portal_group *tpg = conn->tpg;
165         struct iscsi_session *sess = NULL, *sess_p = NULL;
166         struct se_portal_group *se_tpg = &tpg->tpg_se_tpg;
167         struct se_session *se_sess, *se_sess_tmp;
168
169         initiatorname_param = iscsi_find_param_from_key(
170                         INITIATORNAME, conn->param_list);
171         sessiontype_param = iscsi_find_param_from_key(
172                         SESSIONTYPE, conn->param_list);
173         if (!initiatorname_param || !sessiontype_param) {
174                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_INITIATOR_ERR,
175                         ISCSI_LOGIN_STATUS_MISSING_FIELDS);
176                 return -1;
177         }
178
179         sessiontype = (strncmp(sessiontype_param->value, NORMAL, 6)) ? 1 : 0;
180
181         spin_lock_bh(&se_tpg->session_lock);
182         list_for_each_entry_safe(se_sess, se_sess_tmp, &se_tpg->tpg_sess_list,
183                         sess_list) {
184
185                 sess_p = se_sess->fabric_sess_ptr;
186                 spin_lock(&sess_p->conn_lock);
187                 if (atomic_read(&sess_p->session_fall_back_to_erl0) ||
188                     atomic_read(&sess_p->session_logout) ||
189                     (sess_p->time2retain_timer_flags & ISCSI_TF_EXPIRED)) {
190                         spin_unlock(&sess_p->conn_lock);
191                         continue;
192                 }
193                 if (!memcmp(sess_p->isid, conn->sess->isid, 6) &&
194                    (!strcmp(sess_p->sess_ops->InitiatorName,
195                             initiatorname_param->value) &&
196                    (sess_p->sess_ops->SessionType == sessiontype))) {
197                         atomic_set(&sess_p->session_reinstatement, 1);
198                         atomic_set(&sess_p->session_fall_back_to_erl0, 1);
199                         spin_unlock(&sess_p->conn_lock);
200                         iscsit_inc_session_usage_count(sess_p);
201                         iscsit_stop_time2retain_timer(sess_p);
202                         sess = sess_p;
203                         break;
204                 }
205                 spin_unlock(&sess_p->conn_lock);
206         }
207         spin_unlock_bh(&se_tpg->session_lock);
208         /*
209          * If the Time2Retain handler has expired, the session is already gone.
210          */
211         if (!sess)
212                 return 0;
213
214         pr_debug("%s iSCSI Session SID %u is still active for %s,"
215                 " preforming session reinstatement.\n", (sessiontype) ?
216                 "Discovery" : "Normal", sess->sid,
217                 sess->sess_ops->InitiatorName);
218
219         spin_lock_bh(&sess->conn_lock);
220         if (sess->session_state == TARG_SESS_STATE_FAILED) {
221                 spin_unlock_bh(&sess->conn_lock);
222                 iscsit_dec_session_usage_count(sess);
223                 target_put_session(sess->se_sess);
224                 return 0;
225         }
226         spin_unlock_bh(&sess->conn_lock);
227
228         iscsit_stop_session(sess, 1, 1);
229         iscsit_dec_session_usage_count(sess);
230
231         target_put_session(sess->se_sess);
232         return 0;
233 }
234
235 static void iscsi_login_set_conn_values(
236         struct iscsi_session *sess,
237         struct iscsi_conn *conn,
238         __be16 cid)
239 {
240         conn->sess              = sess;
241         conn->cid               = be16_to_cpu(cid);
242         /*
243          * Generate a random Status sequence number (statsn) for the new
244          * iSCSI connection.
245          */
246         get_random_bytes(&conn->stat_sn, sizeof(u32));
247
248         mutex_lock(&auth_id_lock);
249         conn->auth_id           = iscsit_global->auth_id++;
250         mutex_unlock(&auth_id_lock);
251 }
252
253 static __printf(2, 3) int iscsi_change_param_sprintf(
254         struct iscsi_conn *conn,
255         const char *fmt, ...)
256 {
257         va_list args;
258         unsigned char buf[64];
259
260         memset(buf, 0, sizeof buf);
261
262         va_start(args, fmt);
263         vsnprintf(buf, sizeof buf, fmt, args);
264         va_end(args);
265
266         if (iscsi_change_param_value(buf, conn->param_list, 0) < 0) {
267                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
268                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
269                 return -1;
270         }
271
272         return 0;
273 }
274
275 /*
276  *      This is the leading connection of a new session,
277  *      or session reinstatement.
278  */
279 static int iscsi_login_zero_tsih_s1(
280         struct iscsi_conn *conn,
281         unsigned char *buf)
282 {
283         struct iscsi_session *sess = NULL;
284         struct iscsi_login_req *pdu = (struct iscsi_login_req *)buf;
285         int ret;
286
287         sess = kzalloc(sizeof(struct iscsi_session), GFP_KERNEL);
288         if (!sess) {
289                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
290                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
291                 pr_err("Could not allocate memory for session\n");
292                 return -ENOMEM;
293         }
294
295         iscsi_login_set_conn_values(sess, conn, pdu->cid);
296         sess->init_task_tag     = pdu->itt;
297         memcpy(&sess->isid, pdu->isid, 6);
298         sess->exp_cmd_sn        = be32_to_cpu(pdu->cmdsn);
299         INIT_LIST_HEAD(&sess->sess_conn_list);
300         INIT_LIST_HEAD(&sess->sess_ooo_cmdsn_list);
301         INIT_LIST_HEAD(&sess->cr_active_list);
302         INIT_LIST_HEAD(&sess->cr_inactive_list);
303         init_completion(&sess->async_msg_comp);
304         init_completion(&sess->reinstatement_comp);
305         init_completion(&sess->session_wait_comp);
306         init_completion(&sess->session_waiting_on_uc_comp);
307         mutex_init(&sess->cmdsn_mutex);
308         spin_lock_init(&sess->conn_lock);
309         spin_lock_init(&sess->cr_a_lock);
310         spin_lock_init(&sess->cr_i_lock);
311         spin_lock_init(&sess->session_usage_lock);
312         spin_lock_init(&sess->ttt_lock);
313
314         idr_preload(GFP_KERNEL);
315         spin_lock_bh(&sess_idr_lock);
316         ret = idr_alloc(&sess_idr, NULL, 0, 0, GFP_NOWAIT);
317         if (ret >= 0)
318                 sess->session_index = ret;
319         spin_unlock_bh(&sess_idr_lock);
320         idr_preload_end();
321
322         if (ret < 0) {
323                 pr_err("idr_alloc() for sess_idr failed\n");
324                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
325                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
326                 goto free_sess;
327         }
328
329         sess->creation_time = get_jiffies_64();
330         /*
331          * The FFP CmdSN window values will be allocated from the TPG's
332          * Initiator Node's ACL once the login has been successfully completed.
333          */
334         atomic_set(&sess->max_cmd_sn, be32_to_cpu(pdu->cmdsn));
335
336         sess->sess_ops = kzalloc(sizeof(struct iscsi_sess_ops), GFP_KERNEL);
337         if (!sess->sess_ops) {
338                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
339                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
340                 pr_err("Unable to allocate memory for"
341                                 " struct iscsi_sess_ops.\n");
342                 goto remove_idr;
343         }
344
345         sess->se_sess = transport_init_session(TARGET_PROT_NORMAL);
346         if (IS_ERR(sess->se_sess)) {
347                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
348                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
349                 goto free_ops;
350         }
351
352         return 0;
353
354 free_ops:
355         kfree(sess->sess_ops);
356 remove_idr:
357         spin_lock_bh(&sess_idr_lock);
358         idr_remove(&sess_idr, sess->session_index);
359         spin_unlock_bh(&sess_idr_lock);
360 free_sess:
361         kfree(sess);
362         conn->sess = NULL;
363         return -ENOMEM;
364 }
365
366 static int iscsi_login_zero_tsih_s2(
367         struct iscsi_conn *conn)
368 {
369         struct iscsi_node_attrib *na;
370         struct iscsi_session *sess = conn->sess;
371         bool iser = false;
372
373         sess->tpg = conn->tpg;
374
375         /*
376          * Assign a new TPG Session Handle.  Note this is protected with
377          * struct iscsi_portal_group->np_login_sem from iscsit_access_np().
378          */
379         sess->tsih = ++sess->tpg->ntsih;
380         if (!sess->tsih)
381                 sess->tsih = ++sess->tpg->ntsih;
382
383         /*
384          * Create the default params from user defined values..
385          */
386         if (iscsi_copy_param_list(&conn->param_list,
387                                 conn->tpg->param_list, 1) < 0) {
388                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
389                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
390                 return -1;
391         }
392
393         if (conn->conn_transport->transport_type == ISCSI_INFINIBAND)
394                 iser = true;
395
396         iscsi_set_keys_to_negotiate(conn->param_list, iser);
397
398         if (sess->sess_ops->SessionType)
399                 return iscsi_set_keys_irrelevant_for_discovery(
400                                 conn->param_list);
401
402         na = iscsit_tpg_get_node_attrib(sess);
403
404         /*
405          * Need to send TargetPortalGroupTag back in first login response
406          * on any iSCSI connection where the Initiator provides TargetName.
407          * See 5.3.1.  Login Phase Start
408          *
409          * In our case, we have already located the struct iscsi_tiqn at this point.
410          */
411         if (iscsi_change_param_sprintf(conn, "TargetPortalGroupTag=%hu", sess->tpg->tpgt))
412                 return -1;
413
414         /*
415          * Workaround for Initiators that have broken connection recovery logic.
416          *
417          * "We would really like to get rid of this." Linux-iSCSI.org team
418          */
419         if (iscsi_change_param_sprintf(conn, "ErrorRecoveryLevel=%d", na->default_erl))
420                 return -1;
421
422         /*
423          * Set RDMAExtensions=Yes by default for iSER enabled network portals
424          */
425         if (iser) {
426                 struct iscsi_param *param;
427                 unsigned long mrdsl, off;
428                 int rc;
429
430                 if (iscsi_change_param_sprintf(conn, "RDMAExtensions=Yes"))
431                         return -1;
432
433                 /*
434                  * Make MaxRecvDataSegmentLength PAGE_SIZE aligned for
435                  * Immediate Data + Unsolicitied Data-OUT if necessary..
436                  */
437                 param = iscsi_find_param_from_key("MaxRecvDataSegmentLength",
438                                                   conn->param_list);
439                 if (!param) {
440                         iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
441                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
442                         return -1;
443                 }
444                 rc = kstrtoul(param->value, 0, &mrdsl);
445                 if (rc < 0) {
446                         iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
447                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
448                         return -1;
449                 }
450                 off = mrdsl % PAGE_SIZE;
451                 if (!off)
452                         goto check_prot;
453
454                 if (mrdsl < PAGE_SIZE)
455                         mrdsl = PAGE_SIZE;
456                 else
457                         mrdsl -= off;
458
459                 pr_warn("Aligning ISER MaxRecvDataSegmentLength: %lu down"
460                         " to PAGE_SIZE\n", mrdsl);
461
462                 if (iscsi_change_param_sprintf(conn, "MaxRecvDataSegmentLength=%lu\n", mrdsl))
463                         return -1;
464                 /*
465                  * ISER currently requires that ImmediateData + Unsolicited
466                  * Data be disabled when protection / signature MRs are enabled.
467                  */
468 check_prot:
469                 if (sess->se_sess->sup_prot_ops &
470                    (TARGET_PROT_DOUT_STRIP | TARGET_PROT_DOUT_PASS |
471                     TARGET_PROT_DOUT_INSERT)) {
472
473                         if (iscsi_change_param_sprintf(conn, "ImmediateData=No"))
474                                 return -1;
475
476                         if (iscsi_change_param_sprintf(conn, "InitialR2T=Yes"))
477                                 return -1;
478
479                         pr_debug("Forcing ImmediateData=No + InitialR2T=Yes for"
480                                  " T10-PI enabled ISER session\n");
481                 }
482         }
483
484         return 0;
485 }
486
487 static int iscsi_login_non_zero_tsih_s1(
488         struct iscsi_conn *conn,
489         unsigned char *buf)
490 {
491         struct iscsi_login_req *pdu = (struct iscsi_login_req *)buf;
492
493         iscsi_login_set_conn_values(NULL, conn, pdu->cid);
494         return 0;
495 }
496
497 /*
498  *      Add a new connection to an existing session.
499  */
500 static int iscsi_login_non_zero_tsih_s2(
501         struct iscsi_conn *conn,
502         unsigned char *buf)
503 {
504         struct iscsi_portal_group *tpg = conn->tpg;
505         struct iscsi_session *sess = NULL, *sess_p = NULL;
506         struct se_portal_group *se_tpg = &tpg->tpg_se_tpg;
507         struct se_session *se_sess, *se_sess_tmp;
508         struct iscsi_login_req *pdu = (struct iscsi_login_req *)buf;
509         bool iser = false;
510
511         spin_lock_bh(&se_tpg->session_lock);
512         list_for_each_entry_safe(se_sess, se_sess_tmp, &se_tpg->tpg_sess_list,
513                         sess_list) {
514
515                 sess_p = (struct iscsi_session *)se_sess->fabric_sess_ptr;
516                 if (atomic_read(&sess_p->session_fall_back_to_erl0) ||
517                     atomic_read(&sess_p->session_logout) ||
518                    (sess_p->time2retain_timer_flags & ISCSI_TF_EXPIRED))
519                         continue;
520                 if (!memcmp(sess_p->isid, pdu->isid, 6) &&
521                      (sess_p->tsih == be16_to_cpu(pdu->tsih))) {
522                         iscsit_inc_session_usage_count(sess_p);
523                         iscsit_stop_time2retain_timer(sess_p);
524                         sess = sess_p;
525                         break;
526                 }
527         }
528         spin_unlock_bh(&se_tpg->session_lock);
529
530         /*
531          * If the Time2Retain handler has expired, the session is already gone.
532          */
533         if (!sess) {
534                 pr_err("Initiator attempting to add a connection to"
535                         " a non-existent session, rejecting iSCSI Login.\n");
536                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_INITIATOR_ERR,
537                                 ISCSI_LOGIN_STATUS_NO_SESSION);
538                 return -1;
539         }
540
541         /*
542          * Stop the Time2Retain timer if this is a failed session, we restart
543          * the timer if the login is not successful.
544          */
545         spin_lock_bh(&sess->conn_lock);
546         if (sess->session_state == TARG_SESS_STATE_FAILED)
547                 atomic_set(&sess->session_continuation, 1);
548         spin_unlock_bh(&sess->conn_lock);
549
550         iscsi_login_set_conn_values(sess, conn, pdu->cid);
551
552         if (iscsi_copy_param_list(&conn->param_list,
553                         conn->tpg->param_list, 0) < 0) {
554                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
555                                 ISCSI_LOGIN_STATUS_NO_RESOURCES);
556                 return -1;
557         }
558
559         if (conn->conn_transport->transport_type == ISCSI_INFINIBAND)
560                 iser = true;
561
562         iscsi_set_keys_to_negotiate(conn->param_list, iser);
563         /*
564          * Need to send TargetPortalGroupTag back in first login response
565          * on any iSCSI connection where the Initiator provides TargetName.
566          * See 5.3.1.  Login Phase Start
567          *
568          * In our case, we have already located the struct iscsi_tiqn at this point.
569          */
570         if (iscsi_change_param_sprintf(conn, "TargetPortalGroupTag=%hu", sess->tpg->tpgt))
571                 return -1;
572
573         return 0;
574 }
575
576 int iscsi_login_post_auth_non_zero_tsih(
577         struct iscsi_conn *conn,
578         u16 cid,
579         u32 exp_statsn)
580 {
581         struct iscsi_conn *conn_ptr = NULL;
582         struct iscsi_conn_recovery *cr = NULL;
583         struct iscsi_session *sess = conn->sess;
584
585         /*
586          * By following item 5 in the login table,  if we have found
587          * an existing ISID and a valid/existing TSIH and an existing
588          * CID we do connection reinstatement.  Currently we dont not
589          * support it so we send back an non-zero status class to the
590          * initiator and release the new connection.
591          */
592         conn_ptr = iscsit_get_conn_from_cid_rcfr(sess, cid);
593         if (conn_ptr) {
594                 pr_err("Connection exists with CID %hu for %s,"
595                         " performing connection reinstatement.\n",
596                         conn_ptr->cid, sess->sess_ops->InitiatorName);
597
598                 iscsit_connection_reinstatement_rcfr(conn_ptr);
599                 iscsit_dec_conn_usage_count(conn_ptr);
600         }
601
602         /*
603          * Check for any connection recovery entires containing CID.
604          * We use the original ExpStatSN sent in the first login request
605          * to acknowledge commands for the failed connection.
606          *
607          * Also note that an explict logout may have already been sent,
608          * but the response may not be sent due to additional connection
609          * loss.
610          */
611         if (sess->sess_ops->ErrorRecoveryLevel == 2) {
612                 cr = iscsit_get_inactive_connection_recovery_entry(
613                                 sess, cid);
614                 if (cr) {
615                         pr_debug("Performing implicit logout"
616                                 " for connection recovery on CID: %hu\n",
617                                         conn->cid);
618                         iscsit_discard_cr_cmds_by_expstatsn(cr, exp_statsn);
619                 }
620         }
621
622         /*
623          * Else we follow item 4 from the login table in that we have
624          * found an existing ISID and a valid/existing TSIH and a new
625          * CID we go ahead and continue to add a new connection to the
626          * session.
627          */
628         pr_debug("Adding CID %hu to existing session for %s.\n",
629                         cid, sess->sess_ops->InitiatorName);
630
631         if ((atomic_read(&sess->nconn) + 1) > sess->sess_ops->MaxConnections) {
632                 pr_err("Adding additional connection to this session"
633                         " would exceed MaxConnections %d, login failed.\n",
634                                 sess->sess_ops->MaxConnections);
635                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_INITIATOR_ERR,
636                                 ISCSI_LOGIN_STATUS_ISID_ERROR);
637                 return -1;
638         }
639
640         return 0;
641 }
642
643 static void iscsi_post_login_start_timers(struct iscsi_conn *conn)
644 {
645         struct iscsi_session *sess = conn->sess;
646         /*
647          * FIXME: Unsolicitied NopIN support for ISER
648          */
649         if (conn->conn_transport->transport_type == ISCSI_INFINIBAND)
650                 return;
651
652         if (!sess->sess_ops->SessionType)
653                 iscsit_start_nopin_timer(conn);
654 }
655
656 int iscsit_start_kthreads(struct iscsi_conn *conn)
657 {
658         int ret = 0;
659
660         spin_lock(&iscsit_global->ts_bitmap_lock);
661         conn->bitmap_id = bitmap_find_free_region(iscsit_global->ts_bitmap,
662                                         ISCSIT_BITMAP_BITS, get_order(1));
663         spin_unlock(&iscsit_global->ts_bitmap_lock);
664
665         if (conn->bitmap_id < 0) {
666                 pr_err("bitmap_find_free_region() failed for"
667                        " iscsit_start_kthreads()\n");
668                 return -ENOMEM;
669         }
670
671         conn->tx_thread = kthread_run(iscsi_target_tx_thread, conn,
672                                       "%s", ISCSI_TX_THREAD_NAME);
673         if (IS_ERR(conn->tx_thread)) {
674                 pr_err("Unable to start iscsi_target_tx_thread\n");
675                 ret = PTR_ERR(conn->tx_thread);
676                 goto out_bitmap;
677         }
678         conn->tx_thread_active = true;
679
680         conn->rx_thread = kthread_run(iscsi_target_rx_thread, conn,
681                                       "%s", ISCSI_RX_THREAD_NAME);
682         if (IS_ERR(conn->rx_thread)) {
683                 pr_err("Unable to start iscsi_target_rx_thread\n");
684                 ret = PTR_ERR(conn->rx_thread);
685                 goto out_tx;
686         }
687         conn->rx_thread_active = true;
688
689         return 0;
690 out_tx:
691         send_sig(SIGINT, conn->tx_thread, 1);
692         kthread_stop(conn->tx_thread);
693         conn->tx_thread_active = false;
694 out_bitmap:
695         spin_lock(&iscsit_global->ts_bitmap_lock);
696         bitmap_release_region(iscsit_global->ts_bitmap, conn->bitmap_id,
697                               get_order(1));
698         spin_unlock(&iscsit_global->ts_bitmap_lock);
699         return ret;
700 }
701
702 void iscsi_post_login_handler(
703         struct iscsi_np *np,
704         struct iscsi_conn *conn,
705         u8 zero_tsih)
706 {
707         int stop_timer = 0;
708         struct iscsi_session *sess = conn->sess;
709         struct se_session *se_sess = sess->se_sess;
710         struct iscsi_portal_group *tpg = sess->tpg;
711         struct se_portal_group *se_tpg = &tpg->tpg_se_tpg;
712
713         iscsit_inc_conn_usage_count(conn);
714
715         iscsit_collect_login_stats(conn, ISCSI_STATUS_CLS_SUCCESS,
716                         ISCSI_LOGIN_STATUS_ACCEPT);
717
718         pr_debug("Moving to TARG_CONN_STATE_LOGGED_IN.\n");
719         conn->conn_state = TARG_CONN_STATE_LOGGED_IN;
720
721         iscsi_set_connection_parameters(conn->conn_ops, conn->param_list);
722         /*
723          * SCSI Initiator -> SCSI Target Port Mapping
724          */
725         if (!zero_tsih) {
726                 iscsi_set_session_parameters(sess->sess_ops,
727                                 conn->param_list, 0);
728                 iscsi_release_param_list(conn->param_list);
729                 conn->param_list = NULL;
730
731                 spin_lock_bh(&sess->conn_lock);
732                 atomic_set(&sess->session_continuation, 0);
733                 if (sess->session_state == TARG_SESS_STATE_FAILED) {
734                         pr_debug("Moving to"
735                                         " TARG_SESS_STATE_LOGGED_IN.\n");
736                         sess->session_state = TARG_SESS_STATE_LOGGED_IN;
737                         stop_timer = 1;
738                 }
739
740                 pr_debug("iSCSI Login successful on CID: %hu from %pISpc to"
741                         " %pISpc,%hu\n", conn->cid, &conn->login_sockaddr,
742                         &conn->local_sockaddr, tpg->tpgt);
743
744                 list_add_tail(&conn->conn_list, &sess->sess_conn_list);
745                 atomic_inc(&sess->nconn);
746                 pr_debug("Incremented iSCSI Connection count to %hu"
747                         " from node: %s\n", atomic_read(&sess->nconn),
748                         sess->sess_ops->InitiatorName);
749                 spin_unlock_bh(&sess->conn_lock);
750
751                 iscsi_post_login_start_timers(conn);
752                 /*
753                  * Determine CPU mask to ensure connection's RX and TX kthreads
754                  * are scheduled on the same CPU.
755                  */
756                 iscsit_thread_get_cpumask(conn);
757                 conn->conn_rx_reset_cpumask = 1;
758                 conn->conn_tx_reset_cpumask = 1;
759                 /*
760                  * Wakeup the sleeping iscsi_target_rx_thread() now that
761                  * iscsi_conn is in TARG_CONN_STATE_LOGGED_IN state.
762                  */
763                 complete(&conn->rx_login_comp);
764                 iscsit_dec_conn_usage_count(conn);
765
766                 if (stop_timer) {
767                         spin_lock_bh(&se_tpg->session_lock);
768                         iscsit_stop_time2retain_timer(sess);
769                         spin_unlock_bh(&se_tpg->session_lock);
770                 }
771                 iscsit_dec_session_usage_count(sess);
772                 return;
773         }
774
775         iscsi_set_session_parameters(sess->sess_ops, conn->param_list, 1);
776         iscsi_release_param_list(conn->param_list);
777         conn->param_list = NULL;
778
779         iscsit_determine_maxcmdsn(sess);
780
781         spin_lock_bh(&se_tpg->session_lock);
782         __transport_register_session(&sess->tpg->tpg_se_tpg,
783                         se_sess->se_node_acl, se_sess, sess);
784         pr_debug("Moving to TARG_SESS_STATE_LOGGED_IN.\n");
785         sess->session_state = TARG_SESS_STATE_LOGGED_IN;
786
787         pr_debug("iSCSI Login successful on CID: %hu from %pISpc to %pISpc,%hu\n",
788                 conn->cid, &conn->login_sockaddr, &conn->local_sockaddr,
789                 tpg->tpgt);
790
791         spin_lock_bh(&sess->conn_lock);
792         list_add_tail(&conn->conn_list, &sess->sess_conn_list);
793         atomic_inc(&sess->nconn);
794         pr_debug("Incremented iSCSI Connection count to %hu from node:"
795                 " %s\n", atomic_read(&sess->nconn),
796                 sess->sess_ops->InitiatorName);
797         spin_unlock_bh(&sess->conn_lock);
798
799         sess->sid = tpg->sid++;
800         if (!sess->sid)
801                 sess->sid = tpg->sid++;
802         pr_debug("Established iSCSI session from node: %s\n",
803                         sess->sess_ops->InitiatorName);
804
805         tpg->nsessions++;
806         if (tpg->tpg_tiqn)
807                 tpg->tpg_tiqn->tiqn_nsessions++;
808
809         pr_debug("Incremented number of active iSCSI sessions to %u on"
810                 " iSCSI Target Portal Group: %hu\n", tpg->nsessions, tpg->tpgt);
811         spin_unlock_bh(&se_tpg->session_lock);
812
813         iscsi_post_login_start_timers(conn);
814         /*
815          * Determine CPU mask to ensure connection's RX and TX kthreads
816          * are scheduled on the same CPU.
817          */
818         iscsit_thread_get_cpumask(conn);
819         conn->conn_rx_reset_cpumask = 1;
820         conn->conn_tx_reset_cpumask = 1;
821         /*
822          * Wakeup the sleeping iscsi_target_rx_thread() now that
823          * iscsi_conn is in TARG_CONN_STATE_LOGGED_IN state.
824          */
825         complete(&conn->rx_login_comp);
826         iscsit_dec_conn_usage_count(conn);
827 }
828
829 static void iscsi_handle_login_thread_timeout(unsigned long data)
830 {
831         struct iscsi_np *np = (struct iscsi_np *) data;
832
833         spin_lock_bh(&np->np_thread_lock);
834         pr_err("iSCSI Login timeout on Network Portal %pISpc\n",
835                         &np->np_sockaddr);
836
837         if (np->np_login_timer_flags & ISCSI_TF_STOP) {
838                 spin_unlock_bh(&np->np_thread_lock);
839                 return;
840         }
841
842         if (np->np_thread)
843                 send_sig(SIGINT, np->np_thread, 1);
844
845         np->np_login_timer_flags &= ~ISCSI_TF_RUNNING;
846         spin_unlock_bh(&np->np_thread_lock);
847 }
848
849 static void iscsi_start_login_thread_timer(struct iscsi_np *np)
850 {
851         /*
852          * This used the TA_LOGIN_TIMEOUT constant because at this
853          * point we do not have access to ISCSI_TPG_ATTRIB(tpg)->login_timeout
854          */
855         spin_lock_bh(&np->np_thread_lock);
856         init_timer(&np->np_login_timer);
857         np->np_login_timer.expires = (get_jiffies_64() + TA_LOGIN_TIMEOUT * HZ);
858         np->np_login_timer.data = (unsigned long)np;
859         np->np_login_timer.function = iscsi_handle_login_thread_timeout;
860         np->np_login_timer_flags &= ~ISCSI_TF_STOP;
861         np->np_login_timer_flags |= ISCSI_TF_RUNNING;
862         add_timer(&np->np_login_timer);
863
864         pr_debug("Added timeout timer to iSCSI login request for"
865                         " %u seconds.\n", TA_LOGIN_TIMEOUT);
866         spin_unlock_bh(&np->np_thread_lock);
867 }
868
869 static void iscsi_stop_login_thread_timer(struct iscsi_np *np)
870 {
871         spin_lock_bh(&np->np_thread_lock);
872         if (!(np->np_login_timer_flags & ISCSI_TF_RUNNING)) {
873                 spin_unlock_bh(&np->np_thread_lock);
874                 return;
875         }
876         np->np_login_timer_flags |= ISCSI_TF_STOP;
877         spin_unlock_bh(&np->np_thread_lock);
878
879         del_timer_sync(&np->np_login_timer);
880
881         spin_lock_bh(&np->np_thread_lock);
882         np->np_login_timer_flags &= ~ISCSI_TF_RUNNING;
883         spin_unlock_bh(&np->np_thread_lock);
884 }
885
886 int iscsit_setup_np(
887         struct iscsi_np *np,
888         struct sockaddr_storage *sockaddr)
889 {
890         struct socket *sock = NULL;
891         int backlog = ISCSIT_TCP_BACKLOG, ret, opt = 0, len;
892
893         switch (np->np_network_transport) {
894         case ISCSI_TCP:
895                 np->np_ip_proto = IPPROTO_TCP;
896                 np->np_sock_type = SOCK_STREAM;
897                 break;
898         case ISCSI_SCTP_TCP:
899                 np->np_ip_proto = IPPROTO_SCTP;
900                 np->np_sock_type = SOCK_STREAM;
901                 break;
902         case ISCSI_SCTP_UDP:
903                 np->np_ip_proto = IPPROTO_SCTP;
904                 np->np_sock_type = SOCK_SEQPACKET;
905                 break;
906         default:
907                 pr_err("Unsupported network_transport: %d\n",
908                                 np->np_network_transport);
909                 return -EINVAL;
910         }
911
912         np->np_ip_proto = IPPROTO_TCP;
913         np->np_sock_type = SOCK_STREAM;
914
915         ret = sock_create(sockaddr->ss_family, np->np_sock_type,
916                         np->np_ip_proto, &sock);
917         if (ret < 0) {
918                 pr_err("sock_create() failed.\n");
919                 return ret;
920         }
921         np->np_socket = sock;
922         /*
923          * Setup the np->np_sockaddr from the passed sockaddr setup
924          * in iscsi_target_configfs.c code..
925          */
926         memcpy(&np->np_sockaddr, sockaddr,
927                         sizeof(struct sockaddr_storage));
928
929         if (sockaddr->ss_family == AF_INET6)
930                 len = sizeof(struct sockaddr_in6);
931         else
932                 len = sizeof(struct sockaddr_in);
933         /*
934          * Set SO_REUSEADDR, and disable Nagel Algorithm with TCP_NODELAY.
935          */
936         /* FIXME: Someone please explain why this is endian-safe */
937         opt = 1;
938         if (np->np_network_transport == ISCSI_TCP) {
939                 ret = kernel_setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
940                                 (char *)&opt, sizeof(opt));
941                 if (ret < 0) {
942                         pr_err("kernel_setsockopt() for TCP_NODELAY"
943                                 " failed: %d\n", ret);
944                         goto fail;
945                 }
946         }
947
948         /* FIXME: Someone please explain why this is endian-safe */
949         ret = kernel_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
950                         (char *)&opt, sizeof(opt));
951         if (ret < 0) {
952                 pr_err("kernel_setsockopt() for SO_REUSEADDR"
953                         " failed\n");
954                 goto fail;
955         }
956
957         ret = kernel_setsockopt(sock, IPPROTO_IP, IP_FREEBIND,
958                         (char *)&opt, sizeof(opt));
959         if (ret < 0) {
960                 pr_err("kernel_setsockopt() for IP_FREEBIND"
961                         " failed\n");
962                 goto fail;
963         }
964
965         ret = kernel_bind(sock, (struct sockaddr *)&np->np_sockaddr, len);
966         if (ret < 0) {
967                 pr_err("kernel_bind() failed: %d\n", ret);
968                 goto fail;
969         }
970
971         ret = kernel_listen(sock, backlog);
972         if (ret != 0) {
973                 pr_err("kernel_listen() failed: %d\n", ret);
974                 goto fail;
975         }
976
977         return 0;
978 fail:
979         np->np_socket = NULL;
980         sock_release(sock);
981         return ret;
982 }
983
984 int iscsi_target_setup_login_socket(
985         struct iscsi_np *np,
986         struct sockaddr_storage *sockaddr)
987 {
988         struct iscsit_transport *t;
989         int rc;
990
991         t = iscsit_get_transport(np->np_network_transport);
992         if (!t)
993                 return -EINVAL;
994
995         rc = t->iscsit_setup_np(np, sockaddr);
996         if (rc < 0) {
997                 iscsit_put_transport(t);
998                 return rc;
999         }
1000
1001         np->np_transport = t;
1002         np->enabled = true;
1003         return 0;
1004 }
1005
1006 int iscsit_accept_np(struct iscsi_np *np, struct iscsi_conn *conn)
1007 {
1008         struct socket *new_sock, *sock = np->np_socket;
1009         struct sockaddr_in sock_in;
1010         struct sockaddr_in6 sock_in6;
1011         int rc, err;
1012
1013         rc = kernel_accept(sock, &new_sock, 0);
1014         if (rc < 0)
1015                 return rc;
1016
1017         conn->sock = new_sock;
1018         conn->login_family = np->np_sockaddr.ss_family;
1019
1020         if (np->np_sockaddr.ss_family == AF_INET6) {
1021                 memset(&sock_in6, 0, sizeof(struct sockaddr_in6));
1022
1023                 rc = conn->sock->ops->getname(conn->sock,
1024                                 (struct sockaddr *)&sock_in6, &err, 1);
1025                 if (!rc) {
1026                         if (!ipv6_addr_v4mapped(&sock_in6.sin6_addr)) {
1027                                 memcpy(&conn->login_sockaddr, &sock_in6, sizeof(sock_in6));
1028                         } else {
1029                                 /* Pretend to be an ipv4 socket */
1030                                 sock_in.sin_family = AF_INET;
1031                                 sock_in.sin_port = sock_in6.sin6_port;
1032                                 memcpy(&sock_in.sin_addr, &sock_in6.sin6_addr.s6_addr32[3], 4);
1033                                 memcpy(&conn->login_sockaddr, &sock_in, sizeof(sock_in));
1034                         }
1035                 }
1036
1037                 rc = conn->sock->ops->getname(conn->sock,
1038                                 (struct sockaddr *)&sock_in6, &err, 0);
1039                 if (!rc) {
1040                         if (!ipv6_addr_v4mapped(&sock_in6.sin6_addr)) {
1041                                 memcpy(&conn->local_sockaddr, &sock_in6, sizeof(sock_in6));
1042                         } else {
1043                                 /* Pretend to be an ipv4 socket */
1044                                 sock_in.sin_family = AF_INET;
1045                                 sock_in.sin_port = sock_in6.sin6_port;
1046                                 memcpy(&sock_in.sin_addr, &sock_in6.sin6_addr.s6_addr32[3], 4);
1047                                 memcpy(&conn->local_sockaddr, &sock_in, sizeof(sock_in));
1048                         }
1049                 }
1050         } else {
1051                 memset(&sock_in, 0, sizeof(struct sockaddr_in));
1052
1053                 rc = conn->sock->ops->getname(conn->sock,
1054                                 (struct sockaddr *)&sock_in, &err, 1);
1055                 if (!rc)
1056                         memcpy(&conn->login_sockaddr, &sock_in, sizeof(sock_in));
1057
1058                 rc = conn->sock->ops->getname(conn->sock,
1059                                 (struct sockaddr *)&sock_in, &err, 0);
1060                 if (!rc)
1061                         memcpy(&conn->local_sockaddr, &sock_in, sizeof(sock_in));
1062         }
1063
1064         return 0;
1065 }
1066
1067 int iscsit_get_login_rx(struct iscsi_conn *conn, struct iscsi_login *login)
1068 {
1069         struct iscsi_login_req *login_req;
1070         u32 padding = 0, payload_length;
1071
1072         if (iscsi_login_rx_data(conn, login->req, ISCSI_HDR_LEN) < 0)
1073                 return -1;
1074
1075         login_req = (struct iscsi_login_req *)login->req;
1076         payload_length  = ntoh24(login_req->dlength);
1077         padding = ((-payload_length) & 3);
1078
1079         pr_debug("Got Login Command, Flags 0x%02x, ITT: 0x%08x,"
1080                 " CmdSN: 0x%08x, ExpStatSN: 0x%08x, CID: %hu, Length: %u\n",
1081                 login_req->flags, login_req->itt, login_req->cmdsn,
1082                 login_req->exp_statsn, login_req->cid, payload_length);
1083         /*
1084          * Setup the initial iscsi_login values from the leading
1085          * login request PDU.
1086          */
1087         if (login->first_request) {
1088                 login_req = (struct iscsi_login_req *)login->req;
1089                 login->leading_connection = (!login_req->tsih) ? 1 : 0;
1090                 login->current_stage    = ISCSI_LOGIN_CURRENT_STAGE(login_req->flags);
1091                 login->version_min      = login_req->min_version;
1092                 login->version_max      = login_req->max_version;
1093                 memcpy(login->isid, login_req->isid, 6);
1094                 login->cmd_sn           = be32_to_cpu(login_req->cmdsn);
1095                 login->init_task_tag    = login_req->itt;
1096                 login->initial_exp_statsn = be32_to_cpu(login_req->exp_statsn);
1097                 login->cid              = be16_to_cpu(login_req->cid);
1098                 login->tsih             = be16_to_cpu(login_req->tsih);
1099         }
1100
1101         if (iscsi_target_check_login_request(conn, login) < 0)
1102                 return -1;
1103
1104         memset(login->req_buf, 0, MAX_KEY_VALUE_PAIRS);
1105         if (iscsi_login_rx_data(conn, login->req_buf,
1106                                 payload_length + padding) < 0)
1107                 return -1;
1108
1109         return 0;
1110 }
1111
1112 int iscsit_put_login_tx(struct iscsi_conn *conn, struct iscsi_login *login,
1113                         u32 length)
1114 {
1115         if (iscsi_login_tx_data(conn, login->rsp, login->rsp_buf, length) < 0)
1116                 return -1;
1117
1118         return 0;
1119 }
1120
1121 static int
1122 iscsit_conn_set_transport(struct iscsi_conn *conn, struct iscsit_transport *t)
1123 {
1124         int rc;
1125
1126         if (!t->owner) {
1127                 conn->conn_transport = t;
1128                 return 0;
1129         }
1130
1131         rc = try_module_get(t->owner);
1132         if (!rc) {
1133                 pr_err("try_module_get() failed for %s\n", t->name);
1134                 return -EINVAL;
1135         }
1136
1137         conn->conn_transport = t;
1138         return 0;
1139 }
1140
1141 void iscsi_target_login_sess_out(struct iscsi_conn *conn,
1142                                  bool zero_tsih, bool new_sess)
1143 {
1144         if (!new_sess)
1145                 goto old_sess_out;
1146
1147         pr_err("iSCSI Login negotiation failed.\n");
1148         iscsit_collect_login_stats(conn, ISCSI_STATUS_CLS_INITIATOR_ERR,
1149                                    ISCSI_LOGIN_STATUS_INIT_ERR);
1150         if (!zero_tsih || !conn->sess)
1151                 goto old_sess_out;
1152
1153         transport_free_session(conn->sess->se_sess);
1154
1155         spin_lock_bh(&sess_idr_lock);
1156         idr_remove(&sess_idr, conn->sess->session_index);
1157         spin_unlock_bh(&sess_idr_lock);
1158
1159         kfree(conn->sess->sess_ops);
1160         kfree(conn->sess);
1161         conn->sess = NULL;
1162
1163 old_sess_out:
1164         /*
1165          * If login negotiation fails check if the Time2Retain timer
1166          * needs to be restarted.
1167          */
1168         if (!zero_tsih && conn->sess) {
1169                 spin_lock_bh(&conn->sess->conn_lock);
1170                 if (conn->sess->session_state == TARG_SESS_STATE_FAILED) {
1171                         struct se_portal_group *se_tpg =
1172                                         &conn->tpg->tpg_se_tpg;
1173
1174                         atomic_set(&conn->sess->session_continuation, 0);
1175                         spin_unlock_bh(&conn->sess->conn_lock);
1176                         spin_lock_bh(&se_tpg->session_lock);
1177                         iscsit_start_time2retain_handler(conn->sess);
1178                         spin_unlock_bh(&se_tpg->session_lock);
1179                 } else
1180                         spin_unlock_bh(&conn->sess->conn_lock);
1181                 iscsit_dec_session_usage_count(conn->sess);
1182         }
1183
1184         if (!IS_ERR(conn->conn_rx_hash.tfm))
1185                 crypto_free_hash(conn->conn_rx_hash.tfm);
1186         if (!IS_ERR(conn->conn_tx_hash.tfm))
1187                 crypto_free_hash(conn->conn_tx_hash.tfm);
1188
1189         free_cpumask_var(conn->conn_cpumask);
1190
1191         kfree(conn->conn_ops);
1192
1193         if (conn->param_list) {
1194                 iscsi_release_param_list(conn->param_list);
1195                 conn->param_list = NULL;
1196         }
1197         iscsi_target_nego_release(conn);
1198
1199         if (conn->sock) {
1200                 sock_release(conn->sock);
1201                 conn->sock = NULL;
1202         }
1203
1204         if (conn->conn_transport->iscsit_wait_conn)
1205                 conn->conn_transport->iscsit_wait_conn(conn);
1206
1207         if (conn->conn_transport->iscsit_free_conn)
1208                 conn->conn_transport->iscsit_free_conn(conn);
1209
1210         iscsit_put_transport(conn->conn_transport);
1211         kfree(conn);
1212 }
1213
1214 static int __iscsi_target_login_thread(struct iscsi_np *np)
1215 {
1216         u8 *buffer, zero_tsih = 0;
1217         int ret = 0, rc;
1218         struct iscsi_conn *conn = NULL;
1219         struct iscsi_login *login;
1220         struct iscsi_portal_group *tpg = NULL;
1221         struct iscsi_login_req *pdu;
1222         struct iscsi_tpg_np *tpg_np;
1223         bool new_sess = false;
1224
1225         flush_signals(current);
1226
1227         spin_lock_bh(&np->np_thread_lock);
1228         if (atomic_dec_if_positive(&np->np_reset_count) >= 0) {
1229                 np->np_thread_state = ISCSI_NP_THREAD_ACTIVE;
1230                 spin_unlock_bh(&np->np_thread_lock);
1231                 complete(&np->np_restart_comp);
1232                 return 1;
1233         } else if (np->np_thread_state == ISCSI_NP_THREAD_SHUTDOWN) {
1234                 spin_unlock_bh(&np->np_thread_lock);
1235                 goto exit;
1236         } else {
1237                 np->np_thread_state = ISCSI_NP_THREAD_ACTIVE;
1238         }
1239         spin_unlock_bh(&np->np_thread_lock);
1240
1241         conn = kzalloc(sizeof(struct iscsi_conn), GFP_KERNEL);
1242         if (!conn) {
1243                 pr_err("Could not allocate memory for"
1244                         " new connection\n");
1245                 /* Get another socket */
1246                 return 1;
1247         }
1248         pr_debug("Moving to TARG_CONN_STATE_FREE.\n");
1249         conn->conn_state = TARG_CONN_STATE_FREE;
1250
1251         if (iscsit_conn_set_transport(conn, np->np_transport) < 0) {
1252                 kfree(conn);
1253                 return 1;
1254         }
1255
1256         rc = np->np_transport->iscsit_accept_np(np, conn);
1257         if (rc == -ENOSYS) {
1258                 complete(&np->np_restart_comp);
1259                 iscsit_put_transport(conn->conn_transport);
1260                 kfree(conn);
1261                 conn = NULL;
1262                 goto exit;
1263         } else if (rc < 0) {
1264                 spin_lock_bh(&np->np_thread_lock);
1265                 if (atomic_dec_if_positive(&np->np_reset_count) >= 0) {
1266                         np->np_thread_state = ISCSI_NP_THREAD_ACTIVE;
1267                         spin_unlock_bh(&np->np_thread_lock);
1268                         complete(&np->np_restart_comp);
1269                         iscsit_put_transport(conn->conn_transport);
1270                         kfree(conn);
1271                         conn = NULL;
1272                         /* Get another socket */
1273                         return 1;
1274                 }
1275                 spin_unlock_bh(&np->np_thread_lock);
1276                 iscsit_put_transport(conn->conn_transport);
1277                 kfree(conn);
1278                 conn = NULL;
1279                 goto out;
1280         }
1281         /*
1282          * Perform the remaining iSCSI connection initialization items..
1283          */
1284         login = iscsi_login_init_conn(conn);
1285         if (!login) {
1286                 goto new_sess_out;
1287         }
1288
1289         iscsi_start_login_thread_timer(np);
1290
1291         pr_debug("Moving to TARG_CONN_STATE_XPT_UP.\n");
1292         conn->conn_state = TARG_CONN_STATE_XPT_UP;
1293         /*
1294          * This will process the first login request + payload..
1295          */
1296         rc = np->np_transport->iscsit_get_login_rx(conn, login);
1297         if (rc == 1)
1298                 return 1;
1299         else if (rc < 0)
1300                 goto new_sess_out;
1301
1302         buffer = &login->req[0];
1303         pdu = (struct iscsi_login_req *)buffer;
1304         /*
1305          * Used by iscsit_tx_login_rsp() for Login Resonses PDUs
1306          * when Status-Class != 0.
1307         */
1308         conn->login_itt = pdu->itt;
1309
1310         spin_lock_bh(&np->np_thread_lock);
1311         if (np->np_thread_state != ISCSI_NP_THREAD_ACTIVE) {
1312                 spin_unlock_bh(&np->np_thread_lock);
1313                 pr_err("iSCSI Network Portal on %pISpc currently not"
1314                         " active.\n", &np->np_sockaddr);
1315                 iscsit_tx_login_rsp(conn, ISCSI_STATUS_CLS_TARGET_ERR,
1316                                 ISCSI_LOGIN_STATUS_SVC_UNAVAILABLE);
1317                 goto new_sess_out;
1318         }
1319         spin_unlock_bh(&np->np_thread_lock);
1320
1321         conn->network_transport = np->np_network_transport;
1322
1323         pr_debug("Received iSCSI login request from %pISpc on %s Network"
1324                 " Portal %pISpc\n", &conn->login_sockaddr, np->np_transport->name,
1325                 &conn->local_sockaddr);
1326
1327         pr_debug("Moving to TARG_CONN_STATE_IN_LOGIN.\n");
1328         conn->conn_state        = TARG_CONN_STATE_IN_LOGIN;
1329
1330         if (iscsi_login_check_initiator_version(conn, pdu->max_version,
1331                         pdu->min_version) < 0)
1332                 goto new_sess_out;
1333
1334         zero_tsih = (pdu->tsih == 0x0000);
1335         if (zero_tsih) {
1336                 /*
1337                  * This is the leading connection of a new session.
1338                  * We wait until after authentication to check for
1339                  * session reinstatement.
1340                  */
1341                 if (iscsi_login_zero_tsih_s1(conn, buffer) < 0)
1342                         goto new_sess_out;
1343         } else {
1344                 /*
1345                  * Add a new connection to an existing session.
1346                  * We check for a non-existant session in
1347                  * iscsi_login_non_zero_tsih_s2() below based
1348                  * on ISID/TSIH, but wait until after authentication
1349                  * to check for connection reinstatement, etc.
1350                  */
1351                 if (iscsi_login_non_zero_tsih_s1(conn, buffer) < 0)
1352                         goto new_sess_out;
1353         }
1354         /*
1355          * SessionType: Discovery
1356          *
1357          *      Locates Default Portal
1358          *
1359          * SessionType: Normal
1360          *
1361          *      Locates Target Portal from NP -> Target IQN
1362          */
1363         rc = iscsi_target_locate_portal(np, conn, login);
1364         if (rc < 0) {
1365                 tpg = conn->tpg;
1366                 goto new_sess_out;
1367         }
1368         login->zero_tsih = zero_tsih;
1369
1370         if (conn->sess)
1371                 conn->sess->se_sess->sup_prot_ops =
1372                         conn->conn_transport->iscsit_get_sup_prot_ops(conn);
1373
1374         tpg = conn->tpg;
1375         if (!tpg) {
1376                 pr_err("Unable to locate struct iscsi_conn->tpg\n");
1377                 goto new_sess_out;
1378         }
1379
1380         if (zero_tsih) {
1381                 if (iscsi_login_zero_tsih_s2(conn) < 0)
1382                         goto new_sess_out;
1383         } else {
1384                 if (iscsi_login_non_zero_tsih_s2(conn, buffer) < 0)
1385                         goto old_sess_out;
1386         }
1387
1388         ret = iscsi_target_start_negotiation(login, conn);
1389         if (ret < 0)
1390                 goto new_sess_out;
1391
1392         iscsi_stop_login_thread_timer(np);
1393
1394         if (ret == 1) {
1395                 tpg_np = conn->tpg_np;
1396
1397                 iscsi_post_login_handler(np, conn, zero_tsih);
1398                 iscsit_deaccess_np(np, tpg, tpg_np);
1399         }
1400
1401         tpg = NULL;
1402         tpg_np = NULL;
1403         /* Get another socket */
1404         return 1;
1405
1406 new_sess_out:
1407         new_sess = true;
1408 old_sess_out:
1409         iscsi_stop_login_thread_timer(np);
1410         tpg_np = conn->tpg_np;
1411         iscsi_target_login_sess_out(conn, zero_tsih, new_sess);
1412         new_sess = false;
1413
1414         if (tpg) {
1415                 iscsit_deaccess_np(np, tpg, tpg_np);
1416                 tpg = NULL;
1417                 tpg_np = NULL;
1418         }
1419
1420 out:
1421         return 1;
1422
1423 exit:
1424         iscsi_stop_login_thread_timer(np);
1425         spin_lock_bh(&np->np_thread_lock);
1426         np->np_thread_state = ISCSI_NP_THREAD_EXIT;
1427         spin_unlock_bh(&np->np_thread_lock);
1428
1429         return 0;
1430 }
1431
1432 int iscsi_target_login_thread(void *arg)
1433 {
1434         struct iscsi_np *np = arg;
1435         int ret;
1436
1437         allow_signal(SIGINT);
1438
1439         while (1) {
1440                 ret = __iscsi_target_login_thread(np);
1441                 /*
1442                  * We break and exit here unless another sock_accept() call
1443                  * is expected.
1444                  */
1445                 if (ret != 1)
1446                         break;
1447         }
1448
1449         while (!kthread_should_stop()) {
1450                 msleep(100);
1451         }
1452
1453         return 0;
1454 }