GNU Linux-libre 4.14.313-gnu1
[releases.git] / drivers / staging / lustre / lustre / mgc / mgc_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2015, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/mgc/mgc_request.c
33  *
34  * Author: Nathan Rutman <nathan@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_MGC
38 #define D_MGC D_CONFIG /*|D_WARNING*/
39
40 #include <linux/module.h>
41
42 #include <lprocfs_status.h>
43 #include <lustre_dlm.h>
44 #include <lustre_disk.h>
45 #include <lustre_log.h>
46 #include <lustre_swab.h>
47 #include <obd_class.h>
48
49 #include "mgc_internal.h"
50
51 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
52                           int type)
53 {
54         __u64 resname = 0;
55
56         if (len > sizeof(resname)) {
57                 CERROR("name too long: %s\n", name);
58                 return -EINVAL;
59         }
60         if (len <= 0) {
61                 CERROR("missing name: %s\n", name);
62                 return -EINVAL;
63         }
64         memcpy(&resname, name, len);
65
66         /* Always use the same endianness for the resid */
67         memset(res_id, 0, sizeof(*res_id));
68         res_id->name[0] = cpu_to_le64(resname);
69         /* XXX: unfortunately, sptlprc and config llog share one lock */
70         switch (type) {
71         case CONFIG_T_CONFIG:
72         case CONFIG_T_SPTLRPC:
73                 resname = 0;
74                 break;
75         case CONFIG_T_RECOVER:
76         case CONFIG_T_PARAMS:
77                 resname = type;
78                 break;
79         default:
80                 LBUG();
81         }
82         res_id->name[1] = cpu_to_le64(resname);
83         CDEBUG(D_MGC, "log %s to resid %#llx/%#llx (%.8s)\n", name,
84                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
85         return 0;
86 }
87
88 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
89 {
90         /* fsname is at most 8 chars long, maybe contain "-".
91          * e.g. "lustre", "SUN-000"
92          */
93         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
94 }
95 EXPORT_SYMBOL(mgc_fsname2resid);
96
97 static int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id, int type)
98 {
99         char *name_end;
100         int len;
101
102         /* logname consists of "fsname-nodetype".
103          * e.g. "lustre-MDT0001", "SUN-000-client"
104          * there is an exception: llog "params"
105          */
106         name_end = strrchr(logname, '-');
107         if (!name_end)
108                 len = strlen(logname);
109         else
110                 len = name_end - logname;
111         return mgc_name2resid(logname, len, res_id, type);
112 }
113
114 /********************** config llog list **********************/
115 static LIST_HEAD(config_llog_list);
116 static DEFINE_SPINLOCK(config_list_lock);
117
118 /* Take a reference to a config log */
119 static int config_log_get(struct config_llog_data *cld)
120 {
121         atomic_inc(&cld->cld_refcount);
122         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
123                atomic_read(&cld->cld_refcount));
124         return 0;
125 }
126
127 /* Drop a reference to a config log.  When no longer referenced,
128  * we can free the config log data
129  */
130 static void config_log_put(struct config_llog_data *cld)
131 {
132         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
133                atomic_read(&cld->cld_refcount));
134         LASSERT(atomic_read(&cld->cld_refcount) > 0);
135
136         /* spinlock to make sure no item with 0 refcount in the list */
137         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
138                 list_del(&cld->cld_list_chain);
139                 spin_unlock(&config_list_lock);
140
141                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
142
143                 if (cld->cld_recover)
144                         config_log_put(cld->cld_recover);
145                 if (cld->cld_params)
146                         config_log_put(cld->cld_params);
147                 if (cld->cld_sptlrpc)
148                         config_log_put(cld->cld_sptlrpc);
149                 if (cld_is_sptlrpc(cld))
150                         sptlrpc_conf_log_stop(cld->cld_logname);
151
152                 class_export_put(cld->cld_mgcexp);
153                 kfree(cld);
154         }
155 }
156
157 /* Find a config log by name */
158 static
159 struct config_llog_data *config_log_find(char *logname,
160                                          struct config_llog_instance *cfg)
161 {
162         struct config_llog_data *cld;
163         struct config_llog_data *found = NULL;
164         void *instance;
165
166         LASSERT(logname);
167
168         instance = cfg ? cfg->cfg_instance : NULL;
169         spin_lock(&config_list_lock);
170         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
171                 /* check if instance equals */
172                 if (instance != cld->cld_cfg.cfg_instance)
173                         continue;
174
175                 /* instance may be NULL, should check name */
176                 if (strcmp(logname, cld->cld_logname) == 0) {
177                         found = cld;
178                         config_log_get(found);
179                         break;
180                 }
181         }
182         spin_unlock(&config_list_lock);
183         return found;
184 }
185
186 static
187 struct config_llog_data *do_config_log_add(struct obd_device *obd,
188                                            char *logname,
189                                            int type,
190                                            struct config_llog_instance *cfg,
191                                            struct super_block *sb)
192 {
193         struct config_llog_data *cld;
194         int                   rc;
195
196         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
197                cfg ? cfg->cfg_instance : NULL);
198
199         cld = kzalloc(sizeof(*cld) + strlen(logname) + 1, GFP_NOFS);
200         if (!cld)
201                 return ERR_PTR(-ENOMEM);
202
203         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
204         if (rc) {
205                 kfree(cld);
206                 return ERR_PTR(rc);
207         }
208
209         strcpy(cld->cld_logname, logname);
210         if (cfg)
211                 cld->cld_cfg = *cfg;
212         else
213                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
214         mutex_init(&cld->cld_lock);
215         cld->cld_cfg.cfg_last_idx = 0;
216         cld->cld_cfg.cfg_flags = 0;
217         cld->cld_cfg.cfg_sb = sb;
218         cld->cld_type = type;
219         atomic_set(&cld->cld_refcount, 1);
220
221         /* Keep the mgc around until we are done */
222         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
223
224         if (cld_is_sptlrpc(cld)) {
225                 sptlrpc_conf_log_start(logname);
226                 cld->cld_cfg.cfg_obdname = obd->obd_name;
227         }
228
229         spin_lock(&config_list_lock);
230         list_add(&cld->cld_list_chain, &config_llog_list);
231         spin_unlock(&config_list_lock);
232
233         if (cld_is_sptlrpc(cld)) {
234                 rc = mgc_process_log(obd, cld);
235                 if (rc && rc != -ENOENT)
236                         CERROR("failed processing sptlrpc log: %d\n", rc);
237         }
238
239         return cld;
240 }
241
242 static struct config_llog_data *
243 config_recover_log_add(struct obd_device *obd, char *fsname,
244                        struct config_llog_instance *cfg,
245                        struct super_block *sb)
246 {
247         struct config_llog_instance lcfg = *cfg;
248         struct config_llog_data *cld;
249         char logname[32];
250
251         /* we have to use different llog for clients and mdts for cmd
252          * where only clients are notified if one of cmd server restarts
253          */
254         LASSERT(strlen(fsname) < sizeof(logname) / 2);
255         strcpy(logname, fsname);
256         LASSERT(lcfg.cfg_instance);
257         strcat(logname, "-cliir");
258
259         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
260         return cld;
261 }
262
263 static struct config_llog_data *
264 config_params_log_add(struct obd_device *obd,
265                       struct config_llog_instance *cfg, struct super_block *sb)
266 {
267         struct config_llog_instance     lcfg = *cfg;
268         struct config_llog_data         *cld;
269
270         lcfg.cfg_instance = sb;
271
272         cld = do_config_log_add(obd, PARAMS_FILENAME, CONFIG_T_PARAMS,
273                                 &lcfg, sb);
274
275         return cld;
276 }
277
278 /** Add this log to the list of active logs watched by an MGC.
279  * Active means we're watching for updates.
280  * We have one active log per "mount" - client instance or servername.
281  * Each instance may be at a different point in the log.
282  */
283 static struct config_llog_data *
284 config_log_add(struct obd_device *obd, char *logname,
285                struct config_llog_instance *cfg, struct super_block *sb)
286 {
287         struct lustre_sb_info *lsi = s2lsi(sb);
288         struct config_llog_data *cld;
289         struct config_llog_data *sptlrpc_cld;
290         struct config_llog_data *params_cld;
291         struct config_llog_data *recover_cld = NULL;
292         char                    seclogname[32];
293         char                    *ptr;
294         int                     rc;
295
296         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
297
298         /*
299          * for each regular log, the depended sptlrpc log name is
300          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
301          */
302         ptr = strrchr(logname, '-');
303         if (!ptr || ptr - logname > 8) {
304                 CERROR("logname %s is too long\n", logname);
305                 return ERR_PTR(-EINVAL);
306         }
307
308         memcpy(seclogname, logname, ptr - logname);
309         strcpy(seclogname + (ptr - logname), "-sptlrpc");
310
311         sptlrpc_cld = config_log_find(seclogname, NULL);
312         if (!sptlrpc_cld) {
313                 sptlrpc_cld = do_config_log_add(obd, seclogname,
314                                                 CONFIG_T_SPTLRPC, NULL, NULL);
315                 if (IS_ERR(sptlrpc_cld)) {
316                         CERROR("can't create sptlrpc log: %s\n", seclogname);
317                         rc = PTR_ERR(sptlrpc_cld);
318                         goto out_err;
319                 }
320         }
321         params_cld = config_params_log_add(obd, cfg, sb);
322         if (IS_ERR(params_cld)) {
323                 rc = PTR_ERR(params_cld);
324                 CERROR("%s: can't create params log: rc = %d\n",
325                        obd->obd_name, rc);
326                 goto out_sptlrpc;
327         }
328
329         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
330         if (IS_ERR(cld)) {
331                 CERROR("can't create log: %s\n", logname);
332                 rc = PTR_ERR(cld);
333                 goto out_params;
334         }
335
336         LASSERT(lsi->lsi_lmd);
337         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR)) {
338                 ptr = strrchr(seclogname, '-');
339                 if (ptr) {
340                         *ptr = 0;
341                 } else {
342                         CERROR("%s: sptlrpc log name not correct, %s: rc = %d\n",
343                                obd->obd_name, seclogname, -EINVAL);
344                         rc = -EINVAL;
345                         goto out_cld;
346                 }
347                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
348                 if (IS_ERR(recover_cld)) {
349                         rc = PTR_ERR(recover_cld);
350                         goto out_cld;
351                 }
352         }
353
354         mutex_lock(&cld->cld_lock);
355         cld->cld_recover = recover_cld;
356         cld->cld_params = params_cld;
357         cld->cld_sptlrpc = sptlrpc_cld;
358         mutex_unlock(&cld->cld_lock);
359
360         return cld;
361
362 out_cld:
363         config_log_put(cld);
364
365 out_params:
366         config_log_put(params_cld);
367
368 out_sptlrpc:
369         config_log_put(sptlrpc_cld);
370
371 out_err:
372         return ERR_PTR(rc);
373 }
374
375 static DEFINE_MUTEX(llog_process_lock);
376
377 static inline void config_mark_cld_stop(struct config_llog_data *cld)
378 {
379         mutex_lock(&cld->cld_lock);
380         spin_lock(&config_list_lock);
381         cld->cld_stopping = 1;
382         spin_unlock(&config_list_lock);
383         mutex_unlock(&cld->cld_lock);
384 }
385
386 /** Stop watching for updates on this log.
387  */
388 static int config_log_end(char *logname, struct config_llog_instance *cfg)
389 {
390         struct config_llog_data *cld;
391         struct config_llog_data *cld_sptlrpc = NULL;
392         struct config_llog_data *cld_params = NULL;
393         struct config_llog_data *cld_recover = NULL;
394         int rc = 0;
395
396         cld = config_log_find(logname, cfg);
397         if (!cld)
398                 return -ENOENT;
399
400         mutex_lock(&cld->cld_lock);
401         /*
402          * if cld_stopping is set, it means we didn't start the log thus
403          * not owning the start ref. this can happen after previous umount:
404          * the cld still hanging there waiting for lock cancel, and we
405          * remount again but failed in the middle and call log_end without
406          * calling start_log.
407          */
408         if (unlikely(cld->cld_stopping)) {
409                 mutex_unlock(&cld->cld_lock);
410                 /* drop the ref from the find */
411                 config_log_put(cld);
412                 return rc;
413         }
414
415         spin_lock(&config_list_lock);
416         cld->cld_stopping = 1;
417         spin_unlock(&config_list_lock);
418
419         cld_recover = cld->cld_recover;
420         cld->cld_recover = NULL;
421
422         cld_params = cld->cld_params;
423         cld->cld_params = NULL;
424         cld_sptlrpc = cld->cld_sptlrpc;
425         cld->cld_sptlrpc = NULL;
426         mutex_unlock(&cld->cld_lock);
427
428         if (cld_recover) {
429                 config_mark_cld_stop(cld_recover);
430                 config_log_put(cld_recover);
431         }
432
433         if (cld_params) {
434                 config_mark_cld_stop(cld_params);
435                 config_log_put(cld_params);
436         }
437
438         if (cld_sptlrpc)
439                 config_log_put(cld_sptlrpc);
440
441         /* drop the ref from the find */
442         config_log_put(cld);
443         /* drop the start ref */
444         config_log_put(cld);
445
446         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
447                rc);
448         return rc;
449 }
450
451 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
452 {
453         struct obd_device       *obd = data;
454         struct obd_import       *imp;
455         struct obd_connect_data *ocd;
456         struct config_llog_data *cld;
457         int rc;
458
459         rc = lprocfs_climp_check(obd);
460         if (rc)
461                 return rc;
462
463         imp = obd->u.cli.cl_import;
464         ocd = &imp->imp_connect_data;
465
466         seq_printf(m, "imperative_recovery: %s\n",
467                    OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
468         seq_printf(m, "client_state:\n");
469
470         spin_lock(&config_list_lock);
471         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
472                 if (!cld->cld_recover)
473                         continue;
474                 seq_printf(m, "    - { client: %s, nidtbl_version: %u }\n",
475                            cld->cld_logname,
476                            cld->cld_recover->cld_cfg.cfg_last_idx);
477         }
478         spin_unlock(&config_list_lock);
479
480         up_read(&obd->u.cli.cl_sem);
481         return 0;
482 }
483
484 /* reenqueue any lost locks */
485 #define RQ_RUNNING 0x1
486 #define RQ_NOW     0x2
487 #define RQ_LATER   0x4
488 #define RQ_STOP    0x8
489 #define RQ_PRECLEANUP  0x10
490 static int rq_state;
491 static wait_queue_head_t            rq_waitq;
492 static DECLARE_COMPLETION(rq_exit);
493 static DECLARE_COMPLETION(rq_start);
494
495 static void do_requeue(struct config_llog_data *cld)
496 {
497         LASSERT(atomic_read(&cld->cld_refcount) > 0);
498
499         /* Do not run mgc_process_log on a disconnected export or an
500          * export which is being disconnected. Take the client
501          * semaphore to make the check non-racy.
502          */
503         down_read_nested(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem,
504                          OBD_CLI_SEM_MGC);
505
506         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
507                 int rc;
508
509                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
510                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
511                 if (rc && rc != -ENOENT)
512                         CERROR("failed processing log: %d\n", rc);
513         } else {
514                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
515                        cld->cld_logname);
516         }
517         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
518 }
519
520 /* this timeout represents how many seconds MGC should wait before
521  * requeue config and recover lock to the MGS. We need to randomize this
522  * in order to not flood the MGS.
523  */
524 #define MGC_TIMEOUT_MIN_SECONDS   5
525 #define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 */
526
527 static int mgc_requeue_thread(void *data)
528 {
529         bool first = true;
530
531         CDEBUG(D_MGC, "Starting requeue thread\n");
532
533         /* Keep trying failed locks periodically */
534         spin_lock(&config_list_lock);
535         rq_state |= RQ_RUNNING;
536         while (!(rq_state & RQ_STOP)) {
537                 struct l_wait_info lwi;
538                 struct config_llog_data *cld, *cld_prev;
539                 int rand = cfs_rand() & MGC_TIMEOUT_RAND_CENTISEC;
540                 int to;
541
542                 /* Any new or requeued lostlocks will change the state */
543                 rq_state &= ~(RQ_NOW | RQ_LATER);
544                 spin_unlock(&config_list_lock);
545
546                 if (first) {
547                         first = false;
548                         complete(&rq_start);
549                 }
550
551                 /* Always wait a few seconds to allow the server who
552                  * caused the lock revocation to finish its setup, plus some
553                  * random so everyone doesn't try to reconnect at once.
554                  */
555                 to = msecs_to_jiffies(MGC_TIMEOUT_MIN_SECONDS * MSEC_PER_SEC);
556                 /* rand is centi-seconds */
557                 to += msecs_to_jiffies(rand * MSEC_PER_SEC / 100);
558                 lwi = LWI_TIMEOUT(to, NULL, NULL);
559                 l_wait_event(rq_waitq, rq_state & (RQ_STOP | RQ_PRECLEANUP),
560                              &lwi);
561
562                 /*
563                  * iterate & processing through the list. for each cld, process
564                  * its depending sptlrpc cld firstly (if any) and then itself.
565                  *
566                  * it's guaranteed any item in the list must have
567                  * reference > 0; and if cld_lostlock is set, at
568                  * least one reference is taken by the previous enqueue.
569                  */
570                 cld_prev = NULL;
571
572                 spin_lock(&config_list_lock);
573                 rq_state &= ~RQ_PRECLEANUP;
574                 list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
575                         if (!cld->cld_lostlock || cld->cld_stopping)
576                                 continue;
577
578                         /*
579                          * hold reference to avoid being freed during
580                          * subsequent processing.
581                          */
582                         config_log_get(cld);
583                         cld->cld_lostlock = 0;
584                         spin_unlock(&config_list_lock);
585
586                         if (cld_prev)
587                                 config_log_put(cld_prev);
588                         cld_prev = cld;
589
590                         if (likely(!(rq_state & RQ_STOP))) {
591                                 do_requeue(cld);
592                                 spin_lock(&config_list_lock);
593                         } else {
594                                 spin_lock(&config_list_lock);
595                                 break;
596                         }
597                 }
598                 spin_unlock(&config_list_lock);
599                 if (cld_prev)
600                         config_log_put(cld_prev);
601
602                 /* Wait a bit to see if anyone else needs a requeue */
603                 lwi = (struct l_wait_info) { 0 };
604                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
605                              &lwi);
606                 spin_lock(&config_list_lock);
607         }
608
609         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
610         rq_state &= ~RQ_RUNNING;
611         spin_unlock(&config_list_lock);
612
613         complete(&rq_exit);
614
615         CDEBUG(D_MGC, "Ending requeue thread\n");
616         return 0;
617 }
618
619 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
620  * We are responsible for dropping the config log reference from here on out.
621  */
622 static void mgc_requeue_add(struct config_llog_data *cld)
623 {
624         bool wakeup = false;
625
626         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
627                cld->cld_logname, atomic_read(&cld->cld_refcount),
628                cld->cld_stopping, rq_state);
629         LASSERT(atomic_read(&cld->cld_refcount) > 0);
630
631         mutex_lock(&cld->cld_lock);
632         spin_lock(&config_list_lock);
633         if (!(rq_state & RQ_STOP) && !cld->cld_stopping && !cld->cld_lostlock) {
634                 cld->cld_lostlock = 1;
635                 rq_state |= RQ_NOW;
636                 wakeup = true;
637         }
638         spin_unlock(&config_list_lock);
639         mutex_unlock(&cld->cld_lock);
640         if (wakeup)
641                 wake_up(&rq_waitq);
642 }
643
644 static int mgc_llog_init(const struct lu_env *env, struct obd_device *obd)
645 {
646         struct llog_ctxt        *ctxt;
647         int                      rc;
648
649         /* setup only remote ctxt, the local disk context is switched per each
650          * filesystem during mgc_fs_setup()
651          */
652         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_REPL_CTXT, obd,
653                         &llog_client_ops);
654         if (rc)
655                 return rc;
656
657         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
658         LASSERT(ctxt);
659
660         llog_initiator_connect(ctxt);
661         llog_ctxt_put(ctxt);
662
663         return 0;
664 }
665
666 static int mgc_llog_fini(const struct lu_env *env, struct obd_device *obd)
667 {
668         struct llog_ctxt *ctxt;
669
670         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
671         if (ctxt)
672                 llog_cleanup(env, ctxt);
673
674         return 0;
675 }
676
677 static atomic_t mgc_count = ATOMIC_INIT(0);
678 static int mgc_precleanup(struct obd_device *obd)
679 {
680         int rc = 0;
681         int temp;
682
683         if (atomic_dec_and_test(&mgc_count)) {
684                 LASSERT(rq_state & RQ_RUNNING);
685                 /* stop requeue thread */
686                 temp = RQ_STOP;
687         } else {
688                 /* wakeup requeue thread to clean our cld */
689                 temp = RQ_NOW | RQ_PRECLEANUP;
690         }
691
692         spin_lock(&config_list_lock);
693         rq_state |= temp;
694         spin_unlock(&config_list_lock);
695         wake_up(&rq_waitq);
696
697         if (temp & RQ_STOP)
698                 wait_for_completion(&rq_exit);
699         obd_cleanup_client_import(obd);
700
701         rc = mgc_llog_fini(NULL, obd);
702         if (rc)
703                 CERROR("failed to cleanup llogging subsystems\n");
704
705         return rc;
706 }
707
708 static int mgc_cleanup(struct obd_device *obd)
709 {
710         /* COMPAT_146 - old config logs may have added profiles we don't
711          * know about
712          */
713         if (obd->obd_type->typ_refcnt <= 1)
714                 /* Only for the last mgc */
715                 class_del_profiles();
716
717         lprocfs_obd_cleanup(obd);
718         ptlrpcd_decref();
719
720         return client_obd_cleanup(obd);
721 }
722
723 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
724 {
725         struct lprocfs_static_vars lvars = { NULL };
726         struct task_struct *task;
727         int rc;
728
729         rc = ptlrpcd_addref();
730         if (rc < 0)
731                 goto err_noref;
732
733         rc = client_obd_setup(obd, lcfg);
734         if (rc)
735                 goto err_decref;
736
737         rc = mgc_llog_init(NULL, obd);
738         if (rc) {
739                 CERROR("failed to setup llogging subsystems\n");
740                 goto err_cleanup;
741         }
742
743         lprocfs_mgc_init_vars(&lvars);
744         lprocfs_obd_setup(obd, lvars.obd_vars, lvars.sysfs_vars);
745         sptlrpc_lprocfs_cliobd_attach(obd);
746
747         if (atomic_inc_return(&mgc_count) == 1) {
748                 rq_state = 0;
749                 init_waitqueue_head(&rq_waitq);
750
751                 /* start requeue thread */
752                 task = kthread_run(mgc_requeue_thread, NULL, "ll_cfg_requeue");
753                 if (IS_ERR(task)) {
754                         rc = PTR_ERR(task);
755                         CERROR("%s: cannot start requeue thread: rc = %d; no more log updates\n",
756                                obd->obd_name, rc);
757                         goto err_cleanup;
758                 }
759                 /* rc is the task_struct pointer of mgc_requeue_thread. */
760                 rc = 0;
761                 wait_for_completion(&rq_start);
762         }
763
764         return rc;
765
766 err_cleanup:
767         client_obd_cleanup(obd);
768 err_decref:
769         ptlrpcd_decref();
770 err_noref:
771         return rc;
772 }
773
774 /* based on ll_mdc_blocking_ast */
775 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
776                             void *data, int flag)
777 {
778         struct lustre_handle lockh;
779         struct config_llog_data *cld = data;
780         int rc = 0;
781
782         switch (flag) {
783         case LDLM_CB_BLOCKING:
784                 /* mgs wants the lock, give it up... */
785                 LDLM_DEBUG(lock, "MGC blocking CB");
786                 ldlm_lock2handle(lock, &lockh);
787                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
788                 break;
789         case LDLM_CB_CANCELING:
790                 /* We've given up the lock, prepare ourselves to update. */
791                 LDLM_DEBUG(lock, "MGC cancel CB");
792
793                 CDEBUG(D_MGC, "Lock res " DLDLMRES " (%.8s)\n",
794                        PLDLMRES(lock->l_resource),
795                        (char *)&lock->l_resource->lr_name.name[0]);
796
797                 if (!cld) {
798                         CDEBUG(D_INFO, "missing data, won't requeue\n");
799                         break;
800                 }
801
802                 /* held at mgc_process_log(). */
803                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
804
805                 lock->l_ast_data = NULL;
806                 /* Are we done with this log? */
807                 if (cld->cld_stopping) {
808                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
809                                cld->cld_logname);
810                         config_log_put(cld);
811                         break;
812                 }
813                 /* Make sure not to re-enqueue when the mgc is stopping
814                  * (we get called from client_disconnect_export)
815                  */
816                 if (!lock->l_conn_export ||
817                     !lock->l_conn_export->exp_obd->u.cli.cl_conn_count) {
818                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
819                                cld->cld_logname);
820                         config_log_put(cld);
821                         break;
822                 }
823
824                 /* Re-enqueue now */
825                 mgc_requeue_add(cld);
826                 config_log_put(cld);
827                 break;
828         default:
829                 LBUG();
830         }
831
832         return rc;
833 }
834
835 /* Not sure where this should go... */
836 /* This is the timeout value for MGS_CONNECT request plus a ping interval, such
837  * that we can have a chance to try the secondary MGS if any.
838  */
839 #define  MGC_ENQUEUE_LIMIT (INITIAL_CONNECT_TIMEOUT + (AT_OFF ? 0 : at_min) \
840                                 + PING_INTERVAL)
841 #define  MGC_TARGET_REG_LIMIT 10
842 #define  MGC_SEND_PARAM_LIMIT 10
843
844 /* Send parameter to MGS*/
845 static int mgc_set_mgs_param(struct obd_export *exp,
846                              struct mgs_send_param *msp)
847 {
848         struct ptlrpc_request *req;
849         struct mgs_send_param *req_msp, *rep_msp;
850         int rc;
851
852         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
853                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
854                                         MGS_SET_INFO);
855         if (!req)
856                 return -ENOMEM;
857
858         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
859         if (!req_msp) {
860                 ptlrpc_req_finished(req);
861                 return -ENOMEM;
862         }
863
864         memcpy(req_msp, msp, sizeof(*req_msp));
865         ptlrpc_request_set_replen(req);
866
867         /* Limit how long we will wait for the enqueue to complete */
868         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
869         rc = ptlrpc_queue_wait(req);
870         if (!rc) {
871                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
872                 memcpy(msp, rep_msp, sizeof(*rep_msp));
873         }
874
875         ptlrpc_req_finished(req);
876
877         return rc;
878 }
879
880 /* Take a config lock so we can get cancel notifications */
881 static int mgc_enqueue(struct obd_export *exp, __u32 type,
882                        union ldlm_policy_data *policy, __u32 mode,
883                        __u64 *flags, void *bl_cb, void *cp_cb, void *gl_cb,
884                        void *data, __u32 lvb_len, void *lvb_swabber,
885                        struct lustre_handle *lockh)
886 {
887         struct config_llog_data *cld = data;
888         struct ldlm_enqueue_info einfo = {
889                 .ei_type        = type,
890                 .ei_mode        = mode,
891                 .ei_cb_bl       = mgc_blocking_ast,
892                 .ei_cb_cp       = ldlm_completion_ast,
893         };
894         struct ptlrpc_request *req;
895         int short_limit = cld_is_sptlrpc(cld);
896         int rc;
897
898         CDEBUG(D_MGC, "Enqueue for %s (res %#llx)\n", cld->cld_logname,
899                cld->cld_resid.name[0]);
900
901         /* We need a callback for every lockholder, so don't try to
902          * ldlm_lock_match (see rev 1.1.2.11.2.47)
903          */
904         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
905                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
906                                         LDLM_ENQUEUE);
907         if (!req)
908                 return -ENOMEM;
909
910         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
911         ptlrpc_request_set_replen(req);
912
913         /* Limit how long we will wait for the enqueue to complete */
914         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
915         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
916                               NULL, 0, LVB_T_NONE, lockh, 0);
917         /* A failed enqueue should still call the mgc_blocking_ast,
918          * where it will be requeued if needed ("grant failed").
919          */
920         ptlrpc_req_finished(req);
921         return rc;
922 }
923
924 static void mgc_notify_active(struct obd_device *unused)
925 {
926         /* wakeup mgc_requeue_thread to requeue mgc lock */
927         spin_lock(&config_list_lock);
928         rq_state |= RQ_NOW;
929         spin_unlock(&config_list_lock);
930         wake_up(&rq_waitq);
931
932         /* TODO: Help the MGS rebuild nidtbl. -jay */
933 }
934
935 /* Send target_reg message to MGS */
936 static int mgc_target_register(struct obd_export *exp,
937                                struct mgs_target_info *mti)
938 {
939         struct ptlrpc_request  *req;
940         struct mgs_target_info *req_mti, *rep_mti;
941         int                  rc;
942
943         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
944                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
945                                         MGS_TARGET_REG);
946         if (!req)
947                 return -ENOMEM;
948
949         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
950         if (!req_mti) {
951                 ptlrpc_req_finished(req);
952                 return -ENOMEM;
953         }
954
955         memcpy(req_mti, mti, sizeof(*req_mti));
956         ptlrpc_request_set_replen(req);
957         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
958         /* Limit how long we will wait for the enqueue to complete */
959         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
960
961         rc = ptlrpc_queue_wait(req);
962         if (!rc) {
963                 rep_mti = req_capsule_server_get(&req->rq_pill,
964                                                  &RMF_MGS_TARGET_INFO);
965                 memcpy(mti, rep_mti, sizeof(*rep_mti));
966                 CDEBUG(D_MGC, "register %s got index = %d\n",
967                        mti->mti_svname, mti->mti_stripe_index);
968         }
969         ptlrpc_req_finished(req);
970
971         return rc;
972 }
973
974 static int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
975                               u32 keylen, void *key, u32 vallen,
976                               void *val, struct ptlrpc_request_set *set)
977 {
978         int rc = -EINVAL;
979
980         /* Turn off initial_recov after we try all backup servers once */
981         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
982                 struct obd_import *imp = class_exp2cliimp(exp);
983                 int value;
984
985                 if (vallen != sizeof(int))
986                         return -EINVAL;
987                 value = *(int *)val;
988                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
989                        imp->imp_obd->obd_name, value,
990                        imp->imp_deactive, imp->imp_invalid,
991                        imp->imp_replayable, imp->imp_obd->obd_replayable,
992                        ptlrpc_import_state_name(imp->imp_state));
993                 /* Resurrect if we previously died */
994                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
995                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
996                         ptlrpc_reconnect_import(imp);
997                 return 0;
998         }
999         if (KEY_IS(KEY_SET_INFO)) {
1000                 struct mgs_send_param *msp;
1001
1002                 msp = val;
1003                 rc =  mgc_set_mgs_param(exp, msp);
1004                 return rc;
1005         }
1006         if (KEY_IS(KEY_MGSSEC)) {
1007                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1008                 struct sptlrpc_flavor  flvr;
1009
1010                 /*
1011                  * empty string means using current flavor, if which haven't
1012                  * been set yet, set it as null.
1013                  *
1014                  * if flavor has been set previously, check the asking flavor
1015                  * must match the existing one.
1016                  */
1017                 if (vallen == 0) {
1018                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1019                                 return 0;
1020                         val = "null";
1021                         vallen = 4;
1022                 }
1023
1024                 rc = sptlrpc_parse_flavor(val, &flvr);
1025                 if (rc) {
1026                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1027                                (char *)val);
1028                         return rc;
1029                 }
1030
1031                 /*
1032                  * caller already hold a mutex
1033                  */
1034                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1035                         cli->cl_flvr_mgc = flvr;
1036                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1037                                   sizeof(flvr)) != 0) {
1038                         char    str[20];
1039
1040                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1041                                             str, sizeof(str));
1042                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but currently %s is in use\n",
1043                                        (char *)val, str);
1044                         rc = -EPERM;
1045                 }
1046                 return rc;
1047         }
1048
1049         return rc;
1050 }
1051
1052 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1053                         __u32 keylen, void *key, __u32 *vallen, void *val)
1054 {
1055         int rc = -EINVAL;
1056
1057         if (KEY_IS(KEY_CONN_DATA)) {
1058                 struct obd_import *imp = class_exp2cliimp(exp);
1059                 struct obd_connect_data *data = val;
1060
1061                 if (*vallen == sizeof(*data)) {
1062                         *data = imp->imp_connect_data;
1063                         rc = 0;
1064                 }
1065         }
1066
1067         return rc;
1068 }
1069
1070 static int mgc_import_event(struct obd_device *obd,
1071                             struct obd_import *imp,
1072                             enum obd_import_event event)
1073 {
1074         LASSERT(imp->imp_obd == obd);
1075         CDEBUG(D_MGC, "import event %#x\n", event);
1076
1077         switch (event) {
1078         case IMP_EVENT_DISCON:
1079                 /* MGC imports should not wait for recovery */
1080                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1081                         ptlrpc_pinger_ir_down();
1082                 break;
1083         case IMP_EVENT_INACTIVE:
1084                 break;
1085         case IMP_EVENT_INVALIDATE: {
1086                 struct ldlm_namespace *ns = obd->obd_namespace;
1087
1088                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1089                 break;
1090         }
1091         case IMP_EVENT_ACTIVE:
1092                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1093                 /* Clearing obd_no_recov allows us to continue pinging */
1094                 obd->obd_no_recov = 0;
1095                 mgc_notify_active(obd);
1096                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1097                         ptlrpc_pinger_ir_up();
1098                 break;
1099         case IMP_EVENT_OCD:
1100                 break;
1101         case IMP_EVENT_DEACTIVATE:
1102         case IMP_EVENT_ACTIVATE:
1103                 break;
1104         default:
1105                 CERROR("Unknown import event %#x\n", event);
1106                 LBUG();
1107         }
1108         return 0;
1109 }
1110
1111 enum {
1112         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_SHIFT),
1113         CONFIG_READ_NRPAGES      = 4
1114 };
1115
1116 static int mgc_apply_recover_logs(struct obd_device *mgc,
1117                                   struct config_llog_data *cld,
1118                                   __u64 max_version,
1119                                   void *data, int datalen, bool mne_swab)
1120 {
1121         struct config_llog_instance *cfg = &cld->cld_cfg;
1122         struct mgs_nidtbl_entry *entry;
1123         struct lustre_cfg       *lcfg;
1124         struct lustre_cfg_bufs   bufs;
1125         u64   prev_version = 0;
1126         char *inst;
1127         char *buf;
1128         int   bufsz;
1129         int   pos;
1130         int   rc  = 0;
1131         int   off = 0;
1132
1133         LASSERT(cfg->cfg_instance);
1134         LASSERT(cfg->cfg_sb == cfg->cfg_instance);
1135
1136         inst = kzalloc(PAGE_SIZE, GFP_KERNEL);
1137         if (!inst)
1138                 return -ENOMEM;
1139
1140         pos = snprintf(inst, PAGE_SIZE, "%p", cfg->cfg_instance);
1141         if (pos >= PAGE_SIZE) {
1142                 kfree(inst);
1143                 return -E2BIG;
1144         }
1145
1146         ++pos;
1147         buf   = inst + pos;
1148         bufsz = PAGE_SIZE - pos;
1149
1150         while (datalen > 0) {
1151                 int   entry_len = sizeof(*entry);
1152                 int is_ost, i;
1153                 struct obd_device *obd;
1154                 char *obdname;
1155                 char *cname;
1156                 char *params;
1157                 char *uuid;
1158                 size_t len;
1159
1160                 rc = -EINVAL;
1161                 if (datalen < sizeof(*entry))
1162                         break;
1163
1164                 entry = (typeof(entry))(data + off);
1165
1166                 /* sanity check */
1167                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1168                         break;
1169                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1170                         break;
1171                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1172                         break;
1173
1174                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1175                 if (datalen < entry_len) /* must have entry_len at least */
1176                         break;
1177
1178                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1179                 if (mne_swab)
1180                         lustre_swab_mgs_nidtbl_entry(entry);
1181                 if (entry->mne_length > PAGE_SIZE) {
1182                         CERROR("MNE too large (%u)\n", entry->mne_length);
1183                         break;
1184                 }
1185
1186                 if (entry->mne_length < entry_len)
1187                         break;
1188
1189                 off     += entry->mne_length;
1190                 datalen -= entry->mne_length;
1191                 if (datalen < 0)
1192                         break;
1193
1194                 if (entry->mne_version > max_version) {
1195                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1196                                entry->mne_version, max_version);
1197                         break;
1198                 }
1199
1200                 if (prev_version >= entry->mne_version) {
1201                         CERROR("index unsorted, prev %lld, now %lld\n",
1202                                prev_version, entry->mne_version);
1203                         break;
1204                 }
1205                 prev_version = entry->mne_version;
1206
1207                 /*
1208                  * Write a string with format "nid::instance" to
1209                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1210                  */
1211
1212                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1213                 memset(buf, 0, bufsz);
1214                 obdname = buf;
1215                 pos = 0;
1216
1217                 /* lustre-OST0001-osc-<instance #> */
1218                 strcpy(obdname, cld->cld_logname);
1219                 cname = strrchr(obdname, '-');
1220                 if (!cname) {
1221                         CERROR("mgc %s: invalid logname %s\n",
1222                                mgc->obd_name, obdname);
1223                         break;
1224                 }
1225
1226                 pos = cname - obdname;
1227                 obdname[pos] = 0;
1228                 pos += sprintf(obdname + pos, "-%s%04x",
1229                                   is_ost ? "OST" : "MDT", entry->mne_index);
1230
1231                 cname = is_ost ? "osc" : "mdc";
1232                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1233                 lustre_cfg_bufs_reset(&bufs, obdname);
1234
1235                 /* find the obd by obdname */
1236                 obd = class_name2obd(obdname);
1237                 if (!obd) {
1238                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1239                                mgc->obd_name, obdname);
1240                         rc = 0;
1241                         /* this is a safe race, when the ost is starting up...*/
1242                         continue;
1243                 }
1244
1245                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1246                 ++pos;
1247                 params = buf + pos;
1248                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1249                 uuid = buf + pos;
1250
1251                 down_read(&obd->u.cli.cl_sem);
1252                 if (!obd->u.cli.cl_import) {
1253                         /* client does not connect to the OST yet */
1254                         up_read(&obd->u.cli.cl_sem);
1255                         rc = 0;
1256                         continue;
1257                 }
1258
1259                 /* iterate all nids to find one */
1260                 /* find uuid by nid */
1261                 rc = -ENOENT;
1262                 for (i = 0; i < entry->mne_nid_count; i++) {
1263                         rc = client_import_find_conn(obd->u.cli.cl_import,
1264                                                      entry->u.nids[0],
1265                                                      (struct obd_uuid *)uuid);
1266                         if (!rc)
1267                                 break;
1268                 }
1269
1270                 up_read(&obd->u.cli.cl_sem);
1271                 if (rc < 0) {
1272                         CERROR("mgc: cannot find uuid by nid %s\n",
1273                                libcfs_nid2str(entry->u.nids[0]));
1274                         break;
1275                 }
1276
1277                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1278                        uuid, libcfs_nid2str(entry->u.nids[0]));
1279
1280                 pos += strlen(uuid);
1281                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1282                 LASSERT(pos < bufsz);
1283
1284                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1285
1286                 rc = -ENOMEM;
1287                 len = lustre_cfg_len(bufs.lcfg_bufcount, bufs.lcfg_buflen);
1288                 lcfg = kzalloc(len, GFP_NOFS);
1289                 if (!lcfg) {
1290                         rc = -ENOMEM;
1291                         break;
1292                 }
1293                 lustre_cfg_init(lcfg, LCFG_PARAM, &bufs);
1294
1295                 CDEBUG(D_INFO, "ir apply logs %lld/%lld for %s -> %s\n",
1296                        prev_version, max_version, obdname, params);
1297
1298                 rc = class_process_config(lcfg);
1299                 kfree(lcfg);
1300                 if (rc)
1301                         CDEBUG(D_INFO, "process config for %s error %d\n",
1302                                obdname, rc);
1303
1304                 /* continue, even one with error */
1305         }
1306
1307         kfree(inst);
1308         return rc;
1309 }
1310
1311 /**
1312  * This function is called if this client was notified for target restarting
1313  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery logs.
1314  */
1315 static int mgc_process_recover_log(struct obd_device *obd,
1316                                    struct config_llog_data *cld)
1317 {
1318         struct ptlrpc_request *req = NULL;
1319         struct config_llog_instance *cfg = &cld->cld_cfg;
1320         struct mgs_config_body *body;
1321         struct mgs_config_res  *res;
1322         struct ptlrpc_bulk_desc *desc;
1323         struct page **pages;
1324         int nrpages;
1325         bool eof = true;
1326         bool mne_swab;
1327         int i;
1328         int ealen;
1329         int rc;
1330
1331         /* allocate buffer for bulk transfer.
1332          * if this is the first time for this mgs to read logs,
1333          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1334          * once; otherwise, it only reads increment of logs, this should be
1335          * small and CONFIG_READ_NRPAGES will be used.
1336          */
1337         nrpages = CONFIG_READ_NRPAGES;
1338         if (cfg->cfg_last_idx == 0) /* the first time */
1339                 nrpages = CONFIG_READ_NRPAGES_INIT;
1340
1341         pages = kcalloc(nrpages, sizeof(*pages), GFP_KERNEL);
1342         if (!pages) {
1343                 rc = -ENOMEM;
1344                 goto out;
1345         }
1346
1347         for (i = 0; i < nrpages; i++) {
1348                 pages[i] = alloc_page(GFP_KERNEL);
1349                 if (!pages[i]) {
1350                         rc = -ENOMEM;
1351                         goto out;
1352                 }
1353         }
1354
1355 again:
1356         LASSERT(cld_is_recover(cld));
1357         LASSERT(mutex_is_locked(&cld->cld_lock));
1358         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1359                                    &RQF_MGS_CONFIG_READ);
1360         if (!req) {
1361                 rc = -ENOMEM;
1362                 goto out;
1363         }
1364
1365         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1366         if (rc)
1367                 goto out;
1368
1369         /* pack request */
1370         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1371         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1372         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1373             >= sizeof(body->mcb_name)) {
1374                 rc = -E2BIG;
1375                 goto out;
1376         }
1377         body->mcb_offset = cfg->cfg_last_idx + 1;
1378         body->mcb_type   = cld->cld_type;
1379         body->mcb_bits   = PAGE_SHIFT;
1380         body->mcb_units  = nrpages;
1381
1382         /* allocate bulk transfer descriptor */
1383         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1,
1384                                     PTLRPC_BULK_PUT_SINK | PTLRPC_BULK_BUF_KIOV,
1385                                     MGS_BULK_PORTAL,
1386                                     &ptlrpc_bulk_kiov_pin_ops);
1387         if (!desc) {
1388                 rc = -ENOMEM;
1389                 goto out;
1390         }
1391
1392         for (i = 0; i < nrpages; i++)
1393                 desc->bd_frag_ops->add_kiov_frag(desc, pages[i], 0, PAGE_SIZE);
1394
1395         ptlrpc_request_set_replen(req);
1396         rc = ptlrpc_queue_wait(req);
1397         if (rc)
1398                 goto out;
1399
1400         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1401         if (res->mcr_size < res->mcr_offset) {
1402                 rc = -EINVAL;
1403                 goto out;
1404         }
1405
1406         /* always update the index even though it might have errors with
1407          * handling the recover logs
1408          */
1409         cfg->cfg_last_idx = res->mcr_offset;
1410         eof = res->mcr_offset == res->mcr_size;
1411
1412         CDEBUG(D_INFO, "Latest version %lld, more %d.\n",
1413                res->mcr_offset, eof == false);
1414
1415         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1416         if (ealen < 0) {
1417                 rc = ealen;
1418                 goto out;
1419         }
1420
1421         if (ealen > nrpages << PAGE_SHIFT) {
1422                 rc = -EINVAL;
1423                 goto out;
1424         }
1425
1426         if (ealen == 0) { /* no logs transferred */
1427                 if (!eof)
1428                         rc = -EINVAL;
1429                 goto out;
1430         }
1431
1432         mne_swab = !!ptlrpc_rep_need_swab(req);
1433 #if OBD_OCD_VERSION(3, 0, 53, 0) > LUSTRE_VERSION_CODE
1434         /* This import flag means the server did an extra swab of IR MNE
1435          * records (fixed in LU-1252), reverse it here if needed. LU-1644
1436          */
1437         if (unlikely(req->rq_import->imp_need_mne_swab))
1438                 mne_swab = !mne_swab;
1439 #endif
1440
1441         for (i = 0; i < nrpages && ealen > 0; i++) {
1442                 int rc2;
1443                 void *ptr;
1444
1445                 ptr = kmap(pages[i]);
1446                 rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset, ptr,
1447                                              min_t(int, ealen, PAGE_SIZE),
1448                                              mne_swab);
1449                 kunmap(pages[i]);
1450                 if (rc2 < 0) {
1451                         CWARN("Process recover log %s error %d\n",
1452                               cld->cld_logname, rc2);
1453                         break;
1454                 }
1455
1456                 ealen -= PAGE_SIZE;
1457         }
1458
1459 out:
1460         if (req)
1461                 ptlrpc_req_finished(req);
1462
1463         if (rc == 0 && !eof)
1464                 goto again;
1465
1466         if (pages) {
1467                 for (i = 0; i < nrpages; i++) {
1468                         if (!pages[i])
1469                                 break;
1470                         __free_page(pages[i]);
1471                 }
1472                 kfree(pages);
1473         }
1474         return rc;
1475 }
1476
1477 /* local_only means it cannot get remote llogs */
1478 static int mgc_process_cfg_log(struct obd_device *mgc,
1479                                struct config_llog_data *cld, int local_only)
1480 {
1481         struct llog_ctxt        *ctxt;
1482         struct lustre_sb_info   *lsi = NULL;
1483         int                      rc = 0;
1484         bool                     sptlrpc_started = false;
1485         struct lu_env           *env;
1486
1487         LASSERT(cld);
1488         LASSERT(mutex_is_locked(&cld->cld_lock));
1489
1490         /*
1491          * local copy of sptlrpc log is controlled elsewhere, don't try to
1492          * read it up here.
1493          */
1494         if (cld_is_sptlrpc(cld) && local_only)
1495                 return 0;
1496
1497         if (cld->cld_cfg.cfg_sb)
1498                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1499
1500         env = kzalloc(sizeof(*env), GFP_KERNEL);
1501         if (!env)
1502                 return -ENOMEM;
1503
1504         rc = lu_env_init(env, LCT_MG_THREAD);
1505         if (rc)
1506                 goto out_free;
1507
1508         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1509         LASSERT(ctxt);
1510
1511         if (local_only) /* no local log at client side */ {
1512                 rc = -EIO;
1513                 goto out_pop;
1514         }
1515
1516         if (cld_is_sptlrpc(cld)) {
1517                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1518                 sptlrpc_started = true;
1519         }
1520
1521         /* logname and instance info should be the same, so use our
1522          * copy of the instance for the update.  The cfg_last_idx will
1523          * be updated here.
1524          */
1525         rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1526                                      &cld->cld_cfg);
1527
1528 out_pop:
1529         __llog_ctxt_put(env, ctxt);
1530
1531         /*
1532          * update settings on existing OBDs. doing it inside
1533          * of llog_process_lock so no device is attaching/detaching
1534          * in parallel.
1535          * the logname must be <fsname>-sptlrpc
1536          */
1537         if (sptlrpc_started) {
1538                 LASSERT(cld_is_sptlrpc(cld));
1539                 sptlrpc_conf_log_update_end(cld->cld_logname);
1540                 class_notify_sptlrpc_conf(cld->cld_logname,
1541                                           strlen(cld->cld_logname) -
1542                                           strlen("-sptlrpc"));
1543         }
1544
1545         lu_env_fini(env);
1546 out_free:
1547         kfree(env);
1548         return rc;
1549 }
1550
1551 static bool mgc_import_in_recovery(struct obd_import *imp)
1552 {
1553         bool in_recovery = true;
1554
1555         spin_lock(&imp->imp_lock);
1556         if (imp->imp_state == LUSTRE_IMP_FULL ||
1557             imp->imp_state == LUSTRE_IMP_CLOSED)
1558                 in_recovery = false;
1559         spin_unlock(&imp->imp_lock);
1560
1561         return in_recovery;
1562 }
1563
1564 /**
1565  * Get a configuration log from the MGS and process it.
1566  *
1567  * This function is called for both clients and servers to process the
1568  * configuration log from the MGS.  The MGC enqueues a DLM lock on the
1569  * log from the MGS, and if the lock gets revoked the MGC will be notified
1570  * by the lock cancellation callback that the config log has changed,
1571  * and will enqueue another MGS lock on it, and then continue processing
1572  * the new additions to the end of the log.
1573  *
1574  * Since the MGC import is not replayable, if the import is being evicted
1575  * (rcl == -ESHUTDOWN, \see ptlrpc_import_delay_req()), retry to process
1576  * the log until recovery is finished or the import is closed.
1577  *
1578  * Make a local copy of the log before parsing it if appropriate (non-MGS
1579  * server) so that the server can start even when the MGS is down.
1580  *
1581  * There shouldn't be multiple processes running process_log at once --
1582  * sounds like badness.  It actually might be fine, as long as they're not
1583  * trying to update from the same log simultaneously, in which case we
1584  * should use a per-log semaphore instead of cld_lock.
1585  *
1586  * \param[in] mgc       MGC device by which to fetch the configuration log
1587  * \param[in] cld       log processing state (stored in lock callback data)
1588  *
1589  * \retval              0 on success
1590  * \retval              negative errno on failure
1591  */
1592 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1593 {
1594         struct lustre_handle lockh = { 0 };
1595         __u64 flags = LDLM_FL_NO_LRU;
1596         bool retry = false;
1597         int rc = 0, rcl;
1598
1599         LASSERT(cld);
1600
1601         /* I don't want multiple processes running process_log at once --
1602          * sounds like badness.  It actually might be fine, as long as
1603          * we're not trying to update from the same log
1604          * simultaneously (in which case we should use a per-log sem.)
1605          */
1606 restart:
1607         mutex_lock(&cld->cld_lock);
1608         if (cld->cld_stopping) {
1609                 mutex_unlock(&cld->cld_lock);
1610                 return 0;
1611         }
1612
1613         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
1614
1615         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
1616                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1617
1618         /* Get the cfg lock on the llog */
1619         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, LDLM_PLAIN, NULL,
1620                           LCK_CR, &flags, NULL, NULL, NULL,
1621                           cld, 0, NULL, &lockh);
1622         if (rcl == 0) {
1623                 /* Get the cld, it will be released in mgc_blocking_ast. */
1624                 config_log_get(cld);
1625                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
1626                 LASSERT(rc == 0);
1627         } else {
1628                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1629
1630                 if (rcl == -ESHUTDOWN &&
1631                     atomic_read(&mgc->u.cli.cl_mgc_refcount) > 0 && !retry) {
1632                         int secs = cfs_time_seconds(obd_timeout);
1633                         struct obd_import *imp;
1634                         struct l_wait_info lwi;
1635
1636                         mutex_unlock(&cld->cld_lock);
1637                         imp = class_exp2cliimp(mgc->u.cli.cl_mgc_mgsexp);
1638
1639                         /*
1640                          * Let's force the pinger, and wait the import to be
1641                          * connected, note: since mgc import is non-replayable,
1642                          * and even the import state is disconnected, it does
1643                          * not mean the "recovery" is stopped, so we will keep
1644                          * waitting until timeout or the import state is
1645                          * FULL or closed
1646                          */
1647                         ptlrpc_pinger_force(imp);
1648
1649                         lwi = LWI_TIMEOUT(secs, NULL, NULL);
1650                         l_wait_event(imp->imp_recovery_waitq,
1651                                      !mgc_import_in_recovery(imp), &lwi);
1652
1653                         if (imp->imp_state == LUSTRE_IMP_FULL) {
1654                                 retry = true;
1655                                 goto restart;
1656                         } else {
1657                                 mutex_lock(&cld->cld_lock);
1658                                 spin_lock(&config_list_lock);
1659                                 cld->cld_lostlock = 1;
1660                                 spin_unlock(&config_list_lock);
1661                         }
1662                 } else {
1663                         /* mark cld_lostlock so that it will requeue
1664                          * after MGC becomes available.
1665                          */
1666                         spin_lock(&config_list_lock);
1667                         cld->cld_lostlock = 1;
1668                         spin_unlock(&config_list_lock);
1669                 }
1670         }
1671
1672         if (cld_is_recover(cld)) {
1673                 rc = 0; /* this is not a fatal error for recover log */
1674                 if (!rcl) {
1675                         rc = mgc_process_recover_log(mgc, cld);
1676                         if (rc) {
1677                                 CERROR("%s: recover log %s failed: rc = %d not fatal.\n",
1678                                        mgc->obd_name, cld->cld_logname, rc);
1679                                 rc = 0;
1680                                 spin_lock(&config_list_lock);
1681                                 cld->cld_lostlock = 1;
1682                                 spin_unlock(&config_list_lock);
1683                         }
1684                 }
1685         } else {
1686                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
1687         }
1688
1689         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1690                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1691
1692         mutex_unlock(&cld->cld_lock);
1693
1694         /* Now drop the lock so MGS can revoke it */
1695         if (!rcl)
1696                 ldlm_lock_decref(&lockh, LCK_CR);
1697
1698         return rc;
1699 }
1700
1701 /** Called from lustre_process_log.
1702  * LCFG_LOG_START gets the config log from the MGS, processes it to start
1703  * any services, and adds it to the list logs to watch (follow).
1704  */
1705 static int mgc_process_config(struct obd_device *obd, u32 len, void *buf)
1706 {
1707         struct lustre_cfg *lcfg = buf;
1708         struct config_llog_instance *cfg = NULL;
1709         char *logname;
1710         int rc = 0;
1711
1712         switch (lcfg->lcfg_command) {
1713         case LCFG_LOV_ADD_OBD: {
1714                 /* Overloading this cfg command: register a new target */
1715                 struct mgs_target_info *mti;
1716
1717                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
1718                     sizeof(struct mgs_target_info)) {
1719                         rc = -EINVAL;
1720                         goto out;
1721                 }
1722
1723                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
1724                 CDEBUG(D_MGC, "add_target %s %#x\n",
1725                        mti->mti_svname, mti->mti_flags);
1726                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
1727                 break;
1728         }
1729         case LCFG_LOV_DEL_OBD:
1730                 /* Unregister has no meaning at the moment. */
1731                 CERROR("lov_del_obd unimplemented\n");
1732                 rc = -ENOSYS;
1733                 break;
1734         case LCFG_SPTLRPC_CONF: {
1735                 rc = sptlrpc_process_config(lcfg);
1736                 break;
1737         }
1738         case LCFG_LOG_START: {
1739                 struct config_llog_data *cld;
1740                 struct super_block *sb;
1741
1742                 logname = lustre_cfg_string(lcfg, 1);
1743                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
1744                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
1745
1746                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
1747                        cfg->cfg_last_idx);
1748
1749                 /* We're only called through here on the initial mount */
1750                 cld = config_log_add(obd, logname, cfg, sb);
1751                 if (IS_ERR(cld)) {
1752                         rc = PTR_ERR(cld);
1753                         break;
1754                 }
1755
1756                 /* COMPAT_146 */
1757                 /* FIXME only set this for old logs!  Right now this forces
1758                  * us to always skip the "inside markers" check
1759                  */
1760                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
1761
1762                 rc = mgc_process_log(obd, cld);
1763                 if (rc == 0 && cld->cld_recover) {
1764                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
1765                                          imp_connect_data, IMP_RECOV)) {
1766                                 rc = mgc_process_log(obd, cld->cld_recover);
1767                         } else {
1768                                 struct config_llog_data *cir;
1769
1770                                 mutex_lock(&cld->cld_lock);
1771                                 cir = cld->cld_recover;
1772                                 cld->cld_recover = NULL;
1773                                 mutex_unlock(&cld->cld_lock);
1774                                 config_log_put(cir);
1775                         }
1776
1777                         if (rc)
1778                                 CERROR("Cannot process recover llog %d\n", rc);
1779                 }
1780
1781                 if (rc == 0 && cld->cld_params) {
1782                         rc = mgc_process_log(obd, cld->cld_params);
1783                         if (rc == -ENOENT) {
1784                                 CDEBUG(D_MGC,
1785                                        "There is no params config file yet\n");
1786                                 rc = 0;
1787                         }
1788                         /* params log is optional */
1789                         if (rc)
1790                                 CERROR(
1791                                        "%s: can't process params llog: rc = %d\n",
1792                                        obd->obd_name, rc);
1793                 }
1794
1795                 break;
1796         }
1797         case LCFG_LOG_END: {
1798                 logname = lustre_cfg_string(lcfg, 1);
1799
1800                 if (lcfg->lcfg_bufcount >= 2)
1801                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
1802                                 lcfg, 2);
1803                 rc = config_log_end(logname, cfg);
1804                 break;
1805         }
1806         default: {
1807                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1808                 rc = -EINVAL;
1809                 goto out;
1810         }
1811         }
1812 out:
1813         return rc;
1814 }
1815
1816 static struct obd_ops mgc_obd_ops = {
1817         .owner          = THIS_MODULE,
1818         .setup          = mgc_setup,
1819         .precleanup     = mgc_precleanup,
1820         .cleanup        = mgc_cleanup,
1821         .add_conn       = client_import_add_conn,
1822         .del_conn       = client_import_del_conn,
1823         .connect        = client_connect_import,
1824         .disconnect     = client_disconnect_export,
1825         .set_info_async = mgc_set_info_async,
1826         .get_info       = mgc_get_info,
1827         .import_event   = mgc_import_event,
1828         .process_config = mgc_process_config,
1829 };
1830
1831 static int __init mgc_init(void)
1832 {
1833         return class_register_type(&mgc_obd_ops, NULL,
1834                                    LUSTRE_MGC_NAME, NULL);
1835 }
1836
1837 static void /*__exit*/ mgc_exit(void)
1838 {
1839         class_unregister_type(LUSTRE_MGC_NAME);
1840 }
1841
1842 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
1843 MODULE_DESCRIPTION("Lustre Management Client");
1844 MODULE_VERSION(LUSTRE_VERSION_STRING);
1845 MODULE_LICENSE("GPL");
1846
1847 module_init(mgc_init);
1848 module_exit(mgc_exit);