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