Whamcloud - gitweb
55c4cc554d5c7650ccdaefbf9f7ebc93b47a5553
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2016, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_export.h>
44 #include <obd.h>
45 #include <lprocfs_status.h>
46 #include <lustre_log.h>
47 #include <lustre_kernelcomm.h>
48 #include "mdt_internal.h"
49
50 static struct lprocfs_vars lprocfs_mdt_hsm_vars[];
51
52 /**
53  * get obj and HSM attributes on a fid
54  * \param mti [IN] context
55  * \param fid [IN] object fid
56  * \param hsm [OUT] HSM meta data
57  * \retval obj or error (-ENOENT if not found)
58  */
59 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
60                                       const struct lu_fid *fid,
61                                       struct md_hsm *hsm)
62 {
63         struct md_attr          *ma;
64         struct mdt_object       *obj;
65         int                      rc;
66         ENTRY;
67
68         ma = &mti->mti_attr;
69         ma->ma_need = MA_HSM;
70         ma->ma_valid = 0;
71
72         /* find object by FID */
73         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
74         if (IS_ERR(obj))
75                 RETURN(obj);
76
77         if (!mdt_object_exists(obj)) {
78                 /* no more object */
79                 mdt_object_put(mti->mti_env, obj);
80                 RETURN(ERR_PTR(-ENOENT));
81         }
82
83         rc = mdt_attr_get_complex(mti, obj, ma);
84         if (rc) {
85                 mdt_object_put(mti->mti_env, obj);
86                 RETURN(ERR_PTR(rc));
87         }
88
89         if (ma->ma_valid & MA_HSM)
90                 *hsm = ma->ma_hsm;
91         else
92                 memset(hsm, 0, sizeof(*hsm));
93         ma->ma_valid = 0;
94         RETURN(obj);
95 }
96
97 void mdt_hsm_dump_hal(int level, const char *prefix,
98                       struct hsm_action_list *hal)
99 {
100         int                      i, sz;
101         struct hsm_action_item  *hai;
102         char                     buf[12];
103
104         CDEBUG(level, "%s: HAL header: version %X count %d compound %#llx"
105                       " archive_id %d flags %#llx\n",
106                prefix, hal->hal_version, hal->hal_count,
107                hal->hal_compound_id, hal->hal_archive_id, hal->hal_flags);
108
109         hai = hai_first(hal);
110         for (i = 0; i < hal->hal_count; i++) {
111                 sz = hai->hai_len - sizeof(*hai);
112                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
113                        " compound/cookie=%#llx/%#llx"
114                        " action=%s extent=%#llx-%#llx gid=%#llx"
115                        " datalen=%d data=[%s]\n",
116                        prefix, i,
117                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
118                        hal->hal_compound_id, hai->hai_cookie,
119                        hsm_copytool_action2name(hai->hai_action),
120                        hai->hai_extent.offset,
121                        hai->hai_extent.length,
122                        hai->hai_gid, sz,
123                        hai_dump_data_field(hai, buf, sizeof(buf)));
124                 hai = hai_next(hai);
125         }
126 }
127
128 /**
129  * data passed to llog_cat_process() callback
130  * to scan requests and take actions
131  */
132 struct hsm_scan_request {
133         int                      hal_sz;
134         int                      hal_used_sz;
135         struct hsm_action_list  *hal;
136 };
137
138 struct hsm_scan_data {
139         struct mdt_thread_info          *mti;
140         char                             fs_name[MTI_NAME_MAXLEN+1];
141         /* request to be send to agents */
142         int                              max_requests;  /** vector size */
143         int                              request_cnt;   /** used count */
144         struct hsm_scan_request         *request;
145 };
146
147 /**
148  *  llog_cat_process() callback, used to:
149  *  - find waiting request and start action
150  *  - purge canceled and done requests
151  * \param env [IN] environment
152  * \param llh [IN] llog handle
153  * \param hdr [IN] llog record
154  * \param data [IN/OUT] cb data = struct hsm_scan_data
155  * \retval 0 success
156  * \retval -ve failure
157  */
158 static int mdt_coordinator_cb(const struct lu_env *env,
159                               struct llog_handle *llh,
160                               struct llog_rec_hdr *hdr,
161                               void *data)
162 {
163         struct llog_agent_req_rec       *larr;
164         struct hsm_scan_data            *hsd;
165         struct hsm_action_item          *hai;
166         struct mdt_device               *mdt;
167         struct coordinator              *cdt;
168         int                              rc;
169         ENTRY;
170
171         hsd = data;
172         mdt = hsd->mti->mti_mdt;
173         cdt = &mdt->mdt_coordinator;
174
175         larr = (struct llog_agent_req_rec *)hdr;
176         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
177         switch (larr->arr_status) {
178         case ARS_WAITING: {
179                 int i;
180                 struct hsm_scan_request *request;
181
182                 /* Are agents full? */
183                 if (atomic_read(&cdt->cdt_request_count) >=
184                     cdt->cdt_max_requests)
185                         break;
186
187                 /* first search whether the request is found in the
188                  * list we have built. */
189                 request = NULL;
190                 for (i = 0; i < hsd->request_cnt; i++) {
191                         if (hsd->request[i].hal->hal_compound_id ==
192                             larr->arr_compound_id) {
193                                 request = &hsd->request[i];
194                                 break;
195                         }
196                 }
197
198                 if (!request) {
199                         struct hsm_action_list *hal;
200
201                         if (hsd->request_cnt == hsd->max_requests)
202                                 /* Unknown request and no more room
203                                  * for a new request. Continue to scan
204                                  * to find other entries for already
205                                  * existing requests.
206                                  */
207                                 RETURN(0);
208
209                         request = &hsd->request[hsd->request_cnt];
210
211                         /* allocates hai vector size just needs to be large
212                          * enough */
213                         request->hal_sz =
214                                 sizeof(*request->hal) +
215                                 cfs_size_round(MTI_NAME_MAXLEN+1) +
216                                 2 * cfs_size_round(larr->arr_hai.hai_len);
217                         OBD_ALLOC(hal, request->hal_sz);
218                         if (!hal)
219                                 RETURN(-ENOMEM);
220                         hal->hal_version = HAL_VERSION;
221                         strlcpy(hal->hal_fsname, hsd->fs_name,
222                                 MTI_NAME_MAXLEN + 1);
223                         hal->hal_compound_id = larr->arr_compound_id;
224                         hal->hal_archive_id = larr->arr_archive_id;
225                         hal->hal_flags = larr->arr_flags;
226                         hal->hal_count = 0;
227                         request->hal_used_sz = hal_size(hal);
228                         request->hal = hal;
229                         hsd->request_cnt++;
230                         hai = hai_first(hal);
231                 } else {
232                         /* request is known */
233                         /* we check if record archive num is the same as the
234                          * known request, if not we will serve it in multiple
235                          * time because we do not know if the agent can serve
236                          * multiple backend
237                          * a use case is a compound made of multiple restore
238                          * where the files are not archived in the same backend
239                          */
240                         if (larr->arr_archive_id !=
241                             request->hal->hal_archive_id)
242                                 RETURN(0);
243
244                         if (request->hal_sz <
245                             request->hal_used_sz +
246                             cfs_size_round(larr->arr_hai.hai_len)) {
247                                 /* Not enough room, need an extension */
248                                 void *hal_buffer;
249                                 int sz;
250
251                                 sz = 2 * request->hal_sz;
252                                 OBD_ALLOC(hal_buffer, sz);
253                                 if (!hal_buffer)
254                                         RETURN(-ENOMEM);
255                                 memcpy(hal_buffer, request->hal,
256                                        request->hal_used_sz);
257                                 OBD_FREE(request->hal,
258                                          request->hal_sz);
259                                 request->hal = hal_buffer;
260                                 request->hal_sz = sz;
261                         }
262                         hai = hai_first(request->hal);
263                         for (i = 0; i < request->hal->hal_count; i++)
264                                 hai = hai_next(hai);
265                 }
266                 memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
267                 hai->hai_cookie = larr->arr_hai.hai_cookie;
268                 hai->hai_gid = larr->arr_hai.hai_gid;
269
270                 request->hal_used_sz += cfs_size_round(hai->hai_len);
271                 request->hal->hal_count++;
272                 break;
273         }
274         case ARS_STARTED: {
275                 struct hsm_progress_kernel pgs;
276                 struct cdt_agent_req *car;
277                 cfs_time_t now = cfs_time_current_sec();
278                 cfs_time_t last;
279
280                 /* we search for a running request
281                  * error may happen if coordinator crashes or stopped
282                  * with running request
283                  */
284                 car = mdt_cdt_find_request(cdt, larr->arr_hai.hai_cookie);
285                 if (car == NULL) {
286                         last = larr->arr_req_change;
287                 } else {
288                         last = car->car_req_update;
289                         mdt_cdt_put_request(car);
290                 }
291
292                 /* test if request too long, if yes cancel it
293                  * the same way the copy tool acknowledge a cancel request */
294                 if (now <= last + cdt->cdt_active_req_timeout)
295                         RETURN(0);
296
297                 dump_llog_agent_req_rec("request timed out, start cleaning",
298                                         larr);
299                 /* a too old cancel request just needs to be removed
300                  * this can happen, if copy tool does not support
301                  * cancel for other requests, we have to remove the
302                  * running request and notify the copytool */
303                 pgs.hpk_fid = larr->arr_hai.hai_fid;
304                 pgs.hpk_cookie = larr->arr_hai.hai_cookie;
305                 pgs.hpk_extent = larr->arr_hai.hai_extent;
306                 pgs.hpk_flags = HP_FLAG_COMPLETED;
307                 pgs.hpk_errval = ENOSYS;
308                 pgs.hpk_data_version = 0;
309
310                 /* update request state, but do not record in llog, to
311                  * avoid deadlock on cdt_llog_lock */
312                 rc = mdt_hsm_update_request_state(hsd->mti, &pgs, 0);
313                 if (rc)
314                         CERROR("%s: cannot cleanup timed out request: "
315                                DFID" for cookie %#llx action=%s\n",
316                                mdt_obd_name(mdt),
317                                PFID(&pgs.hpk_fid), pgs.hpk_cookie,
318                                hsm_copytool_action2name(
319                                        larr->arr_hai.hai_action));
320
321                 if (rc == -ENOENT) {
322                         /* The request no longer exists, forget
323                          * about it, and do not send a cancel request
324                          * to the client, for which an error will be
325                          * sent back, leading to an endless cycle of
326                          * cancellation. */
327                         RETURN(LLOG_DEL_RECORD);
328                 }
329
330                 /* XXX A cancel request cannot be cancelled. */
331                 if (larr->arr_hai.hai_action == HSMA_CANCEL)
332                         RETURN(0);
333
334                 larr->arr_status = ARS_CANCELED;
335                 larr->arr_req_change = now;
336                 rc = llog_write(hsd->mti->mti_env, llh, hdr, hdr->lrh_index);
337                 if (rc < 0)
338                         CERROR("%s: cannot update agent log: rc = %d\n",
339                                mdt_obd_name(mdt), rc);
340                 break;
341         }
342         case ARS_FAILED:
343         case ARS_CANCELED:
344         case ARS_SUCCEED:
345                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
346                     cfs_time_current_sec())
347                         RETURN(LLOG_DEL_RECORD);
348                 break;
349         }
350         RETURN(0);
351 }
352
353 /**
354  * create /proc entries for coordinator
355  * \param mdt [IN]
356  * \retval 0 success
357  * \retval -ve failure
358  */
359 int hsm_cdt_procfs_init(struct mdt_device *mdt)
360 {
361         struct coordinator      *cdt = &mdt->mdt_coordinator;
362         int                      rc = 0;
363         ENTRY;
364
365         /* init /proc entries, failure is not critical */
366         cdt->cdt_proc_dir = lprocfs_register("hsm",
367                                              mdt2obd_dev(mdt)->obd_proc_entry,
368                                              lprocfs_mdt_hsm_vars, mdt);
369         if (IS_ERR(cdt->cdt_proc_dir)) {
370                 rc = PTR_ERR(cdt->cdt_proc_dir);
371                 CERROR("%s: Cannot create 'hsm' directory in mdt proc dir,"
372                        " rc=%d\n", mdt_obd_name(mdt), rc);
373                 cdt->cdt_proc_dir = NULL;
374                 RETURN(rc);
375         }
376
377         RETURN(0);
378 }
379
380 /**
381  * remove /proc entries for coordinator
382  * \param mdt [IN]
383  */
384 void hsm_cdt_procfs_fini(struct mdt_device *mdt)
385 {
386         struct coordinator *cdt = &mdt->mdt_coordinator;
387
388         if (cdt->cdt_proc_dir != NULL)
389                 lprocfs_remove(&cdt->cdt_proc_dir);
390 }
391
392 /**
393  * get vector of hsm cdt /proc vars
394  * \param none
395  * \retval var vector
396  */
397 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
398 {
399         return lprocfs_mdt_hsm_vars;
400 }
401
402 /* Release the ressource used by the coordinator. Called when the
403  * coordinator is stopping. */
404 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
405 {
406         struct coordinator              *cdt = &mdt->mdt_coordinator;
407         struct cdt_agent_req            *car, *tmp1;
408         struct hsm_agent                *ha, *tmp2;
409         struct cdt_restore_handle       *crh, *tmp3;
410         struct mdt_thread_info          *cdt_mti;
411
412         /* start cleaning */
413         down_write(&cdt->cdt_request_lock);
414         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
415                                  car_request_list) {
416                 cfs_hash_del(cdt->cdt_request_cookie_hash,
417                              &car->car_hai->hai_cookie,
418                              &car->car_cookie_hash);
419                 list_del(&car->car_request_list);
420                 mdt_cdt_put_request(car);
421         }
422         up_write(&cdt->cdt_request_lock);
423
424         down_write(&cdt->cdt_agent_lock);
425         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
426                 list_del(&ha->ha_list);
427                 OBD_FREE_PTR(ha);
428         }
429         up_write(&cdt->cdt_agent_lock);
430
431         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
432         mutex_lock(&cdt->cdt_restore_lock);
433         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_hdl, crh_list) {
434                 list_del(&crh->crh_list);
435                 /* give back layout lock */
436                 mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
437                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
438         }
439         mutex_unlock(&cdt->cdt_restore_lock);
440 }
441
442 /*
443  * Coordinator state transition table, indexed on enum cdt_states, taking
444  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
445  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
446  */
447 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
448         /* from -> to:    stopped init   running disable stopping */
449         /* stopped */   { true,   true,  false,  false,  false },
450         /* init */      { true,   false, true,   false,  true },
451         /* running */   { false,  false, true,   true,   true },
452         /* disable */   { false,  false, true,   true,   true },
453         /* stopping */  { true,   false, false,  false,  true }
454 };
455
456 /**
457  * Change coordinator thread state
458  * Some combinations are not valid, so catch them here.
459  *
460  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
461  * the transition was not possible.
462  */
463 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state,
464                          enum cdt_states *old_state)
465 {
466         int rc;
467         enum cdt_states state;
468
469         spin_lock(&cdt->cdt_state_lock);
470
471         state = cdt->cdt_state;
472
473         if (cdt_transition[state][new_state]) {
474                 cdt->cdt_state = new_state;
475                 spin_unlock(&cdt->cdt_state_lock);
476                 if (old_state)
477                         *old_state = state;
478                 rc = 0;
479         } else {
480                 spin_unlock(&cdt->cdt_state_lock);
481                 CDEBUG(D_HSM,
482                        "unexpected coordinator transition, from=%s, to=%s\n",
483                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
484                 rc = -EINVAL;
485         }
486
487         return rc;
488 }
489
490 /**
491  * coordinator thread
492  * \param data [IN] obd device
493  * \retval 0 success
494  * \retval -ve failure
495  */
496 static int mdt_coordinator(void *data)
497 {
498         struct mdt_thread_info  *mti = data;
499         struct mdt_device       *mdt = mti->mti_mdt;
500         struct coordinator      *cdt = &mdt->mdt_coordinator;
501         struct hsm_scan_data     hsd = { NULL };
502         int                      rc = 0;
503         int                      request_sz;
504         ENTRY;
505
506         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
507                mdt_obd_name(mdt), current_pid());
508
509         /* we use a copy of cdt_max_requests in the cb, so if cdt_max_requests
510          * increases due to a change from /proc we do not overflow the
511          * hsd.request[] vector
512          */
513         hsd.max_requests = cdt->cdt_max_requests;
514         request_sz = hsd.max_requests * sizeof(*hsd.request);
515         OBD_ALLOC_LARGE(hsd.request, request_sz);
516         if (!hsd.request)
517                 GOTO(out, rc = -ENOMEM);
518
519         hsd.mti = mti;
520         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
521
522         set_cdt_state(cdt, CDT_RUNNING, NULL);
523
524         /* Inform mdt_hsm_cdt_start(). */
525         wake_up_all(&cdt->cdt_waitq);
526
527         while (1) {
528                 struct l_wait_info lwi;
529                 int i;
530
531                 lwi = LWI_TIMEOUT(cfs_time_seconds(cdt->cdt_loop_period),
532                                   NULL, NULL);
533                 l_wait_event(cdt->cdt_waitq,
534                              cdt->cdt_event || (cdt->cdt_state == CDT_STOPPING),
535                              &lwi);
536
537                 CDEBUG(D_HSM, "coordinator resumes\n");
538
539                 if (cdt->cdt_state == CDT_STOPPING) {
540                         rc = 0;
541                         break;
542                 }
543
544                 cdt->cdt_event = false;
545
546                 /* if coordinator is suspended continue to wait */
547                 if (cdt->cdt_state == CDT_DISABLE) {
548                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
549                         continue;
550                 }
551
552                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
553
554                 if (hsd.max_requests != cdt->cdt_max_requests) {
555                         /* cdt_max_requests has changed,
556                          * we need to allocate a new buffer
557                          */
558                         OBD_FREE_LARGE(hsd.request, request_sz);
559                         hsd.max_requests = cdt->cdt_max_requests;
560                         request_sz = hsd.max_requests * sizeof(*hsd.request);
561                         OBD_ALLOC_LARGE(hsd.request, request_sz);
562                         if (!hsd.request) {
563                                 rc = -ENOMEM;
564                                 break;
565                         }
566                 }
567
568                 hsd.request_cnt = 0;
569
570                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
571                                       &hsd, WRITE);
572                 if (rc < 0)
573                         goto clean_cb_alloc;
574
575                 CDEBUG(D_HSM, "found %d requests to send\n", hsd.request_cnt);
576
577                 if (list_empty(&cdt->cdt_agents)) {
578                         CDEBUG(D_HSM, "no agent available, "
579                                       "coordinator sleeps\n");
580                         goto clean_cb_alloc;
581                 }
582
583                 /* here hsd contains a list of requests to be started */
584                 for (i = 0; i < hsd.request_cnt; i++) {
585                         struct hsm_scan_request *request = &hsd.request[i];
586                         struct hsm_action_list  *hal = request->hal;
587                         struct hsm_action_item  *hai;
588                         __u64                   *cookies;
589                         int                      sz, j;
590                         enum agent_req_status    status;
591
592                         /* still room for work ? */
593                         if (atomic_read(&cdt->cdt_request_count) >=
594                             cdt->cdt_max_requests)
595                                 break;
596
597                         rc = mdt_hsm_agent_send(mti, hal, 0);
598                         /* if failure, we suppose it is temporary
599                          * if the copy tool failed to do the request
600                          * it has to use hsm_progress
601                          */
602                         status = (rc ? ARS_WAITING : ARS_STARTED);
603
604                         /* set up cookie vector to set records status
605                          * after copy tools start or failed
606                          */
607                         sz = hal->hal_count * sizeof(__u64);
608                         OBD_ALLOC(cookies, sz);
609                         if (cookies == NULL)
610                                 continue;
611
612                         hai = hai_first(hal);
613                         for (j = 0; j < hal->hal_count; j++) {
614                                 cookies[j] = hai->hai_cookie;
615                                 hai = hai_next(hai);
616                         }
617
618                         rc = mdt_agent_record_update(mti->mti_env, mdt, cookies,
619                                                      hal->hal_count, status);
620                         if (rc)
621                                 CERROR("%s: mdt_agent_record_update() failed, "
622                                        "rc=%d, cannot update status to %s "
623                                        "for %d cookies\n",
624                                        mdt_obd_name(mdt), rc,
625                                        agent_req_status2name(status),
626                                        hal->hal_count);
627
628                         OBD_FREE(cookies, sz);
629                 }
630 clean_cb_alloc:
631                 /* free hal allocated by callback */
632                 for (i = 0; i < hsd.request_cnt; i++) {
633                         struct hsm_scan_request *request = &hsd.request[i];
634
635                         OBD_FREE(request->hal, request->hal_sz);
636                 }
637         }
638         EXIT;
639 out:
640         set_cdt_state(cdt, CDT_STOPPING, NULL);
641
642         if (hsd.request)
643                 OBD_FREE_LARGE(hsd.request, request_sz);
644
645         mdt_hsm_cdt_cleanup(mdt);
646
647         set_cdt_state(cdt, CDT_STOPPED, NULL);
648         wake_up_all(&cdt->cdt_waitq);
649
650         if (rc != 0)
651                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
652                        mdt_obd_name(mdt), current_pid(), rc);
653         else
654                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
655                               " no error\n",
656                        mdt_obd_name(mdt), current_pid());
657
658         return rc;
659 }
660
661 /**
662  * lookup a restore handle by FID
663  * caller needs to hold cdt_restore_lock
664  * \param cdt [IN] coordinator
665  * \param fid [IN] FID
666  * \retval cdt_restore_handle found
667  * \retval NULL not found
668  */
669 struct cdt_restore_handle *mdt_hsm_restore_hdl_find(struct coordinator *cdt,
670                                                        const struct lu_fid *fid)
671 {
672         struct cdt_restore_handle       *crh;
673         ENTRY;
674
675         list_for_each_entry(crh, &cdt->cdt_restore_hdl, crh_list) {
676                 if (lu_fid_eq(&crh->crh_fid, fid))
677                         RETURN(crh);
678         }
679         RETURN(NULL);
680 }
681
682 /**
683  * data passed to llog_cat_process() callback
684  * to scan requests and take actions
685  */
686 struct hsm_restore_data {
687         struct mdt_thread_info  *hrd_mti;
688 };
689
690 /**
691  *  llog_cat_process() callback, used to:
692  *  - find restore request and allocate the restore handle
693  * \param env [IN] environment
694  * \param llh [IN] llog handle
695  * \param hdr [IN] llog record
696  * \param data [IN/OUT] cb data = struct hsm_restore_data
697  * \retval 0 success
698  * \retval -ve failure
699  */
700 static int hsm_restore_cb(const struct lu_env *env,
701                           struct llog_handle *llh,
702                           struct llog_rec_hdr *hdr, void *data)
703 {
704         struct llog_agent_req_rec       *larr;
705         struct hsm_restore_data         *hrd;
706         struct cdt_restore_handle       *crh;
707         struct hsm_action_item          *hai;
708         struct mdt_thread_info          *mti;
709         struct coordinator              *cdt;
710         struct mdt_object               *child;
711         int rc;
712         ENTRY;
713
714         hrd = data;
715         mti = hrd->hrd_mti;
716         cdt = &mti->mti_mdt->mdt_coordinator;
717
718         larr = (struct llog_agent_req_rec *)hdr;
719         hai = &larr->arr_hai;
720         if (hai->hai_cookie > cdt->cdt_last_cookie)
721                 /* update the cookie to avoid collision */
722                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
723
724         if (hai->hai_action != HSMA_RESTORE ||
725             agent_req_in_final_state(larr->arr_status))
726                 RETURN(0);
727
728         /* restore request not in a final state */
729
730         /* force replay of restore requests left in started state from previous
731          * CDT context, to be canceled later if finally found to be incompatible
732          * when being re-started */
733         if (larr->arr_status == ARS_STARTED) {
734                 larr->arr_status = ARS_WAITING;
735                 larr->arr_req_change = cfs_time_current_sec();
736                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
737                 if (rc != 0)
738                         GOTO(out, rc);
739         }
740
741         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
742         if (crh == NULL)
743                 RETURN(-ENOMEM);
744
745         crh->crh_fid = hai->hai_fid;
746         /* in V1 all file is restored
747         crh->extent.start = hai->hai_extent.offset;
748         crh->extent.end = hai->hai_extent.offset + hai->hai_extent.length;
749         */
750         crh->crh_extent.start = 0;
751         crh->crh_extent.end = hai->hai_extent.length;
752         /* get the layout lock */
753         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
754         child = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
755                                      MDS_INODELOCK_LAYOUT);
756         if (IS_ERR(child))
757                 GOTO(out, rc = PTR_ERR(child));
758
759         rc = 0;
760         /* we choose to not keep a reference
761          * on the object during the restore time which can be very long */
762         mdt_object_put(mti->mti_env, child);
763
764         mutex_lock(&cdt->cdt_restore_lock);
765         list_add_tail(&crh->crh_list, &cdt->cdt_restore_hdl);
766         mutex_unlock(&cdt->cdt_restore_lock);
767
768 out:
769         RETURN(rc);
770 }
771
772 /**
773  * restore coordinator state at startup
774  * the goal is to take a layout lock for each registered restore request
775  * \param mti [IN] context
776  */
777 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
778 {
779         struct hsm_restore_data  hrd;
780         int                      rc;
781         ENTRY;
782
783         hrd.hrd_mti = mti;
784
785         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
786                               hsm_restore_cb, &hrd, WRITE);
787
788         RETURN(rc);
789 }
790
791 static int hsm_init_ucred(struct lu_ucred *uc)
792 {
793         ENTRY;
794
795         uc->uc_valid = UCRED_OLD;
796         uc->uc_o_uid = 0;
797         uc->uc_o_gid = 0;
798         uc->uc_o_fsuid = 0;
799         uc->uc_o_fsgid = 0;
800         uc->uc_uid = 0;
801         uc->uc_gid = 0;
802         uc->uc_fsuid = 0;
803         uc->uc_fsgid = 0;
804         uc->uc_suppgids[0] = -1;
805         uc->uc_suppgids[1] = -1;
806         uc->uc_cap = CFS_CAP_FS_MASK;
807         uc->uc_umask = 0777;
808         uc->uc_ginfo = NULL;
809         uc->uc_identity = NULL;
810
811         RETURN(0);
812 }
813
814 /**
815  * wake up coordinator thread
816  * \param mdt [IN] device
817  * \retval 0 success
818  * \retval -ve failure
819  */
820 int mdt_hsm_cdt_wakeup(struct mdt_device *mdt)
821 {
822         struct coordinator      *cdt = &mdt->mdt_coordinator;
823         ENTRY;
824
825         if (cdt->cdt_state == CDT_STOPPED)
826                 RETURN(-ESRCH);
827
828         /* wake up coordinator */
829         cdt->cdt_event = true;
830         wake_up_all(&cdt->cdt_waitq);
831
832         RETURN(0);
833 }
834
835 /**
836  * initialize coordinator struct
837  * \param mdt [IN] device
838  * \retval 0 success
839  * \retval -ve failure
840  */
841 int mdt_hsm_cdt_init(struct mdt_device *mdt)
842 {
843         struct coordinator      *cdt = &mdt->mdt_coordinator;
844         struct mdt_thread_info  *cdt_mti = NULL;
845         int                      rc;
846         ENTRY;
847
848         init_waitqueue_head(&cdt->cdt_waitq);
849         init_rwsem(&cdt->cdt_llog_lock);
850         init_rwsem(&cdt->cdt_agent_lock);
851         init_rwsem(&cdt->cdt_request_lock);
852         mutex_init(&cdt->cdt_restore_lock);
853         spin_lock_init(&cdt->cdt_state_lock);
854         cdt->cdt_state = CDT_STOPPED;
855
856         INIT_LIST_HEAD(&cdt->cdt_request_list);
857         INIT_LIST_HEAD(&cdt->cdt_agents);
858         INIT_LIST_HEAD(&cdt->cdt_restore_hdl);
859
860         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
861                                                        CFS_HASH_BITS_MIN,
862                                                        CFS_HASH_BITS_MAX,
863                                                        CFS_HASH_BKT_BITS,
864                                                        0 /* extra bytes */,
865                                                        CFS_HASH_MIN_THETA,
866                                                        CFS_HASH_MAX_THETA,
867                                                 &cdt_request_cookie_hash_ops,
868                                                        CFS_HASH_DEFAULT);
869         if (cdt->cdt_request_cookie_hash == NULL)
870                 RETURN(-ENOMEM);
871
872         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
873         if (rc < 0)
874                 GOTO(out_request_cookie_hash, rc);
875
876         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
877         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
878         if (rc < 0)
879                 GOTO(out_env, rc);
880
881         lu_context_enter(&cdt->cdt_session);
882         cdt->cdt_env.le_ses = &cdt->cdt_session;
883
884         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
885         LASSERT(cdt_mti != NULL);
886
887         cdt_mti->mti_env = &cdt->cdt_env;
888         cdt_mti->mti_mdt = mdt;
889
890         hsm_init_ucred(mdt_ucred(cdt_mti));
891
892         /* default values for /proc tunnables
893          * can be override by MGS conf */
894         cdt->cdt_default_archive_id = 1;
895         cdt->cdt_grace_delay = 60;
896         cdt->cdt_loop_period = 10;
897         cdt->cdt_max_requests = 3;
898         cdt->cdt_policy = CDT_DEFAULT_POLICY;
899         cdt->cdt_active_req_timeout = 3600;
900
901         RETURN(0);
902
903 out_env:
904         lu_env_fini(&cdt->cdt_env);
905 out_request_cookie_hash:
906         cfs_hash_putref(cdt->cdt_request_cookie_hash);
907         cdt->cdt_request_cookie_hash = NULL;
908
909         return rc;
910 }
911
912 /**
913  * free a coordinator thread
914  * \param mdt [IN] device
915  */
916 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
917 {
918         struct coordinator *cdt = &mdt->mdt_coordinator;
919         ENTRY;
920
921         lu_context_exit(cdt->cdt_env.le_ses);
922         lu_context_fini(cdt->cdt_env.le_ses);
923
924         lu_env_fini(&cdt->cdt_env);
925
926         cfs_hash_putref(cdt->cdt_request_cookie_hash);
927         cdt->cdt_request_cookie_hash = NULL;
928
929         RETURN(0);
930 }
931
932 /**
933  * start a coordinator thread
934  * \param mdt [IN] device
935  * \retval 0 success
936  * \retval -ve failure
937  */
938 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
939 {
940         struct coordinator      *cdt = &mdt->mdt_coordinator;
941         int                      rc;
942         void                    *ptr;
943         struct mdt_thread_info  *cdt_mti;
944         struct task_struct      *task;
945         ENTRY;
946
947         /* functions defined but not yet used
948          * this avoid compilation warning
949          */
950         ptr = dump_requests;
951
952         rc = set_cdt_state(cdt, CDT_INIT, NULL);
953         if (rc) {
954                 CERROR("%s: Coordinator already started or stopping\n",
955                        mdt_obd_name(mdt));
956                 RETURN(-EALREADY);
957         }
958
959         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
960         cdt->cdt_policy = CDT_DEFAULT_POLICY;
961
962         atomic_set(&cdt->cdt_compound_id, cfs_time_current_sec());
963         /* just need to be larger than previous one */
964         /* cdt_last_cookie is protected by cdt_llog_lock */
965         cdt->cdt_last_cookie = cfs_time_current_sec();
966         atomic_set(&cdt->cdt_request_count, 0);
967         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
968         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
969         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
970
971         /* to avoid deadlock when start is made through /proc
972          * /proc entries are created by the coordinator thread */
973
974         /* set up list of started restore requests */
975         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
976         rc = mdt_hsm_pending_restore(cdt_mti);
977         if (rc)
978                 CERROR("%s: cannot take the layout locks needed"
979                        " for registered restore: %d\n",
980                        mdt_obd_name(mdt), rc);
981
982         if (mdt->mdt_bottom->dd_rdonly)
983                 RETURN(0);
984
985         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
986         if (IS_ERR(task)) {
987                 rc = PTR_ERR(task);
988                 set_cdt_state(cdt, CDT_STOPPED, NULL);
989                 CERROR("%s: error starting coordinator thread: %d\n",
990                        mdt_obd_name(mdt), rc);
991         } else {
992                 wait_event(cdt->cdt_waitq,
993                            cdt->cdt_state != CDT_INIT);
994                 if (cdt->cdt_state == CDT_RUNNING) {
995                         CDEBUG(D_HSM, "%s: coordinator thread started\n",
996                                mdt_obd_name(mdt));
997                         rc = 0;
998                 } else {
999                         CDEBUG(D_HSM,
1000                                "%s: coordinator thread failed to start\n",
1001                                mdt_obd_name(mdt));
1002                         rc = -EINVAL;
1003                 }
1004         }
1005
1006         RETURN(rc);
1007 }
1008
1009 /**
1010  * stop a coordinator thread
1011  * \param mdt [IN] device
1012  */
1013 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1014 {
1015         struct coordinator *cdt = &mdt->mdt_coordinator;
1016         int rc;
1017
1018         ENTRY;
1019         /* stop coordinator thread */
1020         rc = set_cdt_state(cdt, CDT_STOPPING, NULL);
1021         if (rc != 0)
1022                 RETURN(rc);
1023
1024         wake_up_all(&cdt->cdt_waitq);
1025         wait_event(cdt->cdt_waitq, cdt->cdt_state != CDT_STOPPING);
1026
1027         RETURN(rc);
1028 }
1029
1030 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1031                               const struct lu_fid *fid,
1032                               u32 archive_id)
1033 {
1034         struct mdt_object *obj;
1035         struct md_hsm mh;
1036         int rc;
1037
1038         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1039         if (IS_ERR(obj))
1040                 GOTO(out, rc = PTR_ERR(obj));
1041
1042         if (mh.mh_flags & HS_EXISTS &&
1043             mh.mh_arch_id == archive_id)
1044                 GOTO(out_obj, rc = 0);
1045
1046         mh.mh_flags |= HS_EXISTS;
1047         mh.mh_arch_id = archive_id;
1048         rc = mdt_hsm_attr_set(mti, obj, &mh);
1049
1050 out_obj:
1051         mdt_object_put(mti->mti_env, obj);
1052 out:
1053         return rc;
1054 }
1055
1056 /**
1057  * register all requests from an hal in the memory list
1058  * \param mti [IN] context
1059  * \param hal [IN] request
1060  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1061  *  which is running the CT
1062  * \retval 0 success
1063  * \retval -ve failure
1064  */
1065 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1066                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1067 {
1068         struct mdt_device       *mdt = mti->mti_mdt;
1069         struct coordinator      *cdt = &mdt->mdt_coordinator;
1070         struct hsm_action_item  *hai;
1071         int                      rc = 0, i;
1072         ENTRY;
1073
1074         /* register request in memory list */
1075         hai = hai_first(hal);
1076         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1077                 struct cdt_agent_req *car;
1078
1079                 /* in case of a cancel request, we first mark the ondisk
1080                  * record of the request we want to stop as canceled
1081                  * this does not change the cancel record
1082                  * it will be done when updating the request status
1083                  */
1084                 if (hai->hai_action == HSMA_CANCEL) {
1085                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1086                                                      &hai->hai_cookie,
1087                                                      1, ARS_CANCELED);
1088                         if (rc) {
1089                                 CERROR("%s: mdt_agent_record_update() failed, "
1090                                        "rc=%d, cannot update status to %s "
1091                                        "for cookie %#llx\n",
1092                                        mdt_obd_name(mdt), rc,
1093                                        agent_req_status2name(ARS_CANCELED),
1094                                        hai->hai_cookie);
1095                                 GOTO(out, rc);
1096                         }
1097
1098                         /* find the running request to set it canceled */
1099                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1100                         if (car != NULL) {
1101                                 car->car_canceled = 1;
1102                                 /* uuid has to be changed to the one running the
1103                                 * request to cancel */
1104                                 *uuid = car->car_uuid;
1105                                 mdt_cdt_put_request(car);
1106                         }
1107                         /* no need to memorize cancel request
1108                          * this also avoid a deadlock when we receive
1109                          * a purge all requests command
1110                          */
1111                         continue;
1112                 }
1113
1114                 if (hai->hai_action == HSMA_ARCHIVE) {
1115                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1116                                                 hal->hal_archive_id);
1117                         if (rc == -ENOENT)
1118                                 continue;
1119                         else if (rc < 0)
1120                                 GOTO(out, rc);
1121                 }
1122
1123                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1124                                             hal->hal_archive_id, hal->hal_flags,
1125                                             uuid, hai);
1126                 if (IS_ERR(car))
1127                         GOTO(out, rc = PTR_ERR(car));
1128
1129                 rc = mdt_cdt_add_request(cdt, car);
1130                 if (rc != 0)
1131                         mdt_cdt_free_request(car);
1132         }
1133 out:
1134         RETURN(rc);
1135 }
1136
1137 /**
1138  * swap layouts between 2 fids
1139  * \param mti [IN] context
1140  * \param obj [IN]
1141  * \param dfid [IN]
1142  * \param mh_common [IN] MD HSM
1143  */
1144 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1145                             struct mdt_object *obj, const struct lu_fid *dfid,
1146                             struct md_hsm *mh_common)
1147 {
1148         struct mdt_object       *dobj;
1149         struct mdt_lock_handle  *dlh;
1150         int                      rc;
1151         ENTRY;
1152
1153         if (!mdt_object_exists(obj))
1154                 GOTO(out, rc = -ENOENT);
1155
1156         /* we already have layout lock on obj so take only
1157          * on dfid */
1158         dlh = &mti->mti_lh[MDT_LH_OLD];
1159         mdt_lock_reg_init(dlh, LCK_EX);
1160         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1161         if (IS_ERR(dobj))
1162                 GOTO(out, rc = PTR_ERR(dobj));
1163
1164         /* if copy tool closes the volatile before sending the final
1165          * progress through llapi_hsm_copy_end(), all the objects
1166          * are removed and mdd_swap_layout LBUG */
1167         if (!mdt_object_exists(dobj)) {
1168                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1169                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1170                 GOTO(out_dobj, rc = -ENOENT);
1171         }
1172         /* Since we only handle restores here, unconditionally use
1173          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1174          * be preserved in case of failure during swap_layout and not
1175          * leave a file in an intermediate but incoherent state.
1176          * But need to setup HSM xattr of data FID before, reuse
1177          * mti and mh presets for FID in hsm_cdt_request_completed(),
1178          * only need to clear RELEASED and DIRTY.
1179          */
1180         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1181         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1182         if (rc == 0)
1183                 rc = mo_swap_layouts(mti->mti_env,
1184                                      mdt_object_child(obj),
1185                                      mdt_object_child(dobj),
1186                                      SWAP_LAYOUTS_MDS_HSM);
1187
1188 out_dobj:
1189         mdt_object_unlock_put(mti, dobj, dlh, 1);
1190 out:
1191         RETURN(rc);
1192 }
1193
1194 /**
1195  * update status of a completed request
1196  * \param mti [IN] context
1197  * \param pgs [IN] progress of the copy tool
1198  * \param update_record [IN] update llog record
1199  * \retval 0 success
1200  * \retval -ve failure
1201  */
1202 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1203                                      struct hsm_progress_kernel *pgs,
1204                                      const struct cdt_agent_req *car,
1205                                      enum agent_req_status *status)
1206 {
1207         const struct lu_env     *env = mti->mti_env;
1208         struct mdt_device       *mdt = mti->mti_mdt;
1209         struct coordinator      *cdt = &mdt->mdt_coordinator;
1210         struct mdt_object       *obj = NULL;
1211         int                      cl_flags = 0, rc = 0;
1212         struct md_hsm            mh;
1213         bool                     is_mh_changed;
1214         bool                     need_changelog = true;
1215         ENTRY;
1216
1217         /* default is to retry */
1218         *status = ARS_WAITING;
1219
1220         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1221          * if error/removed continue anyway to get correct reporting done */
1222         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1223         /* we will update MD HSM only if needed */
1224         is_mh_changed = false;
1225
1226         /* no need to change mh->mh_arch_id
1227          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1228          */
1229         if (pgs->hpk_errval != 0) {
1230                 switch (pgs->hpk_errval) {
1231                 case ENOSYS:
1232                         /* the copy tool does not support cancel
1233                          * so the cancel request is failed
1234                          * As we cannot distinguish a cancel progress
1235                          * from another action progress (they have the
1236                          * same cookie), we suppose here the CT returns
1237                          * ENOSYS only if does not support cancel
1238                          */
1239                         /* this can also happen when cdt calls it to
1240                          * for a timed out request */
1241                         *status = ARS_FAILED;
1242                         /* to have a cancel event in changelog */
1243                         pgs->hpk_errval = ECANCELED;
1244                         break;
1245                 case ECANCELED:
1246                         /* the request record has already been set to
1247                          * ARS_CANCELED, this set the cancel request
1248                          * to ARS_SUCCEED */
1249                         *status = ARS_SUCCEED;
1250                         break;
1251                 default:
1252                         /* retry only if current policy or requested, and
1253                          * object is not on error/removed */
1254                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1255                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1256                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1257                         break;
1258                 }
1259
1260                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1261                         CERROR("%s: Request %#llx on "DFID
1262                                " failed, error code %d too large\n",
1263                                mdt_obd_name(mdt),
1264                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1265                                pgs->hpk_errval);
1266                         hsm_set_cl_error(&cl_flags,
1267                                          CLF_HSM_ERROVERFLOW);
1268                         rc = -EINVAL;
1269                 } else {
1270                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1271                 }
1272
1273                 switch (car->car_hai->hai_action) {
1274                 case HSMA_ARCHIVE:
1275                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1276                         break;
1277                 case HSMA_RESTORE:
1278                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1279                         break;
1280                 case HSMA_REMOVE:
1281                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1282                         break;
1283                 case HSMA_CANCEL:
1284                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1285                         CERROR("%s: Failed request %#llx on "DFID
1286                                " cannot be a CANCEL\n",
1287                                mdt_obd_name(mdt),
1288                                pgs->hpk_cookie,
1289                                PFID(&pgs->hpk_fid));
1290                         break;
1291                 default:
1292                         CERROR("%s: Failed request %#llx on "DFID
1293                                " %d is an unknown action\n",
1294                                mdt_obd_name(mdt),
1295                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1296                                car->car_hai->hai_action);
1297                         rc = -EINVAL;
1298                         break;
1299                 }
1300         } else {
1301                 *status = ARS_SUCCEED;
1302                 switch (car->car_hai->hai_action) {
1303                 case HSMA_ARCHIVE:
1304                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1305                         /* set ARCHIVE keep EXIST and clear LOST and
1306                          * DIRTY */
1307                         mh.mh_arch_ver = pgs->hpk_data_version;
1308                         mh.mh_flags |= HS_ARCHIVED;
1309                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1310                         is_mh_changed = true;
1311                         break;
1312                 case HSMA_RESTORE:
1313                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1314
1315                         /* do not clear RELEASED and DIRTY here
1316                          * this will occur in hsm_swap_layouts()
1317                          */
1318
1319                         /* Restoring has changed the file version on
1320                          * disk. */
1321                         mh.mh_arch_ver = pgs->hpk_data_version;
1322                         is_mh_changed = true;
1323                         break;
1324                 case HSMA_REMOVE:
1325                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1326                         /* clear ARCHIVED EXISTS and LOST */
1327                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1328                         is_mh_changed = true;
1329                         break;
1330                 case HSMA_CANCEL:
1331                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1332                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1333                                mdt_obd_name(mdt),
1334                                pgs->hpk_cookie,
1335                                PFID(&pgs->hpk_fid));
1336                         break;
1337                 default:
1338                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1339                                mdt_obd_name(mdt),
1340                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1341                                car->car_hai->hai_action);
1342                         rc = -EINVAL;
1343                         break;
1344                 }
1345         }
1346
1347         /* rc != 0 means error when analysing action, it may come from
1348          * a crasy CT no need to manage DIRTY
1349          */
1350         if (rc == 0)
1351                 hsm_set_cl_flags(&cl_flags,
1352                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1353
1354         /* unlock is done later, after layout lock management */
1355         if (is_mh_changed && !IS_ERR(obj))
1356                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1357
1358         /* we give back layout lock only if restore was successful or
1359          * if no retry will be attempted and if object is still alive,
1360          * in other cases we just unlock the object */
1361         if (car->car_hai->hai_action == HSMA_RESTORE) {
1362                 struct cdt_restore_handle       *crh;
1363
1364                 /* restore in data FID done, we swap the layouts
1365                  * only if restore is successful */
1366                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1367                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1368                                               &mh);
1369                         if (rc) {
1370                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1371                                         *status = ARS_FAILED;
1372                                 pgs->hpk_errval = -rc;
1373                         }
1374                 }
1375                 /* we have to retry, so keep layout lock */
1376                 if (*status == ARS_WAITING)
1377                         GOTO(out, rc);
1378
1379                 /* restore special case, need to create ChangeLog record
1380                  * before to give back layout lock to avoid concurrent
1381                  * file updater to post out of order ChangeLog */
1382                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1383                              &car->car_hai->hai_fid);
1384                 need_changelog = false;
1385
1386                 /* give back layout lock */
1387                 mutex_lock(&cdt->cdt_restore_lock);
1388                 crh = mdt_hsm_restore_hdl_find(cdt, &car->car_hai->hai_fid);
1389                 if (crh != NULL)
1390                         list_del(&crh->crh_list);
1391                 mutex_unlock(&cdt->cdt_restore_lock);
1392                 /* Just give back layout lock, we keep the reference
1393                  * which is given back later with the lock for HSM
1394                  * flags.
1395                  * XXX obj may be invalid so we do not pass it. */
1396                 if (crh != NULL)
1397                         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
1398
1399                 if (crh != NULL)
1400                         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1401         }
1402
1403         GOTO(out, rc);
1404
1405 out:
1406         /* always add a ChangeLog record */
1407         if (need_changelog)
1408                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1409                              &car->car_hai->hai_fid);
1410
1411         if (!IS_ERR(obj))
1412                 mdt_object_put(mti->mti_env, obj);
1413
1414         RETURN(rc);
1415 }
1416
1417 /**
1418  * update status of a request
1419  * \param mti [IN] context
1420  * \param pgs [IN] progress of the copy tool
1421  * \param update_record [IN] update llog record
1422  * \retval 0 success
1423  * \retval -ve failure
1424  */
1425 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1426                                  struct hsm_progress_kernel *pgs,
1427                                  const int update_record)
1428 {
1429         struct mdt_device       *mdt = mti->mti_mdt;
1430         struct coordinator      *cdt = &mdt->mdt_coordinator;
1431         struct cdt_agent_req    *car;
1432         int                      rc = 0;
1433         ENTRY;
1434
1435         /* no coordinator started, so we cannot serve requests */
1436         if (cdt->cdt_state == CDT_STOPPED)
1437                 RETURN(-EAGAIN);
1438
1439         /* first do sanity checks */
1440         car = mdt_cdt_update_request(cdt, pgs);
1441         if (IS_ERR(car)) {
1442                 CERROR("%s: Cannot find running request for cookie %#llx"
1443                        " on fid="DFID"\n",
1444                        mdt_obd_name(mdt),
1445                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1446
1447                 RETURN(PTR_ERR(car));
1448         }
1449
1450         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1451                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1452                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1453                       hsm_copytool_action2name(car->car_hai->hai_action),
1454                       pgs->hpk_flags, pgs->hpk_errval,
1455                       PFID(&car->car_hai->hai_fid),
1456                       PFID(&car->car_hai->hai_dfid));
1457
1458         /* progress is done on FID or data FID depending of the action and
1459          * of the copy progress */
1460         /* for restore progress is used to send back the data FID to cdt */
1461         if (car->car_hai->hai_action == HSMA_RESTORE &&
1462             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1463                 car->car_hai->hai_dfid = pgs->hpk_fid;
1464
1465         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1466              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1467             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1468              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1469                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1470                        " does not match request FID "DFID" nor data FID "
1471                        DFID"\n",
1472                        mdt_obd_name(mdt),
1473                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1474                        PFID(&car->car_hai->hai_fid),
1475                        PFID(&car->car_hai->hai_dfid));
1476                 GOTO(out, rc = -EINVAL);
1477         }
1478
1479         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1480                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1481                        " is not coherent (err=%d and not completed"
1482                        " (flags=%d))\n",
1483                        mdt_obd_name(mdt),
1484                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1485                        hsm_copytool_action2name(car->car_hai->hai_action),
1486                        pgs->hpk_errval, pgs->hpk_flags);
1487                 GOTO(out, rc = -EINVAL);
1488         }
1489
1490         /* now progress is valid */
1491
1492         /* we use a root like ucred */
1493         hsm_init_ucred(mdt_ucred(mti));
1494
1495         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1496                 enum agent_req_status    status;
1497
1498                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1499
1500                 CDEBUG(D_HSM, "%s record: fid="DFID" cookie=%#llx action=%s "
1501                               "status=%s\n",
1502                        update_record ? "Updating" : "Not updating",
1503                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1504                        hsm_copytool_action2name(car->car_hai->hai_action),
1505                        agent_req_status2name(status));
1506
1507                 /* update record first (LU-9075) */
1508                 if (update_record) {
1509                         int rc1;
1510
1511                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1512                                                      &pgs->hpk_cookie, 1,
1513                                                      status);
1514                         if (rc1)
1515                                 CERROR("%s: mdt_agent_record_update() failed,"
1516                                        " rc=%d, cannot update status to %s"
1517                                        " for cookie %#llx\n",
1518                                        mdt_obd_name(mdt), rc1,
1519                                        agent_req_status2name(status),
1520                                        pgs->hpk_cookie);
1521                         rc = (rc != 0 ? rc : rc1);
1522                 }
1523
1524                 /* then remove request from memory list (LU-9075) */
1525                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1526
1527                 /* ct has completed a request, so a slot is available, wakeup
1528                  * cdt to find new work */
1529                 mdt_hsm_cdt_wakeup(mdt);
1530         } else {
1531                 /* if copytool send a progress on a canceled request
1532                  * we inform copytool it should stop
1533                  */
1534                 if (car->car_canceled == 1)
1535                         rc = -ECANCELED;
1536         }
1537         GOTO(out, rc);
1538
1539 out:
1540         /* remove ref got from mdt_cdt_update_request() */
1541         mdt_cdt_put_request(car);
1542
1543         return rc;
1544 }
1545
1546
1547 /**
1548  * data passed to llog_cat_process() callback
1549  * to cancel requests
1550  */
1551 struct hsm_cancel_all_data {
1552         struct mdt_device       *mdt;
1553 };
1554
1555 /**
1556  *  llog_cat_process() callback, used to:
1557  *  - purge all requests
1558  * \param env [IN] environment
1559  * \param llh [IN] llog handle
1560  * \param hdr [IN] llog record
1561  * \param data [IN] cb data = struct hsm_cancel_all_data
1562  * \retval 0 success
1563  * \retval -ve failure
1564  */
1565 static int mdt_cancel_all_cb(const struct lu_env *env,
1566                              struct llog_handle *llh,
1567                              struct llog_rec_hdr *hdr, void *data)
1568 {
1569         struct llog_agent_req_rec       *larr;
1570         struct hsm_cancel_all_data      *hcad;
1571         int                              rc = 0;
1572         ENTRY;
1573
1574         larr = (struct llog_agent_req_rec *)hdr;
1575         hcad = data;
1576         if (larr->arr_status == ARS_WAITING ||
1577             larr->arr_status == ARS_STARTED) {
1578                 larr->arr_status = ARS_CANCELED;
1579                 larr->arr_req_change = cfs_time_current_sec();
1580                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1581         }
1582
1583         RETURN(rc);
1584 }
1585
1586 /**
1587  * cancel all actions
1588  * \param obd [IN] MDT device
1589  */
1590 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1591 {
1592         struct lu_env                    env;
1593         struct lu_context                session;
1594         struct mdt_thread_info          *mti;
1595         struct coordinator              *cdt = &mdt->mdt_coordinator;
1596         struct cdt_agent_req            *car;
1597         struct hsm_action_list          *hal = NULL;
1598         struct hsm_action_item          *hai;
1599         struct hsm_cancel_all_data       hcad;
1600         int                              hal_sz = 0, hal_len, rc;
1601         enum cdt_states                  old_state;
1602         ENTRY;
1603
1604         rc = lu_env_init(&env, LCT_MD_THREAD);
1605         if (rc < 0)
1606                 RETURN(rc);
1607
1608         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1609         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1610         if (rc < 0)
1611                 GOTO(out_env, rc);
1612
1613         lu_context_enter(&session);
1614         env.le_ses = &session;
1615
1616         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1617         LASSERT(mti != NULL);
1618
1619         mti->mti_env = &env;
1620         mti->mti_mdt = mdt;
1621
1622         hsm_init_ucred(mdt_ucred(mti));
1623
1624         /* disable coordinator */
1625         rc = set_cdt_state(cdt, CDT_DISABLE, &old_state);
1626         if (rc)
1627                 RETURN(rc);
1628
1629         /* send cancel to all running requests */
1630         down_read(&cdt->cdt_request_lock);
1631         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1632                 mdt_cdt_get_request(car);
1633                 /* request is not yet removed from list, it will be done
1634                  * when copytool will return progress
1635                  */
1636
1637                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1638                         mdt_cdt_put_request(car);
1639                         continue;
1640                 }
1641
1642                 /* needed size */
1643                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1644                           cfs_size_round(car->car_hai->hai_len);
1645
1646                 if (hal_len > hal_sz && hal_sz > 0) {
1647                         /* not enough room, free old buffer */
1648                         OBD_FREE(hal, hal_sz);
1649                         hal = NULL;
1650                 }
1651
1652                 /* empty buffer, allocate one */
1653                 if (hal == NULL) {
1654                         hal_sz = hal_len;
1655                         OBD_ALLOC(hal, hal_sz);
1656                         if (hal == NULL) {
1657                                 mdt_cdt_put_request(car);
1658                                 up_read(&cdt->cdt_request_lock);
1659                                 GOTO(out_cdt_state, rc = -ENOMEM);
1660                         }
1661                 }
1662
1663                 hal->hal_version = HAL_VERSION;
1664                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1665                                 MTI_NAME_MAXLEN);
1666                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1667                 hal->hal_compound_id = car->car_compound_id;
1668                 hal->hal_archive_id = car->car_archive_id;
1669                 hal->hal_flags = car->car_flags;
1670                 hal->hal_count = 0;
1671
1672                 hai = hai_first(hal);
1673                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1674                 hai->hai_action = HSMA_CANCEL;
1675                 hal->hal_count = 1;
1676
1677                 /* it is possible to safely call mdt_hsm_agent_send()
1678                  * (ie without a deadlock on cdt_request_lock), because the
1679                  * write lock is taken only if we are not in purge mode
1680                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1681                  *   nor mdt_cdt_remove_request())
1682                  */
1683                 /* no conflict with cdt thread because cdt is disable and we
1684                  * have the request lock */
1685                 mdt_hsm_agent_send(mti, hal, 1);
1686
1687                 mdt_cdt_put_request(car);
1688         }
1689         up_read(&cdt->cdt_request_lock);
1690
1691         if (hal != NULL)
1692                 OBD_FREE(hal, hal_sz);
1693
1694         /* cancel all on-disk records */
1695         hcad.mdt = mdt;
1696
1697         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
1698                               mdt_cancel_all_cb, &hcad, WRITE);
1699 out_cdt_state:
1700         /* Enable coordinator, unless the coordinator was stopping. */
1701         set_cdt_state(cdt, old_state, NULL);
1702         lu_context_exit(&session);
1703         lu_context_fini(&session);
1704 out_env:
1705         lu_env_fini(&env);
1706
1707         RETURN(rc);
1708 }
1709
1710 /**
1711  * check if a request is compatible with file status
1712  * \param hai [IN] request description
1713  * \param archive_id [IN] request archive id
1714  * \param rq_flags [IN] request flags
1715  * \param hsm [IN] file HSM metadata
1716  * \retval boolean
1717  */
1718 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1719                               u32 archive_id, u64 rq_flags,
1720                               const struct md_hsm *hsm)
1721 {
1722         int      is_compat = false;
1723         int      hsm_flags;
1724         ENTRY;
1725
1726         hsm_flags = hsm->mh_flags;
1727         switch (hai->hai_action) {
1728         case HSMA_ARCHIVE:
1729                 if (!(hsm_flags & HS_NOARCHIVE) &&
1730                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1731                         is_compat = true;
1732
1733                 if (hsm_flags & HS_EXISTS &&
1734                     archive_id != 0 &&
1735                     archive_id != hsm->mh_arch_id)
1736                         is_compat = false;
1737
1738                 break;
1739         case HSMA_RESTORE:
1740                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1741                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1742                         is_compat = true;
1743                 break;
1744         case HSMA_REMOVE:
1745                 if (!(hsm_flags & HS_RELEASED) &&
1746                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1747                         is_compat = true;
1748                 break;
1749         case HSMA_CANCEL:
1750                 is_compat = true;
1751                 break;
1752         }
1753         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1754                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1755                       PFID(&hai->hai_fid),
1756                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1757                       hai->hai_extent.offset, hai->hai_extent.length,
1758                       hsm->mh_flags,
1759                       (is_compat ? "compatible" : "uncompatible"));
1760
1761         RETURN(is_compat);
1762 }
1763
1764 /*
1765  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1766  */
1767 static const struct {
1768         __u64            bit;
1769         char            *name;
1770         char            *nickname;
1771 } hsm_policy_names[] = {
1772         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1773         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1774         { 0 },
1775 };
1776
1777 /**
1778  * convert a policy name to a bit
1779  * \param name [IN] policy name
1780  * \retval 0 unknown
1781  * \retval   policy bit
1782  */
1783 static __u64 hsm_policy_str2bit(const char *name)
1784 {
1785         int      i;
1786
1787         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1788                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1789                     strcmp(hsm_policy_names[i].name, name) == 0)
1790                         return hsm_policy_names[i].bit;
1791         return 0;
1792 }
1793
1794 /**
1795  * convert a policy bit field to a string
1796  * \param mask [IN] policy bit field
1797  * \param hexa [IN] print mask before bit names
1798  * \param buffer [OUT] string
1799  * \param count [IN] size of buffer
1800  */
1801 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1802                                 const bool hexa)
1803 {
1804         int      i, j;
1805         __u64    bit;
1806         ENTRY;
1807
1808         if (hexa)
1809                 seq_printf(m, "(%#llx) ", mask);
1810
1811         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1812                 bit = (1ULL << i);
1813
1814                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1815                         if (hsm_policy_names[j].bit == bit)
1816                                 break;
1817                 }
1818                 if (bit & mask)
1819                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1820                 else
1821                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1822         }
1823         /* remove last ' ' */
1824         m->count--;
1825         seq_putc(m, '\n');
1826 }
1827
1828 /* methods to read/write HSM policy flags */
1829 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1830 {
1831         struct mdt_device       *mdt = m->private;
1832         struct coordinator      *cdt = &mdt->mdt_coordinator;
1833         ENTRY;
1834
1835         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1836         RETURN(0);
1837 }
1838
1839 static ssize_t
1840 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1841                          size_t count, loff_t *off)
1842 {
1843         struct seq_file         *m = file->private_data;
1844         struct mdt_device       *mdt = m->private;
1845         struct coordinator      *cdt = &mdt->mdt_coordinator;
1846         char                    *start, *token, sign;
1847         char                    *buf;
1848         __u64                    policy;
1849         __u64                    add_mask, remove_mask, set_mask;
1850         int                      rc;
1851         ENTRY;
1852
1853         if (count + 1 > PAGE_SIZE)
1854                 RETURN(-EINVAL);
1855
1856         OBD_ALLOC(buf, count + 1);
1857         if (buf == NULL)
1858                 RETURN(-ENOMEM);
1859
1860         if (copy_from_user(buf, buffer, count))
1861                 GOTO(out, rc = -EFAULT);
1862
1863         buf[count] = '\0';
1864
1865         start = buf;
1866         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1867                start);
1868
1869         add_mask = remove_mask = set_mask = 0;
1870         do {
1871                 token = strsep(&start, "\n ");
1872                 sign = *token;
1873
1874                 if (sign == '\0')
1875                         continue;
1876
1877                 if (sign == '-' || sign == '+')
1878                         token++;
1879
1880                 policy = hsm_policy_str2bit(token);
1881                 if (policy == 0) {
1882                         CWARN("%s: '%s' is unknown, "
1883                               "supported policies are:\n", mdt_obd_name(mdt),
1884                               token);
1885                         hsm_policy_bit2str(m, 0, false);
1886                         GOTO(out, rc = -EINVAL);
1887                 }
1888                 switch (sign) {
1889                 case '-':
1890                         remove_mask |= policy;
1891                         break;
1892                 case '+':
1893                         add_mask |= policy;
1894                         break;
1895                 default:
1896                         set_mask |= policy;
1897                         break;
1898                 }
1899
1900         } while (start != NULL);
1901
1902         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
1903                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
1904
1905         /* if no sign in all string, it is a clear and set
1906          * if some sign found, all unsigned are converted
1907          * to add
1908          * P1 P2 = set to P1 and P2
1909          * P1 -P2 = add P1 clear P2 same as +P1 -P2
1910          */
1911         if (remove_mask == 0 && add_mask == 0) {
1912                 cdt->cdt_policy = set_mask;
1913         } else {
1914                 cdt->cdt_policy |= set_mask | add_mask;
1915                 cdt->cdt_policy &= ~remove_mask;
1916         }
1917
1918         GOTO(out, rc = count);
1919
1920 out:
1921         OBD_FREE(buf, count + 1);
1922         RETURN(rc);
1923 }
1924 LPROC_SEQ_FOPS(mdt_hsm_policy);
1925
1926 #define GENERATE_PROC_METHOD(VAR)                                       \
1927 static int mdt_hsm_##VAR##_seq_show(struct seq_file *m, void *data)     \
1928 {                                                                       \
1929         struct mdt_device       *mdt = m->private;                      \
1930         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1931         ENTRY;                                                          \
1932                                                                         \
1933         seq_printf(m, "%llu\n", (__u64)cdt->VAR);                       \
1934         RETURN(0);                                                      \
1935 }                                                                       \
1936 static ssize_t                                                          \
1937 mdt_hsm_##VAR##_seq_write(struct file *file, const char __user *buffer, \
1938                           size_t count, loff_t *off)                    \
1939                                                                         \
1940 {                                                                       \
1941         struct seq_file         *m = file->private_data;                \
1942         struct mdt_device       *mdt = m->private;                      \
1943         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1944         __s64                    val;                                   \
1945         int                      rc;                                    \
1946         ENTRY;                                                          \
1947                                                                         \
1948         rc = lprocfs_str_to_s64(buffer, count, &val);                   \
1949         if (rc)                                                         \
1950                 RETURN(rc);                                             \
1951         if (val > 0 && val < INT_MAX) {                                 \
1952                 cdt->VAR = val;                                         \
1953                 RETURN(count);                                          \
1954         }                                                               \
1955         RETURN(-EINVAL);                                                \
1956 }                                                                       \
1957
1958 GENERATE_PROC_METHOD(cdt_loop_period)
1959 GENERATE_PROC_METHOD(cdt_grace_delay)
1960 GENERATE_PROC_METHOD(cdt_active_req_timeout)
1961 GENERATE_PROC_METHOD(cdt_max_requests)
1962 GENERATE_PROC_METHOD(cdt_default_archive_id)
1963
1964 /*
1965  * procfs write method for MDT/hsm_control
1966  * proc entry is in mdt directory so data is mdt obd_device pointer
1967  */
1968 #define CDT_ENABLE_CMD   "enabled"
1969 #define CDT_STOP_CMD     "shutdown"
1970 #define CDT_DISABLE_CMD  "disabled"
1971 #define CDT_PURGE_CMD    "purge"
1972 #define CDT_HELP_CMD     "help"
1973 #define CDT_MAX_CMD_LEN  10
1974
1975 ssize_t
1976 mdt_hsm_cdt_control_seq_write(struct file *file, const char __user *buffer,
1977                               size_t count, loff_t *off)
1978 {
1979         struct seq_file         *m = file->private_data;
1980         struct obd_device       *obd = m->private;
1981         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
1982         struct coordinator      *cdt = &(mdt->mdt_coordinator);
1983         int                      rc, usage = 0;
1984         char                     kernbuf[CDT_MAX_CMD_LEN];
1985         ENTRY;
1986
1987         if (count == 0 || count >= sizeof(kernbuf))
1988                 RETURN(-EINVAL);
1989
1990         if (copy_from_user(kernbuf, buffer, count))
1991                 RETURN(-EFAULT);
1992         kernbuf[count] = 0;
1993
1994         if (kernbuf[count - 1] == '\n')
1995                 kernbuf[count - 1] = 0;
1996
1997         rc = 0;
1998         if (strcmp(kernbuf, CDT_ENABLE_CMD) == 0) {
1999                 if (cdt->cdt_state == CDT_DISABLE) {
2000                         rc = set_cdt_state(cdt, CDT_RUNNING, NULL);
2001                         mdt_hsm_cdt_wakeup(mdt);
2002                 } else {
2003                         rc = mdt_hsm_cdt_start(mdt);
2004                 }
2005         } else if (strcmp(kernbuf, CDT_STOP_CMD) == 0) {
2006                 if ((cdt->cdt_state == CDT_STOPPING) ||
2007                     (cdt->cdt_state == CDT_STOPPED)) {
2008                         CERROR("%s: Coordinator already stopped\n",
2009                                mdt_obd_name(mdt));
2010                         rc = -EALREADY;
2011                 } else {
2012                         rc = mdt_hsm_cdt_stop(mdt);
2013                         mdt_hsm_cdt_wakeup(mdt);
2014                 }
2015         } else if (strcmp(kernbuf, CDT_DISABLE_CMD) == 0) {
2016                 if ((cdt->cdt_state == CDT_STOPPING) ||
2017                     (cdt->cdt_state == CDT_STOPPED)) {
2018                         CERROR("%s: Coordinator is stopped\n",
2019                                mdt_obd_name(mdt));
2020                         rc = -EINVAL;
2021                 } else {
2022                         rc = set_cdt_state(cdt, CDT_DISABLE, NULL);
2023                 }
2024         } else if (strcmp(kernbuf, CDT_PURGE_CMD) == 0) {
2025                 rc = hsm_cancel_all_actions(mdt);
2026         } else if (strcmp(kernbuf, CDT_HELP_CMD) == 0) {
2027                 usage = 1;
2028         } else {
2029                 usage = 1;
2030                 rc = -EINVAL;
2031         }
2032
2033         if (usage == 1)
2034                 CERROR("%s: Valid coordinator control commands are: "
2035                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2036                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2037                        CDT_PURGE_CMD, CDT_HELP_CMD);
2038
2039         if (rc)
2040                 RETURN(rc);
2041
2042         RETURN(count);
2043 }
2044
2045 int mdt_hsm_cdt_control_seq_show(struct seq_file *m, void *data)
2046 {
2047         struct obd_device       *obd = m->private;
2048         struct coordinator      *cdt;
2049         ENTRY;
2050
2051         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2052
2053         seq_printf(m, "%s\n", cdt_mdt_state2str(cdt->cdt_state));
2054
2055         RETURN(0);
2056 }
2057
2058 static int
2059 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2060 {
2061         bool first = true;
2062         int i;
2063         ENTRY;
2064
2065         for (i = 0; i < 8 * sizeof(mask); i++) {
2066                 if (mask & (1UL << i)) {
2067                         seq_printf(m, "%s%s", first ? "" : " ",
2068                                    hsm_copytool_action2name(i));
2069                         first = false;
2070                 }
2071         }
2072         seq_putc(m, '\n');
2073
2074         RETURN(0);
2075 }
2076
2077 static int
2078 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2079 {
2080         struct mdt_device *mdt = m->private;
2081         struct coordinator *cdt = &mdt->mdt_coordinator;
2082
2083         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2084 }
2085
2086 static int
2087 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2088 {
2089         struct mdt_device *mdt = m->private;
2090         struct coordinator *cdt = &mdt->mdt_coordinator;
2091
2092         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2093 }
2094
2095 static int
2096 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2097 {
2098         struct mdt_device *mdt = m->private;
2099         struct coordinator *cdt = &mdt->mdt_coordinator;
2100
2101         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2102 }
2103
2104 static inline enum hsm_copytool_action
2105 hsm_copytool_name2action(const char *name)
2106 {
2107         if (strcasecmp(name, "NOOP") == 0)
2108                 return HSMA_NONE;
2109         else if (strcasecmp(name, "ARCHIVE") == 0)
2110                 return HSMA_ARCHIVE;
2111         else if (strcasecmp(name, "RESTORE") == 0)
2112                 return HSMA_RESTORE;
2113         else if (strcasecmp(name, "REMOVE") == 0)
2114                 return HSMA_REMOVE;
2115         else if (strcasecmp(name, "CANCEL") == 0)
2116                 return HSMA_CANCEL;
2117         else
2118                 return -1;
2119 }
2120
2121 static ssize_t
2122 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2123                             size_t user_count, __u64 *mask)
2124 {
2125         char *buf, *pos, *name;
2126         size_t buf_size;
2127         __u64 new_mask = 0;
2128         int rc;
2129         ENTRY;
2130
2131         if (!(user_count < 4096))
2132                 RETURN(-ENOMEM);
2133
2134         buf_size = user_count + 1;
2135
2136         OBD_ALLOC(buf, buf_size);
2137         if (buf == NULL)
2138                 RETURN(-ENOMEM);
2139
2140         if (copy_from_user(buf, user_buf, buf_size - 1))
2141                 GOTO(out, rc = -EFAULT);
2142
2143         buf[buf_size - 1] = '\0';
2144
2145         pos = buf;
2146         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2147                 int action;
2148
2149                 if (*name == '\0')
2150                         continue;
2151
2152                 action = hsm_copytool_name2action(name);
2153                 if (action < 0)
2154                         GOTO(out, rc = -EINVAL);
2155
2156                 new_mask |= (1UL << action);
2157         }
2158
2159         *mask = new_mask;
2160         rc = user_count;
2161 out:
2162         OBD_FREE(buf, buf_size);
2163
2164         RETURN(rc);
2165 }
2166
2167 static ssize_t
2168 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2169                                         size_t count, loff_t *off)
2170 {
2171         struct seq_file         *m = file->private_data;
2172         struct mdt_device       *mdt = m->private;
2173         struct coordinator *cdt = &mdt->mdt_coordinator;
2174
2175         return mdt_write_hsm_request_mask(file, buf, count,
2176                                            &cdt->cdt_user_request_mask);
2177 }
2178
2179 static ssize_t
2180 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2181                                         size_t count, loff_t *off)
2182 {
2183         struct seq_file         *m = file->private_data;
2184         struct mdt_device       *mdt = m->private;
2185         struct coordinator      *cdt = &mdt->mdt_coordinator;
2186
2187         return mdt_write_hsm_request_mask(file, buf, count,
2188                                            &cdt->cdt_group_request_mask);
2189 }
2190
2191 static ssize_t
2192 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2193                                         size_t count, loff_t *off)
2194 {
2195         struct seq_file         *m = file->private_data;
2196         struct mdt_device       *mdt = m->private;
2197         struct coordinator      *cdt = &mdt->mdt_coordinator;
2198
2199         return mdt_write_hsm_request_mask(file, buf, count,
2200                                            &cdt->cdt_other_request_mask);
2201 }
2202
2203 LPROC_SEQ_FOPS(mdt_hsm_cdt_loop_period);
2204 LPROC_SEQ_FOPS(mdt_hsm_cdt_grace_delay);
2205 LPROC_SEQ_FOPS(mdt_hsm_cdt_active_req_timeout);
2206 LPROC_SEQ_FOPS(mdt_hsm_cdt_max_requests);
2207 LPROC_SEQ_FOPS(mdt_hsm_cdt_default_archive_id);
2208 LPROC_SEQ_FOPS(mdt_hsm_user_request_mask);
2209 LPROC_SEQ_FOPS(mdt_hsm_group_request_mask);
2210 LPROC_SEQ_FOPS(mdt_hsm_other_request_mask);
2211
2212 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2213         { .name =       "agents",
2214           .fops =       &mdt_hsm_agent_fops                     },
2215         { .name =       "actions",
2216           .fops =       &mdt_hsm_actions_fops,
2217           .proc_mode =  0444                                    },
2218         { .name =       "default_archive_id",
2219           .fops =       &mdt_hsm_cdt_default_archive_id_fops    },
2220         { .name =       "grace_delay",
2221           .fops =       &mdt_hsm_cdt_grace_delay_fops           },
2222         { .name =       "loop_period",
2223           .fops =       &mdt_hsm_cdt_loop_period_fops           },
2224         { .name =       "max_requests",
2225           .fops =       &mdt_hsm_cdt_max_requests_fops          },
2226         { .name =       "policy",
2227           .fops =       &mdt_hsm_policy_fops                    },
2228         { .name =       "active_request_timeout",
2229           .fops =       &mdt_hsm_cdt_active_req_timeout_fops    },
2230         { .name =       "active_requests",
2231           .fops =       &mdt_hsm_active_requests_fops           },
2232         { .name =       "user_request_mask",
2233           .fops =       &mdt_hsm_user_request_mask_fops,        },
2234         { .name =       "group_request_mask",
2235           .fops =       &mdt_hsm_group_request_mask_fops,       },
2236         { .name =       "other_request_mask",
2237           .fops =       &mdt_hsm_other_request_mask_fops,       },
2238         { 0 }
2239 };